es6.js 4.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636
  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. "use strict";
  4. var BABYLON;
  5. (function (BABYLON) {
  6. /**
  7. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  8. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  9. */
  10. var EffectFallbacks = /** @class */ (function () {
  11. function EffectFallbacks() {
  12. this._defines = {};
  13. this._currentRank = 32;
  14. this._maxRank = -1;
  15. }
  16. /**
  17. * Removes the fallback from the bound mesh.
  18. */
  19. EffectFallbacks.prototype.unBindMesh = function () {
  20. this._mesh = null;
  21. };
  22. /**
  23. * Adds a fallback on the specified property.
  24. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  25. * @param define The name of the define in the shader
  26. */
  27. EffectFallbacks.prototype.addFallback = function (rank, define) {
  28. if (!this._defines[rank]) {
  29. if (rank < this._currentRank) {
  30. this._currentRank = rank;
  31. }
  32. if (rank > this._maxRank) {
  33. this._maxRank = rank;
  34. }
  35. this._defines[rank] = new Array();
  36. }
  37. this._defines[rank].push(define);
  38. };
  39. /**
  40. * Sets the mesh to use CPU skinning when needing to fallback.
  41. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  42. * @param mesh The mesh to use the fallbacks.
  43. */
  44. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  45. this._mesh = mesh;
  46. if (rank < this._currentRank) {
  47. this._currentRank = rank;
  48. }
  49. if (rank > this._maxRank) {
  50. this._maxRank = rank;
  51. }
  52. };
  53. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  54. /**
  55. * Checks to see if more fallbacks are still availible.
  56. */
  57. get: function () {
  58. return this._currentRank <= this._maxRank;
  59. },
  60. enumerable: true,
  61. configurable: true
  62. });
  63. /**
  64. * Removes the defines that shoould be removed when falling back.
  65. * @param currentDefines defines the current define statements for the shader.
  66. * @param effect defines the current effect we try to compile
  67. * @returns The resulting defines with defines of the current rank removed.
  68. */
  69. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  70. // First we try to switch to CPU skinning
  71. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  72. this._mesh.computeBonesUsingShaders = false;
  73. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. this._uniformBuffersNames = {};
  163. this._isReady = false;
  164. this._compilationError = "";
  165. this.name = baseName;
  166. if (attributesNamesOrOptions.attributes) {
  167. var options = attributesNamesOrOptions;
  168. this._engine = uniformsNamesOrEngine;
  169. this._attributesNames = options.attributes;
  170. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  171. this._samplers = options.samplers;
  172. this.defines = options.defines;
  173. this.onError = options.onError;
  174. this.onCompiled = options.onCompiled;
  175. this._fallbacks = options.fallbacks;
  176. this._indexParameters = options.indexParameters;
  177. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  178. if (options.uniformBuffersNames) {
  179. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  180. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  181. }
  182. }
  183. }
  184. else {
  185. this._engine = engine;
  186. this.defines = defines;
  187. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  188. this._samplers = samplers;
  189. this._attributesNames = attributesNamesOrOptions;
  190. this.onError = onError;
  191. this.onCompiled = onCompiled;
  192. this._indexParameters = indexParameters;
  193. this._fallbacks = fallbacks;
  194. }
  195. this.uniqueId = Effect._uniqueIdSeed++;
  196. if (this._getFromCache(baseName)) {
  197. this._prepareEffect();
  198. return;
  199. }
  200. var vertexSource;
  201. var fragmentSource;
  202. if (baseName.vertexElement) {
  203. vertexSource = document.getElementById(baseName.vertexElement);
  204. if (!vertexSource) {
  205. vertexSource = baseName.vertexElement;
  206. }
  207. }
  208. else {
  209. vertexSource = baseName.vertex || baseName;
  210. }
  211. if (baseName.fragmentElement) {
  212. fragmentSource = document.getElementById(baseName.fragmentElement);
  213. if (!fragmentSource) {
  214. fragmentSource = baseName.fragmentElement;
  215. }
  216. }
  217. else {
  218. fragmentSource = baseName.fragment || baseName;
  219. }
  220. var finalVertexCode;
  221. this._loadVertexShaderAsync(vertexSource)
  222. .then(function (vertexCode) {
  223. return _this._processIncludesAsync(vertexCode);
  224. })
  225. .then(function (vertexCodeWithIncludes) {
  226. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  227. return _this._loadFragmentShaderAsync(fragmentSource);
  228. })
  229. .then(function (fragmentCode) {
  230. return _this._processIncludesAsync(fragmentCode);
  231. })
  232. .then(function (fragmentCodeWithIncludes) {
  233. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  234. if (baseName) {
  235. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  236. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  237. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  238. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  239. }
  240. else {
  241. _this._vertexSourceCode = finalVertexCode;
  242. _this._fragmentSourceCode = migratedFragmentCode;
  243. }
  244. _this._setInCache(baseName);
  245. _this._prepareEffect();
  246. });
  247. }
  248. Effect.prototype._getSourceCacheKey = function (baseName) {
  249. var cacheKey = baseName;
  250. if (this._indexParameters) {
  251. for (var key in this._indexParameters) {
  252. if (this._indexParameters.hasOwnProperty(key)) {
  253. cacheKey += "|";
  254. cacheKey += key;
  255. cacheKey += "_";
  256. cacheKey += this._indexParameters[key];
  257. }
  258. }
  259. }
  260. return cacheKey;
  261. };
  262. Effect.prototype._getFromCache = function (baseName) {
  263. if (typeof baseName !== "string") {
  264. return false;
  265. }
  266. var cacheKey = this._getSourceCacheKey(baseName);
  267. var sources = Effect._sourceCache[cacheKey];
  268. if (!sources) {
  269. return false;
  270. }
  271. this._vertexSourceCode = sources.vertex;
  272. this._fragmentSourceCode = sources.fragment;
  273. return true;
  274. };
  275. Effect.prototype._setInCache = function (baseName) {
  276. if (typeof baseName !== "string") {
  277. return;
  278. }
  279. var cacheKey = this._getSourceCacheKey(baseName);
  280. Effect._sourceCache[cacheKey] = {
  281. vertex: this._vertexSourceCode,
  282. fragment: this._fragmentSourceCode
  283. };
  284. };
  285. Object.defineProperty(Effect.prototype, "key", {
  286. /**
  287. * Unique key for this effect
  288. */
  289. get: function () {
  290. return this._key;
  291. },
  292. enumerable: true,
  293. configurable: true
  294. });
  295. /**
  296. * If the effect has been compiled and prepared.
  297. * @returns if the effect is compiled and prepared.
  298. */
  299. Effect.prototype.isReady = function () {
  300. return this._isReady;
  301. };
  302. /**
  303. * The engine the effect was initialized with.
  304. * @returns the engine.
  305. */
  306. Effect.prototype.getEngine = function () {
  307. return this._engine;
  308. };
  309. /**
  310. * The compiled webGL program for the effect
  311. * @returns the webGL program.
  312. */
  313. Effect.prototype.getProgram = function () {
  314. return this._program;
  315. };
  316. /**
  317. * The set of names of attribute variables for the shader.
  318. * @returns An array of attribute names.
  319. */
  320. Effect.prototype.getAttributesNames = function () {
  321. return this._attributesNames;
  322. };
  323. /**
  324. * Returns the attribute at the given index.
  325. * @param index The index of the attribute.
  326. * @returns The location of the attribute.
  327. */
  328. Effect.prototype.getAttributeLocation = function (index) {
  329. return this._attributes[index];
  330. };
  331. /**
  332. * Returns the attribute based on the name of the variable.
  333. * @param name of the attribute to look up.
  334. * @returns the attribute location.
  335. */
  336. Effect.prototype.getAttributeLocationByName = function (name) {
  337. var index = this._attributesNames.indexOf(name);
  338. return this._attributes[index];
  339. };
  340. /**
  341. * The number of attributes.
  342. * @returns the numnber of attributes.
  343. */
  344. Effect.prototype.getAttributesCount = function () {
  345. return this._attributes.length;
  346. };
  347. /**
  348. * Gets the index of a uniform variable.
  349. * @param uniformName of the uniform to look up.
  350. * @returns the index.
  351. */
  352. Effect.prototype.getUniformIndex = function (uniformName) {
  353. return this._uniformsNames.indexOf(uniformName);
  354. };
  355. /**
  356. * Returns the attribute based on the name of the variable.
  357. * @param uniformName of the uniform to look up.
  358. * @returns the location of the uniform.
  359. */
  360. Effect.prototype.getUniform = function (uniformName) {
  361. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  362. };
  363. /**
  364. * Returns an array of sampler variable names
  365. * @returns The array of sampler variable neames.
  366. */
  367. Effect.prototype.getSamplers = function () {
  368. return this._samplers;
  369. };
  370. /**
  371. * The error from the last compilation.
  372. * @returns the error string.
  373. */
  374. Effect.prototype.getCompilationError = function () {
  375. return this._compilationError;
  376. };
  377. /**
  378. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  379. * @param func The callback to be used.
  380. */
  381. Effect.prototype.executeWhenCompiled = function (func) {
  382. if (this.isReady()) {
  383. func(this);
  384. return;
  385. }
  386. this.onCompileObservable.add(function (effect) {
  387. func(effect);
  388. });
  389. };
  390. /** @ignore */
  391. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  392. if (BABYLON.Tools.IsWindowObjectExist()) {
  393. // DOM element ?
  394. if (vertex instanceof HTMLElement) {
  395. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  396. return Promise.resolve(vertexCode);
  397. }
  398. }
  399. // Base64 encoded ?
  400. if (vertex.substr(0, 7) === "base64:") {
  401. var vertexBinary = window.atob(vertex.substr(7));
  402. return Promise.resolve(vertexBinary);
  403. }
  404. // Is in local store ?
  405. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  406. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  407. }
  408. var vertexShaderUrl;
  409. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  410. vertexShaderUrl = vertex;
  411. }
  412. else {
  413. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  414. }
  415. // Vertex shader
  416. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  417. };
  418. /** @ignore */
  419. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  420. if (BABYLON.Tools.IsWindowObjectExist()) {
  421. // DOM element ?
  422. if (fragment instanceof HTMLElement) {
  423. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  424. return Promise.resolve(fragmentCode);
  425. }
  426. }
  427. // Base64 encoded ?
  428. if (fragment.substr(0, 7) === "base64:") {
  429. var fragmentBinary = window.atob(fragment.substr(7));
  430. return Promise.resolve(fragmentBinary);
  431. }
  432. // Is in local store ?
  433. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  434. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  435. }
  436. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  437. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  438. }
  439. var fragmentShaderUrl;
  440. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  441. fragmentShaderUrl = fragment;
  442. }
  443. else {
  444. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  445. }
  446. // Fragment shader
  447. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  448. };
  449. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  450. // Rebuild shaders source code
  451. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  452. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  453. vertexCode = prefix + vertexCode;
  454. fragmentCode = prefix + fragmentCode;
  455. // Number lines of shaders source code
  456. var i = 2;
  457. var regex = /\n/gm;
  458. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  459. i = 2;
  460. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  461. // Dump shaders name and formatted source code
  462. if (this.name.vertexElement) {
  463. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  464. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  465. }
  466. else if (this.name.vertex) {
  467. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  468. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  469. }
  470. else {
  471. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  472. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  473. }
  474. };
  475. ;
  476. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  477. var preparedSourceCode = this._processPrecision(sourceCode);
  478. if (this._engine.webGLVersion == 1) {
  479. return preparedSourceCode;
  480. }
  481. // Already converted
  482. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  483. return preparedSourceCode.replace("#version 300 es", "");
  484. }
  485. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  486. // Remove extensions
  487. // #extension GL_OES_standard_derivatives : enable
  488. // #extension GL_EXT_shader_texture_lod : enable
  489. // #extension GL_EXT_frag_depth : enable
  490. // #extension GL_EXT_draw_buffers : require
  491. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  492. var result = preparedSourceCode.replace(regex, "");
  493. // Migrate to GLSL v300
  494. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  495. result = result.replace(/attribute[ \t]/g, "in ");
  496. result = result.replace(/[ \t]attribute/g, " in");
  497. if (isFragment) {
  498. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  499. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  500. result = result.replace(/texture2D\s*\(/g, "texture(");
  501. result = result.replace(/textureCube\s*\(/g, "texture(");
  502. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  503. result = result.replace(/gl_FragColor/g, "glFragColor");
  504. result = result.replace(/gl_FragData/g, "glFragData");
  505. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  506. }
  507. return result;
  508. };
  509. Effect.prototype._processIncludesAsync = function (sourceCode) {
  510. var _this = this;
  511. return new Promise(function (resolve, reject) {
  512. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  513. var match = regex.exec(sourceCode);
  514. var returnValue = sourceCode;
  515. while (match != null) {
  516. var includeFile = match[1];
  517. // Uniform declaration
  518. if (includeFile.indexOf("__decl__") !== -1) {
  519. includeFile = includeFile.replace(/__decl__/, "");
  520. if (_this._engine.supportsUniformBuffers) {
  521. includeFile = includeFile.replace(/Vertex/, "Ubo");
  522. includeFile = includeFile.replace(/Fragment/, "Ubo");
  523. }
  524. includeFile = includeFile + "Declaration";
  525. }
  526. if (Effect.IncludesShadersStore[includeFile]) {
  527. // Substitution
  528. var includeContent = Effect.IncludesShadersStore[includeFile];
  529. if (match[2]) {
  530. var splits = match[3].split(",");
  531. for (var index = 0; index < splits.length; index += 2) {
  532. var source = new RegExp(splits[index], "g");
  533. var dest = splits[index + 1];
  534. includeContent = includeContent.replace(source, dest);
  535. }
  536. }
  537. if (match[4]) {
  538. var indexString = match[5];
  539. if (indexString.indexOf("..") !== -1) {
  540. var indexSplits = indexString.split("..");
  541. var minIndex = parseInt(indexSplits[0]);
  542. var maxIndex = parseInt(indexSplits[1]);
  543. var sourceIncludeContent = includeContent.slice(0);
  544. includeContent = "";
  545. if (isNaN(maxIndex)) {
  546. maxIndex = _this._indexParameters[indexSplits[1]];
  547. }
  548. for (var i = minIndex; i < maxIndex; i++) {
  549. if (!_this._engine.supportsUniformBuffers) {
  550. // Ubo replacement
  551. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  552. return p1 + "{X}";
  553. });
  554. }
  555. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  556. }
  557. }
  558. else {
  559. if (!_this._engine.supportsUniformBuffers) {
  560. // Ubo replacement
  561. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  562. return p1 + "{X}";
  563. });
  564. }
  565. includeContent = includeContent.replace(/\{X\}/g, indexString);
  566. }
  567. }
  568. // Replace
  569. returnValue = returnValue.replace(match[0], includeContent);
  570. }
  571. else {
  572. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  573. _this._engine._loadFileAsync(includeShaderUrl)
  574. .then(function (fileContent) {
  575. Effect.IncludesShadersStore[includeFile] = fileContent;
  576. return _this._processIncludesAsync(returnValue);
  577. })
  578. .then(function (returnValue) {
  579. resolve(returnValue);
  580. });
  581. return;
  582. }
  583. match = regex.exec(sourceCode);
  584. }
  585. resolve(returnValue);
  586. });
  587. };
  588. Effect.prototype._processPrecision = function (source) {
  589. if (source.indexOf("precision highp float") === -1) {
  590. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  591. source = "precision mediump float;\n" + source;
  592. }
  593. else {
  594. source = "precision highp float;\n" + source;
  595. }
  596. }
  597. else {
  598. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  599. source = source.replace("precision highp float", "precision mediump float");
  600. }
  601. }
  602. return source;
  603. };
  604. /**
  605. * Recompiles the webGL program
  606. * @param vertexSourceCode The source code for the vertex shader.
  607. * @param fragmentSourceCode The source code for the fragment shader.
  608. * @param onCompiled Callback called when completed.
  609. * @param onError Callback called on error.
  610. */
  611. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  612. var _this = this;
  613. this._isReady = false;
  614. this._vertexSourceCodeOverride = vertexSourceCode;
  615. this._fragmentSourceCodeOverride = fragmentSourceCode;
  616. this.onError = function (effect, error) {
  617. if (onError) {
  618. onError(error);
  619. }
  620. };
  621. this.onCompiled = function () {
  622. var scenes = _this.getEngine().scenes;
  623. for (var i = 0; i < scenes.length; i++) {
  624. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  625. }
  626. if (onCompiled) {
  627. onCompiled(_this._program);
  628. }
  629. };
  630. this._fallbacks = null;
  631. this._prepareEffect();
  632. };
  633. /**
  634. * Gets the uniform locations of the the specified variable names
  635. * @param names THe names of the variables to lookup.
  636. * @returns Array of locations in the same order as variable names.
  637. */
  638. Effect.prototype.getSpecificUniformLocations = function (names) {
  639. var engine = this._engine;
  640. return engine.getUniforms(this._program, names);
  641. };
  642. /**
  643. * Prepares the effect
  644. */
  645. Effect.prototype._prepareEffect = function () {
  646. var attributesNames = this._attributesNames;
  647. var defines = this.defines;
  648. var fallbacks = this._fallbacks;
  649. this._valueCache = {};
  650. var previousProgram = this._program;
  651. try {
  652. var engine = this._engine;
  653. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  654. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  655. }
  656. else {
  657. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  658. }
  659. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  660. if (engine.supportsUniformBuffers) {
  661. for (var name in this._uniformBuffersNames) {
  662. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  663. }
  664. }
  665. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  666. this._attributes = engine.getAttributes(this._program, attributesNames);
  667. var index;
  668. for (index = 0; index < this._samplers.length; index++) {
  669. var sampler = this.getUniform(this._samplers[index]);
  670. if (sampler == null) {
  671. this._samplers.splice(index, 1);
  672. index--;
  673. }
  674. }
  675. engine.bindSamplers(this);
  676. this._compilationError = "";
  677. this._isReady = true;
  678. if (this.onCompiled) {
  679. this.onCompiled(this);
  680. }
  681. this.onCompileObservable.notifyObservers(this);
  682. this.onCompileObservable.clear();
  683. // Unbind mesh reference in fallbacks
  684. if (this._fallbacks) {
  685. this._fallbacks.unBindMesh();
  686. }
  687. if (previousProgram) {
  688. this.getEngine()._deleteProgram(previousProgram);
  689. }
  690. }
  691. catch (e) {
  692. this._compilationError = e.message;
  693. // Let's go through fallbacks then
  694. BABYLON.Tools.Error("Unable to compile effect:");
  695. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  696. return " " + uniform;
  697. }));
  698. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  699. return " " + attribute;
  700. }));
  701. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  702. BABYLON.Tools.Error("Error: " + this._compilationError);
  703. if (previousProgram) {
  704. this._program = previousProgram;
  705. this._isReady = true;
  706. if (this.onError) {
  707. this.onError(this, this._compilationError);
  708. }
  709. this.onErrorObservable.notifyObservers(this);
  710. }
  711. if (fallbacks && fallbacks.isMoreFallbacks) {
  712. BABYLON.Tools.Error("Trying next fallback.");
  713. this.defines = fallbacks.reduce(this.defines, this);
  714. this._prepareEffect();
  715. }
  716. else {
  717. if (this.onError) {
  718. this.onError(this, this._compilationError);
  719. }
  720. this.onErrorObservable.notifyObservers(this);
  721. this.onErrorObservable.clear();
  722. // Unbind mesh reference in fallbacks
  723. if (this._fallbacks) {
  724. this._fallbacks.unBindMesh();
  725. }
  726. }
  727. }
  728. };
  729. Object.defineProperty(Effect.prototype, "isSupported", {
  730. /**
  731. * Checks if the effect is supported. (Must be called after compilation)
  732. */
  733. get: function () {
  734. return this._compilationError === "";
  735. },
  736. enumerable: true,
  737. configurable: true
  738. });
  739. /**
  740. * Binds a texture to the engine to be used as output of the shader.
  741. * @param channel Name of the output variable.
  742. * @param texture Texture to bind.
  743. */
  744. Effect.prototype._bindTexture = function (channel, texture) {
  745. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  746. };
  747. /**
  748. * Sets a texture on the engine to be used in the shader.
  749. * @param channel Name of the sampler variable.
  750. * @param texture Texture to set.
  751. */
  752. Effect.prototype.setTexture = function (channel, texture) {
  753. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  754. };
  755. /**
  756. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  757. * @param channel Name of the sampler variable.
  758. * @param texture Texture to set.
  759. */
  760. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  761. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  762. };
  763. /**
  764. * Sets an array of textures on the engine to be used in the shader.
  765. * @param channel Name of the variable.
  766. * @param textures Textures to set.
  767. */
  768. Effect.prototype.setTextureArray = function (channel, textures) {
  769. if (this._samplers.indexOf(channel + "Ex") === -1) {
  770. var initialPos = this._samplers.indexOf(channel);
  771. for (var index = 1; index < textures.length; index++) {
  772. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  773. }
  774. }
  775. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  776. };
  777. /**
  778. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  779. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  780. * @param channel Name of the sampler variable.
  781. * @param postProcess Post process to get the input texture from.
  782. */
  783. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  784. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  785. };
  786. /**
  787. * Sets the output texture of the passed in post process to be input of this effect.
  788. * @param channel Name of the sampler variable.
  789. * @param postProcess Post process to get the output texture from.
  790. */
  791. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  792. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  793. };
  794. /** @ignore */
  795. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  796. var cache = this._valueCache[uniformName];
  797. var flag = matrix.updateFlag;
  798. if (cache !== undefined && cache === flag) {
  799. return false;
  800. }
  801. this._valueCache[uniformName] = flag;
  802. return true;
  803. };
  804. /** @ignore */
  805. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  806. var cache = this._valueCache[uniformName];
  807. if (!cache) {
  808. cache = [x, y];
  809. this._valueCache[uniformName] = cache;
  810. return true;
  811. }
  812. var changed = false;
  813. if (cache[0] !== x) {
  814. cache[0] = x;
  815. changed = true;
  816. }
  817. if (cache[1] !== y) {
  818. cache[1] = y;
  819. changed = true;
  820. }
  821. return changed;
  822. };
  823. /** @ignore */
  824. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  825. var cache = this._valueCache[uniformName];
  826. if (!cache) {
  827. cache = [x, y, z];
  828. this._valueCache[uniformName] = cache;
  829. return true;
  830. }
  831. var changed = false;
  832. if (cache[0] !== x) {
  833. cache[0] = x;
  834. changed = true;
  835. }
  836. if (cache[1] !== y) {
  837. cache[1] = y;
  838. changed = true;
  839. }
  840. if (cache[2] !== z) {
  841. cache[2] = z;
  842. changed = true;
  843. }
  844. return changed;
  845. };
  846. /** @ignore */
  847. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  848. var cache = this._valueCache[uniformName];
  849. if (!cache) {
  850. cache = [x, y, z, w];
  851. this._valueCache[uniformName] = cache;
  852. return true;
  853. }
  854. var changed = false;
  855. if (cache[0] !== x) {
  856. cache[0] = x;
  857. changed = true;
  858. }
  859. if (cache[1] !== y) {
  860. cache[1] = y;
  861. changed = true;
  862. }
  863. if (cache[2] !== z) {
  864. cache[2] = z;
  865. changed = true;
  866. }
  867. if (cache[3] !== w) {
  868. cache[3] = w;
  869. changed = true;
  870. }
  871. return changed;
  872. };
  873. /**
  874. * Binds a buffer to a uniform.
  875. * @param buffer Buffer to bind.
  876. * @param name Name of the uniform variable to bind to.
  877. */
  878. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  879. var bufferName = this._uniformBuffersNames[name];
  880. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  881. return;
  882. }
  883. Effect._baseCache[bufferName] = buffer;
  884. this._engine.bindUniformBufferBase(buffer, bufferName);
  885. };
  886. /**
  887. * Binds block to a uniform.
  888. * @param blockName Name of the block to bind.
  889. * @param index Index to bind.
  890. */
  891. Effect.prototype.bindUniformBlock = function (blockName, index) {
  892. this._engine.bindUniformBlock(this._program, blockName, index);
  893. };
  894. /**
  895. * Sets an interger value on a uniform variable.
  896. * @param uniformName Name of the variable.
  897. * @param value Value to be set.
  898. * @returns this effect.
  899. */
  900. Effect.prototype.setInt = function (uniformName, value) {
  901. var cache = this._valueCache[uniformName];
  902. if (cache !== undefined && cache === value)
  903. return this;
  904. this._valueCache[uniformName] = value;
  905. this._engine.setInt(this.getUniform(uniformName), value);
  906. return this;
  907. };
  908. /**
  909. * Sets an int array on a uniform variable.
  910. * @param uniformName Name of the variable.
  911. * @param array array to be set.
  912. * @returns this effect.
  913. */
  914. Effect.prototype.setIntArray = function (uniformName, array) {
  915. this._valueCache[uniformName] = null;
  916. this._engine.setIntArray(this.getUniform(uniformName), array);
  917. return this;
  918. };
  919. /**
  920. * 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)
  921. * @param uniformName Name of the variable.
  922. * @param array array to be set.
  923. * @returns this effect.
  924. */
  925. Effect.prototype.setIntArray2 = function (uniformName, array) {
  926. this._valueCache[uniformName] = null;
  927. this._engine.setIntArray2(this.getUniform(uniformName), array);
  928. return this;
  929. };
  930. /**
  931. * 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)
  932. * @param uniformName Name of the variable.
  933. * @param array array to be set.
  934. * @returns this effect.
  935. */
  936. Effect.prototype.setIntArray3 = function (uniformName, array) {
  937. this._valueCache[uniformName] = null;
  938. this._engine.setIntArray3(this.getUniform(uniformName), array);
  939. return this;
  940. };
  941. /**
  942. * 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)
  943. * @param uniformName Name of the variable.
  944. * @param array array to be set.
  945. * @returns this effect.
  946. */
  947. Effect.prototype.setIntArray4 = function (uniformName, array) {
  948. this._valueCache[uniformName] = null;
  949. this._engine.setIntArray4(this.getUniform(uniformName), array);
  950. return this;
  951. };
  952. /**
  953. * Sets an float array on a uniform variable.
  954. * @param uniformName Name of the variable.
  955. * @param array array to be set.
  956. * @returns this effect.
  957. */
  958. Effect.prototype.setFloatArray = function (uniformName, array) {
  959. this._valueCache[uniformName] = null;
  960. this._engine.setFloatArray(this.getUniform(uniformName), array);
  961. return this;
  962. };
  963. /**
  964. * 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)
  965. * @param uniformName Name of the variable.
  966. * @param array array to be set.
  967. * @returns this effect.
  968. */
  969. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  970. this._valueCache[uniformName] = null;
  971. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  972. return this;
  973. };
  974. /**
  975. * 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)
  976. * @param uniformName Name of the variable.
  977. * @param array array to be set.
  978. * @returns this effect.
  979. */
  980. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  981. this._valueCache[uniformName] = null;
  982. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  983. return this;
  984. };
  985. /**
  986. * 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)
  987. * @param uniformName Name of the variable.
  988. * @param array array to be set.
  989. * @returns this effect.
  990. */
  991. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  992. this._valueCache[uniformName] = null;
  993. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  994. return this;
  995. };
  996. /**
  997. * Sets an array on a uniform variable.
  998. * @param uniformName Name of the variable.
  999. * @param array array to be set.
  1000. * @returns this effect.
  1001. */
  1002. Effect.prototype.setArray = function (uniformName, array) {
  1003. this._valueCache[uniformName] = null;
  1004. this._engine.setArray(this.getUniform(uniformName), array);
  1005. return this;
  1006. };
  1007. /**
  1008. * 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)
  1009. * @param uniformName Name of the variable.
  1010. * @param array array to be set.
  1011. * @returns this effect.
  1012. */
  1013. Effect.prototype.setArray2 = function (uniformName, array) {
  1014. this._valueCache[uniformName] = null;
  1015. this._engine.setArray2(this.getUniform(uniformName), array);
  1016. return this;
  1017. };
  1018. /**
  1019. * 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)
  1020. * @param uniformName Name of the variable.
  1021. * @param array array to be set.
  1022. * @returns this effect.
  1023. */
  1024. Effect.prototype.setArray3 = function (uniformName, array) {
  1025. this._valueCache[uniformName] = null;
  1026. this._engine.setArray3(this.getUniform(uniformName), array);
  1027. return this;
  1028. };
  1029. /**
  1030. * 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)
  1031. * @param uniformName Name of the variable.
  1032. * @param array array to be set.
  1033. * @returns this effect.
  1034. */
  1035. Effect.prototype.setArray4 = function (uniformName, array) {
  1036. this._valueCache[uniformName] = null;
  1037. this._engine.setArray4(this.getUniform(uniformName), array);
  1038. return this;
  1039. };
  1040. /**
  1041. * Sets matrices on a uniform variable.
  1042. * @param uniformName Name of the variable.
  1043. * @param matrices matrices to be set.
  1044. * @returns this effect.
  1045. */
  1046. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1047. if (!matrices) {
  1048. return this;
  1049. }
  1050. this._valueCache[uniformName] = null;
  1051. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1052. return this;
  1053. };
  1054. /**
  1055. * Sets matrix on a uniform variable.
  1056. * @param uniformName Name of the variable.
  1057. * @param matrix matrix to be set.
  1058. * @returns this effect.
  1059. */
  1060. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1061. if (this._cacheMatrix(uniformName, matrix)) {
  1062. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1063. }
  1064. return this;
  1065. };
  1066. /**
  1067. * 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)
  1068. * @param uniformName Name of the variable.
  1069. * @param matrix matrix to be set.
  1070. * @returns this effect.
  1071. */
  1072. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1073. this._valueCache[uniformName] = null;
  1074. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1075. return this;
  1076. };
  1077. /**
  1078. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1079. * @param uniformName Name of the variable.
  1080. * @param matrix matrix to be set.
  1081. * @returns this effect.
  1082. */
  1083. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1084. this._valueCache[uniformName] = null;
  1085. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param value value to be set.
  1092. * @returns this effect.
  1093. */
  1094. Effect.prototype.setFloat = function (uniformName, value) {
  1095. var cache = this._valueCache[uniformName];
  1096. if (cache !== undefined && cache === value)
  1097. return this;
  1098. this._valueCache[uniformName] = value;
  1099. this._engine.setFloat(this.getUniform(uniformName), value);
  1100. return this;
  1101. };
  1102. /**
  1103. * Sets a boolean on a uniform variable.
  1104. * @param uniformName Name of the variable.
  1105. * @param bool value to be set.
  1106. * @returns this effect.
  1107. */
  1108. Effect.prototype.setBool = function (uniformName, bool) {
  1109. var cache = this._valueCache[uniformName];
  1110. if (cache !== undefined && cache === bool)
  1111. return this;
  1112. this._valueCache[uniformName] = bool;
  1113. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1114. return this;
  1115. };
  1116. /**
  1117. * Sets a Vector2 on a uniform variable.
  1118. * @param uniformName Name of the variable.
  1119. * @param vector2 vector2 to be set.
  1120. * @returns this effect.
  1121. */
  1122. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1123. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1124. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1125. }
  1126. return this;
  1127. };
  1128. /**
  1129. * Sets a float2 on a uniform variable.
  1130. * @param uniformName Name of the variable.
  1131. * @param x First float in float2.
  1132. * @param y Second float in float2.
  1133. * @returns this effect.
  1134. */
  1135. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1136. if (this._cacheFloat2(uniformName, x, y)) {
  1137. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1138. }
  1139. return this;
  1140. };
  1141. /**
  1142. * Sets a Vector3 on a uniform variable.
  1143. * @param uniformName Name of the variable.
  1144. * @param vector3 Value to be set.
  1145. * @returns this effect.
  1146. */
  1147. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1148. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1149. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1150. }
  1151. return this;
  1152. };
  1153. /**
  1154. * Sets a float3 on a uniform variable.
  1155. * @param uniformName Name of the variable.
  1156. * @param x First float in float3.
  1157. * @param y Second float in float3.
  1158. * @param z Third float in float3.
  1159. * @returns this effect.
  1160. */
  1161. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1162. if (this._cacheFloat3(uniformName, x, y, z)) {
  1163. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1164. }
  1165. return this;
  1166. };
  1167. /**
  1168. * Sets a Vector4 on a uniform variable.
  1169. * @param uniformName Name of the variable.
  1170. * @param vector4 Value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1174. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1175. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a float4 on a uniform variable.
  1181. * @param uniformName Name of the variable.
  1182. * @param x First float in float4.
  1183. * @param y Second float in float4.
  1184. * @param z Third float in float4.
  1185. * @param w Fourth float in float4.
  1186. * @returns this effect.
  1187. */
  1188. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1189. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1190. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1191. }
  1192. return this;
  1193. };
  1194. /**
  1195. * Sets a Color3 on a uniform variable.
  1196. * @param uniformName Name of the variable.
  1197. * @param color3 Value to be set.
  1198. * @returns this effect.
  1199. */
  1200. Effect.prototype.setColor3 = function (uniformName, color3) {
  1201. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1202. this._engine.setColor3(this.getUniform(uniformName), color3);
  1203. }
  1204. return this;
  1205. };
  1206. /**
  1207. * Sets a Color4 on a uniform variable.
  1208. * @param uniformName Name of the variable.
  1209. * @param color3 Value to be set.
  1210. * @param alpha Alpha value to be set.
  1211. * @returns this effect.
  1212. */
  1213. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1214. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1215. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1216. }
  1217. return this;
  1218. };
  1219. /**
  1220. * Sets a Color4 on a uniform variable
  1221. * @param uniformName defines the name of the variable
  1222. * @param color4 defines the value to be set
  1223. * @returns this effect.
  1224. */
  1225. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1226. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1227. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1228. }
  1229. return this;
  1230. };
  1231. /**
  1232. * Resets the cache of effects.
  1233. */
  1234. Effect.ResetCache = function () {
  1235. Effect._baseCache = {};
  1236. };
  1237. Effect._uniqueIdSeed = 0;
  1238. Effect._baseCache = {};
  1239. Effect._sourceCache = {};
  1240. // Statics
  1241. /**
  1242. * Store of each shader (The can be looked up using effect.key)
  1243. */
  1244. Effect.ShadersStore = {};
  1245. /**
  1246. * Store of each included file for a shader (The can be looked up using effect.key)
  1247. */
  1248. Effect.IncludesShadersStore = {};
  1249. return Effect;
  1250. }());
  1251. BABYLON.Effect = Effect;
  1252. })(BABYLON || (BABYLON = {}));
  1253. //# sourceMappingURL=babylon.effect.js.map
  1254. "use strict";
  1255. //# sourceMappingURL=babylon.types.js.map
  1256. "use strict";
  1257. var BABYLON;
  1258. (function (BABYLON) {
  1259. var KeyboardEventTypes = /** @class */ (function () {
  1260. function KeyboardEventTypes() {
  1261. }
  1262. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1263. get: function () {
  1264. return KeyboardEventTypes._KEYDOWN;
  1265. },
  1266. enumerable: true,
  1267. configurable: true
  1268. });
  1269. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1270. get: function () {
  1271. return KeyboardEventTypes._KEYUP;
  1272. },
  1273. enumerable: true,
  1274. configurable: true
  1275. });
  1276. KeyboardEventTypes._KEYDOWN = 0x01;
  1277. KeyboardEventTypes._KEYUP = 0x02;
  1278. return KeyboardEventTypes;
  1279. }());
  1280. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1281. var KeyboardInfo = /** @class */ (function () {
  1282. function KeyboardInfo(type, event) {
  1283. this.type = type;
  1284. this.event = event;
  1285. }
  1286. return KeyboardInfo;
  1287. }());
  1288. BABYLON.KeyboardInfo = KeyboardInfo;
  1289. /**
  1290. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1291. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1292. */
  1293. var KeyboardInfoPre = /** @class */ (function (_super) {
  1294. __extends(KeyboardInfoPre, _super);
  1295. function KeyboardInfoPre(type, event) {
  1296. var _this = _super.call(this, type, event) || this;
  1297. _this.skipOnPointerObservable = false;
  1298. return _this;
  1299. }
  1300. return KeyboardInfoPre;
  1301. }(KeyboardInfo));
  1302. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1303. })(BABYLON || (BABYLON = {}));
  1304. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1305. "use strict";
  1306. var BABYLON;
  1307. (function (BABYLON) {
  1308. var PointerEventTypes = /** @class */ (function () {
  1309. function PointerEventTypes() {
  1310. }
  1311. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1312. get: function () {
  1313. return PointerEventTypes._POINTERDOWN;
  1314. },
  1315. enumerable: true,
  1316. configurable: true
  1317. });
  1318. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1319. get: function () {
  1320. return PointerEventTypes._POINTERUP;
  1321. },
  1322. enumerable: true,
  1323. configurable: true
  1324. });
  1325. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1326. get: function () {
  1327. return PointerEventTypes._POINTERMOVE;
  1328. },
  1329. enumerable: true,
  1330. configurable: true
  1331. });
  1332. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1333. get: function () {
  1334. return PointerEventTypes._POINTERWHEEL;
  1335. },
  1336. enumerable: true,
  1337. configurable: true
  1338. });
  1339. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1340. get: function () {
  1341. return PointerEventTypes._POINTERPICK;
  1342. },
  1343. enumerable: true,
  1344. configurable: true
  1345. });
  1346. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1347. get: function () {
  1348. return PointerEventTypes._POINTERTAP;
  1349. },
  1350. enumerable: true,
  1351. configurable: true
  1352. });
  1353. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1354. get: function () {
  1355. return PointerEventTypes._POINTERDOUBLETAP;
  1356. },
  1357. enumerable: true,
  1358. configurable: true
  1359. });
  1360. PointerEventTypes._POINTERDOWN = 0x01;
  1361. PointerEventTypes._POINTERUP = 0x02;
  1362. PointerEventTypes._POINTERMOVE = 0x04;
  1363. PointerEventTypes._POINTERWHEEL = 0x08;
  1364. PointerEventTypes._POINTERPICK = 0x10;
  1365. PointerEventTypes._POINTERTAP = 0x20;
  1366. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1367. return PointerEventTypes;
  1368. }());
  1369. BABYLON.PointerEventTypes = PointerEventTypes;
  1370. var PointerInfoBase = /** @class */ (function () {
  1371. function PointerInfoBase(type, event) {
  1372. this.type = type;
  1373. this.event = event;
  1374. }
  1375. return PointerInfoBase;
  1376. }());
  1377. BABYLON.PointerInfoBase = PointerInfoBase;
  1378. /**
  1379. * This class is used to store pointer related info for the onPrePointerObservable event.
  1380. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1381. */
  1382. var PointerInfoPre = /** @class */ (function (_super) {
  1383. __extends(PointerInfoPre, _super);
  1384. function PointerInfoPre(type, event, localX, localY) {
  1385. var _this = _super.call(this, type, event) || this;
  1386. _this.skipOnPointerObservable = false;
  1387. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1388. return _this;
  1389. }
  1390. return PointerInfoPre;
  1391. }(PointerInfoBase));
  1392. BABYLON.PointerInfoPre = PointerInfoPre;
  1393. /**
  1394. * This type contains all the data related to a pointer event in Babylon.js.
  1395. * 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.
  1396. */
  1397. var PointerInfo = /** @class */ (function (_super) {
  1398. __extends(PointerInfo, _super);
  1399. function PointerInfo(type, event, pickInfo) {
  1400. var _this = _super.call(this, type, event) || this;
  1401. _this.pickInfo = pickInfo;
  1402. return _this;
  1403. }
  1404. return PointerInfo;
  1405. }(PointerInfoBase));
  1406. BABYLON.PointerInfo = PointerInfo;
  1407. })(BABYLON || (BABYLON = {}));
  1408. //# sourceMappingURL=babylon.pointerEvents.js.map
  1409. "use strict";
  1410. var BABYLON;
  1411. (function (BABYLON) {
  1412. BABYLON.ToGammaSpace = 1 / 2.2;
  1413. BABYLON.ToLinearSpace = 2.2;
  1414. BABYLON.Epsilon = 0.001;
  1415. /**
  1416. * Class used to hold a RBG color
  1417. */
  1418. var Color3 = /** @class */ (function () {
  1419. /**
  1420. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1421. * @param r defines the red component (between 0 and 1, default is 0)
  1422. * @param g defines the green component (between 0 and 1, default is 0)
  1423. * @param b defines the blue component (between 0 and 1, default is 0)
  1424. */
  1425. function Color3(
  1426. /**
  1427. * Defines the red component (between 0 and 1, default is 0)
  1428. */
  1429. r,
  1430. /**
  1431. * Defines the green component (between 0 and 1, default is 0)
  1432. */
  1433. g,
  1434. /**
  1435. * Defines the blue component (between 0 and 1, default is 0)
  1436. */
  1437. b) {
  1438. if (r === void 0) { r = 0; }
  1439. if (g === void 0) { g = 0; }
  1440. if (b === void 0) { b = 0; }
  1441. this.r = r;
  1442. this.g = g;
  1443. this.b = b;
  1444. }
  1445. /**
  1446. * Creates a string with the Color3 current values
  1447. * @returns the string representation of the Color3 object
  1448. */
  1449. Color3.prototype.toString = function () {
  1450. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1451. };
  1452. /**
  1453. * Returns the string "Color3"
  1454. * @returns "Color3"
  1455. */
  1456. Color3.prototype.getClassName = function () {
  1457. return "Color3";
  1458. };
  1459. /**
  1460. * Compute the Color3 hash code
  1461. * @returns an unique number that can be used to hash Color3 objects
  1462. */
  1463. Color3.prototype.getHashCode = function () {
  1464. var hash = this.r || 0;
  1465. hash = (hash * 397) ^ (this.g || 0);
  1466. hash = (hash * 397) ^ (this.b || 0);
  1467. return hash;
  1468. };
  1469. // Operators
  1470. /**
  1471. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1472. * @param array defines the array where to store the r,g,b components
  1473. * @param index defines an optional index in the target array to define where to start storing values
  1474. * @returns the current Color3 object
  1475. */
  1476. Color3.prototype.toArray = function (array, index) {
  1477. if (index === undefined) {
  1478. index = 0;
  1479. }
  1480. array[index] = this.r;
  1481. array[index + 1] = this.g;
  1482. array[index + 2] = this.b;
  1483. return this;
  1484. };
  1485. /**
  1486. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1487. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1488. * @returns a new {BABYLON.Color4} object
  1489. */
  1490. Color3.prototype.toColor4 = function (alpha) {
  1491. if (alpha === void 0) { alpha = 1; }
  1492. return new Color4(this.r, this.g, this.b, alpha);
  1493. };
  1494. /**
  1495. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1496. * @returns the new array
  1497. */
  1498. Color3.prototype.asArray = function () {
  1499. var result = new Array();
  1500. this.toArray(result, 0);
  1501. return result;
  1502. };
  1503. /**
  1504. * Returns the luminance value
  1505. * @returns a float value
  1506. */
  1507. Color3.prototype.toLuminance = function () {
  1508. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1509. };
  1510. /**
  1511. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1512. * @param otherColor defines the second operand
  1513. * @returns the new Color3 object
  1514. */
  1515. Color3.prototype.multiply = function (otherColor) {
  1516. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1517. };
  1518. /**
  1519. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1520. * @param otherColor defines the second operand
  1521. * @param result defines the Color3 object where to store the result
  1522. * @returns the current Color3
  1523. */
  1524. Color3.prototype.multiplyToRef = 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. * Determines equality between Color3 objects
  1532. * @param otherColor defines the second operand
  1533. * @returns true if the rgb values are equal to the passed ones
  1534. */
  1535. Color3.prototype.equals = function (otherColor) {
  1536. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1537. };
  1538. /**
  1539. * Determines equality between the current Color3 object and a set of r,b,g values
  1540. * @param r defines the red component to check
  1541. * @param g defines the green component to check
  1542. * @param b defines the blue component to check
  1543. * @returns true if the rgb values are equal to the passed ones
  1544. */
  1545. Color3.prototype.equalsFloats = function (r, g, b) {
  1546. return this.r === r && this.g === g && this.b === b;
  1547. };
  1548. /**
  1549. * Multiplies in place each rgb value by scale
  1550. * @param scale defines the scaling factor
  1551. * @returns the updated Color3
  1552. */
  1553. Color3.prototype.scale = function (scale) {
  1554. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1555. };
  1556. /**
  1557. * Multiplies the rgb values by scale and stores the result into "result"
  1558. * @param scale defines the scaling factor
  1559. * @param result defines the Color3 object where to store the result
  1560. * @returns the unmodified current Color3
  1561. */
  1562. Color3.prototype.scaleToRef = function (scale, result) {
  1563. result.r = this.r * scale;
  1564. result.g = this.g * scale;
  1565. result.b = this.b * scale;
  1566. return this;
  1567. };
  1568. /**
  1569. * Scale the current Color3 values by a factor and add the result to a given Color3
  1570. * @param scale defines the scale factor
  1571. * @param result defines color to store the result into
  1572. * @returns the unmodified current Color3
  1573. */
  1574. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1575. result.r += this.r * scale;
  1576. result.g += this.g * scale;
  1577. result.b += this.b * scale;
  1578. return this;
  1579. };
  1580. /**
  1581. * Clamps the rgb values by the min and max values and stores the result into "result"
  1582. * @param min defines minimum clamping value (default is 0)
  1583. * @param max defines maximum clamping value (default is 1)
  1584. * @param result defines color to store the result into
  1585. * @returns the original Color3
  1586. */
  1587. Color3.prototype.clampToRef = function (min, max, result) {
  1588. if (min === void 0) { min = 0; }
  1589. if (max === void 0) { max = 1; }
  1590. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1591. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1592. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1593. return this;
  1594. };
  1595. /**
  1596. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1597. * @param otherColor defines the second operand
  1598. * @returns the new Color3
  1599. */
  1600. Color3.prototype.add = function (otherColor) {
  1601. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1602. };
  1603. /**
  1604. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1605. * @param otherColor defines the second operand
  1606. * @param result defines Color3 object to store the result into
  1607. * @returns the unmodified current Color3
  1608. */
  1609. Color3.prototype.addToRef = function (otherColor, result) {
  1610. result.r = this.r + otherColor.r;
  1611. result.g = this.g + otherColor.g;
  1612. result.b = this.b + otherColor.b;
  1613. return this;
  1614. };
  1615. /**
  1616. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1617. * @param otherColor defines the second operand
  1618. * @returns the new Color3
  1619. */
  1620. Color3.prototype.subtract = function (otherColor) {
  1621. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1622. };
  1623. /**
  1624. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1625. * @param otherColor defines the second operand
  1626. * @param result defines Color3 object to store the result into
  1627. * @returns the unmodified current Color3
  1628. */
  1629. Color3.prototype.subtractToRef = function (otherColor, result) {
  1630. result.r = this.r - otherColor.r;
  1631. result.g = this.g - otherColor.g;
  1632. result.b = this.b - otherColor.b;
  1633. return this;
  1634. };
  1635. /**
  1636. * Copy the current object
  1637. * @returns a new Color3 copied the current one
  1638. */
  1639. Color3.prototype.clone = function () {
  1640. return new Color3(this.r, this.g, this.b);
  1641. };
  1642. /**
  1643. * Copies the rgb values from the source in the current Color3
  1644. * @param source defines the source Color3 object
  1645. * @returns the updated Color3 object
  1646. */
  1647. Color3.prototype.copyFrom = function (source) {
  1648. this.r = source.r;
  1649. this.g = source.g;
  1650. this.b = source.b;
  1651. return this;
  1652. };
  1653. /**
  1654. * Updates the Color3 rgb values from the passed floats
  1655. * @param r defines the red component to read from
  1656. * @param g defines the green component to read from
  1657. * @param b defines the blue component to read from
  1658. * @returns the current Color3 object
  1659. */
  1660. Color3.prototype.copyFromFloats = function (r, g, b) {
  1661. this.r = r;
  1662. this.g = g;
  1663. this.b = b;
  1664. return this;
  1665. };
  1666. /**
  1667. * Updates the Color3 rgb values from the passed floats
  1668. * @param r defines the red component to read from
  1669. * @param g defines the green component to read from
  1670. * @param b defines the blue component to read from
  1671. * @returns the current Color3 object
  1672. */
  1673. Color3.prototype.set = function (r, g, b) {
  1674. return this.copyFromFloats(r, g, b);
  1675. };
  1676. /**
  1677. * Compute the Color3 hexadecimal code as a string
  1678. * @returns a string containing the hexadecimal representation of the Color3 object
  1679. */
  1680. Color3.prototype.toHexString = function () {
  1681. var intR = (this.r * 255) | 0;
  1682. var intG = (this.g * 255) | 0;
  1683. var intB = (this.b * 255) | 0;
  1684. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1685. };
  1686. /**
  1687. * Computes a new Color3 converted from the current one to linear space
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.prototype.toLinearSpace = function () {
  1691. var convertedColor = new Color3();
  1692. this.toLinearSpaceToRef(convertedColor);
  1693. return convertedColor;
  1694. };
  1695. /**
  1696. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1697. * @param convertedColor defines the Color3 object where to store the linear space version
  1698. * @returns the unmodified Color3
  1699. */
  1700. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1701. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1702. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1703. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1704. return this;
  1705. };
  1706. /**
  1707. * Computes a new Color3 converted from the current one to gamma space
  1708. * @returns a new Color3 object
  1709. */
  1710. Color3.prototype.toGammaSpace = function () {
  1711. var convertedColor = new Color3();
  1712. this.toGammaSpaceToRef(convertedColor);
  1713. return convertedColor;
  1714. };
  1715. /**
  1716. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1717. * @param convertedColor defines the Color3 object where to store the gamma space version
  1718. * @returns the unmodified Color3
  1719. */
  1720. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1721. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1722. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1723. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1724. return this;
  1725. };
  1726. // Statics
  1727. /**
  1728. * Creates a new Color3 from the string containing valid hexadecimal values
  1729. * @param hex defines a string containing valid hexadecimal values
  1730. * @returns a new Color3 object
  1731. */
  1732. Color3.FromHexString = function (hex) {
  1733. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1734. return new Color3(0, 0, 0);
  1735. }
  1736. var r = parseInt(hex.substring(1, 3), 16);
  1737. var g = parseInt(hex.substring(3, 5), 16);
  1738. var b = parseInt(hex.substring(5, 7), 16);
  1739. return Color3.FromInts(r, g, b);
  1740. };
  1741. /**
  1742. * Creates a new Vector3 from the starting index of the passed array
  1743. * @param array defines the source array
  1744. * @param offset defines an offset in the source array
  1745. * @returns a new Color3 object
  1746. */
  1747. Color3.FromArray = function (array, offset) {
  1748. if (offset === void 0) { offset = 0; }
  1749. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1750. };
  1751. /**
  1752. * Creates a new Color3 from integer values (< 256)
  1753. * @param r defines the red component to read from (value between 0 and 255)
  1754. * @param g defines the green component to read from (value between 0 and 255)
  1755. * @param b defines the blue component to read from (value between 0 and 255)
  1756. * @returns a new Color3 object
  1757. */
  1758. Color3.FromInts = function (r, g, b) {
  1759. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1760. };
  1761. /**
  1762. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1763. * @param start defines the start Color3 value
  1764. * @param end defines the end Color3 value
  1765. * @param amount defines the gradient value between start and end
  1766. * @returns a new Color3 object
  1767. */
  1768. Color3.Lerp = function (start, end, amount) {
  1769. var r = start.r + ((end.r - start.r) * amount);
  1770. var g = start.g + ((end.g - start.g) * amount);
  1771. var b = start.b + ((end.b - start.b) * amount);
  1772. return new Color3(r, g, b);
  1773. };
  1774. /**
  1775. * Returns a Color3 value containing a red color
  1776. * @returns a new Color3 object
  1777. */
  1778. Color3.Red = function () { return new Color3(1, 0, 0); };
  1779. /**
  1780. * Returns a Color3 value containing a green color
  1781. * @returns a new Color3 object
  1782. */
  1783. Color3.Green = function () { return new Color3(0, 1, 0); };
  1784. /**
  1785. * Returns a Color3 value containing a blue color
  1786. * @returns a new Color3 object
  1787. */
  1788. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1789. /**
  1790. * Returns a Color3 value containing a black color
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.Black = function () { return new Color3(0, 0, 0); };
  1794. /**
  1795. * Returns a Color3 value containing a white color
  1796. * @returns a new Color3 object
  1797. */
  1798. Color3.White = function () { return new Color3(1, 1, 1); };
  1799. /**
  1800. * Returns a Color3 value containing a purple color
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1804. /**
  1805. * Returns a Color3 value containing a magenta color
  1806. * @returns a new Color3 object
  1807. */
  1808. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1809. /**
  1810. * Returns a Color3 value containing a yellow color
  1811. * @returns a new Color3 object
  1812. */
  1813. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1814. /**
  1815. * Returns a Color3 value containing a gray color
  1816. * @returns a new Color3 object
  1817. */
  1818. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1819. /**
  1820. * Returns a Color3 value containing a teal color
  1821. * @returns a new Color3 object
  1822. */
  1823. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1824. /**
  1825. * Returns a Color3 value containing a random color
  1826. * @returns a new Color3 object
  1827. */
  1828. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1829. return Color3;
  1830. }());
  1831. BABYLON.Color3 = Color3;
  1832. /**
  1833. * Class used to hold a RBGA color
  1834. */
  1835. var Color4 = /** @class */ (function () {
  1836. /**
  1837. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1838. * @param r defines the red component (between 0 and 1, default is 0)
  1839. * @param g defines the green component (between 0 and 1, default is 0)
  1840. * @param b defines the blue component (between 0 and 1, default is 0)
  1841. * @param a defines the alpha component (between 0 and 1, default is 1)
  1842. */
  1843. function Color4(
  1844. /**
  1845. * Defines the red component (between 0 and 1, default is 0)
  1846. */
  1847. r,
  1848. /**
  1849. * Defines the green component (between 0 and 1, default is 0)
  1850. */
  1851. g,
  1852. /**
  1853. * Defines the blue component (between 0 and 1, default is 0)
  1854. */
  1855. b,
  1856. /**
  1857. * Defines the alpha component (between 0 and 1, default is 1)
  1858. */
  1859. a) {
  1860. if (r === void 0) { r = 0; }
  1861. if (g === void 0) { g = 0; }
  1862. if (b === void 0) { b = 0; }
  1863. if (a === void 0) { a = 1; }
  1864. this.r = r;
  1865. this.g = g;
  1866. this.b = b;
  1867. this.a = a;
  1868. }
  1869. // Operators
  1870. /**
  1871. * Adds in place the passed Color4 values to the current Color4 object
  1872. * @param right defines the second operand
  1873. * @returns the current updated Color4 object
  1874. */
  1875. Color4.prototype.addInPlace = function (right) {
  1876. this.r += right.r;
  1877. this.g += right.g;
  1878. this.b += right.b;
  1879. this.a += right.a;
  1880. return this;
  1881. };
  1882. /**
  1883. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1884. * @returns the new array
  1885. */
  1886. Color4.prototype.asArray = function () {
  1887. var result = new Array();
  1888. this.toArray(result, 0);
  1889. return result;
  1890. };
  1891. /**
  1892. * Stores from the starting index in the passed array the Color4 successive values
  1893. * @param array defines the array where to store the r,g,b components
  1894. * @param index defines an optional index in the target array to define where to start storing values
  1895. * @returns the current Color4 object
  1896. */
  1897. Color4.prototype.toArray = function (array, index) {
  1898. if (index === undefined) {
  1899. index = 0;
  1900. }
  1901. array[index] = this.r;
  1902. array[index + 1] = this.g;
  1903. array[index + 2] = this.b;
  1904. array[index + 3] = this.a;
  1905. return this;
  1906. };
  1907. /**
  1908. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1909. * @param right defines the second operand
  1910. * @returns a new Color4 object
  1911. */
  1912. Color4.prototype.add = function (right) {
  1913. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1914. };
  1915. /**
  1916. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1917. * @param right defines the second operand
  1918. * @returns a new Color4 object
  1919. */
  1920. Color4.prototype.subtract = function (right) {
  1921. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1922. };
  1923. /**
  1924. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1925. * @param right defines the second operand
  1926. * @param result defines the Color4 object where to store the result
  1927. * @returns the current Color4 object
  1928. */
  1929. Color4.prototype.subtractToRef = function (right, result) {
  1930. result.r = this.r - right.r;
  1931. result.g = this.g - right.g;
  1932. result.b = this.b - right.b;
  1933. result.a = this.a - right.a;
  1934. return this;
  1935. };
  1936. /**
  1937. * Creates a new Color4 with the current Color4 values multiplied by scale
  1938. * @param scale defines the scaling factor to apply
  1939. * @returns a new Color4 object
  1940. */
  1941. Color4.prototype.scale = function (scale) {
  1942. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1943. };
  1944. /**
  1945. * Multiplies the current Color4 values by scale and stores the result in "result"
  1946. * @param scale defines the scaling factor to apply
  1947. * @param result defines the Color4 object where to store the result
  1948. * @returns the current unmodified Color4
  1949. */
  1950. Color4.prototype.scaleToRef = function (scale, result) {
  1951. result.r = this.r * scale;
  1952. result.g = this.g * scale;
  1953. result.b = this.b * scale;
  1954. result.a = this.a * scale;
  1955. return this;
  1956. };
  1957. /**
  1958. * Scale the current Color4 values by a factor and add the result to a given Color4
  1959. * @param scale defines the scale factor
  1960. * @param result defines the Color4 object where to store the result
  1961. * @returns the unmodified current Color4
  1962. */
  1963. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1964. result.r += this.r * scale;
  1965. result.g += this.g * scale;
  1966. result.b += this.b * scale;
  1967. result.a += this.a * scale;
  1968. return this;
  1969. };
  1970. /**
  1971. * Clamps the rgb values by the min and max values and stores the result into "result"
  1972. * @param min defines minimum clamping value (default is 0)
  1973. * @param max defines maximum clamping value (default is 1)
  1974. * @param result defines color to store the result into.
  1975. * @returns the cuurent Color4
  1976. */
  1977. Color4.prototype.clampToRef = function (min, max, result) {
  1978. if (min === void 0) { min = 0; }
  1979. if (max === void 0) { max = 1; }
  1980. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1981. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1982. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1983. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1984. return this;
  1985. };
  1986. /**
  1987. * Multipy an Color4 value by another and return a new Color4 object
  1988. * @param color defines the Color4 value to multiply by
  1989. * @returns a new Color4 object
  1990. */
  1991. Color4.prototype.multiply = function (color) {
  1992. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1993. };
  1994. /**
  1995. * Multipy a Color4 value by another and push the result in a reference value
  1996. * @param color defines the Color4 value to multiply by
  1997. * @param result defines the Color4 to fill the result in
  1998. * @returns the result Color4
  1999. */
  2000. Color4.prototype.multiplyToRef = function (color, result) {
  2001. result.r = this.r * color.r;
  2002. result.g = this.g * color.g;
  2003. result.b = this.b * color.b;
  2004. result.a = this.a * color.a;
  2005. return result;
  2006. };
  2007. /**
  2008. * Creates a string with the Color4 current values
  2009. * @returns the string representation of the Color4 object
  2010. */
  2011. Color4.prototype.toString = function () {
  2012. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2013. };
  2014. /**
  2015. * Returns the string "Color4"
  2016. * @returns "Color4"
  2017. */
  2018. Color4.prototype.getClassName = function () {
  2019. return "Color4";
  2020. };
  2021. /**
  2022. * Compute the Color4 hash code
  2023. * @returns an unique number that can be used to hash Color4 objects
  2024. */
  2025. Color4.prototype.getHashCode = function () {
  2026. var hash = this.r || 0;
  2027. hash = (hash * 397) ^ (this.g || 0);
  2028. hash = (hash * 397) ^ (this.b || 0);
  2029. hash = (hash * 397) ^ (this.a || 0);
  2030. return hash;
  2031. };
  2032. /**
  2033. * Creates a new Color4 copied from the current one
  2034. * @returns a new Color4 object
  2035. */
  2036. Color4.prototype.clone = function () {
  2037. return new Color4(this.r, this.g, this.b, this.a);
  2038. };
  2039. /**
  2040. * Copies the passed Color4 values into the current one
  2041. * @param source defines the source Color4 object
  2042. * @returns the current updated Color4 object
  2043. */
  2044. Color4.prototype.copyFrom = function (source) {
  2045. this.r = source.r;
  2046. this.g = source.g;
  2047. this.b = source.b;
  2048. this.a = source.a;
  2049. return this;
  2050. };
  2051. /**
  2052. * Copies the passed float values into the current one
  2053. * @param r defines the red component to read from
  2054. * @param g defines the green component to read from
  2055. * @param b defines the blue component to read from
  2056. * @param a defines the alpha component to read from
  2057. * @returns the current updated Color4 object
  2058. */
  2059. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2060. this.r = r;
  2061. this.g = g;
  2062. this.b = b;
  2063. this.a = a;
  2064. return this;
  2065. };
  2066. /**
  2067. * Copies the passed float values into the current one
  2068. * @param r defines the red component to read from
  2069. * @param g defines the green component to read from
  2070. * @param b defines the blue component to read from
  2071. * @param a defines the alpha component to read from
  2072. * @returns the current updated Color4 object
  2073. */
  2074. Color4.prototype.set = function (r, g, b, a) {
  2075. return this.copyFromFloats(r, g, b, a);
  2076. };
  2077. /**
  2078. * Compute the Color4 hexadecimal code as a string
  2079. * @returns a string containing the hexadecimal representation of the Color4 object
  2080. */
  2081. Color4.prototype.toHexString = function () {
  2082. var intR = (this.r * 255) | 0;
  2083. var intG = (this.g * 255) | 0;
  2084. var intB = (this.b * 255) | 0;
  2085. var intA = (this.a * 255) | 0;
  2086. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2087. };
  2088. /**
  2089. * Computes a new Color4 converted from the current one to linear space
  2090. * @returns a new Color4 object
  2091. */
  2092. Color4.prototype.toLinearSpace = function () {
  2093. var convertedColor = new Color4();
  2094. this.toLinearSpaceToRef(convertedColor);
  2095. return convertedColor;
  2096. };
  2097. /**
  2098. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2099. * @param convertedColor defines the Color4 object where to store the linear space version
  2100. * @returns the unmodified Color4
  2101. */
  2102. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2103. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2104. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2105. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2106. convertedColor.a = this.a;
  2107. return this;
  2108. };
  2109. /**
  2110. * Computes a new Color4 converted from the current one to gamma space
  2111. * @returns a new Color4 object
  2112. */
  2113. Color4.prototype.toGammaSpace = function () {
  2114. var convertedColor = new Color4();
  2115. this.toGammaSpaceToRef(convertedColor);
  2116. return convertedColor;
  2117. };
  2118. /**
  2119. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2120. * @param convertedColor defines the Color4 object where to store the gamma space version
  2121. * @returns the unmodified Color4
  2122. */
  2123. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2124. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2125. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2126. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2127. convertedColor.a = this.a;
  2128. return this;
  2129. };
  2130. // Statics
  2131. /**
  2132. * Creates a new Color4 from the string containing valid hexadecimal values
  2133. * @param hex defines a string containing valid hexadecimal values
  2134. * @returns a new Color4 object
  2135. */
  2136. Color4.FromHexString = function (hex) {
  2137. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2138. return new Color4(0.0, 0.0, 0.0, 0.0);
  2139. }
  2140. var r = parseInt(hex.substring(1, 3), 16);
  2141. var g = parseInt(hex.substring(3, 5), 16);
  2142. var b = parseInt(hex.substring(5, 7), 16);
  2143. var a = parseInt(hex.substring(7, 9), 16);
  2144. return Color4.FromInts(r, g, b, a);
  2145. };
  2146. /**
  2147. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2148. * @param left defines the start value
  2149. * @param right defines the end value
  2150. * @param amount defines the gradient factor
  2151. * @returns a new Color4 object
  2152. */
  2153. Color4.Lerp = function (left, right, amount) {
  2154. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2155. Color4.LerpToRef(left, right, amount, result);
  2156. return result;
  2157. };
  2158. /**
  2159. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2160. * @param left defines the start value
  2161. * @param right defines the end value
  2162. * @param amount defines the gradient factor
  2163. * @param result defines the Color4 object where to store data
  2164. */
  2165. Color4.LerpToRef = function (left, right, amount, result) {
  2166. result.r = left.r + (right.r - left.r) * amount;
  2167. result.g = left.g + (right.g - left.g) * amount;
  2168. result.b = left.b + (right.b - left.b) * amount;
  2169. result.a = left.a + (right.a - left.a) * amount;
  2170. };
  2171. /**
  2172. * Creates a new Color4 from the starting index element of the passed array
  2173. * @param array defines the source array to read from
  2174. * @param offset defines the offset in the source array
  2175. * @returns a new Color4 object
  2176. */
  2177. Color4.FromArray = function (array, offset) {
  2178. if (offset === void 0) { offset = 0; }
  2179. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2180. };
  2181. /**
  2182. * Creates a new Color3 from integer values (< 256)
  2183. * @param r defines the red component to read from (value between 0 and 255)
  2184. * @param g defines the green component to read from (value between 0 and 255)
  2185. * @param b defines the blue component to read from (value between 0 and 255)
  2186. * @param a defines the alpha component to read from (value between 0 and 255)
  2187. * @returns a new Color3 object
  2188. */
  2189. Color4.FromInts = function (r, g, b, a) {
  2190. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2191. };
  2192. /**
  2193. * Check the content of a given array and convert it to an array containing RGBA data
  2194. * If the original array was already containing count * 4 values then it is returned directly
  2195. * @param colors defines the array to check
  2196. * @param count defines the number of RGBA data to expect
  2197. * @returns an array containing count * 4 values (RGBA)
  2198. */
  2199. Color4.CheckColors4 = function (colors, count) {
  2200. // Check if color3 was used
  2201. if (colors.length === count * 3) {
  2202. var colors4 = [];
  2203. for (var index = 0; index < colors.length; index += 3) {
  2204. var newIndex = (index / 3) * 4;
  2205. colors4[newIndex] = colors[index];
  2206. colors4[newIndex + 1] = colors[index + 1];
  2207. colors4[newIndex + 2] = colors[index + 2];
  2208. colors4[newIndex + 3] = 1.0;
  2209. }
  2210. return colors4;
  2211. }
  2212. return colors;
  2213. };
  2214. return Color4;
  2215. }());
  2216. BABYLON.Color4 = Color4;
  2217. var Vector2 = /** @class */ (function () {
  2218. /**
  2219. * Creates a new Vector2 from the passed x and y coordinates.
  2220. */
  2221. function Vector2(x, y) {
  2222. this.x = x;
  2223. this.y = y;
  2224. }
  2225. /**
  2226. * Returns a string with the Vector2 coordinates.
  2227. */
  2228. Vector2.prototype.toString = function () {
  2229. return "{X: " + this.x + " Y:" + this.y + "}";
  2230. };
  2231. /**
  2232. * Returns the string "Vector2"
  2233. */
  2234. Vector2.prototype.getClassName = function () {
  2235. return "Vector2";
  2236. };
  2237. /**
  2238. * Returns the Vector2 hash code as a number.
  2239. */
  2240. Vector2.prototype.getHashCode = function () {
  2241. var hash = this.x || 0;
  2242. hash = (hash * 397) ^ (this.y || 0);
  2243. return hash;
  2244. };
  2245. // Operators
  2246. /**
  2247. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2248. * Returns the Vector2.
  2249. */
  2250. Vector2.prototype.toArray = function (array, index) {
  2251. if (index === void 0) { index = 0; }
  2252. array[index] = this.x;
  2253. array[index + 1] = this.y;
  2254. return this;
  2255. };
  2256. /**
  2257. * Returns a new array with 2 elements : the Vector2 coordinates.
  2258. */
  2259. Vector2.prototype.asArray = function () {
  2260. var result = new Array();
  2261. this.toArray(result, 0);
  2262. return result;
  2263. };
  2264. /**
  2265. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2266. * Returns the updated Vector2.
  2267. */
  2268. Vector2.prototype.copyFrom = function (source) {
  2269. this.x = source.x;
  2270. this.y = source.y;
  2271. return this;
  2272. };
  2273. /**
  2274. * Sets the Vector2 coordinates with the passed floats.
  2275. * Returns the updated Vector2.
  2276. */
  2277. Vector2.prototype.copyFromFloats = function (x, y) {
  2278. this.x = x;
  2279. this.y = y;
  2280. return this;
  2281. };
  2282. /**
  2283. * Sets the Vector2 coordinates with the passed floats.
  2284. * Returns the updated Vector2.
  2285. */
  2286. Vector2.prototype.set = function (x, y) {
  2287. return this.copyFromFloats(x, y);
  2288. };
  2289. /**
  2290. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2291. */
  2292. Vector2.prototype.add = function (otherVector) {
  2293. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2294. };
  2295. /**
  2296. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2297. * Returns the Vector2.
  2298. */
  2299. Vector2.prototype.addToRef = function (otherVector, result) {
  2300. result.x = this.x + otherVector.x;
  2301. result.y = this.y + otherVector.y;
  2302. return this;
  2303. };
  2304. /**
  2305. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2306. * Returns the updated Vector2.
  2307. */
  2308. Vector2.prototype.addInPlace = function (otherVector) {
  2309. this.x += otherVector.x;
  2310. this.y += otherVector.y;
  2311. return this;
  2312. };
  2313. /**
  2314. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2315. */
  2316. Vector2.prototype.addVector3 = function (otherVector) {
  2317. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2318. };
  2319. /**
  2320. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2321. */
  2322. Vector2.prototype.subtract = function (otherVector) {
  2323. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2324. };
  2325. /**
  2326. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2327. * Returns the Vector2.
  2328. */
  2329. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2330. result.x = this.x - otherVector.x;
  2331. result.y = this.y - otherVector.y;
  2332. return this;
  2333. };
  2334. /**
  2335. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2336. * Returns the updated Vector2.
  2337. */
  2338. Vector2.prototype.subtractInPlace = function (otherVector) {
  2339. this.x -= otherVector.x;
  2340. this.y -= otherVector.y;
  2341. return this;
  2342. };
  2343. /**
  2344. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2345. * Returns the updated Vector2.
  2346. */
  2347. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2348. this.x *= otherVector.x;
  2349. this.y *= otherVector.y;
  2350. return this;
  2351. };
  2352. /**
  2353. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2354. */
  2355. Vector2.prototype.multiply = function (otherVector) {
  2356. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2357. };
  2358. /**
  2359. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2360. * Returns the Vector2.
  2361. */
  2362. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2363. result.x = this.x * otherVector.x;
  2364. result.y = this.y * otherVector.y;
  2365. return this;
  2366. };
  2367. /**
  2368. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2369. */
  2370. Vector2.prototype.multiplyByFloats = function (x, y) {
  2371. return new Vector2(this.x * x, this.y * y);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2375. */
  2376. Vector2.prototype.divide = function (otherVector) {
  2377. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2378. };
  2379. /**
  2380. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2381. * Returns the Vector2.
  2382. */
  2383. Vector2.prototype.divideToRef = function (otherVector, result) {
  2384. result.x = this.x / otherVector.x;
  2385. result.y = this.y / otherVector.y;
  2386. return this;
  2387. };
  2388. /**
  2389. * Divides the current Vector3 coordinates by the passed ones.
  2390. * Returns the updated Vector3.
  2391. */
  2392. Vector2.prototype.divideInPlace = function (otherVector) {
  2393. return this.divideToRef(otherVector, this);
  2394. };
  2395. /**
  2396. * Returns a new Vector2 with current Vector2 negated coordinates.
  2397. */
  2398. Vector2.prototype.negate = function () {
  2399. return new Vector2(-this.x, -this.y);
  2400. };
  2401. /**
  2402. * Multiply the Vector2 coordinates by scale.
  2403. * Returns the updated Vector2.
  2404. */
  2405. Vector2.prototype.scaleInPlace = function (scale) {
  2406. this.x *= scale;
  2407. this.y *= scale;
  2408. return this;
  2409. };
  2410. /**
  2411. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2412. */
  2413. Vector2.prototype.scale = function (scale) {
  2414. var result = new Vector2(0, 0);
  2415. this.scaleToRef(scale, result);
  2416. return result;
  2417. };
  2418. /**
  2419. * Scale the current Vector2 values by a factor to a given Vector2
  2420. * @param scale defines the scale factor
  2421. * @param result defines the Vector2 object where to store the result
  2422. * @returns the unmodified current Vector2
  2423. */
  2424. Vector2.prototype.scaleToRef = function (scale, result) {
  2425. result.x = this.x * scale;
  2426. result.y = this.y * scale;
  2427. return this;
  2428. };
  2429. /**
  2430. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2431. * @param scale defines the scale factor
  2432. * @param result defines the Vector2 object where to store the result
  2433. * @returns the unmodified current Vector2
  2434. */
  2435. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2436. result.x += this.x * scale;
  2437. result.y += this.y * scale;
  2438. return this;
  2439. };
  2440. /**
  2441. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2442. */
  2443. Vector2.prototype.equals = function (otherVector) {
  2444. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2445. };
  2446. /**
  2447. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2448. */
  2449. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2450. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2451. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2452. };
  2453. // Properties
  2454. /**
  2455. * Returns the vector length (float).
  2456. */
  2457. Vector2.prototype.length = function () {
  2458. return Math.sqrt(this.x * this.x + this.y * this.y);
  2459. };
  2460. /**
  2461. * Returns the vector squared length (float);
  2462. */
  2463. Vector2.prototype.lengthSquared = function () {
  2464. return (this.x * this.x + this.y * this.y);
  2465. };
  2466. // Methods
  2467. /**
  2468. * Normalize the vector.
  2469. * Returns the updated Vector2.
  2470. */
  2471. Vector2.prototype.normalize = function () {
  2472. var len = this.length();
  2473. if (len === 0)
  2474. return this;
  2475. var num = 1.0 / len;
  2476. this.x *= num;
  2477. this.y *= num;
  2478. return this;
  2479. };
  2480. /**
  2481. * Returns a new Vector2 copied from the Vector2.
  2482. */
  2483. Vector2.prototype.clone = function () {
  2484. return new Vector2(this.x, this.y);
  2485. };
  2486. // Statics
  2487. /**
  2488. * Returns a new Vector2(0, 0)
  2489. */
  2490. Vector2.Zero = function () {
  2491. return new Vector2(0, 0);
  2492. };
  2493. /**
  2494. * Returns a new Vector2(1, 1)
  2495. */
  2496. Vector2.One = function () {
  2497. return new Vector2(1, 1);
  2498. };
  2499. /**
  2500. * Returns a new Vector2 set from the passed index element of the passed array.
  2501. */
  2502. Vector2.FromArray = function (array, offset) {
  2503. if (offset === void 0) { offset = 0; }
  2504. return new Vector2(array[offset], array[offset + 1]);
  2505. };
  2506. /**
  2507. * Sets "result" from the passed index element of the passed array.
  2508. */
  2509. Vector2.FromArrayToRef = function (array, offset, result) {
  2510. result.x = array[offset];
  2511. result.y = array[offset + 1];
  2512. };
  2513. /**
  2514. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2515. */
  2516. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2517. var squared = amount * amount;
  2518. var cubed = amount * squared;
  2519. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2520. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2521. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2522. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2523. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2524. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2525. return new Vector2(x, y);
  2526. };
  2527. /**
  2528. * 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".
  2529. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2530. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2531. */
  2532. Vector2.Clamp = function (value, min, max) {
  2533. var x = value.x;
  2534. x = (x > max.x) ? max.x : x;
  2535. x = (x < min.x) ? min.x : x;
  2536. var y = value.y;
  2537. y = (y > max.y) ? max.y : y;
  2538. y = (y < min.y) ? min.y : y;
  2539. return new Vector2(x, y);
  2540. };
  2541. /**
  2542. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2543. */
  2544. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2545. var squared = amount * amount;
  2546. var cubed = amount * squared;
  2547. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2548. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2549. var part3 = (cubed - (2.0 * squared)) + amount;
  2550. var part4 = cubed - squared;
  2551. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2552. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2553. return new Vector2(x, y);
  2554. };
  2555. /**
  2556. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2557. */
  2558. Vector2.Lerp = function (start, end, amount) {
  2559. var x = start.x + ((end.x - start.x) * amount);
  2560. var y = start.y + ((end.y - start.y) * amount);
  2561. return new Vector2(x, y);
  2562. };
  2563. /**
  2564. * Returns the dot product (float) of the vector "left" and the vector "right".
  2565. */
  2566. Vector2.Dot = function (left, right) {
  2567. return left.x * right.x + left.y * right.y;
  2568. };
  2569. /**
  2570. * Returns a new Vector2 equal to the normalized passed vector.
  2571. */
  2572. Vector2.Normalize = function (vector) {
  2573. var newVector = vector.clone();
  2574. newVector.normalize();
  2575. return newVector;
  2576. };
  2577. /**
  2578. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2579. */
  2580. Vector2.Minimize = function (left, right) {
  2581. var x = (left.x < right.x) ? left.x : right.x;
  2582. var y = (left.y < right.y) ? left.y : right.y;
  2583. return new Vector2(x, y);
  2584. };
  2585. /**
  2586. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2587. */
  2588. Vector2.Maximize = function (left, right) {
  2589. var x = (left.x > right.x) ? left.x : right.x;
  2590. var y = (left.y > right.y) ? left.y : right.y;
  2591. return new Vector2(x, y);
  2592. };
  2593. /**
  2594. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2595. */
  2596. Vector2.Transform = function (vector, transformation) {
  2597. var r = Vector2.Zero();
  2598. Vector2.TransformToRef(vector, transformation, r);
  2599. return r;
  2600. };
  2601. /**
  2602. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2603. */
  2604. Vector2.TransformToRef = function (vector, transformation, result) {
  2605. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2606. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2607. result.x = x;
  2608. result.y = y;
  2609. };
  2610. /**
  2611. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2612. */
  2613. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2614. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2615. var sign = a < 0 ? -1 : 1;
  2616. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2617. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2618. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2619. };
  2620. /**
  2621. * Returns the distance (float) between the vectors "value1" and "value2".
  2622. */
  2623. Vector2.Distance = function (value1, value2) {
  2624. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2625. };
  2626. /**
  2627. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2628. */
  2629. Vector2.DistanceSquared = function (value1, value2) {
  2630. var x = value1.x - value2.x;
  2631. var y = value1.y - value2.y;
  2632. return (x * x) + (y * y);
  2633. };
  2634. /**
  2635. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2636. */
  2637. Vector2.Center = function (value1, value2) {
  2638. var center = value1.add(value2);
  2639. center.scaleInPlace(0.5);
  2640. return center;
  2641. };
  2642. /**
  2643. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2644. */
  2645. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2646. var l2 = Vector2.DistanceSquared(segA, segB);
  2647. if (l2 === 0.0) {
  2648. return Vector2.Distance(p, segA);
  2649. }
  2650. var v = segB.subtract(segA);
  2651. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2652. var proj = segA.add(v.multiplyByFloats(t, t));
  2653. return Vector2.Distance(p, proj);
  2654. };
  2655. return Vector2;
  2656. }());
  2657. BABYLON.Vector2 = Vector2;
  2658. /**
  2659. * Classed used to store (x,y,z) vector representation
  2660. * A Vector3 is the main object used in 3D geometry
  2661. * It can represent etiher the coordinates of a point the space, either a direction
  2662. * Reminder: Babylon.js uses a left handed forward facing system
  2663. */
  2664. var Vector3 = /** @class */ (function () {
  2665. /**
  2666. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2667. * @param x defines the first coordinates (on X axis)
  2668. * @param y defines the second coordinates (on Y axis)
  2669. * @param z defines the third coordinates (on Z axis)
  2670. */
  2671. function Vector3(
  2672. /**
  2673. * Defines the first coordinates (on X axis)
  2674. */
  2675. x,
  2676. /**
  2677. * Defines the second coordinates (on Y axis)
  2678. */
  2679. y,
  2680. /**
  2681. * Defines the third coordinates (on Z axis)
  2682. */
  2683. z) {
  2684. this.x = x;
  2685. this.y = y;
  2686. this.z = z;
  2687. }
  2688. /**
  2689. * Creates a string representation of the Vector3
  2690. * @returns a string with the Vector3 coordinates.
  2691. */
  2692. Vector3.prototype.toString = function () {
  2693. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2694. };
  2695. /**
  2696. * Gets the class name
  2697. * @returns the string "Vector3"
  2698. */
  2699. Vector3.prototype.getClassName = function () {
  2700. return "Vector3";
  2701. };
  2702. /**
  2703. * Creates the Vector3 hash code
  2704. * @returns a number which tends to be unique between Vector3 instances
  2705. */
  2706. Vector3.prototype.getHashCode = function () {
  2707. var hash = this.x || 0;
  2708. hash = (hash * 397) ^ (this.y || 0);
  2709. hash = (hash * 397) ^ (this.z || 0);
  2710. return hash;
  2711. };
  2712. // Operators
  2713. /**
  2714. * Creates an array containing three elements : the coordinates of the Vector3
  2715. * @returns a new array of numbers
  2716. */
  2717. Vector3.prototype.asArray = function () {
  2718. var result = [];
  2719. this.toArray(result, 0);
  2720. return result;
  2721. };
  2722. /**
  2723. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2724. * @param array defines the destination array
  2725. * @param index defines the offset in the destination array
  2726. * @returns the current Vector3
  2727. */
  2728. Vector3.prototype.toArray = function (array, index) {
  2729. if (index === void 0) { index = 0; }
  2730. array[index] = this.x;
  2731. array[index + 1] = this.y;
  2732. array[index + 2] = this.z;
  2733. return this;
  2734. };
  2735. /**
  2736. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2737. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2738. */
  2739. Vector3.prototype.toQuaternion = function () {
  2740. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2741. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2742. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2743. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2744. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2745. var cosy = Math.cos(this.y * 0.5);
  2746. var siny = Math.sin(this.y * 0.5);
  2747. result.x = coszMinusx * siny;
  2748. result.y = -sinzMinusx * siny;
  2749. result.z = sinxPlusz * cosy;
  2750. result.w = cosxPlusz * cosy;
  2751. return result;
  2752. };
  2753. /**
  2754. * Adds the passed vector to the current Vector3
  2755. * @param otherVector defines the second operand
  2756. * @returns the current updated Vector3
  2757. */
  2758. Vector3.prototype.addInPlace = function (otherVector) {
  2759. this.x += otherVector.x;
  2760. this.y += otherVector.y;
  2761. this.z += otherVector.z;
  2762. return this;
  2763. };
  2764. /**
  2765. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2766. * @param otherVector defines the second operand
  2767. * @returns the resulting Vector3
  2768. */
  2769. Vector3.prototype.add = function (otherVector) {
  2770. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2771. };
  2772. /**
  2773. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2774. * @param otherVector defines the second operand
  2775. * @param result defines the Vector3 object where to store the result
  2776. * @returns the current Vector3
  2777. */
  2778. Vector3.prototype.addToRef = function (otherVector, result) {
  2779. result.x = this.x + otherVector.x;
  2780. result.y = this.y + otherVector.y;
  2781. result.z = this.z + otherVector.z;
  2782. return this;
  2783. };
  2784. /**
  2785. * Subtract the passed vector from the current Vector3
  2786. * @param otherVector defines the second operand
  2787. * @returns the current updated Vector3
  2788. */
  2789. Vector3.prototype.subtractInPlace = function (otherVector) {
  2790. this.x -= otherVector.x;
  2791. this.y -= otherVector.y;
  2792. this.z -= otherVector.z;
  2793. return this;
  2794. };
  2795. /**
  2796. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2797. * @param otherVector defines the second operand
  2798. * @returns the resulting Vector3
  2799. */
  2800. Vector3.prototype.subtract = function (otherVector) {
  2801. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2802. };
  2803. /**
  2804. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2805. * @param otherVector defines the second operand
  2806. * @param result defines the Vector3 object where to store the result
  2807. * @returns the current Vector3
  2808. */
  2809. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2810. result.x = this.x - otherVector.x;
  2811. result.y = this.y - otherVector.y;
  2812. result.z = this.z - otherVector.z;
  2813. return this;
  2814. };
  2815. /**
  2816. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2817. * @param x defines the x coordinate of the operand
  2818. * @param y defines the y coordinate of the operand
  2819. * @param z defines the z coordinate of the operand
  2820. * @returns the resulting Vector3
  2821. */
  2822. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2823. return new Vector3(this.x - x, this.y - y, this.z - z);
  2824. };
  2825. /**
  2826. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2827. * @param x defines the x coordinate of the operand
  2828. * @param y defines the y coordinate of the operand
  2829. * @param z defines the z coordinate of the operand
  2830. * @param result defines the Vector3 object where to store the result
  2831. * @returns the current Vector3
  2832. */
  2833. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2834. result.x = this.x - x;
  2835. result.y = this.y - y;
  2836. result.z = this.z - z;
  2837. return this;
  2838. };
  2839. /**
  2840. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2841. * @returns a new Vector3
  2842. */
  2843. Vector3.prototype.negate = function () {
  2844. return new Vector3(-this.x, -this.y, -this.z);
  2845. };
  2846. /**
  2847. * Multiplies the Vector3 coordinates by the float "scale"
  2848. * @param scale defines the multiplier factor
  2849. * @returns the current updated Vector3
  2850. */
  2851. Vector3.prototype.scaleInPlace = function (scale) {
  2852. this.x *= scale;
  2853. this.y *= scale;
  2854. this.z *= scale;
  2855. return this;
  2856. };
  2857. /**
  2858. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2859. * @param scale defines the multiplier factor
  2860. * @returns a new Vector3
  2861. */
  2862. Vector3.prototype.scale = function (scale) {
  2863. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2864. };
  2865. /**
  2866. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2867. * @param scale defines the multiplier factor
  2868. * @param result defines the Vector3 object where to store the result
  2869. * @returns the current Vector3
  2870. */
  2871. Vector3.prototype.scaleToRef = function (scale, result) {
  2872. result.x = this.x * scale;
  2873. result.y = this.y * scale;
  2874. result.z = this.z * scale;
  2875. return this;
  2876. };
  2877. /**
  2878. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2879. * @param scale defines the scale factor
  2880. * @param result defines the Vector3 object where to store the result
  2881. * @returns the unmodified current Vector3
  2882. */
  2883. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2884. result.x += this.x * scale;
  2885. result.y += this.y * scale;
  2886. result.z += this.z * scale;
  2887. return this;
  2888. };
  2889. /**
  2890. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2891. * @param otherVector defines the second operand
  2892. * @returns true if both vectors are equals
  2893. */
  2894. Vector3.prototype.equals = function (otherVector) {
  2895. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2896. };
  2897. /**
  2898. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2899. * @param otherVector defines the second operand
  2900. * @param epsilon defines the minimal distance to define values as equals
  2901. * @returns true if both vectors are distant less than epsilon
  2902. */
  2903. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2904. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2905. 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);
  2906. };
  2907. /**
  2908. * Returns true if the current Vector3 coordinates equals the passed floats
  2909. * @param x defines the x coordinate of the operand
  2910. * @param y defines the y coordinate of the operand
  2911. * @param z defines the z coordinate of the operand
  2912. * @returns true if both vectors are equals
  2913. */
  2914. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2915. return this.x === x && this.y === y && this.z === z;
  2916. };
  2917. /**
  2918. * Multiplies the current Vector3 coordinates by the passed ones
  2919. * @param otherVector defines the second operand
  2920. * @returns the current updated Vector3
  2921. */
  2922. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2923. this.x *= otherVector.x;
  2924. this.y *= otherVector.y;
  2925. this.z *= otherVector.z;
  2926. return this;
  2927. };
  2928. /**
  2929. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2930. * @param otherVector defines the second operand
  2931. * @returns the new Vector3
  2932. */
  2933. Vector3.prototype.multiply = function (otherVector) {
  2934. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2935. };
  2936. /**
  2937. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2938. * @param otherVector defines the second operand
  2939. * @param result defines the Vector3 object where to store the result
  2940. * @returns the current Vector3
  2941. */
  2942. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2943. result.x = this.x * otherVector.x;
  2944. result.y = this.y * otherVector.y;
  2945. result.z = this.z * otherVector.z;
  2946. return this;
  2947. };
  2948. /**
  2949. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2950. * @param x defines the x coordinate of the operand
  2951. * @param y defines the y coordinate of the operand
  2952. * @param z defines the z coordinate of the operand
  2953. * @returns the new Vector3
  2954. */
  2955. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2956. return new Vector3(this.x * x, this.y * y, this.z * z);
  2957. };
  2958. /**
  2959. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2960. * @param otherVector defines the second operand
  2961. * @returns the new Vector3
  2962. */
  2963. Vector3.prototype.divide = function (otherVector) {
  2964. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2965. };
  2966. /**
  2967. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2968. * @param otherVector defines the second operand
  2969. * @param result defines the Vector3 object where to store the result
  2970. * @returns the current Vector3
  2971. */
  2972. Vector3.prototype.divideToRef = function (otherVector, result) {
  2973. result.x = this.x / otherVector.x;
  2974. result.y = this.y / otherVector.y;
  2975. result.z = this.z / otherVector.z;
  2976. return this;
  2977. };
  2978. /**
  2979. * Divides the current Vector3 coordinates by the passed ones.
  2980. * @param otherVector defines the second operand
  2981. * @returns the current updated Vector3
  2982. */
  2983. Vector3.prototype.divideInPlace = function (otherVector) {
  2984. return this.divideToRef(otherVector, this);
  2985. };
  2986. /**
  2987. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2988. * @param other defines the second operand
  2989. * @returns the current updated Vector3
  2990. */
  2991. Vector3.prototype.minimizeInPlace = function (other) {
  2992. if (other.x < this.x)
  2993. this.x = other.x;
  2994. if (other.y < this.y)
  2995. this.y = other.y;
  2996. if (other.z < this.z)
  2997. this.z = other.z;
  2998. return this;
  2999. };
  3000. /**
  3001. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  3002. * @param other defines the second operand
  3003. * @returns the current updated Vector3
  3004. */
  3005. Vector3.prototype.maximizeInPlace = function (other) {
  3006. if (other.x > this.x)
  3007. this.x = other.x;
  3008. if (other.y > this.y)
  3009. this.y = other.y;
  3010. if (other.z > this.z)
  3011. this.z = other.z;
  3012. return this;
  3013. };
  3014. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3015. /**
  3016. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3017. */
  3018. get: function () {
  3019. var absX = Math.abs(this.x);
  3020. var absY = Math.abs(this.y);
  3021. if (absX !== absY) {
  3022. return true;
  3023. }
  3024. var absZ = Math.abs(this.z);
  3025. if (absX !== absZ) {
  3026. return true;
  3027. }
  3028. if (absY !== absZ) {
  3029. return true;
  3030. }
  3031. return false;
  3032. },
  3033. enumerable: true,
  3034. configurable: true
  3035. });
  3036. // Properties
  3037. /**
  3038. * Gets the length of the Vector3
  3039. * @returns the length of the Vecto3
  3040. */
  3041. Vector3.prototype.length = function () {
  3042. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3043. };
  3044. /**
  3045. * Gets the squared length of the Vector3
  3046. * @returns squared length of the Vector3
  3047. */
  3048. Vector3.prototype.lengthSquared = function () {
  3049. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3050. };
  3051. /**
  3052. * Normalize the current Vector3.
  3053. * Please note that this is an in place operation.
  3054. * @returns the current updated Vector3
  3055. */
  3056. Vector3.prototype.normalize = function () {
  3057. var len = this.length();
  3058. if (len === 0 || len === 1.0)
  3059. return this;
  3060. var num = 1.0 / len;
  3061. this.x *= num;
  3062. this.y *= num;
  3063. this.z *= num;
  3064. return this;
  3065. };
  3066. /**
  3067. * Normalize the current Vector3 to a new vector
  3068. * @returns the new Vector3
  3069. */
  3070. Vector3.prototype.normalizeToNew = function () {
  3071. var normalized = new Vector3(0, 0, 0);
  3072. this.normalizeToRef(normalized);
  3073. return normalized;
  3074. };
  3075. /**
  3076. * Normalize the current Vector3 to the reference
  3077. * @param reference define the Vector3 to update
  3078. * @returns the updated Vector3
  3079. */
  3080. Vector3.prototype.normalizeToRef = function (reference) {
  3081. var len = this.length();
  3082. if (len === 0 || len === 1.0) {
  3083. reference.set(this.x, this.y, this.z);
  3084. return reference;
  3085. }
  3086. var scale = 1.0 / len;
  3087. this.scaleToRef(scale, reference);
  3088. return reference;
  3089. };
  3090. /**
  3091. * Creates a new Vector3 copied from the current Vector3
  3092. * @returns the new Vector3
  3093. */
  3094. Vector3.prototype.clone = function () {
  3095. return new Vector3(this.x, this.y, this.z);
  3096. };
  3097. /**
  3098. * Copies the passed vector coordinates to the current Vector3 ones
  3099. * @param source defines the source Vector3
  3100. * @returns the current updated Vector3
  3101. */
  3102. Vector3.prototype.copyFrom = function (source) {
  3103. this.x = source.x;
  3104. this.y = source.y;
  3105. this.z = source.z;
  3106. return this;
  3107. };
  3108. /**
  3109. * Copies the passed floats to the current Vector3 coordinates
  3110. * @param x defines the x coordinate of the operand
  3111. * @param y defines the y coordinate of the operand
  3112. * @param z defines the z coordinate of the operand
  3113. * @returns the current updated Vector3
  3114. */
  3115. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3116. this.x = x;
  3117. this.y = y;
  3118. this.z = z;
  3119. return this;
  3120. };
  3121. /**
  3122. * Copies the passed floats to the current Vector3 coordinates
  3123. * @param x defines the x coordinate of the operand
  3124. * @param y defines the y coordinate of the operand
  3125. * @param z defines the z coordinate of the operand
  3126. * @returns the current updated Vector3
  3127. */
  3128. Vector3.prototype.set = function (x, y, z) {
  3129. return this.copyFromFloats(x, y, z);
  3130. };
  3131. // Statics
  3132. /**
  3133. * Get the clip factor between two vectors
  3134. * @param vector0 defines the first operand
  3135. * @param vector1 defines the second operand
  3136. * @param axis defines the axis to use
  3137. * @param size defines the size along the axis
  3138. * @returns the clip factor
  3139. */
  3140. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3141. var d0 = Vector3.Dot(vector0, axis) - size;
  3142. var d1 = Vector3.Dot(vector1, axis) - size;
  3143. var s = d0 / (d0 - d1);
  3144. return s;
  3145. };
  3146. /**
  3147. * Get angle between two vectors
  3148. * @param vector0 angle between vector0 and vector1
  3149. * @param vector1 angle between vector0 and vector1
  3150. * @param normal direction of the normal
  3151. * @return the angle between vector0 and vector1
  3152. */
  3153. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3154. var v0 = vector0.clone().normalize();
  3155. var v1 = vector1.clone().normalize();
  3156. var dot = Vector3.Dot(v0, v1);
  3157. var n = Vector3.Cross(v0, v1);
  3158. if (Vector3.Dot(n, normal) > 0) {
  3159. return Math.acos(dot);
  3160. }
  3161. return -Math.acos(dot);
  3162. };
  3163. /**
  3164. * Returns a new Vector3 set from the index "offset" of the passed array
  3165. * @param array defines the source array
  3166. * @param offset defines the offset in the source array
  3167. * @returns the new Vector3
  3168. */
  3169. Vector3.FromArray = function (array, offset) {
  3170. if (!offset) {
  3171. offset = 0;
  3172. }
  3173. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3174. };
  3175. /**
  3176. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3177. * This function is deprecated. Use FromArray instead
  3178. * @param array defines the source array
  3179. * @param offset defines the offset in the source array
  3180. * @returns the new Vector3
  3181. */
  3182. Vector3.FromFloatArray = function (array, offset) {
  3183. return Vector3.FromArray(array, offset);
  3184. };
  3185. /**
  3186. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3187. * @param array defines the source array
  3188. * @param offset defines the offset in the source array
  3189. * @param result defines the Vector3 where to store the result
  3190. */
  3191. Vector3.FromArrayToRef = function (array, offset, result) {
  3192. result.x = array[offset];
  3193. result.y = array[offset + 1];
  3194. result.z = array[offset + 2];
  3195. };
  3196. /**
  3197. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3198. * This function is deprecated. Use FromArrayToRef instead.
  3199. * @param array defines the source array
  3200. * @param offset defines the offset in the source array
  3201. * @param result defines the Vector3 where to store the result
  3202. */
  3203. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3204. return Vector3.FromArrayToRef(array, offset, result);
  3205. };
  3206. /**
  3207. * Sets the passed vector "result" with the passed floats.
  3208. * @param x defines the x coordinate of the source
  3209. * @param y defines the y coordinate of the source
  3210. * @param z defines the z coordinate of the source
  3211. * @param result defines the Vector3 where to store the result
  3212. */
  3213. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3214. result.x = x;
  3215. result.y = y;
  3216. result.z = z;
  3217. };
  3218. /**
  3219. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3220. * @returns a new empty Vector3
  3221. */
  3222. Vector3.Zero = function () {
  3223. return new Vector3(0.0, 0.0, 0.0);
  3224. };
  3225. /**
  3226. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3227. * @returns a new unit Vector3
  3228. */
  3229. Vector3.One = function () {
  3230. return new Vector3(1.0, 1.0, 1.0);
  3231. };
  3232. /**
  3233. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3234. * @returns a new up Vector3
  3235. */
  3236. Vector3.Up = function () {
  3237. return new Vector3(0.0, 1.0, 0.0);
  3238. };
  3239. /**
  3240. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3241. * @returns a new forward Vector3
  3242. */
  3243. Vector3.Forward = function () {
  3244. return new Vector3(0.0, 0.0, 1.0);
  3245. };
  3246. /**
  3247. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3248. * @returns a new right Vector3
  3249. */
  3250. Vector3.Right = function () {
  3251. return new Vector3(1.0, 0.0, 0.0);
  3252. };
  3253. /**
  3254. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3255. * @returns a new left Vector3
  3256. */
  3257. Vector3.Left = function () {
  3258. return new Vector3(-1.0, 0.0, 0.0);
  3259. };
  3260. /**
  3261. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3262. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3263. * @param vector defines the Vector3 to transform
  3264. * @param transformation defines the transformation matrix
  3265. * @returns the transformed Vector3
  3266. */
  3267. Vector3.TransformCoordinates = function (vector, transformation) {
  3268. var result = Vector3.Zero();
  3269. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3270. return result;
  3271. };
  3272. /**
  3273. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3274. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3275. * @param vector defines the Vector3 to transform
  3276. * @param transformation defines the transformation matrix
  3277. * @param result defines the Vector3 where to store the result
  3278. */
  3279. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3280. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3281. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3282. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3283. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3284. result.x = x / w;
  3285. result.y = y / w;
  3286. result.z = z / w;
  3287. };
  3288. /**
  3289. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3290. * This method computes tranformed coordinates only, not transformed direction vectors
  3291. * @param x define the x coordinate of the source vector
  3292. * @param y define the y coordinate of the source vector
  3293. * @param z define the z coordinate of the source vector
  3294. * @param transformation defines the transformation matrix
  3295. * @param result defines the Vector3 where to store the result
  3296. */
  3297. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3298. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3299. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3300. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3301. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3302. result.x = rx / rw;
  3303. result.y = ry / rw;
  3304. result.z = rz / rw;
  3305. };
  3306. /**
  3307. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3308. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3309. * @param vector defines the Vector3 to transform
  3310. * @param transformation defines the transformation matrix
  3311. * @returns the new Vector3
  3312. */
  3313. Vector3.TransformNormal = function (vector, transformation) {
  3314. var result = Vector3.Zero();
  3315. Vector3.TransformNormalToRef(vector, transformation, result);
  3316. return result;
  3317. };
  3318. /**
  3319. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3320. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3321. * @param vector defines the Vector3 to transform
  3322. * @param transformation defines the transformation matrix
  3323. * @param result defines the Vector3 where to store the result
  3324. */
  3325. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3326. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3327. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3328. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3329. result.x = x;
  3330. result.y = y;
  3331. result.z = z;
  3332. };
  3333. /**
  3334. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3335. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3336. * @param x define the x coordinate of the source vector
  3337. * @param y define the y coordinate of the source vector
  3338. * @param z define the z coordinate of the source vector
  3339. * @param transformation defines the transformation matrix
  3340. * @param result defines the Vector3 where to store the result
  3341. */
  3342. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3343. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3344. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3345. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3349. * @param value1 defines the first control point
  3350. * @param value2 defines the second control point
  3351. * @param value3 defines the third control point
  3352. * @param value4 defines the fourth control point
  3353. * @param amount defines the amount on the spline to use
  3354. * @returns the new Vector3
  3355. */
  3356. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3357. var squared = amount * amount;
  3358. var cubed = amount * squared;
  3359. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3360. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3361. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3362. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3363. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3364. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3365. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3366. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3367. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3368. return new Vector3(x, y, z);
  3369. };
  3370. /**
  3371. * 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"
  3372. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3373. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3374. * @param value defines the current value
  3375. * @param min defines the lower range value
  3376. * @param max defines the upper range value
  3377. * @returns the new Vector3
  3378. */
  3379. Vector3.Clamp = function (value, min, max) {
  3380. var x = value.x;
  3381. x = (x > max.x) ? max.x : x;
  3382. x = (x < min.x) ? min.x : x;
  3383. var y = value.y;
  3384. y = (y > max.y) ? max.y : y;
  3385. y = (y < min.y) ? min.y : y;
  3386. var z = value.z;
  3387. z = (z > max.z) ? max.z : z;
  3388. z = (z < min.z) ? min.z : z;
  3389. return new Vector3(x, y, z);
  3390. };
  3391. /**
  3392. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3393. * @param value1 defines the first control point
  3394. * @param tangent1 defines the first tangent vector
  3395. * @param value2 defines the second control point
  3396. * @param tangent2 defines the second tangent vector
  3397. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3398. * @returns the new Vector3
  3399. */
  3400. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3401. var squared = amount * amount;
  3402. var cubed = amount * squared;
  3403. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3404. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3405. var part3 = (cubed - (2.0 * squared)) + amount;
  3406. var part4 = cubed - squared;
  3407. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3408. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3409. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3410. return new Vector3(x, y, z);
  3411. };
  3412. /**
  3413. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3414. * @param start defines the start value
  3415. * @param end defines the end value
  3416. * @param amount max defines amount between both (between 0 and 1)
  3417. * @returns the new Vector3
  3418. */
  3419. Vector3.Lerp = function (start, end, amount) {
  3420. var result = new Vector3(0, 0, 0);
  3421. Vector3.LerpToRef(start, end, amount, result);
  3422. return result;
  3423. };
  3424. /**
  3425. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3426. * @param start defines the start value
  3427. * @param end defines the end value
  3428. * @param amount max defines amount between both (between 0 and 1)
  3429. * @param result defines the Vector3 where to store the result
  3430. */
  3431. Vector3.LerpToRef = function (start, end, amount, result) {
  3432. result.x = start.x + ((end.x - start.x) * amount);
  3433. result.y = start.y + ((end.y - start.y) * amount);
  3434. result.z = start.z + ((end.z - start.z) * amount);
  3435. };
  3436. /**
  3437. * Returns the dot product (float) between the vectors "left" and "right"
  3438. * @param left defines the left operand
  3439. * @param right defines the right operand
  3440. * @returns the dot product
  3441. */
  3442. Vector3.Dot = function (left, right) {
  3443. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3444. };
  3445. /**
  3446. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3447. * The cross product is then orthogonal to both "left" and "right"
  3448. * @param left defines the left operand
  3449. * @param right defines the right operand
  3450. * @returns the cross product
  3451. */
  3452. Vector3.Cross = function (left, right) {
  3453. var result = Vector3.Zero();
  3454. Vector3.CrossToRef(left, right, result);
  3455. return result;
  3456. };
  3457. /**
  3458. * Sets the passed vector "result" with the cross product of "left" and "right"
  3459. * The cross product is then orthogonal to both "left" and "right"
  3460. * @param left defines the left operand
  3461. * @param right defines the right operand
  3462. * @param result defines the Vector3 where to store the result
  3463. */
  3464. Vector3.CrossToRef = function (left, right, result) {
  3465. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3466. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3467. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3468. result.copyFrom(MathTmp.Vector3[0]);
  3469. };
  3470. /**
  3471. * Returns a new Vector3 as the normalization of the passed vector
  3472. * @param vector defines the Vector3 to normalize
  3473. * @returns the new Vector3
  3474. */
  3475. Vector3.Normalize = function (vector) {
  3476. var result = Vector3.Zero();
  3477. Vector3.NormalizeToRef(vector, result);
  3478. return result;
  3479. };
  3480. /**
  3481. * Sets the passed vector "result" with the normalization of the passed first vector
  3482. * @param vector defines the Vector3 to normalize
  3483. * @param result defines the Vector3 where to store the result
  3484. */
  3485. Vector3.NormalizeToRef = function (vector, result) {
  3486. result.copyFrom(vector);
  3487. result.normalize();
  3488. };
  3489. /**
  3490. * Project a Vector3 onto screen space
  3491. * @param vector defines the Vector3 to project
  3492. * @param world defines the world matrix to use
  3493. * @param transform defines the transform (view x projection) matrix to use
  3494. * @param viewport defines the screen viewport to use
  3495. * @returns the new Vector3
  3496. */
  3497. Vector3.Project = function (vector, world, transform, viewport) {
  3498. var cw = viewport.width;
  3499. var ch = viewport.height;
  3500. var cx = viewport.x;
  3501. var cy = viewport.y;
  3502. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3503. 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);
  3504. var matrix = MathTmp.Matrix[0];
  3505. world.multiplyToRef(transform, matrix);
  3506. matrix.multiplyToRef(viewportMatrix, matrix);
  3507. return Vector3.TransformCoordinates(vector, matrix);
  3508. };
  3509. /**
  3510. * Unproject from screen space to object space
  3511. * @param source defines the screen space Vector3 to use
  3512. * @param viewportWidth defines the current width of the viewport
  3513. * @param viewportHeight defines the current height of the viewport
  3514. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3515. * @param transform defines the transform (view x projection) matrix to use
  3516. * @returns the new Vector3
  3517. */
  3518. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3519. var matrix = MathTmp.Matrix[0];
  3520. world.multiplyToRef(transform, matrix);
  3521. matrix.invert();
  3522. source.x = source.x / viewportWidth * 2 - 1;
  3523. source.y = -(source.y / viewportHeight * 2 - 1);
  3524. var vector = Vector3.TransformCoordinates(source, matrix);
  3525. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3526. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3527. vector = vector.scale(1.0 / num);
  3528. }
  3529. return vector;
  3530. };
  3531. /**
  3532. * Unproject from screen space to object space
  3533. * @param source defines the screen space Vector3 to use
  3534. * @param viewportWidth defines the current width of the viewport
  3535. * @param viewportHeight defines the current height of the viewport
  3536. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3537. * @param view defines the view matrix to use
  3538. * @param projection defines the projection matrix to use
  3539. * @returns the new Vector3
  3540. */
  3541. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3542. var result = Vector3.Zero();
  3543. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3544. return result;
  3545. };
  3546. /**
  3547. * Unproject from screen space to object space
  3548. * @param source defines the screen space Vector3 to use
  3549. * @param viewportWidth defines the current width of the viewport
  3550. * @param viewportHeight defines the current height of the viewport
  3551. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3552. * @param view defines the view matrix to use
  3553. * @param projection defines the projection matrix to use
  3554. * @param result defines the Vector3 where to store the result
  3555. */
  3556. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3557. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3558. };
  3559. /**
  3560. * Unproject from screen space to object space
  3561. * @param sourceX defines the screen space x coordinate to use
  3562. * @param sourceY defines the screen space y coordinate to use
  3563. * @param sourceZ defines the screen space z coordinate to use
  3564. * @param viewportWidth defines the current width of the viewport
  3565. * @param viewportHeight defines the current height of the viewport
  3566. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3567. * @param view defines the view matrix to use
  3568. * @param projection defines the projection matrix to use
  3569. * @param result defines the Vector3 where to store the result
  3570. */
  3571. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3572. var matrix = MathTmp.Matrix[0];
  3573. world.multiplyToRef(view, matrix);
  3574. matrix.multiplyToRef(projection, matrix);
  3575. matrix.invert();
  3576. var screenSource = MathTmp.Vector3[0];
  3577. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3578. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3579. screenSource.z = 2 * sourceZ - 1.0;
  3580. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3581. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3582. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3583. result.scaleInPlace(1.0 / num);
  3584. }
  3585. };
  3586. /**
  3587. * Gets the minimal coordinate values between two Vector3
  3588. * @param left defines the first operand
  3589. * @param right defines the second operand
  3590. * @returns the new Vector3
  3591. */
  3592. Vector3.Minimize = function (left, right) {
  3593. var min = left.clone();
  3594. min.minimizeInPlace(right);
  3595. return min;
  3596. };
  3597. /**
  3598. * Gets the maximal coordinate values between two Vector3
  3599. * @param left defines the first operand
  3600. * @param right defines the second operand
  3601. * @returns the new Vector3
  3602. */
  3603. Vector3.Maximize = function (left, right) {
  3604. var max = left.clone();
  3605. max.maximizeInPlace(right);
  3606. return max;
  3607. };
  3608. /**
  3609. * Returns the distance between the vectors "value1" and "value2"
  3610. * @param value1 defines the first operand
  3611. * @param value2 defines the second operand
  3612. * @returns the distance
  3613. */
  3614. Vector3.Distance = function (value1, value2) {
  3615. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3616. };
  3617. /**
  3618. * Returns the squared distance between the vectors "value1" and "value2"
  3619. * @param value1 defines the first operand
  3620. * @param value2 defines the second operand
  3621. * @returns the squared distance
  3622. */
  3623. Vector3.DistanceSquared = function (value1, value2) {
  3624. var x = value1.x - value2.x;
  3625. var y = value1.y - value2.y;
  3626. var z = value1.z - value2.z;
  3627. return (x * x) + (y * y) + (z * z);
  3628. };
  3629. /**
  3630. * Returns a new Vector3 located at the center between "value1" and "value2"
  3631. * @param value1 defines the first operand
  3632. * @param value2 defines the second operand
  3633. * @returns the new Vector3
  3634. */
  3635. Vector3.Center = function (value1, value2) {
  3636. var center = value1.add(value2);
  3637. center.scaleInPlace(0.5);
  3638. return center;
  3639. };
  3640. /**
  3641. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3642. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3643. * to something in order to rotate it from its local system to the given target system
  3644. * Note: axis1, axis2 and axis3 are normalized during this operation
  3645. * @param axis1 defines the first axis
  3646. * @param axis2 defines the second axis
  3647. * @param axis3 defines the third axis
  3648. * @returns a new Vector3
  3649. */
  3650. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3651. var rotation = Vector3.Zero();
  3652. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3653. return rotation;
  3654. };
  3655. /**
  3656. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3657. * @param axis1 defines the first axis
  3658. * @param axis2 defines the second axis
  3659. * @param axis3 defines the third axis
  3660. * @param ref defines the Vector3 where to store the result
  3661. */
  3662. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3663. var quat = MathTmp.Quaternion[0];
  3664. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3665. quat.toEulerAnglesToRef(ref);
  3666. };
  3667. return Vector3;
  3668. }());
  3669. BABYLON.Vector3 = Vector3;
  3670. //Vector4 class created for EulerAngle class conversion to Quaternion
  3671. var Vector4 = /** @class */ (function () {
  3672. /**
  3673. * Creates a Vector4 object from the passed floats.
  3674. */
  3675. function Vector4(x, y, z, w) {
  3676. this.x = x;
  3677. this.y = y;
  3678. this.z = z;
  3679. this.w = w;
  3680. }
  3681. /**
  3682. * Returns the string with the Vector4 coordinates.
  3683. */
  3684. Vector4.prototype.toString = function () {
  3685. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3686. };
  3687. /**
  3688. * Returns the string "Vector4".
  3689. */
  3690. Vector4.prototype.getClassName = function () {
  3691. return "Vector4";
  3692. };
  3693. /**
  3694. * Returns the Vector4 hash code.
  3695. */
  3696. Vector4.prototype.getHashCode = function () {
  3697. var hash = this.x || 0;
  3698. hash = (hash * 397) ^ (this.y || 0);
  3699. hash = (hash * 397) ^ (this.z || 0);
  3700. hash = (hash * 397) ^ (this.w || 0);
  3701. return hash;
  3702. };
  3703. // Operators
  3704. /**
  3705. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3706. */
  3707. Vector4.prototype.asArray = function () {
  3708. var result = new Array();
  3709. this.toArray(result, 0);
  3710. return result;
  3711. };
  3712. /**
  3713. * Populates the passed array from the passed index with the Vector4 coordinates.
  3714. * Returns the Vector4.
  3715. */
  3716. Vector4.prototype.toArray = function (array, index) {
  3717. if (index === undefined) {
  3718. index = 0;
  3719. }
  3720. array[index] = this.x;
  3721. array[index + 1] = this.y;
  3722. array[index + 2] = this.z;
  3723. array[index + 3] = this.w;
  3724. return this;
  3725. };
  3726. /**
  3727. * Adds the passed vector to the current Vector4.
  3728. * Returns the updated Vector4.
  3729. */
  3730. Vector4.prototype.addInPlace = function (otherVector) {
  3731. this.x += otherVector.x;
  3732. this.y += otherVector.y;
  3733. this.z += otherVector.z;
  3734. this.w += otherVector.w;
  3735. return this;
  3736. };
  3737. /**
  3738. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3739. */
  3740. Vector4.prototype.add = function (otherVector) {
  3741. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3742. };
  3743. /**
  3744. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3745. * Returns the current Vector4.
  3746. */
  3747. Vector4.prototype.addToRef = function (otherVector, result) {
  3748. result.x = this.x + otherVector.x;
  3749. result.y = this.y + otherVector.y;
  3750. result.z = this.z + otherVector.z;
  3751. result.w = this.w + otherVector.w;
  3752. return this;
  3753. };
  3754. /**
  3755. * Subtract in place the passed vector from the current Vector4.
  3756. * Returns the updated Vector4.
  3757. */
  3758. Vector4.prototype.subtractInPlace = function (otherVector) {
  3759. this.x -= otherVector.x;
  3760. this.y -= otherVector.y;
  3761. this.z -= otherVector.z;
  3762. this.w -= otherVector.w;
  3763. return this;
  3764. };
  3765. /**
  3766. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3767. */
  3768. Vector4.prototype.subtract = function (otherVector) {
  3769. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3770. };
  3771. /**
  3772. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3773. * Returns the current Vector4.
  3774. */
  3775. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3776. result.x = this.x - otherVector.x;
  3777. result.y = this.y - otherVector.y;
  3778. result.z = this.z - otherVector.z;
  3779. result.w = this.w - otherVector.w;
  3780. return this;
  3781. };
  3782. /**
  3783. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3784. */
  3785. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3786. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3787. };
  3788. /**
  3789. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3790. * Returns the current Vector4.
  3791. */
  3792. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3793. result.x = this.x - x;
  3794. result.y = this.y - y;
  3795. result.z = this.z - z;
  3796. result.w = this.w - w;
  3797. return this;
  3798. };
  3799. /**
  3800. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3801. */
  3802. Vector4.prototype.negate = function () {
  3803. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3804. };
  3805. /**
  3806. * Multiplies the current Vector4 coordinates by scale (float).
  3807. * Returns the updated Vector4.
  3808. */
  3809. Vector4.prototype.scaleInPlace = function (scale) {
  3810. this.x *= scale;
  3811. this.y *= scale;
  3812. this.z *= scale;
  3813. this.w *= scale;
  3814. return this;
  3815. };
  3816. /**
  3817. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3818. */
  3819. Vector4.prototype.scale = function (scale) {
  3820. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3821. };
  3822. /**
  3823. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3824. * Returns the current Vector4.
  3825. */
  3826. Vector4.prototype.scaleToRef = function (scale, result) {
  3827. result.x = this.x * scale;
  3828. result.y = this.y * scale;
  3829. result.z = this.z * scale;
  3830. result.w = this.w * scale;
  3831. return this;
  3832. };
  3833. /**
  3834. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3835. * @param scale defines the scale factor
  3836. * @param result defines the Vector4 object where to store the result
  3837. * @returns the unmodified current Vector4
  3838. */
  3839. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3840. result.x += this.x * scale;
  3841. result.y += this.y * scale;
  3842. result.z += this.z * scale;
  3843. result.w += this.w * scale;
  3844. return this;
  3845. };
  3846. /**
  3847. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3848. */
  3849. Vector4.prototype.equals = function (otherVector) {
  3850. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3851. };
  3852. /**
  3853. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3854. */
  3855. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3856. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3857. return otherVector
  3858. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3859. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3860. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3861. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3862. };
  3863. /**
  3864. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3865. */
  3866. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3867. return this.x === x && this.y === y && this.z === z && this.w === w;
  3868. };
  3869. /**
  3870. * Multiplies in place the current Vector4 by the passed one.
  3871. * Returns the updated Vector4.
  3872. */
  3873. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3874. this.x *= otherVector.x;
  3875. this.y *= otherVector.y;
  3876. this.z *= otherVector.z;
  3877. this.w *= otherVector.w;
  3878. return this;
  3879. };
  3880. /**
  3881. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3882. */
  3883. Vector4.prototype.multiply = function (otherVector) {
  3884. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3885. };
  3886. /**
  3887. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3888. * Returns the current Vector4.
  3889. */
  3890. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3891. result.x = this.x * otherVector.x;
  3892. result.y = this.y * otherVector.y;
  3893. result.z = this.z * otherVector.z;
  3894. result.w = this.w * otherVector.w;
  3895. return this;
  3896. };
  3897. /**
  3898. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3899. */
  3900. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3901. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3902. };
  3903. /**
  3904. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3905. */
  3906. Vector4.prototype.divide = function (otherVector) {
  3907. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3908. };
  3909. /**
  3910. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3911. * Returns the current Vector4.
  3912. */
  3913. Vector4.prototype.divideToRef = function (otherVector, result) {
  3914. result.x = this.x / otherVector.x;
  3915. result.y = this.y / otherVector.y;
  3916. result.z = this.z / otherVector.z;
  3917. result.w = this.w / otherVector.w;
  3918. return this;
  3919. };
  3920. /**
  3921. * Divides the current Vector3 coordinates by the passed ones.
  3922. * @returns the updated Vector3.
  3923. */
  3924. Vector4.prototype.divideInPlace = function (otherVector) {
  3925. return this.divideToRef(otherVector, this);
  3926. };
  3927. /**
  3928. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3929. * @param other defines the second operand
  3930. * @returns the current updated Vector4
  3931. */
  3932. Vector4.prototype.minimizeInPlace = function (other) {
  3933. if (other.x < this.x)
  3934. this.x = other.x;
  3935. if (other.y < this.y)
  3936. this.y = other.y;
  3937. if (other.z < this.z)
  3938. this.z = other.z;
  3939. if (other.w < this.w)
  3940. this.w = other.w;
  3941. return this;
  3942. };
  3943. /**
  3944. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3945. * @param other defines the second operand
  3946. * @returns the current updated Vector4
  3947. */
  3948. Vector4.prototype.maximizeInPlace = function (other) {
  3949. if (other.x > this.x)
  3950. this.x = other.x;
  3951. if (other.y > this.y)
  3952. this.y = other.y;
  3953. if (other.z > this.z)
  3954. this.z = other.z;
  3955. if (other.w > this.w)
  3956. this.w = other.w;
  3957. return this;
  3958. };
  3959. // Properties
  3960. /**
  3961. * Returns the Vector4 length (float).
  3962. */
  3963. Vector4.prototype.length = function () {
  3964. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3965. };
  3966. /**
  3967. * Returns the Vector4 squared length (float).
  3968. */
  3969. Vector4.prototype.lengthSquared = function () {
  3970. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3971. };
  3972. // Methods
  3973. /**
  3974. * Normalizes in place the Vector4.
  3975. * Returns the updated Vector4.
  3976. */
  3977. Vector4.prototype.normalize = function () {
  3978. var len = this.length();
  3979. if (len === 0)
  3980. return this;
  3981. var num = 1.0 / len;
  3982. this.x *= num;
  3983. this.y *= num;
  3984. this.z *= num;
  3985. this.w *= num;
  3986. return this;
  3987. };
  3988. /**
  3989. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3990. */
  3991. Vector4.prototype.toVector3 = function () {
  3992. return new Vector3(this.x, this.y, this.z);
  3993. };
  3994. /**
  3995. * Returns a new Vector4 copied from the current one.
  3996. */
  3997. Vector4.prototype.clone = function () {
  3998. return new Vector4(this.x, this.y, this.z, this.w);
  3999. };
  4000. /**
  4001. * Updates the current Vector4 with the passed one coordinates.
  4002. * Returns the updated Vector4.
  4003. */
  4004. Vector4.prototype.copyFrom = function (source) {
  4005. this.x = source.x;
  4006. this.y = source.y;
  4007. this.z = source.z;
  4008. this.w = source.w;
  4009. return this;
  4010. };
  4011. /**
  4012. * Updates the current Vector4 coordinates with the passed floats.
  4013. * Returns the updated Vector4.
  4014. */
  4015. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4016. this.x = x;
  4017. this.y = y;
  4018. this.z = z;
  4019. this.w = w;
  4020. return this;
  4021. };
  4022. /**
  4023. * Updates the current Vector4 coordinates with the passed floats.
  4024. * Returns the updated Vector4.
  4025. */
  4026. Vector4.prototype.set = function (x, y, z, w) {
  4027. return this.copyFromFloats(x, y, z, w);
  4028. };
  4029. // Statics
  4030. /**
  4031. * Returns a new Vector4 set from the starting index of the passed array.
  4032. */
  4033. Vector4.FromArray = function (array, offset) {
  4034. if (!offset) {
  4035. offset = 0;
  4036. }
  4037. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4038. };
  4039. /**
  4040. * Updates the passed vector "result" from the starting index of the passed array.
  4041. */
  4042. Vector4.FromArrayToRef = function (array, offset, result) {
  4043. result.x = array[offset];
  4044. result.y = array[offset + 1];
  4045. result.z = array[offset + 2];
  4046. result.w = array[offset + 3];
  4047. };
  4048. /**
  4049. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4050. */
  4051. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4052. Vector4.FromArrayToRef(array, offset, result);
  4053. };
  4054. /**
  4055. * Updates the passed vector "result" coordinates from the passed floats.
  4056. */
  4057. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4058. result.x = x;
  4059. result.y = y;
  4060. result.z = z;
  4061. result.w = w;
  4062. };
  4063. /**
  4064. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4065. */
  4066. Vector4.Zero = function () {
  4067. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4068. };
  4069. /**
  4070. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4071. */
  4072. Vector4.One = function () {
  4073. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4074. };
  4075. /**
  4076. * Returns a new normalized Vector4 from the passed one.
  4077. */
  4078. Vector4.Normalize = function (vector) {
  4079. var result = Vector4.Zero();
  4080. Vector4.NormalizeToRef(vector, result);
  4081. return result;
  4082. };
  4083. /**
  4084. * Updates the passed vector "result" from the normalization of the passed one.
  4085. */
  4086. Vector4.NormalizeToRef = function (vector, result) {
  4087. result.copyFrom(vector);
  4088. result.normalize();
  4089. };
  4090. Vector4.Minimize = function (left, right) {
  4091. var min = left.clone();
  4092. min.minimizeInPlace(right);
  4093. return min;
  4094. };
  4095. Vector4.Maximize = function (left, right) {
  4096. var max = left.clone();
  4097. max.maximizeInPlace(right);
  4098. return max;
  4099. };
  4100. /**
  4101. * Returns the distance (float) between the vectors "value1" and "value2".
  4102. */
  4103. Vector4.Distance = function (value1, value2) {
  4104. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4105. };
  4106. /**
  4107. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4108. */
  4109. Vector4.DistanceSquared = function (value1, value2) {
  4110. var x = value1.x - value2.x;
  4111. var y = value1.y - value2.y;
  4112. var z = value1.z - value2.z;
  4113. var w = value1.w - value2.w;
  4114. return (x * x) + (y * y) + (z * z) + (w * w);
  4115. };
  4116. /**
  4117. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4118. */
  4119. Vector4.Center = function (value1, value2) {
  4120. var center = value1.add(value2);
  4121. center.scaleInPlace(0.5);
  4122. return center;
  4123. };
  4124. /**
  4125. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4126. * This methods computes transformed normalized direction vectors only.
  4127. */
  4128. Vector4.TransformNormal = function (vector, transformation) {
  4129. var result = Vector4.Zero();
  4130. Vector4.TransformNormalToRef(vector, transformation, result);
  4131. return result;
  4132. };
  4133. /**
  4134. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4135. * This methods computes transformed normalized direction vectors only.
  4136. */
  4137. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4138. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4139. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4140. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4141. result.x = x;
  4142. result.y = y;
  4143. result.z = z;
  4144. result.w = vector.w;
  4145. };
  4146. /**
  4147. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4148. * This methods computes transformed normalized direction vectors only.
  4149. */
  4150. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4151. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4152. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4153. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4154. result.w = w;
  4155. };
  4156. return Vector4;
  4157. }());
  4158. BABYLON.Vector4 = Vector4;
  4159. var Size = /** @class */ (function () {
  4160. /**
  4161. * Creates a Size object from the passed width and height (floats).
  4162. */
  4163. function Size(width, height) {
  4164. this.width = width;
  4165. this.height = height;
  4166. }
  4167. // Returns a string with the Size width and height.
  4168. Size.prototype.toString = function () {
  4169. return "{W: " + this.width + ", H: " + this.height + "}";
  4170. };
  4171. /**
  4172. * Returns the string "Size"
  4173. */
  4174. Size.prototype.getClassName = function () {
  4175. return "Size";
  4176. };
  4177. /**
  4178. * Returns the Size hash code.
  4179. */
  4180. Size.prototype.getHashCode = function () {
  4181. var hash = this.width || 0;
  4182. hash = (hash * 397) ^ (this.height || 0);
  4183. return hash;
  4184. };
  4185. /**
  4186. * Updates the current size from the passed one.
  4187. * Returns the updated Size.
  4188. */
  4189. Size.prototype.copyFrom = function (src) {
  4190. this.width = src.width;
  4191. this.height = src.height;
  4192. };
  4193. /**
  4194. * Updates in place the current Size from the passed floats.
  4195. * Returns the updated Size.
  4196. */
  4197. Size.prototype.copyFromFloats = function (width, height) {
  4198. this.width = width;
  4199. this.height = height;
  4200. return this;
  4201. };
  4202. /**
  4203. * Updates in place the current Size from the passed floats.
  4204. * Returns the updated Size.
  4205. */
  4206. Size.prototype.set = function (width, height) {
  4207. return this.copyFromFloats(width, height);
  4208. };
  4209. /**
  4210. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4211. */
  4212. Size.prototype.multiplyByFloats = function (w, h) {
  4213. return new Size(this.width * w, this.height * h);
  4214. };
  4215. /**
  4216. * Returns a new Size copied from the passed one.
  4217. */
  4218. Size.prototype.clone = function () {
  4219. return new Size(this.width, this.height);
  4220. };
  4221. /**
  4222. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4223. */
  4224. Size.prototype.equals = function (other) {
  4225. if (!other) {
  4226. return false;
  4227. }
  4228. return (this.width === other.width) && (this.height === other.height);
  4229. };
  4230. Object.defineProperty(Size.prototype, "surface", {
  4231. /**
  4232. * Returns the surface of the Size : width * height (float).
  4233. */
  4234. get: function () {
  4235. return this.width * this.height;
  4236. },
  4237. enumerable: true,
  4238. configurable: true
  4239. });
  4240. /**
  4241. * Returns a new Size set to (0.0, 0.0)
  4242. */
  4243. Size.Zero = function () {
  4244. return new Size(0.0, 0.0);
  4245. };
  4246. /**
  4247. * Returns a new Size set as the addition result of the current Size and the passed one.
  4248. */
  4249. Size.prototype.add = function (otherSize) {
  4250. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4251. return r;
  4252. };
  4253. /**
  4254. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4255. */
  4256. Size.prototype.subtract = function (otherSize) {
  4257. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4258. return r;
  4259. };
  4260. /**
  4261. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4262. */
  4263. Size.Lerp = function (start, end, amount) {
  4264. var w = start.width + ((end.width - start.width) * amount);
  4265. var h = start.height + ((end.height - start.height) * amount);
  4266. return new Size(w, h);
  4267. };
  4268. return Size;
  4269. }());
  4270. BABYLON.Size = Size;
  4271. var Quaternion = /** @class */ (function () {
  4272. /**
  4273. * Creates a new Quaternion from the passed floats.
  4274. */
  4275. function Quaternion(x, y, z, w) {
  4276. if (x === void 0) { x = 0.0; }
  4277. if (y === void 0) { y = 0.0; }
  4278. if (z === void 0) { z = 0.0; }
  4279. if (w === void 0) { w = 1.0; }
  4280. this.x = x;
  4281. this.y = y;
  4282. this.z = z;
  4283. this.w = w;
  4284. }
  4285. /**
  4286. * Returns a string with the Quaternion coordinates.
  4287. */
  4288. Quaternion.prototype.toString = function () {
  4289. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4290. };
  4291. /**
  4292. * Returns the string "Quaternion".
  4293. */
  4294. Quaternion.prototype.getClassName = function () {
  4295. return "Quaternion";
  4296. };
  4297. /**
  4298. * Returns the Quaternion hash code.
  4299. */
  4300. Quaternion.prototype.getHashCode = function () {
  4301. var hash = this.x || 0;
  4302. hash = (hash * 397) ^ (this.y || 0);
  4303. hash = (hash * 397) ^ (this.z || 0);
  4304. hash = (hash * 397) ^ (this.w || 0);
  4305. return hash;
  4306. };
  4307. /**
  4308. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4309. */
  4310. Quaternion.prototype.asArray = function () {
  4311. return [this.x, this.y, this.z, this.w];
  4312. };
  4313. /**
  4314. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4315. */
  4316. Quaternion.prototype.equals = function (otherQuaternion) {
  4317. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4318. };
  4319. /**
  4320. * Returns a new Quaternion copied from the current one.
  4321. */
  4322. Quaternion.prototype.clone = function () {
  4323. return new Quaternion(this.x, this.y, this.z, this.w);
  4324. };
  4325. /**
  4326. * Updates the current Quaternion from the passed one coordinates.
  4327. * Returns the updated Quaterion.
  4328. */
  4329. Quaternion.prototype.copyFrom = function (other) {
  4330. this.x = other.x;
  4331. this.y = other.y;
  4332. this.z = other.z;
  4333. this.w = other.w;
  4334. return this;
  4335. };
  4336. /**
  4337. * Updates the current Quaternion from the passed float coordinates.
  4338. * Returns the updated Quaterion.
  4339. */
  4340. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4341. this.x = x;
  4342. this.y = y;
  4343. this.z = z;
  4344. this.w = w;
  4345. return this;
  4346. };
  4347. /**
  4348. * Updates the current Quaternion from the passed float coordinates.
  4349. * Returns the updated Quaterion.
  4350. */
  4351. Quaternion.prototype.set = function (x, y, z, w) {
  4352. return this.copyFromFloats(x, y, z, w);
  4353. };
  4354. /**
  4355. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4356. */
  4357. Quaternion.prototype.add = function (other) {
  4358. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4359. };
  4360. /**
  4361. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4362. */
  4363. Quaternion.prototype.subtract = function (other) {
  4364. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4365. };
  4366. /**
  4367. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4368. */
  4369. Quaternion.prototype.scale = function (value) {
  4370. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4371. };
  4372. /**
  4373. * Scale the current Quaternion values by a factor to a given Quaternion
  4374. * @param scale defines the scale factor
  4375. * @param result defines the Quaternion object where to store the result
  4376. * @returns the unmodified current Quaternion
  4377. */
  4378. Quaternion.prototype.scaleToRef = function (scale, result) {
  4379. result.x = this.x * scale;
  4380. result.y = this.y * scale;
  4381. result.z = this.z * scale;
  4382. result.w = this.w * scale;
  4383. return this;
  4384. };
  4385. /**
  4386. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4387. * @param scale defines the scale factor
  4388. * @param result defines the Quaternion object where to store the result
  4389. * @returns the unmodified current Quaternion
  4390. */
  4391. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4392. result.x += this.x * scale;
  4393. result.y += this.y * scale;
  4394. result.z += this.z * scale;
  4395. result.w += this.w * scale;
  4396. return this;
  4397. };
  4398. /**
  4399. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4400. */
  4401. Quaternion.prototype.multiply = function (q1) {
  4402. var result = new Quaternion(0, 0, 0, 1.0);
  4403. this.multiplyToRef(q1, result);
  4404. return result;
  4405. };
  4406. /**
  4407. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4408. * Returns the current Quaternion.
  4409. */
  4410. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4411. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4412. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4413. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4414. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4415. result.copyFromFloats(x, y, z, w);
  4416. return this;
  4417. };
  4418. /**
  4419. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4420. * Returns the updated Quaternion.
  4421. */
  4422. Quaternion.prototype.multiplyInPlace = function (q1) {
  4423. this.multiplyToRef(q1, this);
  4424. return this;
  4425. };
  4426. /**
  4427. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4428. * Returns the current Quaternion.
  4429. */
  4430. Quaternion.prototype.conjugateToRef = function (ref) {
  4431. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4432. return this;
  4433. };
  4434. /**
  4435. * Conjugates in place the current Quaternion.
  4436. * Returns the updated Quaternion.
  4437. */
  4438. Quaternion.prototype.conjugateInPlace = function () {
  4439. this.x *= -1;
  4440. this.y *= -1;
  4441. this.z *= -1;
  4442. return this;
  4443. };
  4444. /**
  4445. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4446. */
  4447. Quaternion.prototype.conjugate = function () {
  4448. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4449. return result;
  4450. };
  4451. /**
  4452. * Returns the Quaternion length (float).
  4453. */
  4454. Quaternion.prototype.length = function () {
  4455. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4456. };
  4457. /**
  4458. * Normalize in place the current Quaternion.
  4459. * Returns the updated Quaternion.
  4460. */
  4461. Quaternion.prototype.normalize = function () {
  4462. var length = 1.0 / this.length();
  4463. this.x *= length;
  4464. this.y *= length;
  4465. this.z *= length;
  4466. this.w *= length;
  4467. return this;
  4468. };
  4469. /**
  4470. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4471. * @param order is a reserved parameter and is ignore for now
  4472. * @returns the new Vector3
  4473. */
  4474. Quaternion.prototype.toEulerAngles = function (order) {
  4475. if (order === void 0) { order = "YZX"; }
  4476. var result = Vector3.Zero();
  4477. this.toEulerAnglesToRef(result, order);
  4478. return result;
  4479. };
  4480. /**
  4481. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4482. * @param result defines the vector which will be filled with the Euler angles
  4483. * @param order is a reserved parameter and is ignore for now
  4484. * @returns the current Quaternion
  4485. */
  4486. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4487. if (order === void 0) { order = "YZX"; }
  4488. var qz = this.z;
  4489. var qx = this.x;
  4490. var qy = this.y;
  4491. var qw = this.w;
  4492. var sqw = qw * qw;
  4493. var sqz = qz * qz;
  4494. var sqx = qx * qx;
  4495. var sqy = qy * qy;
  4496. var zAxisY = qy * qz - qx * qw;
  4497. var limit = .4999999;
  4498. if (zAxisY < -limit) {
  4499. result.y = 2 * Math.atan2(qy, qw);
  4500. result.x = Math.PI / 2;
  4501. result.z = 0;
  4502. }
  4503. else if (zAxisY > limit) {
  4504. result.y = 2 * Math.atan2(qy, qw);
  4505. result.x = -Math.PI / 2;
  4506. result.z = 0;
  4507. }
  4508. else {
  4509. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4510. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4511. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4512. }
  4513. return this;
  4514. };
  4515. /**
  4516. * Updates the passed rotation matrix with the current Quaternion values.
  4517. * Returns the current Quaternion.
  4518. */
  4519. Quaternion.prototype.toRotationMatrix = function (result) {
  4520. var xx = this.x * this.x;
  4521. var yy = this.y * this.y;
  4522. var zz = this.z * this.z;
  4523. var xy = this.x * this.y;
  4524. var zw = this.z * this.w;
  4525. var zx = this.z * this.x;
  4526. var yw = this.y * this.w;
  4527. var yz = this.y * this.z;
  4528. var xw = this.x * this.w;
  4529. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4530. result.m[1] = 2.0 * (xy + zw);
  4531. result.m[2] = 2.0 * (zx - yw);
  4532. result.m[3] = 0;
  4533. result.m[4] = 2.0 * (xy - zw);
  4534. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4535. result.m[6] = 2.0 * (yz + xw);
  4536. result.m[7] = 0;
  4537. result.m[8] = 2.0 * (zx + yw);
  4538. result.m[9] = 2.0 * (yz - xw);
  4539. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4540. result.m[11] = 0;
  4541. result.m[12] = 0;
  4542. result.m[13] = 0;
  4543. result.m[14] = 0;
  4544. result.m[15] = 1.0;
  4545. result._markAsUpdated();
  4546. return this;
  4547. };
  4548. /**
  4549. * Updates the current Quaternion from the passed rotation matrix values.
  4550. * Returns the updated Quaternion.
  4551. */
  4552. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4553. Quaternion.FromRotationMatrixToRef(matrix, this);
  4554. return this;
  4555. };
  4556. // Statics
  4557. /**
  4558. * Returns a new Quaternion set from the passed rotation matrix values.
  4559. */
  4560. Quaternion.FromRotationMatrix = function (matrix) {
  4561. var result = new Quaternion();
  4562. Quaternion.FromRotationMatrixToRef(matrix, result);
  4563. return result;
  4564. };
  4565. /**
  4566. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4567. */
  4568. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4569. var data = matrix.m;
  4570. var m11 = data[0], m12 = data[4], m13 = data[8];
  4571. var m21 = data[1], m22 = data[5], m23 = data[9];
  4572. var m31 = data[2], m32 = data[6], m33 = data[10];
  4573. var trace = m11 + m22 + m33;
  4574. var s;
  4575. if (trace > 0) {
  4576. s = 0.5 / Math.sqrt(trace + 1.0);
  4577. result.w = 0.25 / s;
  4578. result.x = (m32 - m23) * s;
  4579. result.y = (m13 - m31) * s;
  4580. result.z = (m21 - m12) * s;
  4581. }
  4582. else if (m11 > m22 && m11 > m33) {
  4583. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4584. result.w = (m32 - m23) / s;
  4585. result.x = 0.25 * s;
  4586. result.y = (m12 + m21) / s;
  4587. result.z = (m13 + m31) / s;
  4588. }
  4589. else if (m22 > m33) {
  4590. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4591. result.w = (m13 - m31) / s;
  4592. result.x = (m12 + m21) / s;
  4593. result.y = 0.25 * s;
  4594. result.z = (m23 + m32) / s;
  4595. }
  4596. else {
  4597. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4598. result.w = (m21 - m12) / s;
  4599. result.x = (m13 + m31) / s;
  4600. result.y = (m23 + m32) / s;
  4601. result.z = 0.25 * s;
  4602. }
  4603. };
  4604. /**
  4605. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4606. */
  4607. Quaternion.Zero = function () {
  4608. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4609. };
  4610. /**
  4611. * Returns a new Quaternion as the inverted current Quaternion.
  4612. */
  4613. Quaternion.Inverse = function (q) {
  4614. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4615. };
  4616. /**
  4617. * Returns the identity Quaternion.
  4618. */
  4619. Quaternion.Identity = function () {
  4620. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4621. };
  4622. Quaternion.IsIdentity = function (quaternion) {
  4623. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4624. };
  4625. /**
  4626. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4627. */
  4628. Quaternion.RotationAxis = function (axis, angle) {
  4629. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4630. };
  4631. /**
  4632. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4633. */
  4634. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4635. var sin = Math.sin(angle / 2);
  4636. axis.normalize();
  4637. result.w = Math.cos(angle / 2);
  4638. result.x = axis.x * sin;
  4639. result.y = axis.y * sin;
  4640. result.z = axis.z * sin;
  4641. return result;
  4642. };
  4643. /**
  4644. * Retuns a new Quaternion set from the starting index of the passed array.
  4645. */
  4646. Quaternion.FromArray = function (array, offset) {
  4647. if (!offset) {
  4648. offset = 0;
  4649. }
  4650. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4651. };
  4652. /**
  4653. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4654. */
  4655. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4656. var q = new Quaternion();
  4657. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4658. return q;
  4659. };
  4660. /**
  4661. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4662. */
  4663. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4664. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4665. var halfRoll = roll * 0.5;
  4666. var halfPitch = pitch * 0.5;
  4667. var halfYaw = yaw * 0.5;
  4668. var sinRoll = Math.sin(halfRoll);
  4669. var cosRoll = Math.cos(halfRoll);
  4670. var sinPitch = Math.sin(halfPitch);
  4671. var cosPitch = Math.cos(halfPitch);
  4672. var sinYaw = Math.sin(halfYaw);
  4673. var cosYaw = Math.cos(halfYaw);
  4674. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4675. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4676. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4677. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4678. };
  4679. /**
  4680. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4681. */
  4682. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4683. var result = new Quaternion();
  4684. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4685. return result;
  4686. };
  4687. /**
  4688. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4689. */
  4690. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4691. // Produces a quaternion from Euler angles in the z-x-z orientation
  4692. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4693. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4694. var halfBeta = beta * 0.5;
  4695. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4696. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4697. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4698. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4699. };
  4700. /**
  4701. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4702. * cf to Vector3.RotationFromAxis() documentation.
  4703. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4704. */
  4705. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4706. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4707. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4708. return quat;
  4709. };
  4710. /**
  4711. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4712. * cf to Vector3.RotationFromAxis() documentation.
  4713. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4714. */
  4715. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4716. var rotMat = MathTmp.Matrix[0];
  4717. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4718. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4719. };
  4720. Quaternion.Slerp = function (left, right, amount) {
  4721. var result = Quaternion.Identity();
  4722. Quaternion.SlerpToRef(left, right, amount, result);
  4723. return result;
  4724. };
  4725. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4726. var num2;
  4727. var num3;
  4728. var num = amount;
  4729. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4730. var flag = false;
  4731. if (num4 < 0) {
  4732. flag = true;
  4733. num4 = -num4;
  4734. }
  4735. if (num4 > 0.999999) {
  4736. num3 = 1 - num;
  4737. num2 = flag ? -num : num;
  4738. }
  4739. else {
  4740. var num5 = Math.acos(num4);
  4741. var num6 = (1.0 / Math.sin(num5));
  4742. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4743. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4744. }
  4745. result.x = (num3 * left.x) + (num2 * right.x);
  4746. result.y = (num3 * left.y) + (num2 * right.y);
  4747. result.z = (num3 * left.z) + (num2 * right.z);
  4748. result.w = (num3 * left.w) + (num2 * right.w);
  4749. };
  4750. /**
  4751. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4752. */
  4753. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4754. var squared = amount * amount;
  4755. var cubed = amount * squared;
  4756. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4757. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4758. var part3 = (cubed - (2.0 * squared)) + amount;
  4759. var part4 = cubed - squared;
  4760. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4761. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4762. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4763. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4764. return new Quaternion(x, y, z, w);
  4765. };
  4766. return Quaternion;
  4767. }());
  4768. BABYLON.Quaternion = Quaternion;
  4769. var Matrix = /** @class */ (function () {
  4770. function Matrix() {
  4771. this._isIdentity = false;
  4772. this._isIdentityDirty = true;
  4773. this.m = new Float32Array(16);
  4774. this._markAsUpdated();
  4775. }
  4776. Matrix.prototype._markAsUpdated = function () {
  4777. this.updateFlag = Matrix._updateFlagSeed++;
  4778. this._isIdentityDirty = true;
  4779. };
  4780. // Properties
  4781. /**
  4782. * Boolean : True is the matrix is the identity matrix
  4783. */
  4784. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4785. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4786. if (this._isIdentityDirty) {
  4787. this._isIdentityDirty = false;
  4788. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4789. this._isIdentity = false;
  4790. }
  4791. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4792. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4793. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4794. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4795. this._isIdentity = false;
  4796. }
  4797. else {
  4798. this._isIdentity = true;
  4799. }
  4800. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4801. this._isIdentity = false;
  4802. }
  4803. }
  4804. return this._isIdentity;
  4805. };
  4806. /**
  4807. * Returns the matrix determinant (float).
  4808. */
  4809. Matrix.prototype.determinant = function () {
  4810. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4811. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4812. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4813. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4814. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4815. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4816. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4817. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4818. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4819. };
  4820. // Methods
  4821. /**
  4822. * Returns the matrix underlying array.
  4823. */
  4824. Matrix.prototype.toArray = function () {
  4825. return this.m;
  4826. };
  4827. /**
  4828. * Returns the matrix underlying array.
  4829. */
  4830. Matrix.prototype.asArray = function () {
  4831. return this.toArray();
  4832. };
  4833. /**
  4834. * Inverts in place the Matrix.
  4835. * Returns the Matrix inverted.
  4836. */
  4837. Matrix.prototype.invert = function () {
  4838. this.invertToRef(this);
  4839. return this;
  4840. };
  4841. /**
  4842. * Sets all the matrix elements to zero.
  4843. * Returns the Matrix.
  4844. */
  4845. Matrix.prototype.reset = function () {
  4846. for (var index = 0; index < 16; index++) {
  4847. this.m[index] = 0.0;
  4848. }
  4849. this._markAsUpdated();
  4850. return this;
  4851. };
  4852. /**
  4853. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4854. */
  4855. Matrix.prototype.add = function (other) {
  4856. var result = new Matrix();
  4857. this.addToRef(other, result);
  4858. return result;
  4859. };
  4860. /**
  4861. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4862. * Returns the Matrix.
  4863. */
  4864. Matrix.prototype.addToRef = function (other, result) {
  4865. for (var index = 0; index < 16; index++) {
  4866. result.m[index] = this.m[index] + other.m[index];
  4867. }
  4868. result._markAsUpdated();
  4869. return this;
  4870. };
  4871. /**
  4872. * Adds in place the passed matrix to the current Matrix.
  4873. * Returns the updated Matrix.
  4874. */
  4875. Matrix.prototype.addToSelf = function (other) {
  4876. for (var index = 0; index < 16; index++) {
  4877. this.m[index] += other.m[index];
  4878. }
  4879. this._markAsUpdated();
  4880. return this;
  4881. };
  4882. /**
  4883. * Sets the passed matrix with the current inverted Matrix.
  4884. * Returns the unmodified current Matrix.
  4885. */
  4886. Matrix.prototype.invertToRef = function (other) {
  4887. var l1 = this.m[0];
  4888. var l2 = this.m[1];
  4889. var l3 = this.m[2];
  4890. var l4 = this.m[3];
  4891. var l5 = this.m[4];
  4892. var l6 = this.m[5];
  4893. var l7 = this.m[6];
  4894. var l8 = this.m[7];
  4895. var l9 = this.m[8];
  4896. var l10 = this.m[9];
  4897. var l11 = this.m[10];
  4898. var l12 = this.m[11];
  4899. var l13 = this.m[12];
  4900. var l14 = this.m[13];
  4901. var l15 = this.m[14];
  4902. var l16 = this.m[15];
  4903. var l17 = (l11 * l16) - (l12 * l15);
  4904. var l18 = (l10 * l16) - (l12 * l14);
  4905. var l19 = (l10 * l15) - (l11 * l14);
  4906. var l20 = (l9 * l16) - (l12 * l13);
  4907. var l21 = (l9 * l15) - (l11 * l13);
  4908. var l22 = (l9 * l14) - (l10 * l13);
  4909. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4910. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4911. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4912. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4913. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4914. var l28 = (l7 * l16) - (l8 * l15);
  4915. var l29 = (l6 * l16) - (l8 * l14);
  4916. var l30 = (l6 * l15) - (l7 * l14);
  4917. var l31 = (l5 * l16) - (l8 * l13);
  4918. var l32 = (l5 * l15) - (l7 * l13);
  4919. var l33 = (l5 * l14) - (l6 * l13);
  4920. var l34 = (l7 * l12) - (l8 * l11);
  4921. var l35 = (l6 * l12) - (l8 * l10);
  4922. var l36 = (l6 * l11) - (l7 * l10);
  4923. var l37 = (l5 * l12) - (l8 * l9);
  4924. var l38 = (l5 * l11) - (l7 * l9);
  4925. var l39 = (l5 * l10) - (l6 * l9);
  4926. other.m[0] = l23 * l27;
  4927. other.m[4] = l24 * l27;
  4928. other.m[8] = l25 * l27;
  4929. other.m[12] = l26 * l27;
  4930. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4931. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4932. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4933. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4934. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4935. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4936. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4937. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4938. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4939. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4940. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4941. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4942. other._markAsUpdated();
  4943. return this;
  4944. };
  4945. /**
  4946. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4947. * Returns the updated Matrix.
  4948. */
  4949. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4950. this.m[12] = x;
  4951. this.m[13] = y;
  4952. this.m[14] = z;
  4953. this._markAsUpdated();
  4954. return this;
  4955. };
  4956. /**
  4957. * Inserts the translation vector in the current Matrix.
  4958. * Returns the updated Matrix.
  4959. */
  4960. Matrix.prototype.setTranslation = function (vector3) {
  4961. this.m[12] = vector3.x;
  4962. this.m[13] = vector3.y;
  4963. this.m[14] = vector3.z;
  4964. this._markAsUpdated();
  4965. return this;
  4966. };
  4967. /**
  4968. * Returns a new Vector3 as the extracted translation from the Matrix.
  4969. */
  4970. Matrix.prototype.getTranslation = function () {
  4971. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4972. };
  4973. /**
  4974. * Fill a Vector3 with the extracted translation from the Matrix.
  4975. */
  4976. Matrix.prototype.getTranslationToRef = function (result) {
  4977. result.x = this.m[12];
  4978. result.y = this.m[13];
  4979. result.z = this.m[14];
  4980. return this;
  4981. };
  4982. /**
  4983. * Remove rotation and scaling part from the Matrix.
  4984. * Returns the updated Matrix.
  4985. */
  4986. Matrix.prototype.removeRotationAndScaling = function () {
  4987. this.setRowFromFloats(0, 1, 0, 0, 0);
  4988. this.setRowFromFloats(1, 0, 1, 0, 0);
  4989. this.setRowFromFloats(2, 0, 0, 1, 0);
  4990. return this;
  4991. };
  4992. /**
  4993. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4994. */
  4995. Matrix.prototype.multiply = function (other) {
  4996. var result = new Matrix();
  4997. this.multiplyToRef(other, result);
  4998. return result;
  4999. };
  5000. /**
  5001. * Updates the current Matrix from the passed one values.
  5002. * Returns the updated Matrix.
  5003. */
  5004. Matrix.prototype.copyFrom = function (other) {
  5005. for (var index = 0; index < 16; index++) {
  5006. this.m[index] = other.m[index];
  5007. }
  5008. this._markAsUpdated();
  5009. return this;
  5010. };
  5011. /**
  5012. * Populates the passed array from the starting index with the Matrix values.
  5013. * Returns the Matrix.
  5014. */
  5015. Matrix.prototype.copyToArray = function (array, offset) {
  5016. if (offset === void 0) { offset = 0; }
  5017. for (var index = 0; index < 16; index++) {
  5018. array[offset + index] = this.m[index];
  5019. }
  5020. return this;
  5021. };
  5022. /**
  5023. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5024. */
  5025. Matrix.prototype.multiplyToRef = function (other, result) {
  5026. this.multiplyToArray(other, result.m, 0);
  5027. result._markAsUpdated();
  5028. return this;
  5029. };
  5030. /**
  5031. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5032. */
  5033. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5034. var tm0 = this.m[0];
  5035. var tm1 = this.m[1];
  5036. var tm2 = this.m[2];
  5037. var tm3 = this.m[3];
  5038. var tm4 = this.m[4];
  5039. var tm5 = this.m[5];
  5040. var tm6 = this.m[6];
  5041. var tm7 = this.m[7];
  5042. var tm8 = this.m[8];
  5043. var tm9 = this.m[9];
  5044. var tm10 = this.m[10];
  5045. var tm11 = this.m[11];
  5046. var tm12 = this.m[12];
  5047. var tm13 = this.m[13];
  5048. var tm14 = this.m[14];
  5049. var tm15 = this.m[15];
  5050. var om0 = other.m[0];
  5051. var om1 = other.m[1];
  5052. var om2 = other.m[2];
  5053. var om3 = other.m[3];
  5054. var om4 = other.m[4];
  5055. var om5 = other.m[5];
  5056. var om6 = other.m[6];
  5057. var om7 = other.m[7];
  5058. var om8 = other.m[8];
  5059. var om9 = other.m[9];
  5060. var om10 = other.m[10];
  5061. var om11 = other.m[11];
  5062. var om12 = other.m[12];
  5063. var om13 = other.m[13];
  5064. var om14 = other.m[14];
  5065. var om15 = other.m[15];
  5066. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5067. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5068. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5069. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5070. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5071. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5072. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5073. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5074. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5075. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5076. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5077. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5078. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5079. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5080. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5081. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5082. return this;
  5083. };
  5084. /**
  5085. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5086. */
  5087. Matrix.prototype.equals = function (value) {
  5088. return value &&
  5089. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5090. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5091. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5092. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5093. };
  5094. /**
  5095. * Returns a new Matrix from the current Matrix.
  5096. */
  5097. Matrix.prototype.clone = function () {
  5098. 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]);
  5099. };
  5100. /**
  5101. * Returns the string "Matrix"
  5102. */
  5103. Matrix.prototype.getClassName = function () {
  5104. return "Matrix";
  5105. };
  5106. /**
  5107. * Returns the Matrix hash code.
  5108. */
  5109. Matrix.prototype.getHashCode = function () {
  5110. var hash = this.m[0] || 0;
  5111. for (var i = 1; i < 16; i++) {
  5112. hash = (hash * 397) ^ (this.m[i] || 0);
  5113. }
  5114. return hash;
  5115. };
  5116. /**
  5117. * Decomposes the current Matrix into :
  5118. * - a scale vector3 passed as a reference to update,
  5119. * - a rotation quaternion passed as a reference to update,
  5120. * - a translation vector3 passed as a reference to update.
  5121. * Returns the true if operation was successful.
  5122. */
  5123. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5124. translation.x = this.m[12];
  5125. translation.y = this.m[13];
  5126. translation.z = this.m[14];
  5127. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5128. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5129. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5130. if (this.determinant() <= 0) {
  5131. scale.y *= -1;
  5132. }
  5133. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5134. rotation.x = 0;
  5135. rotation.y = 0;
  5136. rotation.z = 0;
  5137. rotation.w = 1;
  5138. return false;
  5139. }
  5140. 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]);
  5141. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5142. return true;
  5143. };
  5144. /**
  5145. * Returns the index-th row of the current matrix as a new Vector4.
  5146. */
  5147. Matrix.prototype.getRow = function (index) {
  5148. if (index < 0 || index > 3) {
  5149. return null;
  5150. }
  5151. var i = index * 4;
  5152. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5153. };
  5154. /**
  5155. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5156. * Returns the updated Matrix.
  5157. */
  5158. Matrix.prototype.setRow = function (index, row) {
  5159. if (index < 0 || index > 3) {
  5160. return this;
  5161. }
  5162. var i = index * 4;
  5163. this.m[i + 0] = row.x;
  5164. this.m[i + 1] = row.y;
  5165. this.m[i + 2] = row.z;
  5166. this.m[i + 3] = row.w;
  5167. this._markAsUpdated();
  5168. return this;
  5169. };
  5170. /**
  5171. * Compute the transpose of the matrix.
  5172. * Returns a new Matrix.
  5173. */
  5174. Matrix.prototype.transpose = function () {
  5175. return Matrix.Transpose(this);
  5176. };
  5177. /**
  5178. * Compute the transpose of the matrix.
  5179. * Returns the current matrix.
  5180. */
  5181. Matrix.prototype.transposeToRef = function (result) {
  5182. Matrix.TransposeToRef(this, result);
  5183. return this;
  5184. };
  5185. /**
  5186. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5187. * Returns the updated Matrix.
  5188. */
  5189. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5190. if (index < 0 || index > 3) {
  5191. return this;
  5192. }
  5193. var i = index * 4;
  5194. this.m[i + 0] = x;
  5195. this.m[i + 1] = y;
  5196. this.m[i + 2] = z;
  5197. this.m[i + 3] = w;
  5198. this._markAsUpdated();
  5199. return this;
  5200. };
  5201. /**
  5202. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5203. * @param scale defines the scale factor
  5204. * @returns a new Matrix
  5205. */
  5206. Matrix.prototype.scale = function (scale) {
  5207. var result = new Matrix();
  5208. this.scaleToRef(scale, result);
  5209. return result;
  5210. };
  5211. /**
  5212. * Scale the current Matrix values by a factor to a given result Matrix
  5213. * @param scale defines the scale factor
  5214. * @param result defines the Matrix to store the result
  5215. * @returns the current Matrix
  5216. */
  5217. Matrix.prototype.scaleToRef = function (scale, result) {
  5218. for (var index = 0; index < 16; index++) {
  5219. result.m[index] = this.m[index] * scale;
  5220. }
  5221. result._markAsUpdated();
  5222. return this;
  5223. };
  5224. /**
  5225. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5226. * @param scale defines the scale factor
  5227. * @param result defines the Matrix to store the result
  5228. * @returns the current Matrix
  5229. */
  5230. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5231. for (var index = 0; index < 16; index++) {
  5232. result.m[index] += this.m[index] * scale;
  5233. }
  5234. result._markAsUpdated();
  5235. return this;
  5236. };
  5237. /**
  5238. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5239. * @param ref matrix to store the result
  5240. */
  5241. Matrix.prototype.toNormalMatrix = function (ref) {
  5242. this.invertToRef(ref);
  5243. ref.transpose();
  5244. var m = ref.m;
  5245. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5246. };
  5247. /**
  5248. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5249. */
  5250. Matrix.prototype.getRotationMatrix = function () {
  5251. var result = Matrix.Identity();
  5252. this.getRotationMatrixToRef(result);
  5253. return result;
  5254. };
  5255. /**
  5256. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5257. * Returns the current Matrix.
  5258. */
  5259. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5260. var m = this.m;
  5261. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5262. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5263. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5264. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5265. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5266. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5267. 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);
  5268. return this;
  5269. };
  5270. // Statics
  5271. /**
  5272. * Returns a new Matrix set from the starting index of the passed array.
  5273. */
  5274. Matrix.FromArray = function (array, offset) {
  5275. var result = new Matrix();
  5276. if (!offset) {
  5277. offset = 0;
  5278. }
  5279. Matrix.FromArrayToRef(array, offset, result);
  5280. return result;
  5281. };
  5282. /**
  5283. * Sets the passed "result" matrix from the starting index of the passed array.
  5284. */
  5285. Matrix.FromArrayToRef = function (array, offset, result) {
  5286. for (var index = 0; index < 16; index++) {
  5287. result.m[index] = array[index + offset];
  5288. }
  5289. result._markAsUpdated();
  5290. };
  5291. /**
  5292. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5293. */
  5294. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5295. for (var index = 0; index < 16; index++) {
  5296. result.m[index] = array[index + offset] * scale;
  5297. }
  5298. result._markAsUpdated();
  5299. };
  5300. /**
  5301. * Sets the passed matrix "result" with the 16 passed floats.
  5302. */
  5303. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5304. result.m[0] = initialM11;
  5305. result.m[1] = initialM12;
  5306. result.m[2] = initialM13;
  5307. result.m[3] = initialM14;
  5308. result.m[4] = initialM21;
  5309. result.m[5] = initialM22;
  5310. result.m[6] = initialM23;
  5311. result.m[7] = initialM24;
  5312. result.m[8] = initialM31;
  5313. result.m[9] = initialM32;
  5314. result.m[10] = initialM33;
  5315. result.m[11] = initialM34;
  5316. result.m[12] = initialM41;
  5317. result.m[13] = initialM42;
  5318. result.m[14] = initialM43;
  5319. result.m[15] = initialM44;
  5320. result._markAsUpdated();
  5321. };
  5322. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5323. /**
  5324. * Static identity matrix to be used as readonly matrix
  5325. * Must not be updated.
  5326. */
  5327. get: function () {
  5328. return Matrix._identityReadOnly;
  5329. },
  5330. enumerable: true,
  5331. configurable: true
  5332. });
  5333. /**
  5334. * Returns a new Matrix set from the 16 passed floats.
  5335. */
  5336. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5337. var result = new Matrix();
  5338. result.m[0] = initialM11;
  5339. result.m[1] = initialM12;
  5340. result.m[2] = initialM13;
  5341. result.m[3] = initialM14;
  5342. result.m[4] = initialM21;
  5343. result.m[5] = initialM22;
  5344. result.m[6] = initialM23;
  5345. result.m[7] = initialM24;
  5346. result.m[8] = initialM31;
  5347. result.m[9] = initialM32;
  5348. result.m[10] = initialM33;
  5349. result.m[11] = initialM34;
  5350. result.m[12] = initialM41;
  5351. result.m[13] = initialM42;
  5352. result.m[14] = initialM43;
  5353. result.m[15] = initialM44;
  5354. return result;
  5355. };
  5356. /**
  5357. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5358. */
  5359. Matrix.Compose = function (scale, rotation, translation) {
  5360. var result = Matrix.Identity();
  5361. Matrix.ComposeToRef(scale, rotation, translation, result);
  5362. return result;
  5363. };
  5364. /**
  5365. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5366. */
  5367. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5368. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5369. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5370. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5371. result.setTranslation(translation);
  5372. };
  5373. /**
  5374. * Returns a new indentity Matrix.
  5375. */
  5376. Matrix.Identity = function () {
  5377. 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);
  5378. };
  5379. /**
  5380. * Sets the passed "result" as an identity matrix.
  5381. */
  5382. Matrix.IdentityToRef = function (result) {
  5383. 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);
  5384. };
  5385. /**
  5386. * Returns a new zero Matrix.
  5387. */
  5388. Matrix.Zero = function () {
  5389. 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);
  5390. };
  5391. /**
  5392. * Returns a new rotation matrix for "angle" radians around the X axis.
  5393. */
  5394. Matrix.RotationX = function (angle) {
  5395. var result = new Matrix();
  5396. Matrix.RotationXToRef(angle, result);
  5397. return result;
  5398. };
  5399. /**
  5400. * Returns a new Matrix as the passed inverted one.
  5401. */
  5402. Matrix.Invert = function (source) {
  5403. var result = new Matrix();
  5404. source.invertToRef(result);
  5405. return result;
  5406. };
  5407. /**
  5408. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5409. */
  5410. Matrix.RotationXToRef = function (angle, result) {
  5411. var s = Math.sin(angle);
  5412. var c = Math.cos(angle);
  5413. result.m[0] = 1.0;
  5414. result.m[15] = 1.0;
  5415. result.m[5] = c;
  5416. result.m[10] = c;
  5417. result.m[9] = -s;
  5418. result.m[6] = s;
  5419. result.m[1] = 0.0;
  5420. result.m[2] = 0.0;
  5421. result.m[3] = 0.0;
  5422. result.m[4] = 0.0;
  5423. result.m[7] = 0.0;
  5424. result.m[8] = 0.0;
  5425. result.m[11] = 0.0;
  5426. result.m[12] = 0.0;
  5427. result.m[13] = 0.0;
  5428. result.m[14] = 0.0;
  5429. result._markAsUpdated();
  5430. };
  5431. /**
  5432. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5433. */
  5434. Matrix.RotationY = function (angle) {
  5435. var result = new Matrix();
  5436. Matrix.RotationYToRef(angle, result);
  5437. return result;
  5438. };
  5439. /**
  5440. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5441. */
  5442. Matrix.RotationYToRef = function (angle, result) {
  5443. var s = Math.sin(angle);
  5444. var c = Math.cos(angle);
  5445. result.m[5] = 1.0;
  5446. result.m[15] = 1.0;
  5447. result.m[0] = c;
  5448. result.m[2] = -s;
  5449. result.m[8] = s;
  5450. result.m[10] = c;
  5451. result.m[1] = 0.0;
  5452. result.m[3] = 0.0;
  5453. result.m[4] = 0.0;
  5454. result.m[6] = 0.0;
  5455. result.m[7] = 0.0;
  5456. result.m[9] = 0.0;
  5457. result.m[11] = 0.0;
  5458. result.m[12] = 0.0;
  5459. result.m[13] = 0.0;
  5460. result.m[14] = 0.0;
  5461. result._markAsUpdated();
  5462. };
  5463. /**
  5464. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5465. */
  5466. Matrix.RotationZ = function (angle) {
  5467. var result = new Matrix();
  5468. Matrix.RotationZToRef(angle, result);
  5469. return result;
  5470. };
  5471. /**
  5472. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5473. */
  5474. Matrix.RotationZToRef = function (angle, result) {
  5475. var s = Math.sin(angle);
  5476. var c = Math.cos(angle);
  5477. result.m[10] = 1.0;
  5478. result.m[15] = 1.0;
  5479. result.m[0] = c;
  5480. result.m[1] = s;
  5481. result.m[4] = -s;
  5482. result.m[5] = c;
  5483. result.m[2] = 0.0;
  5484. result.m[3] = 0.0;
  5485. result.m[6] = 0.0;
  5486. result.m[7] = 0.0;
  5487. result.m[8] = 0.0;
  5488. result.m[9] = 0.0;
  5489. result.m[11] = 0.0;
  5490. result.m[12] = 0.0;
  5491. result.m[13] = 0.0;
  5492. result.m[14] = 0.0;
  5493. result._markAsUpdated();
  5494. };
  5495. /**
  5496. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5497. */
  5498. Matrix.RotationAxis = function (axis, angle) {
  5499. var result = Matrix.Zero();
  5500. Matrix.RotationAxisToRef(axis, angle, result);
  5501. return result;
  5502. };
  5503. /**
  5504. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5505. */
  5506. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5507. var s = Math.sin(-angle);
  5508. var c = Math.cos(-angle);
  5509. var c1 = 1 - c;
  5510. axis.normalize();
  5511. result.m[0] = (axis.x * axis.x) * c1 + c;
  5512. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5513. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5514. result.m[3] = 0.0;
  5515. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5516. result.m[5] = (axis.y * axis.y) * c1 + c;
  5517. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5518. result.m[7] = 0.0;
  5519. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5520. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5521. result.m[10] = (axis.z * axis.z) * c1 + c;
  5522. result.m[11] = 0.0;
  5523. result.m[15] = 1.0;
  5524. result._markAsUpdated();
  5525. };
  5526. /**
  5527. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5528. */
  5529. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5530. var result = new Matrix();
  5531. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5532. return result;
  5533. };
  5534. /**
  5535. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5536. */
  5537. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5538. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5539. this._tempQuaternion.toRotationMatrix(result);
  5540. };
  5541. /**
  5542. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5543. */
  5544. Matrix.Scaling = function (x, y, z) {
  5545. var result = Matrix.Zero();
  5546. Matrix.ScalingToRef(x, y, z, result);
  5547. return result;
  5548. };
  5549. /**
  5550. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5551. */
  5552. Matrix.ScalingToRef = function (x, y, z, result) {
  5553. result.m[0] = x;
  5554. result.m[1] = 0.0;
  5555. result.m[2] = 0.0;
  5556. result.m[3] = 0.0;
  5557. result.m[4] = 0.0;
  5558. result.m[5] = y;
  5559. result.m[6] = 0.0;
  5560. result.m[7] = 0.0;
  5561. result.m[8] = 0.0;
  5562. result.m[9] = 0.0;
  5563. result.m[10] = z;
  5564. result.m[11] = 0.0;
  5565. result.m[12] = 0.0;
  5566. result.m[13] = 0.0;
  5567. result.m[14] = 0.0;
  5568. result.m[15] = 1.0;
  5569. result._markAsUpdated();
  5570. };
  5571. /**
  5572. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5573. */
  5574. Matrix.Translation = function (x, y, z) {
  5575. var result = Matrix.Identity();
  5576. Matrix.TranslationToRef(x, y, z, result);
  5577. return result;
  5578. };
  5579. /**
  5580. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5581. */
  5582. Matrix.TranslationToRef = function (x, y, z, result) {
  5583. 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);
  5584. };
  5585. /**
  5586. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5587. * @param startValue defines the start value
  5588. * @param endValue defines the end value
  5589. * @param gradient defines the gradient factor
  5590. * @returns the new matrix
  5591. */
  5592. Matrix.Lerp = function (startValue, endValue, gradient) {
  5593. var result = Matrix.Zero();
  5594. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5595. return result;
  5596. };
  5597. /**
  5598. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5599. * @param startValue defines the start value
  5600. * @param endValue defines the end value
  5601. * @param gradient defines the gradient factor
  5602. * @param result defines the Matrix object where to store data
  5603. */
  5604. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5605. for (var index = 0; index < 16; index++) {
  5606. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5607. }
  5608. result._markAsUpdated();
  5609. };
  5610. /**
  5611. * Returns a new Matrix whose values are computed by :
  5612. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5613. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5614. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5615. */
  5616. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5617. var startScale = new Vector3(0, 0, 0);
  5618. var startRotation = new Quaternion();
  5619. var startTranslation = new Vector3(0, 0, 0);
  5620. startValue.decompose(startScale, startRotation, startTranslation);
  5621. var endScale = new Vector3(0, 0, 0);
  5622. var endRotation = new Quaternion();
  5623. var endTranslation = new Vector3(0, 0, 0);
  5624. endValue.decompose(endScale, endRotation, endTranslation);
  5625. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5626. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5627. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5628. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5629. };
  5630. /**
  5631. * 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".
  5632. * This methods works for a Left-Handed system.
  5633. */
  5634. Matrix.LookAtLH = function (eye, target, up) {
  5635. var result = Matrix.Zero();
  5636. Matrix.LookAtLHToRef(eye, target, up, result);
  5637. return result;
  5638. };
  5639. /**
  5640. * 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".
  5641. * This methods works for a Left-Handed system.
  5642. */
  5643. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5644. // Z axis
  5645. target.subtractToRef(eye, this._zAxis);
  5646. this._zAxis.normalize();
  5647. // X axis
  5648. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5649. if (this._xAxis.lengthSquared() === 0) {
  5650. this._xAxis.x = 1.0;
  5651. }
  5652. else {
  5653. this._xAxis.normalize();
  5654. }
  5655. // Y axis
  5656. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5657. this._yAxis.normalize();
  5658. // Eye angles
  5659. var ex = -Vector3.Dot(this._xAxis, eye);
  5660. var ey = -Vector3.Dot(this._yAxis, eye);
  5661. var ez = -Vector3.Dot(this._zAxis, eye);
  5662. 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);
  5663. };
  5664. /**
  5665. * 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".
  5666. * This methods works for a Right-Handed system.
  5667. */
  5668. Matrix.LookAtRH = function (eye, target, up) {
  5669. var result = Matrix.Zero();
  5670. Matrix.LookAtRHToRef(eye, target, up, result);
  5671. return result;
  5672. };
  5673. /**
  5674. * 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".
  5675. * This methods works for a Left-Handed system.
  5676. */
  5677. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5678. // Z axis
  5679. eye.subtractToRef(target, this._zAxis);
  5680. this._zAxis.normalize();
  5681. // X axis
  5682. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5683. if (this._xAxis.lengthSquared() === 0) {
  5684. this._xAxis.x = 1.0;
  5685. }
  5686. else {
  5687. this._xAxis.normalize();
  5688. }
  5689. // Y axis
  5690. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5691. this._yAxis.normalize();
  5692. // Eye angles
  5693. var ex = -Vector3.Dot(this._xAxis, eye);
  5694. var ey = -Vector3.Dot(this._yAxis, eye);
  5695. var ez = -Vector3.Dot(this._zAxis, eye);
  5696. 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);
  5697. };
  5698. /**
  5699. * 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.
  5700. */
  5701. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5702. var matrix = Matrix.Zero();
  5703. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5704. return matrix;
  5705. };
  5706. /**
  5707. * 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.
  5708. */
  5709. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5710. var n = znear;
  5711. var f = zfar;
  5712. var a = 2.0 / width;
  5713. var b = 2.0 / height;
  5714. var c = 2.0 / (f - n);
  5715. var d = -(f + n) / (f - n);
  5716. 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);
  5717. };
  5718. /**
  5719. * 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.
  5720. */
  5721. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5722. var matrix = Matrix.Zero();
  5723. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5724. return matrix;
  5725. };
  5726. /**
  5727. * 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.
  5728. */
  5729. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5730. var n = znear;
  5731. var f = zfar;
  5732. var a = 2.0 / (right - left);
  5733. var b = 2.0 / (top - bottom);
  5734. var c = 2.0 / (f - n);
  5735. var d = -(f + n) / (f - n);
  5736. var i0 = (left + right) / (left - right);
  5737. var i1 = (top + bottom) / (bottom - top);
  5738. 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);
  5739. };
  5740. /**
  5741. * 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.
  5742. */
  5743. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5744. var matrix = Matrix.Zero();
  5745. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5746. return matrix;
  5747. };
  5748. /**
  5749. * 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.
  5750. */
  5751. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5752. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5753. result.m[10] *= -1.0;
  5754. };
  5755. /**
  5756. * 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.
  5757. */
  5758. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5759. var matrix = Matrix.Zero();
  5760. var n = znear;
  5761. var f = zfar;
  5762. var a = 2.0 * n / width;
  5763. var b = 2.0 * n / height;
  5764. var c = (f + n) / (f - n);
  5765. var d = -2.0 * f * n / (f - n);
  5766. 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);
  5767. return matrix;
  5768. };
  5769. /**
  5770. * 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.
  5771. */
  5772. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5773. var matrix = Matrix.Zero();
  5774. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5775. return matrix;
  5776. };
  5777. /**
  5778. * 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.
  5779. */
  5780. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5781. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5782. var n = znear;
  5783. var f = zfar;
  5784. var t = 1.0 / (Math.tan(fov * 0.5));
  5785. var a = isVerticalFovFixed ? (t / aspect) : t;
  5786. var b = isVerticalFovFixed ? t : (t * aspect);
  5787. var c = (f + n) / (f - n);
  5788. var d = -2.0 * f * n / (f - n);
  5789. 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);
  5790. };
  5791. /**
  5792. * 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.
  5793. */
  5794. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5795. var matrix = Matrix.Zero();
  5796. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5797. return matrix;
  5798. };
  5799. /**
  5800. * 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.
  5801. */
  5802. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5803. //alternatively this could be expressed as:
  5804. // m = PerspectiveFovLHToRef
  5805. // m[10] *= -1.0;
  5806. // m[11] *= -1.0;
  5807. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5808. var n = znear;
  5809. var f = zfar;
  5810. var t = 1.0 / (Math.tan(fov * 0.5));
  5811. var a = isVerticalFovFixed ? (t / aspect) : t;
  5812. var b = isVerticalFovFixed ? t : (t * aspect);
  5813. var c = -(f + n) / (f - n);
  5814. var d = -2 * f * n / (f - n);
  5815. 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);
  5816. };
  5817. /**
  5818. * 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.
  5819. */
  5820. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5821. if (rightHanded === void 0) { rightHanded = false; }
  5822. var rightHandedFactor = rightHanded ? -1 : 1;
  5823. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5824. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5825. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5826. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5827. var xScale = 2.0 / (leftTan + rightTan);
  5828. var yScale = 2.0 / (upTan + downTan);
  5829. result.m[0] = xScale;
  5830. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5831. result.m[5] = yScale;
  5832. result.m[6] = result.m[7] = 0.0;
  5833. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5834. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5835. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5836. result.m[10] = -zfar / (znear - zfar);
  5837. result.m[11] = 1.0 * rightHandedFactor;
  5838. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5839. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5840. // result.m[14] = (znear * zfar) / (znear - zfar);
  5841. result._markAsUpdated();
  5842. };
  5843. /**
  5844. * Returns the final transformation matrix : world * view * projection * viewport
  5845. */
  5846. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5847. var cw = viewport.width;
  5848. var ch = viewport.height;
  5849. var cx = viewport.x;
  5850. var cy = viewport.y;
  5851. 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);
  5852. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5853. };
  5854. /**
  5855. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5856. */
  5857. Matrix.GetAsMatrix2x2 = function (matrix) {
  5858. return new Float32Array([
  5859. matrix.m[0], matrix.m[1],
  5860. matrix.m[4], matrix.m[5]
  5861. ]);
  5862. };
  5863. /**
  5864. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5865. */
  5866. Matrix.GetAsMatrix3x3 = function (matrix) {
  5867. return new Float32Array([
  5868. matrix.m[0], matrix.m[1], matrix.m[2],
  5869. matrix.m[4], matrix.m[5], matrix.m[6],
  5870. matrix.m[8], matrix.m[9], matrix.m[10]
  5871. ]);
  5872. };
  5873. /**
  5874. * Compute the transpose of the passed Matrix.
  5875. * Returns a new Matrix.
  5876. */
  5877. Matrix.Transpose = function (matrix) {
  5878. var result = new Matrix();
  5879. Matrix.TransposeToRef(matrix, result);
  5880. return result;
  5881. };
  5882. /**
  5883. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5884. */
  5885. Matrix.TransposeToRef = function (matrix, result) {
  5886. result.m[0] = matrix.m[0];
  5887. result.m[1] = matrix.m[4];
  5888. result.m[2] = matrix.m[8];
  5889. result.m[3] = matrix.m[12];
  5890. result.m[4] = matrix.m[1];
  5891. result.m[5] = matrix.m[5];
  5892. result.m[6] = matrix.m[9];
  5893. result.m[7] = matrix.m[13];
  5894. result.m[8] = matrix.m[2];
  5895. result.m[9] = matrix.m[6];
  5896. result.m[10] = matrix.m[10];
  5897. result.m[11] = matrix.m[14];
  5898. result.m[12] = matrix.m[3];
  5899. result.m[13] = matrix.m[7];
  5900. result.m[14] = matrix.m[11];
  5901. result.m[15] = matrix.m[15];
  5902. };
  5903. /**
  5904. * Returns a new Matrix as the reflection matrix across the passed plane.
  5905. */
  5906. Matrix.Reflection = function (plane) {
  5907. var matrix = new Matrix();
  5908. Matrix.ReflectionToRef(plane, matrix);
  5909. return matrix;
  5910. };
  5911. /**
  5912. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5913. */
  5914. Matrix.ReflectionToRef = function (plane, result) {
  5915. plane.normalize();
  5916. var x = plane.normal.x;
  5917. var y = plane.normal.y;
  5918. var z = plane.normal.z;
  5919. var temp = -2 * x;
  5920. var temp2 = -2 * y;
  5921. var temp3 = -2 * z;
  5922. result.m[0] = (temp * x) + 1;
  5923. result.m[1] = temp2 * x;
  5924. result.m[2] = temp3 * x;
  5925. result.m[3] = 0.0;
  5926. result.m[4] = temp * y;
  5927. result.m[5] = (temp2 * y) + 1;
  5928. result.m[6] = temp3 * y;
  5929. result.m[7] = 0.0;
  5930. result.m[8] = temp * z;
  5931. result.m[9] = temp2 * z;
  5932. result.m[10] = (temp3 * z) + 1;
  5933. result.m[11] = 0.0;
  5934. result.m[12] = temp * plane.d;
  5935. result.m[13] = temp2 * plane.d;
  5936. result.m[14] = temp3 * plane.d;
  5937. result.m[15] = 1.0;
  5938. result._markAsUpdated();
  5939. };
  5940. /**
  5941. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5942. */
  5943. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5944. result.m[0] = xaxis.x;
  5945. result.m[1] = xaxis.y;
  5946. result.m[2] = xaxis.z;
  5947. result.m[3] = 0.0;
  5948. result.m[4] = yaxis.x;
  5949. result.m[5] = yaxis.y;
  5950. result.m[6] = yaxis.z;
  5951. result.m[7] = 0.0;
  5952. result.m[8] = zaxis.x;
  5953. result.m[9] = zaxis.y;
  5954. result.m[10] = zaxis.z;
  5955. result.m[11] = 0.0;
  5956. result.m[12] = 0.0;
  5957. result.m[13] = 0.0;
  5958. result.m[14] = 0.0;
  5959. result.m[15] = 1.0;
  5960. result._markAsUpdated();
  5961. };
  5962. /**
  5963. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5964. */
  5965. Matrix.FromQuaternionToRef = function (quat, result) {
  5966. var xx = quat.x * quat.x;
  5967. var yy = quat.y * quat.y;
  5968. var zz = quat.z * quat.z;
  5969. var xy = quat.x * quat.y;
  5970. var zw = quat.z * quat.w;
  5971. var zx = quat.z * quat.x;
  5972. var yw = quat.y * quat.w;
  5973. var yz = quat.y * quat.z;
  5974. var xw = quat.x * quat.w;
  5975. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5976. result.m[1] = 2.0 * (xy + zw);
  5977. result.m[2] = 2.0 * (zx - yw);
  5978. result.m[3] = 0.0;
  5979. result.m[4] = 2.0 * (xy - zw);
  5980. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5981. result.m[6] = 2.0 * (yz + xw);
  5982. result.m[7] = 0.0;
  5983. result.m[8] = 2.0 * (zx + yw);
  5984. result.m[9] = 2.0 * (yz - xw);
  5985. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5986. result.m[11] = 0.0;
  5987. result.m[12] = 0.0;
  5988. result.m[13] = 0.0;
  5989. result.m[14] = 0.0;
  5990. result.m[15] = 1.0;
  5991. result._markAsUpdated();
  5992. };
  5993. Matrix._tempQuaternion = new Quaternion();
  5994. Matrix._xAxis = Vector3.Zero();
  5995. Matrix._yAxis = Vector3.Zero();
  5996. Matrix._zAxis = Vector3.Zero();
  5997. Matrix._updateFlagSeed = 0;
  5998. Matrix._identityReadOnly = Matrix.Identity();
  5999. return Matrix;
  6000. }());
  6001. BABYLON.Matrix = Matrix;
  6002. var Plane = /** @class */ (function () {
  6003. /**
  6004. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6005. */
  6006. function Plane(a, b, c, d) {
  6007. this.normal = new Vector3(a, b, c);
  6008. this.d = d;
  6009. }
  6010. /**
  6011. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6012. */
  6013. Plane.prototype.asArray = function () {
  6014. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6015. };
  6016. // Methods
  6017. /**
  6018. * Returns a new plane copied from the current Plane.
  6019. */
  6020. Plane.prototype.clone = function () {
  6021. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6022. };
  6023. /**
  6024. * Returns the string "Plane".
  6025. */
  6026. Plane.prototype.getClassName = function () {
  6027. return "Plane";
  6028. };
  6029. /**
  6030. * Returns the Plane hash code.
  6031. */
  6032. Plane.prototype.getHashCode = function () {
  6033. var hash = this.normal.getHashCode();
  6034. hash = (hash * 397) ^ (this.d || 0);
  6035. return hash;
  6036. };
  6037. /**
  6038. * Normalize the current Plane in place.
  6039. * Returns the updated Plane.
  6040. */
  6041. Plane.prototype.normalize = function () {
  6042. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6043. var magnitude = 0.0;
  6044. if (norm !== 0) {
  6045. magnitude = 1.0 / norm;
  6046. }
  6047. this.normal.x *= magnitude;
  6048. this.normal.y *= magnitude;
  6049. this.normal.z *= magnitude;
  6050. this.d *= magnitude;
  6051. return this;
  6052. };
  6053. /**
  6054. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6055. */
  6056. Plane.prototype.transform = function (transformation) {
  6057. var transposedMatrix = Matrix.Transpose(transformation);
  6058. var x = this.normal.x;
  6059. var y = this.normal.y;
  6060. var z = this.normal.z;
  6061. var d = this.d;
  6062. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6063. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6064. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6065. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6066. return new Plane(normalX, normalY, normalZ, finalD);
  6067. };
  6068. /**
  6069. * Returns the dot product (float) of the point coordinates and the plane normal.
  6070. */
  6071. Plane.prototype.dotCoordinate = function (point) {
  6072. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6073. };
  6074. /**
  6075. * Updates the current Plane from the plane defined by the three passed points.
  6076. * Returns the updated Plane.
  6077. */
  6078. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6079. var x1 = point2.x - point1.x;
  6080. var y1 = point2.y - point1.y;
  6081. var z1 = point2.z - point1.z;
  6082. var x2 = point3.x - point1.x;
  6083. var y2 = point3.y - point1.y;
  6084. var z2 = point3.z - point1.z;
  6085. var yz = (y1 * z2) - (z1 * y2);
  6086. var xz = (z1 * x2) - (x1 * z2);
  6087. var xy = (x1 * y2) - (y1 * x2);
  6088. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6089. var invPyth;
  6090. if (pyth !== 0) {
  6091. invPyth = 1.0 / pyth;
  6092. }
  6093. else {
  6094. invPyth = 0.0;
  6095. }
  6096. this.normal.x = yz * invPyth;
  6097. this.normal.y = xz * invPyth;
  6098. this.normal.z = xy * invPyth;
  6099. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6100. return this;
  6101. };
  6102. /**
  6103. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6104. */
  6105. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6106. var dot = Vector3.Dot(this.normal, direction);
  6107. return (dot <= epsilon);
  6108. };
  6109. /**
  6110. * Returns the signed distance (float) from the passed point to the Plane.
  6111. */
  6112. Plane.prototype.signedDistanceTo = function (point) {
  6113. return Vector3.Dot(point, this.normal) + this.d;
  6114. };
  6115. // Statics
  6116. /**
  6117. * Returns a new Plane from the passed array.
  6118. */
  6119. Plane.FromArray = function (array) {
  6120. return new Plane(array[0], array[1], array[2], array[3]);
  6121. };
  6122. /**
  6123. * Returns a new Plane defined by the three passed points.
  6124. */
  6125. Plane.FromPoints = function (point1, point2, point3) {
  6126. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6127. result.copyFromPoints(point1, point2, point3);
  6128. return result;
  6129. };
  6130. /**
  6131. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6132. * Note : the vector "normal" is updated because normalized.
  6133. */
  6134. Plane.FromPositionAndNormal = function (origin, normal) {
  6135. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6136. normal.normalize();
  6137. result.normal = normal;
  6138. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6139. return result;
  6140. };
  6141. /**
  6142. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6143. */
  6144. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6145. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6146. return Vector3.Dot(point, normal) + d;
  6147. };
  6148. return Plane;
  6149. }());
  6150. BABYLON.Plane = Plane;
  6151. var Viewport = /** @class */ (function () {
  6152. /**
  6153. * Creates a Viewport object located at (x, y) and sized (width, height).
  6154. */
  6155. function Viewport(x, y, width, height) {
  6156. this.x = x;
  6157. this.y = y;
  6158. this.width = width;
  6159. this.height = height;
  6160. }
  6161. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6162. if (renderWidthOrEngine.getRenderWidth) {
  6163. var engine = renderWidthOrEngine;
  6164. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6165. }
  6166. var renderWidth = renderWidthOrEngine;
  6167. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6168. };
  6169. /**
  6170. * Returns a new Viewport copied from the current one.
  6171. */
  6172. Viewport.prototype.clone = function () {
  6173. return new Viewport(this.x, this.y, this.width, this.height);
  6174. };
  6175. return Viewport;
  6176. }());
  6177. BABYLON.Viewport = Viewport;
  6178. var Frustum = /** @class */ (function () {
  6179. function Frustum() {
  6180. }
  6181. /**
  6182. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6183. */
  6184. Frustum.GetPlanes = function (transform) {
  6185. var frustumPlanes = [];
  6186. for (var index = 0; index < 6; index++) {
  6187. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6188. }
  6189. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6190. return frustumPlanes;
  6191. };
  6192. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6193. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6194. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6195. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6196. frustumPlane.d = transform.m[15] + transform.m[14];
  6197. frustumPlane.normalize();
  6198. };
  6199. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6200. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6201. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6202. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6203. frustumPlane.d = transform.m[15] - transform.m[14];
  6204. frustumPlane.normalize();
  6205. };
  6206. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6207. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6208. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6209. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6210. frustumPlane.d = transform.m[15] + transform.m[12];
  6211. frustumPlane.normalize();
  6212. };
  6213. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6214. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6215. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6216. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6217. frustumPlane.d = transform.m[15] - transform.m[12];
  6218. frustumPlane.normalize();
  6219. };
  6220. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6221. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6222. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6223. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6224. frustumPlane.d = transform.m[15] - transform.m[13];
  6225. frustumPlane.normalize();
  6226. };
  6227. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6228. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6229. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6230. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6231. frustumPlane.d = transform.m[15] + transform.m[13];
  6232. frustumPlane.normalize();
  6233. };
  6234. /**
  6235. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6236. */
  6237. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6238. // Near
  6239. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6240. // Far
  6241. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6242. // Left
  6243. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6244. // Right
  6245. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6246. // Top
  6247. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6248. // Bottom
  6249. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6250. };
  6251. return Frustum;
  6252. }());
  6253. BABYLON.Frustum = Frustum;
  6254. var Space;
  6255. (function (Space) {
  6256. Space[Space["LOCAL"] = 0] = "LOCAL";
  6257. Space[Space["WORLD"] = 1] = "WORLD";
  6258. Space[Space["BONE"] = 2] = "BONE";
  6259. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6260. var Axis = /** @class */ (function () {
  6261. function Axis() {
  6262. }
  6263. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6264. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6265. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6266. return Axis;
  6267. }());
  6268. BABYLON.Axis = Axis;
  6269. ;
  6270. var BezierCurve = /** @class */ (function () {
  6271. function BezierCurve() {
  6272. }
  6273. /**
  6274. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6275. */
  6276. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6277. // Extract X (which is equal to time here)
  6278. var f0 = 1 - 3 * x2 + 3 * x1;
  6279. var f1 = 3 * x2 - 6 * x1;
  6280. var f2 = 3 * x1;
  6281. var refinedT = t;
  6282. for (var i = 0; i < 5; i++) {
  6283. var refinedT2 = refinedT * refinedT;
  6284. var refinedT3 = refinedT2 * refinedT;
  6285. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6286. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6287. refinedT -= (x - t) * slope;
  6288. refinedT = Math.min(1, Math.max(0, refinedT));
  6289. }
  6290. // Resolve cubic bezier for the given x
  6291. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6292. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6293. Math.pow(refinedT, 3);
  6294. };
  6295. return BezierCurve;
  6296. }());
  6297. BABYLON.BezierCurve = BezierCurve;
  6298. var Orientation;
  6299. (function (Orientation) {
  6300. Orientation[Orientation["CW"] = 0] = "CW";
  6301. Orientation[Orientation["CCW"] = 1] = "CCW";
  6302. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6303. var Angle = /** @class */ (function () {
  6304. /**
  6305. * Creates an Angle object of "radians" radians (float).
  6306. */
  6307. function Angle(radians) {
  6308. var _this = this;
  6309. /**
  6310. * Returns the Angle value in degrees (float).
  6311. */
  6312. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6313. /**
  6314. * Returns the Angle value in radians (float).
  6315. */
  6316. this.radians = function () { return _this._radians; };
  6317. this._radians = radians;
  6318. if (this._radians < 0.0)
  6319. this._radians += (2.0 * Math.PI);
  6320. }
  6321. /**
  6322. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6323. */
  6324. Angle.BetweenTwoPoints = function (a, b) {
  6325. var delta = b.subtract(a);
  6326. var theta = Math.atan2(delta.y, delta.x);
  6327. return new Angle(theta);
  6328. };
  6329. /**
  6330. * Returns a new Angle object from the passed float in radians.
  6331. */
  6332. Angle.FromRadians = function (radians) {
  6333. return new Angle(radians);
  6334. };
  6335. /**
  6336. * Returns a new Angle object from the passed float in degrees.
  6337. */
  6338. Angle.FromDegrees = function (degrees) {
  6339. return new Angle(degrees * Math.PI / 180.0);
  6340. };
  6341. return Angle;
  6342. }());
  6343. BABYLON.Angle = Angle;
  6344. var Arc2 = /** @class */ (function () {
  6345. /**
  6346. * Creates an Arc object from the three passed points : start, middle and end.
  6347. */
  6348. function Arc2(startPoint, midPoint, endPoint) {
  6349. this.startPoint = startPoint;
  6350. this.midPoint = midPoint;
  6351. this.endPoint = endPoint;
  6352. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6353. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6354. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6355. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6356. 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);
  6357. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6358. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6359. var a1 = this.startAngle.degrees();
  6360. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6361. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6362. // angles correction
  6363. if (a2 - a1 > +180.0)
  6364. a2 -= 360.0;
  6365. if (a2 - a1 < -180.0)
  6366. a2 += 360.0;
  6367. if (a3 - a2 > +180.0)
  6368. a3 -= 360.0;
  6369. if (a3 - a2 < -180.0)
  6370. a3 += 360.0;
  6371. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6372. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6373. }
  6374. return Arc2;
  6375. }());
  6376. BABYLON.Arc2 = Arc2;
  6377. var Path2 = /** @class */ (function () {
  6378. /**
  6379. * Creates a Path2 object from the starting 2D coordinates x and y.
  6380. */
  6381. function Path2(x, y) {
  6382. this._points = new Array();
  6383. this._length = 0.0;
  6384. this.closed = false;
  6385. this._points.push(new Vector2(x, y));
  6386. }
  6387. /**
  6388. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6389. * Returns the updated Path2.
  6390. */
  6391. Path2.prototype.addLineTo = function (x, y) {
  6392. if (this.closed) {
  6393. return this;
  6394. }
  6395. var newPoint = new Vector2(x, y);
  6396. var previousPoint = this._points[this._points.length - 1];
  6397. this._points.push(newPoint);
  6398. this._length += newPoint.subtract(previousPoint).length();
  6399. return this;
  6400. };
  6401. /**
  6402. * 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.
  6403. * Returns the updated Path2.
  6404. */
  6405. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6406. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6407. if (this.closed) {
  6408. return this;
  6409. }
  6410. var startPoint = this._points[this._points.length - 1];
  6411. var midPoint = new Vector2(midX, midY);
  6412. var endPoint = new Vector2(endX, endY);
  6413. var arc = new Arc2(startPoint, midPoint, endPoint);
  6414. var increment = arc.angle.radians() / numberOfSegments;
  6415. if (arc.orientation === Orientation.CW)
  6416. increment *= -1;
  6417. var currentAngle = arc.startAngle.radians() + increment;
  6418. for (var i = 0; i < numberOfSegments; i++) {
  6419. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6420. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6421. this.addLineTo(x, y);
  6422. currentAngle += increment;
  6423. }
  6424. return this;
  6425. };
  6426. /**
  6427. * Closes the Path2.
  6428. * Returns the Path2.
  6429. */
  6430. Path2.prototype.close = function () {
  6431. this.closed = true;
  6432. return this;
  6433. };
  6434. /**
  6435. * Returns the Path2 total length (float).
  6436. */
  6437. Path2.prototype.length = function () {
  6438. var result = this._length;
  6439. if (!this.closed) {
  6440. var lastPoint = this._points[this._points.length - 1];
  6441. var firstPoint = this._points[0];
  6442. result += (firstPoint.subtract(lastPoint).length());
  6443. }
  6444. return result;
  6445. };
  6446. /**
  6447. * Returns the Path2 internal array of points.
  6448. */
  6449. Path2.prototype.getPoints = function () {
  6450. return this._points;
  6451. };
  6452. /**
  6453. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6454. */
  6455. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6456. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6457. return Vector2.Zero();
  6458. }
  6459. var lengthPosition = normalizedLengthPosition * this.length();
  6460. var previousOffset = 0;
  6461. for (var i = 0; i < this._points.length; i++) {
  6462. var j = (i + 1) % this._points.length;
  6463. var a = this._points[i];
  6464. var b = this._points[j];
  6465. var bToA = b.subtract(a);
  6466. var nextOffset = (bToA.length() + previousOffset);
  6467. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6468. var dir = bToA.normalize();
  6469. var localOffset = lengthPosition - previousOffset;
  6470. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6471. }
  6472. previousOffset = nextOffset;
  6473. }
  6474. return Vector2.Zero();
  6475. };
  6476. /**
  6477. * Returns a new Path2 starting at the coordinates (x, y).
  6478. */
  6479. Path2.StartingAt = function (x, y) {
  6480. return new Path2(x, y);
  6481. };
  6482. return Path2;
  6483. }());
  6484. BABYLON.Path2 = Path2;
  6485. var Path3D = /** @class */ (function () {
  6486. /**
  6487. * new Path3D(path, normal, raw)
  6488. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6489. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6490. * path : an array of Vector3, the curve axis of the Path3D
  6491. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6492. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6493. */
  6494. function Path3D(path, firstNormal, raw) {
  6495. if (firstNormal === void 0) { firstNormal = null; }
  6496. this.path = path;
  6497. this._curve = new Array();
  6498. this._distances = new Array();
  6499. this._tangents = new Array();
  6500. this._normals = new Array();
  6501. this._binormals = new Array();
  6502. for (var p = 0; p < path.length; p++) {
  6503. this._curve[p] = path[p].clone(); // hard copy
  6504. }
  6505. this._raw = raw || false;
  6506. this._compute(firstNormal);
  6507. }
  6508. /**
  6509. * Returns the Path3D array of successive Vector3 designing its curve.
  6510. */
  6511. Path3D.prototype.getCurve = function () {
  6512. return this._curve;
  6513. };
  6514. /**
  6515. * Returns an array populated with tangent vectors on each Path3D curve point.
  6516. */
  6517. Path3D.prototype.getTangents = function () {
  6518. return this._tangents;
  6519. };
  6520. /**
  6521. * Returns an array populated with normal vectors on each Path3D curve point.
  6522. */
  6523. Path3D.prototype.getNormals = function () {
  6524. return this._normals;
  6525. };
  6526. /**
  6527. * Returns an array populated with binormal vectors on each Path3D curve point.
  6528. */
  6529. Path3D.prototype.getBinormals = function () {
  6530. return this._binormals;
  6531. };
  6532. /**
  6533. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6534. */
  6535. Path3D.prototype.getDistances = function () {
  6536. return this._distances;
  6537. };
  6538. /**
  6539. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6540. * Returns the same object updated.
  6541. */
  6542. Path3D.prototype.update = function (path, firstNormal) {
  6543. if (firstNormal === void 0) { firstNormal = null; }
  6544. for (var p = 0; p < path.length; p++) {
  6545. this._curve[p].x = path[p].x;
  6546. this._curve[p].y = path[p].y;
  6547. this._curve[p].z = path[p].z;
  6548. }
  6549. this._compute(firstNormal);
  6550. return this;
  6551. };
  6552. // private function compute() : computes tangents, normals and binormals
  6553. Path3D.prototype._compute = function (firstNormal) {
  6554. var l = this._curve.length;
  6555. // first and last tangents
  6556. this._tangents[0] = this._getFirstNonNullVector(0);
  6557. if (!this._raw) {
  6558. this._tangents[0].normalize();
  6559. }
  6560. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6561. if (!this._raw) {
  6562. this._tangents[l - 1].normalize();
  6563. }
  6564. // normals and binormals at first point : arbitrary vector with _normalVector()
  6565. var tg0 = this._tangents[0];
  6566. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6567. this._normals[0] = pp0;
  6568. if (!this._raw) {
  6569. this._normals[0].normalize();
  6570. }
  6571. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6572. if (!this._raw) {
  6573. this._binormals[0].normalize();
  6574. }
  6575. this._distances[0] = 0.0;
  6576. // normals and binormals : next points
  6577. var prev; // previous vector (segment)
  6578. var cur; // current vector (segment)
  6579. var curTang; // current tangent
  6580. // previous normal
  6581. var prevBinor; // previous binormal
  6582. for (var i = 1; i < l; i++) {
  6583. // tangents
  6584. prev = this._getLastNonNullVector(i);
  6585. if (i < l - 1) {
  6586. cur = this._getFirstNonNullVector(i);
  6587. this._tangents[i] = prev.add(cur);
  6588. this._tangents[i].normalize();
  6589. }
  6590. this._distances[i] = this._distances[i - 1] + prev.length();
  6591. // normals and binormals
  6592. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6593. curTang = this._tangents[i];
  6594. prevBinor = this._binormals[i - 1];
  6595. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6596. if (!this._raw) {
  6597. this._normals[i].normalize();
  6598. }
  6599. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6600. if (!this._raw) {
  6601. this._binormals[i].normalize();
  6602. }
  6603. }
  6604. };
  6605. // private function getFirstNonNullVector(index)
  6606. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6607. Path3D.prototype._getFirstNonNullVector = function (index) {
  6608. var i = 1;
  6609. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6610. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6611. i++;
  6612. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6613. }
  6614. return nNVector;
  6615. };
  6616. // private function getLastNonNullVector(index)
  6617. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6618. Path3D.prototype._getLastNonNullVector = function (index) {
  6619. var i = 1;
  6620. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6621. while (nLVector.length() === 0 && index > i + 1) {
  6622. i++;
  6623. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6624. }
  6625. return nLVector;
  6626. };
  6627. // private function normalVector(v0, vt, va) :
  6628. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6629. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6630. Path3D.prototype._normalVector = function (v0, vt, va) {
  6631. var normal0;
  6632. var tgl = vt.length();
  6633. if (tgl === 0.0) {
  6634. tgl = 1.0;
  6635. }
  6636. if (va === undefined || va === null) {
  6637. var point;
  6638. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6639. point = new Vector3(0.0, -1.0, 0.0);
  6640. }
  6641. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6642. point = new Vector3(1.0, 0.0, 0.0);
  6643. }
  6644. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6645. point = new Vector3(0.0, 0.0, 1.0);
  6646. }
  6647. else {
  6648. point = Vector3.Zero();
  6649. }
  6650. normal0 = Vector3.Cross(vt, point);
  6651. }
  6652. else {
  6653. normal0 = Vector3.Cross(vt, va);
  6654. Vector3.CrossToRef(normal0, vt, normal0);
  6655. }
  6656. normal0.normalize();
  6657. return normal0;
  6658. };
  6659. return Path3D;
  6660. }());
  6661. BABYLON.Path3D = Path3D;
  6662. var Curve3 = /** @class */ (function () {
  6663. /**
  6664. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6665. * A Curve3 is designed from a series of successive Vector3.
  6666. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6667. */
  6668. function Curve3(points) {
  6669. this._length = 0.0;
  6670. this._points = points;
  6671. this._length = this._computeLength(points);
  6672. }
  6673. /**
  6674. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6675. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6676. * @param v1 (Vector3) the control point
  6677. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6678. * @param nbPoints (integer) the wanted number of points in the curve
  6679. */
  6680. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6681. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6682. var bez = new Array();
  6683. var equation = function (t, val0, val1, val2) {
  6684. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6685. return res;
  6686. };
  6687. for (var i = 0; i <= nbPoints; i++) {
  6688. 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)));
  6689. }
  6690. return new Curve3(bez);
  6691. };
  6692. /**
  6693. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6694. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6695. * @param v1 (Vector3) the first control point
  6696. * @param v2 (Vector3) the second control point
  6697. * @param v3 (Vector3) the end point of the Cubic Bezier
  6698. * @param nbPoints (integer) the wanted number of points in the curve
  6699. */
  6700. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6701. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6702. var bez = new Array();
  6703. var equation = function (t, val0, val1, val2, val3) {
  6704. 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;
  6705. return res;
  6706. };
  6707. for (var i = 0; i <= nbPoints; i++) {
  6708. 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)));
  6709. }
  6710. return new Curve3(bez);
  6711. };
  6712. /**
  6713. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6714. * @param p1 (Vector3) the origin point of the Hermite Spline
  6715. * @param t1 (Vector3) the tangent vector at the origin point
  6716. * @param p2 (Vector3) the end point of the Hermite Spline
  6717. * @param t2 (Vector3) the tangent vector at the end point
  6718. * @param nbPoints (integer) the wanted number of points in the curve
  6719. */
  6720. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6721. var hermite = new Array();
  6722. var step = 1.0 / nbPoints;
  6723. for (var i = 0; i <= nbPoints; i++) {
  6724. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6725. }
  6726. return new Curve3(hermite);
  6727. };
  6728. /**
  6729. * Returns a Curve3 object along a CatmullRom Spline curve :
  6730. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6731. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6732. */
  6733. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6734. var totalPoints = new Array();
  6735. totalPoints.push(points[0].clone());
  6736. Array.prototype.push.apply(totalPoints, points);
  6737. totalPoints.push(points[points.length - 1].clone());
  6738. var catmullRom = new Array();
  6739. var step = 1.0 / nbPoints;
  6740. var amount = 0.0;
  6741. for (var i = 0; i < totalPoints.length - 3; i++) {
  6742. amount = 0;
  6743. for (var c = 0; c < nbPoints; c++) {
  6744. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6745. amount += step;
  6746. }
  6747. }
  6748. i--;
  6749. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6750. return new Curve3(catmullRom);
  6751. };
  6752. /**
  6753. * Returns the Curve3 stored array of successive Vector3
  6754. */
  6755. Curve3.prototype.getPoints = function () {
  6756. return this._points;
  6757. };
  6758. /**
  6759. * Returns the computed length (float) of the curve.
  6760. */
  6761. Curve3.prototype.length = function () {
  6762. return this._length;
  6763. };
  6764. /**
  6765. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6766. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6767. * curveA and curveB keep unchanged.
  6768. */
  6769. Curve3.prototype.continue = function (curve) {
  6770. var lastPoint = this._points[this._points.length - 1];
  6771. var continuedPoints = this._points.slice();
  6772. var curvePoints = curve.getPoints();
  6773. for (var i = 1; i < curvePoints.length; i++) {
  6774. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6775. }
  6776. var continuedCurve = new Curve3(continuedPoints);
  6777. return continuedCurve;
  6778. };
  6779. Curve3.prototype._computeLength = function (path) {
  6780. var l = 0;
  6781. for (var i = 1; i < path.length; i++) {
  6782. l += (path[i].subtract(path[i - 1])).length();
  6783. }
  6784. return l;
  6785. };
  6786. return Curve3;
  6787. }());
  6788. BABYLON.Curve3 = Curve3;
  6789. // Vertex formats
  6790. var PositionNormalVertex = /** @class */ (function () {
  6791. function PositionNormalVertex(position, normal) {
  6792. if (position === void 0) { position = Vector3.Zero(); }
  6793. if (normal === void 0) { normal = Vector3.Up(); }
  6794. this.position = position;
  6795. this.normal = normal;
  6796. }
  6797. PositionNormalVertex.prototype.clone = function () {
  6798. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6799. };
  6800. return PositionNormalVertex;
  6801. }());
  6802. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6803. var PositionNormalTextureVertex = /** @class */ (function () {
  6804. function PositionNormalTextureVertex(position, normal, uv) {
  6805. if (position === void 0) { position = Vector3.Zero(); }
  6806. if (normal === void 0) { normal = Vector3.Up(); }
  6807. if (uv === void 0) { uv = Vector2.Zero(); }
  6808. this.position = position;
  6809. this.normal = normal;
  6810. this.uv = uv;
  6811. }
  6812. PositionNormalTextureVertex.prototype.clone = function () {
  6813. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6814. };
  6815. return PositionNormalTextureVertex;
  6816. }());
  6817. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6818. // Temporary pre-allocated objects for engine internal use
  6819. // usage in any internal function :
  6820. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6821. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6822. var Tmp = /** @class */ (function () {
  6823. function Tmp() {
  6824. }
  6825. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6826. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6827. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6828. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6829. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6830. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6831. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6832. Matrix.Zero(), Matrix.Zero(),
  6833. Matrix.Zero(), Matrix.Zero(),
  6834. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6835. return Tmp;
  6836. }());
  6837. BABYLON.Tmp = Tmp;
  6838. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6839. var MathTmp = /** @class */ (function () {
  6840. function MathTmp() {
  6841. }
  6842. MathTmp.Vector3 = [Vector3.Zero()];
  6843. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6844. MathTmp.Quaternion = [Quaternion.Zero()];
  6845. return MathTmp;
  6846. }());
  6847. })(BABYLON || (BABYLON = {}));
  6848. //# sourceMappingURL=babylon.math.js.map
  6849. "use strict";
  6850. var BABYLON;
  6851. (function (BABYLON) {
  6852. var Scalar = /** @class */ (function () {
  6853. function Scalar() {
  6854. }
  6855. /**
  6856. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6857. */
  6858. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6859. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6860. var num = a - b;
  6861. return -epsilon <= num && num <= epsilon;
  6862. };
  6863. /**
  6864. * Returns a string : the upper case translation of the number i to hexadecimal.
  6865. */
  6866. Scalar.ToHex = function (i) {
  6867. var str = i.toString(16);
  6868. if (i <= 15) {
  6869. return ("0" + str).toUpperCase();
  6870. }
  6871. return str.toUpperCase();
  6872. };
  6873. /**
  6874. * Returns -1 if value is negative and +1 is value is positive.
  6875. * Returns the value itself if it's equal to zero.
  6876. */
  6877. Scalar.Sign = function (value) {
  6878. value = +value; // convert to a number
  6879. if (value === 0 || isNaN(value))
  6880. return value;
  6881. return value > 0 ? 1 : -1;
  6882. };
  6883. /**
  6884. * Returns the value itself if it's between min and max.
  6885. * Returns min if the value is lower than min.
  6886. * Returns max if the value is greater than max.
  6887. */
  6888. Scalar.Clamp = function (value, min, max) {
  6889. if (min === void 0) { min = 0; }
  6890. if (max === void 0) { max = 1; }
  6891. return Math.min(max, Math.max(min, value));
  6892. };
  6893. /**
  6894. * Returns the log2 of value.
  6895. */
  6896. Scalar.Log2 = function (value) {
  6897. return Math.log(value) * Math.LOG2E;
  6898. };
  6899. /**
  6900. * Loops the value, so that it is never larger than length and never smaller than 0.
  6901. *
  6902. * This is similar to the modulo operator but it works with floating point numbers.
  6903. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6904. * With t = 5 and length = 2.5, the result would be 0.0.
  6905. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6906. */
  6907. Scalar.Repeat = function (value, length) {
  6908. return value - Math.floor(value / length) * length;
  6909. };
  6910. /**
  6911. * Normalize the value between 0.0 and 1.0 using min and max values
  6912. */
  6913. Scalar.Normalize = function (value, min, max) {
  6914. return (value - min) / (max - min);
  6915. };
  6916. /**
  6917. * Denormalize the value from 0.0 and 1.0 using min and max values
  6918. */
  6919. Scalar.Denormalize = function (normalized, min, max) {
  6920. return (normalized * (max - min) + min);
  6921. };
  6922. /**
  6923. * Calculates the shortest difference between two given angles given in degrees.
  6924. */
  6925. Scalar.DeltaAngle = function (current, target) {
  6926. var num = Scalar.Repeat(target - current, 360.0);
  6927. if (num > 180.0) {
  6928. num -= 360.0;
  6929. }
  6930. return num;
  6931. };
  6932. /**
  6933. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6934. *
  6935. * The returned value will move back and forth between 0 and length
  6936. */
  6937. Scalar.PingPong = function (tx, length) {
  6938. var t = Scalar.Repeat(tx, length * 2.0);
  6939. return length - Math.abs(t - length);
  6940. };
  6941. /**
  6942. * Interpolates between min and max with smoothing at the limits.
  6943. *
  6944. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6945. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6946. */
  6947. Scalar.SmoothStep = function (from, to, tx) {
  6948. var t = Scalar.Clamp(tx);
  6949. t = -2.0 * t * t * t + 3.0 * t * t;
  6950. return to * t + from * (1.0 - t);
  6951. };
  6952. /**
  6953. * Moves a value current towards target.
  6954. *
  6955. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6956. * Negative values of maxDelta pushes the value away from target.
  6957. */
  6958. Scalar.MoveTowards = function (current, target, maxDelta) {
  6959. var result = 0;
  6960. if (Math.abs(target - current) <= maxDelta) {
  6961. result = target;
  6962. }
  6963. else {
  6964. result = current + Scalar.Sign(target - current) * maxDelta;
  6965. }
  6966. return result;
  6967. };
  6968. /**
  6969. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6970. *
  6971. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6972. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6973. */
  6974. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6975. var num = Scalar.DeltaAngle(current, target);
  6976. var result = 0;
  6977. if (-maxDelta < num && num < maxDelta) {
  6978. result = target;
  6979. }
  6980. else {
  6981. target = current + num;
  6982. result = Scalar.MoveTowards(current, target, maxDelta);
  6983. }
  6984. return result;
  6985. };
  6986. /**
  6987. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6988. */
  6989. Scalar.Lerp = function (start, end, amount) {
  6990. return start + ((end - start) * amount);
  6991. };
  6992. /**
  6993. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6994. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6995. */
  6996. Scalar.LerpAngle = function (start, end, amount) {
  6997. var num = Scalar.Repeat(end - start, 360.0);
  6998. if (num > 180.0) {
  6999. num -= 360.0;
  7000. }
  7001. return start + num * Scalar.Clamp(amount);
  7002. };
  7003. /**
  7004. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7005. */
  7006. Scalar.InverseLerp = function (a, b, value) {
  7007. var result = 0;
  7008. if (a != b) {
  7009. result = Scalar.Clamp((value - a) / (b - a));
  7010. }
  7011. else {
  7012. result = 0.0;
  7013. }
  7014. return result;
  7015. };
  7016. /**
  7017. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7018. */
  7019. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7020. var squared = amount * amount;
  7021. var cubed = amount * squared;
  7022. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7023. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7024. var part3 = (cubed - (2.0 * squared)) + amount;
  7025. var part4 = cubed - squared;
  7026. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7027. };
  7028. /**
  7029. * Returns a random float number between and min and max values
  7030. */
  7031. Scalar.RandomRange = function (min, max) {
  7032. if (min === max)
  7033. return min;
  7034. return ((Math.random() * (max - min)) + min);
  7035. };
  7036. /**
  7037. * This function returns percentage of a number in a given range.
  7038. *
  7039. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7040. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7041. */
  7042. Scalar.RangeToPercent = function (number, min, max) {
  7043. return ((number - min) / (max - min));
  7044. };
  7045. /**
  7046. * This function returns number that corresponds to the percentage in a given range.
  7047. *
  7048. * PercentToRange(0.34,0,100) will return 34.
  7049. */
  7050. Scalar.PercentToRange = function (percent, min, max) {
  7051. return ((max - min) * percent + min);
  7052. };
  7053. /**
  7054. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7055. * @param angle The angle to normalize in radian.
  7056. * @return The converted angle.
  7057. */
  7058. Scalar.NormalizeRadians = function (angle) {
  7059. // More precise but slower version kept for reference.
  7060. // angle = angle % Tools.TwoPi;
  7061. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7062. //if (angle > Math.PI) {
  7063. // angle -= Tools.TwoPi;
  7064. //}
  7065. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7066. return angle;
  7067. };
  7068. /**
  7069. * Two pi constants convenient for computation.
  7070. */
  7071. Scalar.TwoPi = Math.PI * 2;
  7072. return Scalar;
  7073. }());
  7074. BABYLON.Scalar = Scalar;
  7075. })(BABYLON || (BABYLON = {}));
  7076. //# sourceMappingURL=babylon.math.scalar.js.map
  7077. "use strict";
  7078. //# sourceMappingURL=babylon.mixins.js.map
  7079. "use strict";
  7080. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7081. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7082. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7083. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7084. //# sourceMappingURL=babylon.webgl2.js.map
  7085. "use strict";
  7086. var BABYLON;
  7087. (function (BABYLON) {
  7088. var __decoratorInitialStore = {};
  7089. var __mergedStore = {};
  7090. var _copySource = function (creationFunction, source, instanciate) {
  7091. var destination = creationFunction();
  7092. // Tags
  7093. if (BABYLON.Tags) {
  7094. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7095. }
  7096. var classStore = getMergedStore(destination);
  7097. // Properties
  7098. for (var property in classStore) {
  7099. var propertyDescriptor = classStore[property];
  7100. var sourceProperty = source[property];
  7101. var propertyType = propertyDescriptor.type;
  7102. if (sourceProperty !== undefined && sourceProperty !== null) {
  7103. switch (propertyType) {
  7104. case 0: // Value
  7105. case 6:// Mesh reference
  7106. destination[property] = sourceProperty;
  7107. break;
  7108. case 1:// Texture
  7109. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7110. break;
  7111. case 2: // Color3
  7112. case 3: // FresnelParameters
  7113. case 4: // Vector2
  7114. case 5: // Vector3
  7115. case 7: // Color Curves
  7116. case 10:// Quaternion
  7117. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7118. break;
  7119. }
  7120. }
  7121. }
  7122. return destination;
  7123. };
  7124. function getDirectStore(target) {
  7125. var classKey = target.getClassName();
  7126. if (!__decoratorInitialStore[classKey]) {
  7127. __decoratorInitialStore[classKey] = {};
  7128. }
  7129. return __decoratorInitialStore[classKey];
  7130. }
  7131. /**
  7132. * Return the list of properties flagged as serializable
  7133. * @param target: host object
  7134. */
  7135. function getMergedStore(target) {
  7136. var classKey = target.getClassName();
  7137. if (__mergedStore[classKey]) {
  7138. return __mergedStore[classKey];
  7139. }
  7140. __mergedStore[classKey] = {};
  7141. var store = __mergedStore[classKey];
  7142. var currentTarget = target;
  7143. var currentKey = classKey;
  7144. while (currentKey) {
  7145. var initialStore = __decoratorInitialStore[currentKey];
  7146. for (var property in initialStore) {
  7147. store[property] = initialStore[property];
  7148. }
  7149. var parent_1 = void 0;
  7150. var done = false;
  7151. do {
  7152. parent_1 = Object.getPrototypeOf(currentTarget);
  7153. if (!parent_1.getClassName) {
  7154. done = true;
  7155. break;
  7156. }
  7157. if (parent_1.getClassName() !== currentKey) {
  7158. break;
  7159. }
  7160. currentTarget = parent_1;
  7161. } while (parent_1);
  7162. if (done) {
  7163. break;
  7164. }
  7165. currentKey = parent_1.getClassName();
  7166. currentTarget = parent_1;
  7167. }
  7168. return store;
  7169. }
  7170. function generateSerializableMember(type, sourceName) {
  7171. return function (target, propertyKey) {
  7172. var classStore = getDirectStore(target);
  7173. if (!classStore[propertyKey]) {
  7174. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7175. }
  7176. };
  7177. }
  7178. function generateExpandMember(setCallback, targetKey) {
  7179. if (targetKey === void 0) { targetKey = null; }
  7180. return function (target, propertyKey) {
  7181. var key = targetKey || ("_" + propertyKey);
  7182. Object.defineProperty(target, propertyKey, {
  7183. get: function () {
  7184. return this[key];
  7185. },
  7186. set: function (value) {
  7187. if (this[key] === value) {
  7188. return;
  7189. }
  7190. this[key] = value;
  7191. target[setCallback].apply(this);
  7192. },
  7193. enumerable: true,
  7194. configurable: true
  7195. });
  7196. };
  7197. }
  7198. function expandToProperty(callback, targetKey) {
  7199. if (targetKey === void 0) { targetKey = null; }
  7200. return generateExpandMember(callback, targetKey);
  7201. }
  7202. BABYLON.expandToProperty = expandToProperty;
  7203. function serialize(sourceName) {
  7204. return generateSerializableMember(0, sourceName); // value member
  7205. }
  7206. BABYLON.serialize = serialize;
  7207. function serializeAsTexture(sourceName) {
  7208. return generateSerializableMember(1, sourceName); // texture member
  7209. }
  7210. BABYLON.serializeAsTexture = serializeAsTexture;
  7211. function serializeAsColor3(sourceName) {
  7212. return generateSerializableMember(2, sourceName); // color3 member
  7213. }
  7214. BABYLON.serializeAsColor3 = serializeAsColor3;
  7215. function serializeAsFresnelParameters(sourceName) {
  7216. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7217. }
  7218. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7219. function serializeAsVector2(sourceName) {
  7220. return generateSerializableMember(4, sourceName); // vector2 member
  7221. }
  7222. BABYLON.serializeAsVector2 = serializeAsVector2;
  7223. function serializeAsVector3(sourceName) {
  7224. return generateSerializableMember(5, sourceName); // vector3 member
  7225. }
  7226. BABYLON.serializeAsVector3 = serializeAsVector3;
  7227. function serializeAsMeshReference(sourceName) {
  7228. return generateSerializableMember(6, sourceName); // mesh reference member
  7229. }
  7230. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7231. function serializeAsColorCurves(sourceName) {
  7232. return generateSerializableMember(7, sourceName); // color curves
  7233. }
  7234. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7235. function serializeAsColor4(sourceName) {
  7236. return generateSerializableMember(8, sourceName); // color 4
  7237. }
  7238. BABYLON.serializeAsColor4 = serializeAsColor4;
  7239. function serializeAsImageProcessingConfiguration(sourceName) {
  7240. return generateSerializableMember(9, sourceName); // image processing
  7241. }
  7242. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7243. function serializeAsQuaternion(sourceName) {
  7244. return generateSerializableMember(10, sourceName); // quaternion member
  7245. }
  7246. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7247. var SerializationHelper = /** @class */ (function () {
  7248. function SerializationHelper() {
  7249. }
  7250. SerializationHelper.Serialize = function (entity, serializationObject) {
  7251. if (!serializationObject) {
  7252. serializationObject = {};
  7253. }
  7254. // Tags
  7255. if (BABYLON.Tags) {
  7256. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7257. }
  7258. var serializedProperties = getMergedStore(entity);
  7259. // Properties
  7260. for (var property in serializedProperties) {
  7261. var propertyDescriptor = serializedProperties[property];
  7262. var targetPropertyName = propertyDescriptor.sourceName || property;
  7263. var propertyType = propertyDescriptor.type;
  7264. var sourceProperty = entity[property];
  7265. if (sourceProperty !== undefined && sourceProperty !== null) {
  7266. switch (propertyType) {
  7267. case 0:// Value
  7268. serializationObject[targetPropertyName] = sourceProperty;
  7269. break;
  7270. case 1:// Texture
  7271. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7272. break;
  7273. case 2:// Color3
  7274. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7275. break;
  7276. case 3:// FresnelParameters
  7277. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7278. break;
  7279. case 4:// Vector2
  7280. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7281. break;
  7282. case 5:// Vector3
  7283. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7284. break;
  7285. case 6:// Mesh reference
  7286. serializationObject[targetPropertyName] = sourceProperty.id;
  7287. break;
  7288. case 7:// Color Curves
  7289. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7290. break;
  7291. case 8:// Color 4
  7292. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7293. break;
  7294. case 9:// Image Processing
  7295. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7296. break;
  7297. }
  7298. }
  7299. }
  7300. return serializationObject;
  7301. };
  7302. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7303. if (rootUrl === void 0) { rootUrl = null; }
  7304. var destination = creationFunction();
  7305. if (!rootUrl) {
  7306. rootUrl = "";
  7307. }
  7308. // Tags
  7309. if (BABYLON.Tags) {
  7310. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7311. }
  7312. var classStore = getMergedStore(destination);
  7313. // Properties
  7314. for (var property in classStore) {
  7315. var propertyDescriptor = classStore[property];
  7316. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7317. var propertyType = propertyDescriptor.type;
  7318. if (sourceProperty !== undefined && sourceProperty !== null) {
  7319. var dest = destination;
  7320. switch (propertyType) {
  7321. case 0:// Value
  7322. dest[property] = sourceProperty;
  7323. break;
  7324. case 1:// Texture
  7325. if (scene) {
  7326. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7327. }
  7328. break;
  7329. case 2:// Color3
  7330. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7331. break;
  7332. case 3:// FresnelParameters
  7333. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7334. break;
  7335. case 4:// Vector2
  7336. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7337. break;
  7338. case 5:// Vector3
  7339. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7340. break;
  7341. case 6:// Mesh reference
  7342. if (scene) {
  7343. dest[property] = scene.getLastMeshByID(sourceProperty);
  7344. }
  7345. break;
  7346. case 7:// Color Curves
  7347. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7348. break;
  7349. case 8:// Color 4
  7350. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7351. break;
  7352. case 9:// Image Processing
  7353. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7354. break;
  7355. }
  7356. }
  7357. }
  7358. return destination;
  7359. };
  7360. SerializationHelper.Clone = function (creationFunction, source) {
  7361. return _copySource(creationFunction, source, false);
  7362. };
  7363. SerializationHelper.Instanciate = function (creationFunction, source) {
  7364. return _copySource(creationFunction, source, true);
  7365. };
  7366. return SerializationHelper;
  7367. }());
  7368. BABYLON.SerializationHelper = SerializationHelper;
  7369. })(BABYLON || (BABYLON = {}));
  7370. //# sourceMappingURL=babylon.decorators.js.map
  7371. "use strict";
  7372. var BABYLON;
  7373. (function (BABYLON) {
  7374. /**
  7375. * Wrapper class for promise with external resolve and reject.
  7376. */
  7377. var Deferred = /** @class */ (function () {
  7378. /**
  7379. * Constructor for this deferred object.
  7380. */
  7381. function Deferred() {
  7382. var _this = this;
  7383. this.promise = new Promise(function (resolve, reject) {
  7384. _this._resolve = resolve;
  7385. _this._reject = reject;
  7386. });
  7387. }
  7388. Object.defineProperty(Deferred.prototype, "resolve", {
  7389. /**
  7390. * The resolve method of the promise associated with this deferred object.
  7391. */
  7392. get: function () {
  7393. return this._resolve;
  7394. },
  7395. enumerable: true,
  7396. configurable: true
  7397. });
  7398. Object.defineProperty(Deferred.prototype, "reject", {
  7399. /**
  7400. * The reject method of the promise associated with this deferred object.
  7401. */
  7402. get: function () {
  7403. return this._reject;
  7404. },
  7405. enumerable: true,
  7406. configurable: true
  7407. });
  7408. return Deferred;
  7409. }());
  7410. BABYLON.Deferred = Deferred;
  7411. })(BABYLON || (BABYLON = {}));
  7412. //# sourceMappingURL=babylon.deferred.js.map
  7413. "use strict";
  7414. var BABYLON;
  7415. (function (BABYLON) {
  7416. /**
  7417. * A class serves as a medium between the observable and its observers
  7418. */
  7419. var EventState = /** @class */ (function () {
  7420. /**
  7421. * Create a new EventState
  7422. * @param mask defines the mask associated with this state
  7423. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7424. * @param target defines the original target of the state
  7425. * @param currentTarget defines the current target of the state
  7426. */
  7427. function EventState(mask, skipNextObservers, target, currentTarget) {
  7428. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7429. this.initalize(mask, skipNextObservers, target, currentTarget);
  7430. }
  7431. /**
  7432. * Initialize the current event state
  7433. * @param mask defines the mask associated with this state
  7434. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7435. * @param target defines the original target of the state
  7436. * @param currentTarget defines the current target of the state
  7437. * @returns the current event state
  7438. */
  7439. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7440. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7441. this.mask = mask;
  7442. this.skipNextObservers = skipNextObservers;
  7443. this.target = target;
  7444. this.currentTarget = currentTarget;
  7445. return this;
  7446. };
  7447. return EventState;
  7448. }());
  7449. BABYLON.EventState = EventState;
  7450. /**
  7451. * Represent an Observer registered to a given Observable object.
  7452. */
  7453. var Observer = /** @class */ (function () {
  7454. /**
  7455. * Creates a new observer
  7456. * @param callback defines the callback to call when the observer is notified
  7457. * @param mask defines the mask of the observer (used to filter notifications)
  7458. * @param scope defines the current scope used to restore the JS context
  7459. */
  7460. function Observer(
  7461. /**
  7462. * Defines the callback to call when the observer is notified
  7463. */
  7464. callback,
  7465. /**
  7466. * Defines the mask of the observer (used to filter notifications)
  7467. */
  7468. mask,
  7469. /**
  7470. * Defines the current scope used to restore the JS context
  7471. */
  7472. scope) {
  7473. if (scope === void 0) { scope = null; }
  7474. this.callback = callback;
  7475. this.mask = mask;
  7476. this.scope = scope;
  7477. /** @ignore */
  7478. this._willBeUnregistered = false;
  7479. /**
  7480. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7481. */
  7482. this.unregisterOnNextCall = false;
  7483. }
  7484. return Observer;
  7485. }());
  7486. BABYLON.Observer = Observer;
  7487. /**
  7488. * Represent a list of observers registered to multiple Observables object.
  7489. */
  7490. var MultiObserver = /** @class */ (function () {
  7491. function MultiObserver() {
  7492. }
  7493. /**
  7494. * Release associated resources
  7495. */
  7496. MultiObserver.prototype.dispose = function () {
  7497. if (this._observers && this._observables) {
  7498. for (var index = 0; index < this._observers.length; index++) {
  7499. this._observables[index].remove(this._observers[index]);
  7500. }
  7501. }
  7502. this._observers = null;
  7503. this._observables = null;
  7504. };
  7505. /**
  7506. * Raise a callback when one of the observable will notify
  7507. * @param observables defines a list of observables to watch
  7508. * @param callback defines the callback to call on notification
  7509. * @param mask defines the mask used to filter notifications
  7510. * @param scope defines the current scope used to restore the JS context
  7511. * @returns the new MultiObserver
  7512. */
  7513. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7514. if (mask === void 0) { mask = -1; }
  7515. if (scope === void 0) { scope = null; }
  7516. var result = new MultiObserver();
  7517. result._observers = new Array();
  7518. result._observables = observables;
  7519. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7520. var observable = observables_1[_i];
  7521. var observer = observable.add(callback, mask, false, scope);
  7522. if (observer) {
  7523. result._observers.push(observer);
  7524. }
  7525. }
  7526. return result;
  7527. };
  7528. return MultiObserver;
  7529. }());
  7530. BABYLON.MultiObserver = MultiObserver;
  7531. /**
  7532. * The Observable class is a simple implementation of the Observable pattern.
  7533. * 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.
  7534. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7535. * 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).
  7536. * 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.
  7537. */
  7538. var Observable = /** @class */ (function () {
  7539. /**
  7540. * Creates a new observable
  7541. * @param onObserverAdded defines a callback to call when a new observer is added
  7542. */
  7543. function Observable(onObserverAdded) {
  7544. this._observers = new Array();
  7545. this._eventState = new EventState(0);
  7546. if (onObserverAdded) {
  7547. this._onObserverAdded = onObserverAdded;
  7548. }
  7549. }
  7550. /**
  7551. * Create a new Observer with the specified callback
  7552. * @param callback the callback that will be executed for that Observer
  7553. * @param mask the mask used to filter observers
  7554. * @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.
  7555. * @param scope optional scope for the callback to be called from
  7556. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7557. * @returns the new observer created for the callback
  7558. */
  7559. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7560. if (mask === void 0) { mask = -1; }
  7561. if (insertFirst === void 0) { insertFirst = false; }
  7562. if (scope === void 0) { scope = null; }
  7563. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7564. if (!callback) {
  7565. return null;
  7566. }
  7567. var observer = new Observer(callback, mask, scope);
  7568. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7569. if (insertFirst) {
  7570. this._observers.unshift(observer);
  7571. }
  7572. else {
  7573. this._observers.push(observer);
  7574. }
  7575. if (this._onObserverAdded) {
  7576. this._onObserverAdded(observer);
  7577. }
  7578. return observer;
  7579. };
  7580. /**
  7581. * Remove an Observer from the Observable object
  7582. * @param observer the instance of the Observer to remove
  7583. * @returns false if it doesn't belong to this Observable
  7584. */
  7585. Observable.prototype.remove = function (observer) {
  7586. if (!observer) {
  7587. return false;
  7588. }
  7589. var index = this._observers.indexOf(observer);
  7590. if (index !== -1) {
  7591. this._observers.splice(index, 1);
  7592. return true;
  7593. }
  7594. return false;
  7595. };
  7596. /**
  7597. * Remove a callback from the Observable object
  7598. * @param callback the callback to remove
  7599. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7600. * @returns false if it doesn't belong to this Observable
  7601. */
  7602. Observable.prototype.removeCallback = function (callback, scope) {
  7603. for (var index = 0; index < this._observers.length; index++) {
  7604. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7605. this._observers.splice(index, 1);
  7606. return true;
  7607. }
  7608. }
  7609. return false;
  7610. };
  7611. Observable.prototype._deferUnregister = function (observer) {
  7612. var _this = this;
  7613. observer.unregisterOnNextCall = false;
  7614. observer._willBeUnregistered = true;
  7615. BABYLON.Tools.SetImmediate(function () {
  7616. _this.remove(observer);
  7617. });
  7618. };
  7619. /**
  7620. * Notify all Observers by calling their respective callback with the given data
  7621. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7622. * @param eventData defines the data to send to all observers
  7623. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7624. * @param target defines the original target of the state
  7625. * @param currentTarget defines the current target of the state
  7626. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7627. */
  7628. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7629. if (mask === void 0) { mask = -1; }
  7630. if (!this._observers.length) {
  7631. return true;
  7632. }
  7633. var state = this._eventState;
  7634. state.mask = mask;
  7635. state.target = target;
  7636. state.currentTarget = currentTarget;
  7637. state.skipNextObservers = false;
  7638. state.lastReturnValue = eventData;
  7639. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7640. var obs = _a[_i];
  7641. if (obs._willBeUnregistered) {
  7642. continue;
  7643. }
  7644. if (obs.mask & mask) {
  7645. if (obs.scope) {
  7646. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7647. }
  7648. else {
  7649. state.lastReturnValue = obs.callback(eventData, state);
  7650. }
  7651. if (obs.unregisterOnNextCall) {
  7652. this._deferUnregister(obs);
  7653. }
  7654. }
  7655. if (state.skipNextObservers) {
  7656. return false;
  7657. }
  7658. }
  7659. return true;
  7660. };
  7661. /**
  7662. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7663. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7664. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7665. * and it is crucial that all callbacks will be executed.
  7666. * The order of the callbacks is kept, callbacks are not executed parallel.
  7667. *
  7668. * @param eventData The data to be sent to each callback
  7669. * @param mask is used to filter observers defaults to -1
  7670. * @param target defines the callback target (see EventState)
  7671. * @param currentTarget defines he current object in the bubbling phase
  7672. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7673. */
  7674. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7675. var _this = this;
  7676. if (mask === void 0) { mask = -1; }
  7677. // create an empty promise
  7678. var p = Promise.resolve(eventData);
  7679. // no observers? return this promise.
  7680. if (!this._observers.length) {
  7681. return p;
  7682. }
  7683. var state = this._eventState;
  7684. state.mask = mask;
  7685. state.target = target;
  7686. state.currentTarget = currentTarget;
  7687. state.skipNextObservers = false;
  7688. // execute one callback after another (not using Promise.all, the order is important)
  7689. this._observers.forEach(function (obs) {
  7690. if (state.skipNextObservers) {
  7691. return;
  7692. }
  7693. if (obs._willBeUnregistered) {
  7694. return;
  7695. }
  7696. if (obs.mask & mask) {
  7697. if (obs.scope) {
  7698. p = p.then(function (lastReturnedValue) {
  7699. state.lastReturnValue = lastReturnedValue;
  7700. return obs.callback.apply(obs.scope, [eventData, state]);
  7701. });
  7702. }
  7703. else {
  7704. p = p.then(function (lastReturnedValue) {
  7705. state.lastReturnValue = lastReturnedValue;
  7706. return obs.callback(eventData, state);
  7707. });
  7708. }
  7709. if (obs.unregisterOnNextCall) {
  7710. _this._deferUnregister(obs);
  7711. }
  7712. }
  7713. });
  7714. // return the eventData
  7715. return p.then(function () { return eventData; });
  7716. };
  7717. /**
  7718. * Notify a specific observer
  7719. * @param observer defines the observer to notify
  7720. * @param eventData defines the data to be sent to each callback
  7721. * @param mask is used to filter observers defaults to -1
  7722. */
  7723. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7724. if (mask === void 0) { mask = -1; }
  7725. var state = this._eventState;
  7726. state.mask = mask;
  7727. state.skipNextObservers = false;
  7728. observer.callback(eventData, state);
  7729. };
  7730. /**
  7731. * Gets a boolean indicating if the observable has at least one observer
  7732. * @returns true is the Observable has at least one Observer registered
  7733. */
  7734. Observable.prototype.hasObservers = function () {
  7735. return this._observers.length > 0;
  7736. };
  7737. /**
  7738. * Clear the list of observers
  7739. */
  7740. Observable.prototype.clear = function () {
  7741. this._observers = new Array();
  7742. this._onObserverAdded = null;
  7743. };
  7744. /**
  7745. * Clone the current observable
  7746. * @returns a new observable
  7747. */
  7748. Observable.prototype.clone = function () {
  7749. var result = new Observable();
  7750. result._observers = this._observers.slice(0);
  7751. return result;
  7752. };
  7753. /**
  7754. * Does this observable handles observer registered with a given mask
  7755. * @param mask defines the mask to be tested
  7756. * @return whether or not one observer registered with the given mask is handeled
  7757. **/
  7758. Observable.prototype.hasSpecificMask = function (mask) {
  7759. if (mask === void 0) { mask = -1; }
  7760. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7761. var obs = _a[_i];
  7762. if (obs.mask & mask || obs.mask === mask) {
  7763. return true;
  7764. }
  7765. }
  7766. return false;
  7767. };
  7768. return Observable;
  7769. }());
  7770. BABYLON.Observable = Observable;
  7771. })(BABYLON || (BABYLON = {}));
  7772. //# sourceMappingURL=babylon.observable.js.map
  7773. "use strict";
  7774. var BABYLON;
  7775. (function (BABYLON) {
  7776. var SmartArray = /** @class */ (function () {
  7777. function SmartArray(capacity) {
  7778. this.length = 0;
  7779. this.data = new Array(capacity);
  7780. this._id = SmartArray._GlobalId++;
  7781. }
  7782. SmartArray.prototype.push = function (value) {
  7783. this.data[this.length++] = value;
  7784. if (this.length > this.data.length) {
  7785. this.data.length *= 2;
  7786. }
  7787. };
  7788. SmartArray.prototype.forEach = function (func) {
  7789. for (var index = 0; index < this.length; index++) {
  7790. func(this.data[index]);
  7791. }
  7792. };
  7793. SmartArray.prototype.sort = function (compareFn) {
  7794. this.data.sort(compareFn);
  7795. };
  7796. SmartArray.prototype.reset = function () {
  7797. this.length = 0;
  7798. };
  7799. SmartArray.prototype.dispose = function () {
  7800. this.reset();
  7801. if (this.data) {
  7802. this.data.length = 0;
  7803. this.data = [];
  7804. }
  7805. };
  7806. SmartArray.prototype.concat = function (array) {
  7807. if (array.length === 0) {
  7808. return;
  7809. }
  7810. if (this.length + array.length > this.data.length) {
  7811. this.data.length = (this.length + array.length) * 2;
  7812. }
  7813. for (var index = 0; index < array.length; index++) {
  7814. this.data[this.length++] = (array.data || array)[index];
  7815. }
  7816. };
  7817. SmartArray.prototype.indexOf = function (value) {
  7818. var position = this.data.indexOf(value);
  7819. if (position >= this.length) {
  7820. return -1;
  7821. }
  7822. return position;
  7823. };
  7824. SmartArray.prototype.contains = function (value) {
  7825. return this.data.indexOf(value) !== -1;
  7826. };
  7827. // Statics
  7828. SmartArray._GlobalId = 0;
  7829. return SmartArray;
  7830. }());
  7831. BABYLON.SmartArray = SmartArray;
  7832. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7833. __extends(SmartArrayNoDuplicate, _super);
  7834. function SmartArrayNoDuplicate() {
  7835. var _this = _super !== null && _super.apply(this, arguments) || this;
  7836. _this._duplicateId = 0;
  7837. return _this;
  7838. }
  7839. SmartArrayNoDuplicate.prototype.push = function (value) {
  7840. _super.prototype.push.call(this, value);
  7841. if (!value.__smartArrayFlags) {
  7842. value.__smartArrayFlags = {};
  7843. }
  7844. value.__smartArrayFlags[this._id] = this._duplicateId;
  7845. };
  7846. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7847. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7848. return false;
  7849. }
  7850. this.push(value);
  7851. return true;
  7852. };
  7853. SmartArrayNoDuplicate.prototype.reset = function () {
  7854. _super.prototype.reset.call(this);
  7855. this._duplicateId++;
  7856. };
  7857. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7858. if (array.length === 0) {
  7859. return;
  7860. }
  7861. if (this.length + array.length > this.data.length) {
  7862. this.data.length = (this.length + array.length) * 2;
  7863. }
  7864. for (var index = 0; index < array.length; index++) {
  7865. var item = (array.data || array)[index];
  7866. this.pushNoDuplicate(item);
  7867. }
  7868. };
  7869. return SmartArrayNoDuplicate;
  7870. }(SmartArray));
  7871. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7872. })(BABYLON || (BABYLON = {}));
  7873. //# sourceMappingURL=babylon.smartArray.js.map
  7874. "use strict";
  7875. var BABYLON;
  7876. (function (BABYLON) {
  7877. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7878. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7879. var LoadFileError = /** @class */ (function (_super) {
  7880. __extends(LoadFileError, _super);
  7881. function LoadFileError(message, request) {
  7882. var _this = _super.call(this, message) || this;
  7883. _this.request = request;
  7884. _this.name = "LoadFileError";
  7885. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7886. return _this;
  7887. }
  7888. // Polyfill for Object.setPrototypeOf if necessary.
  7889. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7890. return LoadFileError;
  7891. }(Error));
  7892. BABYLON.LoadFileError = LoadFileError;
  7893. var RetryStrategy = /** @class */ (function () {
  7894. function RetryStrategy() {
  7895. }
  7896. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7897. if (maxRetries === void 0) { maxRetries = 3; }
  7898. if (baseInterval === void 0) { baseInterval = 500; }
  7899. return function (url, request, retryIndex) {
  7900. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7901. return -1;
  7902. }
  7903. return Math.pow(2, retryIndex) * baseInterval;
  7904. };
  7905. };
  7906. return RetryStrategy;
  7907. }());
  7908. BABYLON.RetryStrategy = RetryStrategy;
  7909. // Screenshots
  7910. var screenshotCanvas;
  7911. var cloneValue = function (source, destinationObject) {
  7912. if (!source)
  7913. return null;
  7914. if (source instanceof BABYLON.Mesh) {
  7915. return null;
  7916. }
  7917. if (source instanceof BABYLON.SubMesh) {
  7918. return source.clone(destinationObject);
  7919. }
  7920. else if (source.clone) {
  7921. return source.clone();
  7922. }
  7923. return null;
  7924. };
  7925. var Tools = /** @class */ (function () {
  7926. function Tools() {
  7927. }
  7928. /**
  7929. * Interpolates between a and b via alpha
  7930. * @param a The lower value (returned when alpha = 0)
  7931. * @param b The upper value (returned when alpha = 1)
  7932. * @param alpha The interpolation-factor
  7933. * @return The mixed value
  7934. */
  7935. Tools.Mix = function (a, b, alpha) {
  7936. return a * (1 - alpha) + b * alpha;
  7937. };
  7938. Tools.Instantiate = function (className) {
  7939. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7940. return Tools.RegisteredExternalClasses[className];
  7941. }
  7942. var arr = className.split(".");
  7943. var fn = (window || this);
  7944. for (var i = 0, len = arr.length; i < len; i++) {
  7945. fn = fn[arr[i]];
  7946. }
  7947. if (typeof fn !== "function") {
  7948. return null;
  7949. }
  7950. return fn;
  7951. };
  7952. /**
  7953. * Provides a slice function that will work even on IE
  7954. * @param data defines the array to slice
  7955. * @returns the new sliced array
  7956. */
  7957. Tools.Slice = function (data) {
  7958. if (data.slice) {
  7959. return data.slice();
  7960. }
  7961. return Array.prototype.slice.call(data);
  7962. };
  7963. Tools.SetImmediate = function (action) {
  7964. if (window.setImmediate) {
  7965. window.setImmediate(action);
  7966. }
  7967. else {
  7968. setTimeout(action, 1);
  7969. }
  7970. };
  7971. Tools.IsExponentOfTwo = function (value) {
  7972. var count = 1;
  7973. do {
  7974. count *= 2;
  7975. } while (count < value);
  7976. return count === value;
  7977. };
  7978. /**
  7979. * Find the next highest power of two.
  7980. * @param x Number to start search from.
  7981. * @return Next highest power of two.
  7982. */
  7983. Tools.CeilingPOT = function (x) {
  7984. x--;
  7985. x |= x >> 1;
  7986. x |= x >> 2;
  7987. x |= x >> 4;
  7988. x |= x >> 8;
  7989. x |= x >> 16;
  7990. x++;
  7991. return x;
  7992. };
  7993. /**
  7994. * Find the next lowest power of two.
  7995. * @param x Number to start search from.
  7996. * @return Next lowest power of two.
  7997. */
  7998. Tools.FloorPOT = function (x) {
  7999. x = x | (x >> 1);
  8000. x = x | (x >> 2);
  8001. x = x | (x >> 4);
  8002. x = x | (x >> 8);
  8003. x = x | (x >> 16);
  8004. return x - (x >> 1);
  8005. };
  8006. /**
  8007. * Find the nearest power of two.
  8008. * @param x Number to start search from.
  8009. * @return Next nearest power of two.
  8010. */
  8011. Tools.NearestPOT = function (x) {
  8012. var c = Tools.CeilingPOT(x);
  8013. var f = Tools.FloorPOT(x);
  8014. return (c - x) > (x - f) ? f : c;
  8015. };
  8016. Tools.GetExponentOfTwo = function (value, max, mode) {
  8017. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8018. var pot;
  8019. switch (mode) {
  8020. case BABYLON.Engine.SCALEMODE_FLOOR:
  8021. pot = Tools.FloorPOT(value);
  8022. break;
  8023. case BABYLON.Engine.SCALEMODE_NEAREST:
  8024. pot = Tools.NearestPOT(value);
  8025. break;
  8026. case BABYLON.Engine.SCALEMODE_CEILING:
  8027. default:
  8028. pot = Tools.CeilingPOT(value);
  8029. break;
  8030. }
  8031. return Math.min(pot, max);
  8032. };
  8033. Tools.GetFilename = function (path) {
  8034. var index = path.lastIndexOf("/");
  8035. if (index < 0)
  8036. return path;
  8037. return path.substring(index + 1);
  8038. };
  8039. /**
  8040. * Extracts the "folder" part of a path (everything before the filename).
  8041. * @param uri The URI to extract the info from
  8042. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8043. * @returns The "folder" part of the path
  8044. */
  8045. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8046. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8047. var index = uri.lastIndexOf("/");
  8048. if (index < 0) {
  8049. if (returnUnchangedIfNoSlash) {
  8050. return uri;
  8051. }
  8052. return "";
  8053. }
  8054. return uri.substring(0, index + 1);
  8055. };
  8056. Tools.GetDOMTextContent = function (element) {
  8057. var result = "";
  8058. var child = element.firstChild;
  8059. while (child) {
  8060. if (child.nodeType === 3) {
  8061. result += child.textContent;
  8062. }
  8063. child = child.nextSibling;
  8064. }
  8065. return result;
  8066. };
  8067. Tools.ToDegrees = function (angle) {
  8068. return angle * 180 / Math.PI;
  8069. };
  8070. Tools.ToRadians = function (angle) {
  8071. return angle * Math.PI / 180;
  8072. };
  8073. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8074. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8075. var output = "";
  8076. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8077. var i = 0;
  8078. var bytes = new Uint8Array(buffer);
  8079. while (i < bytes.length) {
  8080. chr1 = bytes[i++];
  8081. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8082. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8083. enc1 = chr1 >> 2;
  8084. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8085. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8086. enc4 = chr3 & 63;
  8087. if (isNaN(chr2)) {
  8088. enc3 = enc4 = 64;
  8089. }
  8090. else if (isNaN(chr3)) {
  8091. enc4 = 64;
  8092. }
  8093. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8094. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8095. }
  8096. return "data:image/png;base64," + output;
  8097. };
  8098. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8099. if (bias === void 0) { bias = null; }
  8100. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8101. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8102. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8103. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8104. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8105. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8106. }
  8107. if (bias) {
  8108. minimum.x -= minimum.x * bias.x + bias.y;
  8109. minimum.y -= minimum.y * bias.x + bias.y;
  8110. minimum.z -= minimum.z * bias.x + bias.y;
  8111. maximum.x += maximum.x * bias.x + bias.y;
  8112. maximum.y += maximum.y * bias.x + bias.y;
  8113. maximum.z += maximum.z * bias.x + bias.y;
  8114. }
  8115. return {
  8116. minimum: minimum,
  8117. maximum: maximum
  8118. };
  8119. };
  8120. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8121. if (bias === void 0) { bias = null; }
  8122. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8123. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8124. if (!stride) {
  8125. stride = 3;
  8126. }
  8127. for (var index = start; index < start + count; index++) {
  8128. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8129. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8130. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8131. }
  8132. if (bias) {
  8133. minimum.x -= minimum.x * bias.x + bias.y;
  8134. minimum.y -= minimum.y * bias.x + bias.y;
  8135. minimum.z -= minimum.z * bias.x + bias.y;
  8136. maximum.x += maximum.x * bias.x + bias.y;
  8137. maximum.y += maximum.y * bias.x + bias.y;
  8138. maximum.z += maximum.z * bias.x + bias.y;
  8139. }
  8140. return {
  8141. minimum: minimum,
  8142. maximum: maximum
  8143. };
  8144. };
  8145. Tools.Vector2ArrayFeeder = function (array) {
  8146. return function (index) {
  8147. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8148. var length = isFloatArray ? array.length / 2 : array.length;
  8149. if (index >= length) {
  8150. return null;
  8151. }
  8152. if (isFloatArray) {
  8153. var fa = array;
  8154. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8155. }
  8156. var a = array;
  8157. return a[index];
  8158. };
  8159. };
  8160. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8161. if (bias === void 0) { bias = null; }
  8162. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8163. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8164. var i = 0;
  8165. var cur = feeder(i++);
  8166. while (cur) {
  8167. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8168. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8169. cur = feeder(i++);
  8170. }
  8171. if (bias) {
  8172. minimum.x -= minimum.x * bias.x + bias.y;
  8173. minimum.y -= minimum.y * bias.x + bias.y;
  8174. maximum.x += maximum.x * bias.x + bias.y;
  8175. maximum.y += maximum.y * bias.x + bias.y;
  8176. }
  8177. return {
  8178. minimum: minimum,
  8179. maximum: maximum
  8180. };
  8181. };
  8182. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8183. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8184. return null;
  8185. return Array.isArray(obj) ? obj : [obj];
  8186. };
  8187. // Misc.
  8188. Tools.GetPointerPrefix = function () {
  8189. var eventPrefix = "pointer";
  8190. // Check if pointer events are supported
  8191. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8192. eventPrefix = "mouse";
  8193. }
  8194. return eventPrefix;
  8195. };
  8196. /**
  8197. * @param func - the function to be called
  8198. * @param requester - the object that will request the next frame. Falls back to window.
  8199. */
  8200. Tools.QueueNewFrame = function (func, requester) {
  8201. if (!Tools.IsWindowObjectExist()) {
  8202. return setTimeout(func, 16);
  8203. }
  8204. if (!requester) {
  8205. requester = window;
  8206. }
  8207. if (requester.requestAnimationFrame) {
  8208. return requester.requestAnimationFrame(func);
  8209. }
  8210. else if (requester.msRequestAnimationFrame) {
  8211. return requester.msRequestAnimationFrame(func);
  8212. }
  8213. else if (requester.webkitRequestAnimationFrame) {
  8214. return requester.webkitRequestAnimationFrame(func);
  8215. }
  8216. else if (requester.mozRequestAnimationFrame) {
  8217. return requester.mozRequestAnimationFrame(func);
  8218. }
  8219. else if (requester.oRequestAnimationFrame) {
  8220. return requester.oRequestAnimationFrame(func);
  8221. }
  8222. else {
  8223. return window.setTimeout(func, 16);
  8224. }
  8225. };
  8226. Tools.RequestFullscreen = function (element) {
  8227. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8228. if (!requestFunction)
  8229. return;
  8230. requestFunction.call(element);
  8231. };
  8232. Tools.ExitFullscreen = function () {
  8233. if (document.exitFullscreen) {
  8234. document.exitFullscreen();
  8235. }
  8236. else if (document.mozCancelFullScreen) {
  8237. document.mozCancelFullScreen();
  8238. }
  8239. else if (document.webkitCancelFullScreen) {
  8240. document.webkitCancelFullScreen();
  8241. }
  8242. else if (document.msCancelFullScreen) {
  8243. document.msCancelFullScreen();
  8244. }
  8245. };
  8246. Tools.SetCorsBehavior = function (url, element) {
  8247. if (url && url.indexOf("data:") === 0) {
  8248. return;
  8249. }
  8250. if (Tools.CorsBehavior) {
  8251. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8252. element.crossOrigin = Tools.CorsBehavior;
  8253. }
  8254. else {
  8255. var result = Tools.CorsBehavior(url);
  8256. if (result) {
  8257. element.crossOrigin = result;
  8258. }
  8259. }
  8260. }
  8261. };
  8262. // External files
  8263. Tools.CleanUrl = function (url) {
  8264. url = url.replace(/#/mg, "%23");
  8265. return url;
  8266. };
  8267. Tools.LoadImage = function (url, onLoad, onError, database) {
  8268. if (url instanceof ArrayBuffer) {
  8269. url = Tools.EncodeArrayBufferTobase64(url);
  8270. }
  8271. url = Tools.CleanUrl(url);
  8272. url = Tools.PreprocessUrl(url);
  8273. var img = new Image();
  8274. Tools.SetCorsBehavior(url, img);
  8275. var loadHandler = function () {
  8276. img.removeEventListener("load", loadHandler);
  8277. img.removeEventListener("error", errorHandler);
  8278. onLoad(img);
  8279. };
  8280. var errorHandler = function (err) {
  8281. img.removeEventListener("load", loadHandler);
  8282. img.removeEventListener("error", errorHandler);
  8283. Tools.Error("Error while trying to load image: " + url);
  8284. if (onError) {
  8285. onError("Error while trying to load image: " + url, err);
  8286. }
  8287. };
  8288. img.addEventListener("load", loadHandler);
  8289. img.addEventListener("error", errorHandler);
  8290. var noIndexedDB = function () {
  8291. img.src = url;
  8292. };
  8293. var loadFromIndexedDB = function () {
  8294. if (database) {
  8295. database.loadImageFromDB(url, img);
  8296. }
  8297. };
  8298. //ANY database to do!
  8299. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8300. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8301. }
  8302. else {
  8303. if (url.indexOf("file:") !== -1) {
  8304. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8305. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8306. try {
  8307. var blobURL;
  8308. try {
  8309. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8310. }
  8311. catch (ex) {
  8312. // Chrome doesn't support oneTimeOnly parameter
  8313. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8314. }
  8315. img.src = blobURL;
  8316. }
  8317. catch (e) {
  8318. img.src = "";
  8319. }
  8320. return img;
  8321. }
  8322. }
  8323. noIndexedDB();
  8324. }
  8325. return img;
  8326. };
  8327. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8328. url = Tools.CleanUrl(url);
  8329. url = Tools.PreprocessUrl(url);
  8330. // If file and file input are set
  8331. if (url.indexOf("file:") !== -1) {
  8332. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8333. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8334. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8335. }
  8336. }
  8337. var loadUrl = Tools.BaseUrl + url;
  8338. var aborted = false;
  8339. var fileRequest = {
  8340. onCompleteObservable: new BABYLON.Observable(),
  8341. abort: function () { return aborted = true; },
  8342. };
  8343. var requestFile = function () {
  8344. var request = new XMLHttpRequest();
  8345. var retryHandle = null;
  8346. fileRequest.abort = function () {
  8347. aborted = true;
  8348. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8349. request.abort();
  8350. }
  8351. if (retryHandle !== null) {
  8352. clearTimeout(retryHandle);
  8353. retryHandle = null;
  8354. }
  8355. };
  8356. var retryLoop = function (retryIndex) {
  8357. request.open('GET', loadUrl, true);
  8358. if (useArrayBuffer) {
  8359. request.responseType = "arraybuffer";
  8360. }
  8361. if (onProgress) {
  8362. request.addEventListener("progress", onProgress);
  8363. }
  8364. var onLoadEnd = function () {
  8365. request.removeEventListener("loadend", onLoadEnd);
  8366. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8367. fileRequest.onCompleteObservable.clear();
  8368. };
  8369. request.addEventListener("loadend", onLoadEnd);
  8370. var onReadyStateChange = function () {
  8371. if (aborted) {
  8372. return;
  8373. }
  8374. // In case of undefined state in some browsers.
  8375. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8376. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8377. request.removeEventListener("readystatechange", onReadyStateChange);
  8378. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8379. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8380. return;
  8381. }
  8382. var retryStrategy = Tools.DefaultRetryStrategy;
  8383. if (retryStrategy) {
  8384. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8385. if (waitTime !== -1) {
  8386. // Prevent the request from completing for retry.
  8387. request.removeEventListener("loadend", onLoadEnd);
  8388. request = new XMLHttpRequest();
  8389. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8390. return;
  8391. }
  8392. }
  8393. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8394. if (onError) {
  8395. onError(request, e);
  8396. }
  8397. else {
  8398. throw e;
  8399. }
  8400. }
  8401. };
  8402. request.addEventListener("readystatechange", onReadyStateChange);
  8403. request.send();
  8404. };
  8405. retryLoop(0);
  8406. };
  8407. // Caching all files
  8408. if (database && database.enableSceneOffline) {
  8409. var noIndexedDB_1 = function () {
  8410. if (!aborted) {
  8411. requestFile();
  8412. }
  8413. };
  8414. var loadFromIndexedDB = function () {
  8415. // TODO: database needs to support aborting and should return a IFileRequest
  8416. if (aborted) {
  8417. return;
  8418. }
  8419. if (database) {
  8420. database.loadFileFromDB(url, function (data) {
  8421. if (!aborted) {
  8422. onSuccess(data);
  8423. }
  8424. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8425. }, onProgress ? function (event) {
  8426. if (!aborted) {
  8427. onProgress(event);
  8428. }
  8429. } : undefined, noIndexedDB_1, useArrayBuffer);
  8430. }
  8431. };
  8432. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8433. }
  8434. else {
  8435. requestFile();
  8436. }
  8437. return fileRequest;
  8438. };
  8439. /**
  8440. * Load a script (identified by an url). When the url returns, the
  8441. * content of this file is added into a new script element, attached to the DOM (body element)
  8442. */
  8443. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8444. var head = document.getElementsByTagName('head')[0];
  8445. var script = document.createElement('script');
  8446. script.type = 'text/javascript';
  8447. script.src = scriptUrl;
  8448. script.onload = function () {
  8449. if (onSuccess) {
  8450. onSuccess();
  8451. }
  8452. };
  8453. script.onerror = function (e) {
  8454. if (onError) {
  8455. onError("Unable to load script", e);
  8456. }
  8457. };
  8458. head.appendChild(script);
  8459. };
  8460. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8461. var reader = new FileReader();
  8462. var request = {
  8463. onCompleteObservable: new BABYLON.Observable(),
  8464. abort: function () { return reader.abort(); },
  8465. };
  8466. reader.onloadend = function (e) {
  8467. request.onCompleteObservable.notifyObservers(request);
  8468. };
  8469. reader.onload = function (e) {
  8470. //target doesn't have result from ts 1.3
  8471. callback(e.target['result']);
  8472. };
  8473. reader.onprogress = progressCallback;
  8474. reader.readAsDataURL(fileToLoad);
  8475. return request;
  8476. };
  8477. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8478. var reader = new FileReader();
  8479. var request = {
  8480. onCompleteObservable: new BABYLON.Observable(),
  8481. abort: function () { return reader.abort(); },
  8482. };
  8483. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8484. reader.onerror = function (e) {
  8485. Tools.Log("Error while reading file: " + fileToLoad.name);
  8486. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8487. };
  8488. reader.onload = function (e) {
  8489. //target doesn't have result from ts 1.3
  8490. callback(e.target['result']);
  8491. };
  8492. if (progressCallBack) {
  8493. reader.onprogress = progressCallBack;
  8494. }
  8495. if (!useArrayBuffer) {
  8496. // Asynchronous read
  8497. reader.readAsText(fileToLoad);
  8498. }
  8499. else {
  8500. reader.readAsArrayBuffer(fileToLoad);
  8501. }
  8502. return request;
  8503. };
  8504. //returns a downloadable url to a file content.
  8505. Tools.FileAsURL = function (content) {
  8506. var fileBlob = new Blob([content]);
  8507. var url = window.URL || window.webkitURL;
  8508. var link = url.createObjectURL(fileBlob);
  8509. return link;
  8510. };
  8511. // Misc.
  8512. Tools.Format = function (value, decimals) {
  8513. if (decimals === void 0) { decimals = 2; }
  8514. return value.toFixed(decimals);
  8515. };
  8516. Tools.CheckExtends = function (v, min, max) {
  8517. if (v.x < min.x)
  8518. min.x = v.x;
  8519. if (v.y < min.y)
  8520. min.y = v.y;
  8521. if (v.z < min.z)
  8522. min.z = v.z;
  8523. if (v.x > max.x)
  8524. max.x = v.x;
  8525. if (v.y > max.y)
  8526. max.y = v.y;
  8527. if (v.z > max.z)
  8528. max.z = v.z;
  8529. };
  8530. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8531. for (var prop in source) {
  8532. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8533. continue;
  8534. }
  8535. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8536. continue;
  8537. }
  8538. var sourceValue = source[prop];
  8539. var typeOfSourceValue = typeof sourceValue;
  8540. if (typeOfSourceValue === "function") {
  8541. continue;
  8542. }
  8543. try {
  8544. if (typeOfSourceValue === "object") {
  8545. if (sourceValue instanceof Array) {
  8546. destination[prop] = [];
  8547. if (sourceValue.length > 0) {
  8548. if (typeof sourceValue[0] == "object") {
  8549. for (var index = 0; index < sourceValue.length; index++) {
  8550. var clonedValue = cloneValue(sourceValue[index], destination);
  8551. if (destination[prop].indexOf(clonedValue) === -1) {
  8552. destination[prop].push(clonedValue);
  8553. }
  8554. }
  8555. }
  8556. else {
  8557. destination[prop] = sourceValue.slice(0);
  8558. }
  8559. }
  8560. }
  8561. else {
  8562. destination[prop] = cloneValue(sourceValue, destination);
  8563. }
  8564. }
  8565. else {
  8566. destination[prop] = sourceValue;
  8567. }
  8568. }
  8569. catch (e) {
  8570. // Just ignore error (it could be because of a read-only property)
  8571. }
  8572. }
  8573. };
  8574. Tools.IsEmpty = function (obj) {
  8575. for (var i in obj) {
  8576. if (obj.hasOwnProperty(i)) {
  8577. return false;
  8578. }
  8579. }
  8580. return true;
  8581. };
  8582. Tools.RegisterTopRootEvents = function (events) {
  8583. for (var index = 0; index < events.length; index++) {
  8584. var event = events[index];
  8585. window.addEventListener(event.name, event.handler, false);
  8586. try {
  8587. if (window.parent) {
  8588. window.parent.addEventListener(event.name, event.handler, false);
  8589. }
  8590. }
  8591. catch (e) {
  8592. // Silently fails...
  8593. }
  8594. }
  8595. };
  8596. Tools.UnregisterTopRootEvents = function (events) {
  8597. for (var index = 0; index < events.length; index++) {
  8598. var event = events[index];
  8599. window.removeEventListener(event.name, event.handler);
  8600. try {
  8601. if (window.parent) {
  8602. window.parent.removeEventListener(event.name, event.handler);
  8603. }
  8604. }
  8605. catch (e) {
  8606. // Silently fails...
  8607. }
  8608. }
  8609. };
  8610. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8611. if (mimeType === void 0) { mimeType = "image/png"; }
  8612. // Read the contents of the framebuffer
  8613. var numberOfChannelsByLine = width * 4;
  8614. var halfHeight = height / 2;
  8615. //Reading datas from WebGL
  8616. var data = engine.readPixels(0, 0, width, height);
  8617. //To flip image on Y axis.
  8618. for (var i = 0; i < halfHeight; i++) {
  8619. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8620. var currentCell = j + i * numberOfChannelsByLine;
  8621. var targetLine = height - i - 1;
  8622. var targetCell = j + targetLine * numberOfChannelsByLine;
  8623. var temp = data[currentCell];
  8624. data[currentCell] = data[targetCell];
  8625. data[targetCell] = temp;
  8626. }
  8627. }
  8628. // Create a 2D canvas to store the result
  8629. if (!screenshotCanvas) {
  8630. screenshotCanvas = document.createElement('canvas');
  8631. }
  8632. screenshotCanvas.width = width;
  8633. screenshotCanvas.height = height;
  8634. var context = screenshotCanvas.getContext('2d');
  8635. if (context) {
  8636. // Copy the pixels to a 2D canvas
  8637. var imageData = context.createImageData(width, height);
  8638. var castData = (imageData.data);
  8639. castData.set(data);
  8640. context.putImageData(imageData, 0, 0);
  8641. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8642. }
  8643. };
  8644. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8645. if (mimeType === void 0) { mimeType = "image/png"; }
  8646. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8647. if (successCallback) {
  8648. successCallback(base64Image);
  8649. }
  8650. else {
  8651. // We need HTMLCanvasElement.toBlob for HD screenshots
  8652. if (!screenshotCanvas.toBlob) {
  8653. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8654. screenshotCanvas.toBlob = function (callback, type, quality) {
  8655. var _this = this;
  8656. setTimeout(function () {
  8657. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8658. for (var i = 0; i < len; i++) {
  8659. arr[i] = binStr.charCodeAt(i);
  8660. }
  8661. callback(new Blob([arr], { type: type || 'image/png' }));
  8662. });
  8663. };
  8664. }
  8665. screenshotCanvas.toBlob(function (blob) {
  8666. var url = URL.createObjectURL(blob);
  8667. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8668. if (("download" in document.createElement("a"))) {
  8669. var a = window.document.createElement("a");
  8670. a.href = url;
  8671. if (fileName) {
  8672. a.setAttribute("download", fileName);
  8673. }
  8674. else {
  8675. var date = new Date();
  8676. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8677. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8678. }
  8679. window.document.body.appendChild(a);
  8680. a.addEventListener("click", function () {
  8681. if (a.parentElement) {
  8682. a.parentElement.removeChild(a);
  8683. }
  8684. });
  8685. a.click();
  8686. }
  8687. else {
  8688. var newWindow = window.open("");
  8689. if (!newWindow)
  8690. return;
  8691. var img = newWindow.document.createElement("img");
  8692. img.onload = function () {
  8693. // no longer need to read the blob so it's revoked
  8694. URL.revokeObjectURL(url);
  8695. };
  8696. img.src = url;
  8697. newWindow.document.body.appendChild(img);
  8698. }
  8699. });
  8700. }
  8701. };
  8702. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8703. if (mimeType === void 0) { mimeType = "image/png"; }
  8704. var width;
  8705. var height;
  8706. // If a precision value is specified
  8707. if (size.precision) {
  8708. width = Math.round(engine.getRenderWidth() * size.precision);
  8709. height = Math.round(width / engine.getAspectRatio(camera));
  8710. }
  8711. else if (size.width && size.height) {
  8712. width = size.width;
  8713. height = size.height;
  8714. }
  8715. else if (size.width && !size.height) {
  8716. width = size.width;
  8717. height = Math.round(width / engine.getAspectRatio(camera));
  8718. }
  8719. else if (size.height && !size.width) {
  8720. height = size.height;
  8721. width = Math.round(height * engine.getAspectRatio(camera));
  8722. }
  8723. else if (!isNaN(size)) {
  8724. height = size;
  8725. width = size;
  8726. }
  8727. else {
  8728. Tools.Error("Invalid 'size' parameter !");
  8729. return;
  8730. }
  8731. if (!screenshotCanvas) {
  8732. screenshotCanvas = document.createElement('canvas');
  8733. }
  8734. screenshotCanvas.width = width;
  8735. screenshotCanvas.height = height;
  8736. var renderContext = screenshotCanvas.getContext("2d");
  8737. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8738. var newWidth = width;
  8739. var newHeight = newWidth / ratio;
  8740. if (newHeight > height) {
  8741. newHeight = height;
  8742. newWidth = newHeight * ratio;
  8743. }
  8744. var offsetX = Math.max(0, width - newWidth) / 2;
  8745. var offsetY = Math.max(0, height - newHeight) / 2;
  8746. var renderingCanvas = engine.getRenderingCanvas();
  8747. if (renderContext && renderingCanvas) {
  8748. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8749. }
  8750. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8751. };
  8752. /**
  8753. * Generates an image screenshot from the specified camera.
  8754. *
  8755. * @param engine The engine to use for rendering
  8756. * @param camera The camera to use for rendering
  8757. * @param size This parameter can be set to a single number or to an object with the
  8758. * following (optional) properties: precision, width, height. If a single number is passed,
  8759. * it will be used for both width and height. If an object is passed, the screenshot size
  8760. * will be derived from the parameters. The precision property is a multiplier allowing
  8761. * rendering at a higher or lower resolution.
  8762. * @param successCallback The callback receives a single parameter which contains the
  8763. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8764. * src parameter of an <img> to display it.
  8765. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8766. * Check your browser for supported MIME types.
  8767. * @param samples Texture samples (default: 1)
  8768. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8769. * @param fileName A name for for the downloaded file.
  8770. * @constructor
  8771. */
  8772. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8773. if (mimeType === void 0) { mimeType = "image/png"; }
  8774. if (samples === void 0) { samples = 1; }
  8775. if (antialiasing === void 0) { antialiasing = false; }
  8776. var width;
  8777. var height;
  8778. //If a precision value is specified
  8779. if (size.precision) {
  8780. width = Math.round(engine.getRenderWidth() * size.precision);
  8781. height = Math.round(width / engine.getAspectRatio(camera));
  8782. size = { width: width, height: height };
  8783. }
  8784. else if (size.width && size.height) {
  8785. width = size.width;
  8786. height = size.height;
  8787. }
  8788. else if (size.width && !size.height) {
  8789. width = size.width;
  8790. height = Math.round(width / engine.getAspectRatio(camera));
  8791. size = { width: width, height: height };
  8792. }
  8793. else if (size.height && !size.width) {
  8794. height = size.height;
  8795. width = Math.round(height * engine.getAspectRatio(camera));
  8796. size = { width: width, height: height };
  8797. }
  8798. else if (!isNaN(size)) {
  8799. height = size;
  8800. width = size;
  8801. }
  8802. else {
  8803. Tools.Error("Invalid 'size' parameter !");
  8804. return;
  8805. }
  8806. var scene = camera.getScene();
  8807. var previousCamera = null;
  8808. if (scene.activeCamera !== camera) {
  8809. previousCamera = scene.activeCamera;
  8810. scene.activeCamera = camera;
  8811. }
  8812. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8813. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8814. texture.renderList = null;
  8815. texture.samples = samples;
  8816. if (antialiasing) {
  8817. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8818. }
  8819. texture.onAfterRenderObservable.add(function () {
  8820. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8821. });
  8822. scene.incrementRenderId();
  8823. scene.resetCachedMaterial();
  8824. texture.render(true);
  8825. texture.dispose();
  8826. if (previousCamera) {
  8827. scene.activeCamera = previousCamera;
  8828. }
  8829. camera.getProjectionMatrix(true); // Force cache refresh;
  8830. };
  8831. // XHR response validator for local file scenario
  8832. Tools.ValidateXHRData = function (xhr, dataType) {
  8833. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8834. if (dataType === void 0) { dataType = 7; }
  8835. try {
  8836. if (dataType & 1) {
  8837. if (xhr.responseText && xhr.responseText.length > 0) {
  8838. return true;
  8839. }
  8840. else if (dataType === 1) {
  8841. return false;
  8842. }
  8843. }
  8844. if (dataType & 2) {
  8845. // Check header width and height since there is no "TGA" magic number
  8846. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8847. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8848. return true;
  8849. }
  8850. else if (dataType === 2) {
  8851. return false;
  8852. }
  8853. }
  8854. if (dataType & 4) {
  8855. // Check for the "DDS" magic number
  8856. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8857. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8858. return true;
  8859. }
  8860. else {
  8861. return false;
  8862. }
  8863. }
  8864. }
  8865. catch (e) {
  8866. // Global protection
  8867. }
  8868. return false;
  8869. };
  8870. /**
  8871. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8872. * Be aware Math.random() could cause collisions, but:
  8873. * "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"
  8874. */
  8875. Tools.RandomId = function () {
  8876. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8877. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8878. return v.toString(16);
  8879. });
  8880. };
  8881. /**
  8882. * Test if the given uri is a base64 string.
  8883. * @param uri The uri to test
  8884. * @return True if the uri is a base64 string or false otherwise.
  8885. */
  8886. Tools.IsBase64 = function (uri) {
  8887. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8888. };
  8889. /**
  8890. * Decode the given base64 uri.
  8891. * @param uri The uri to decode
  8892. * @return The decoded base64 data.
  8893. */
  8894. Tools.DecodeBase64 = function (uri) {
  8895. var decodedString = atob(uri.split(",")[1]);
  8896. var bufferLength = decodedString.length;
  8897. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8898. for (var i = 0; i < bufferLength; i++) {
  8899. bufferView[i] = decodedString.charCodeAt(i);
  8900. }
  8901. return bufferView.buffer;
  8902. };
  8903. Object.defineProperty(Tools, "NoneLogLevel", {
  8904. get: function () {
  8905. return Tools._NoneLogLevel;
  8906. },
  8907. enumerable: true,
  8908. configurable: true
  8909. });
  8910. Object.defineProperty(Tools, "MessageLogLevel", {
  8911. get: function () {
  8912. return Tools._MessageLogLevel;
  8913. },
  8914. enumerable: true,
  8915. configurable: true
  8916. });
  8917. Object.defineProperty(Tools, "WarningLogLevel", {
  8918. get: function () {
  8919. return Tools._WarningLogLevel;
  8920. },
  8921. enumerable: true,
  8922. configurable: true
  8923. });
  8924. Object.defineProperty(Tools, "ErrorLogLevel", {
  8925. get: function () {
  8926. return Tools._ErrorLogLevel;
  8927. },
  8928. enumerable: true,
  8929. configurable: true
  8930. });
  8931. Object.defineProperty(Tools, "AllLogLevel", {
  8932. get: function () {
  8933. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8934. },
  8935. enumerable: true,
  8936. configurable: true
  8937. });
  8938. Tools._AddLogEntry = function (entry) {
  8939. Tools._LogCache = entry + Tools._LogCache;
  8940. if (Tools.OnNewCacheEntry) {
  8941. Tools.OnNewCacheEntry(entry);
  8942. }
  8943. };
  8944. Tools._FormatMessage = function (message) {
  8945. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8946. var date = new Date();
  8947. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8948. };
  8949. Tools._LogDisabled = function (message) {
  8950. // nothing to do
  8951. };
  8952. Tools._LogEnabled = function (message) {
  8953. var formattedMessage = Tools._FormatMessage(message);
  8954. console.log("BJS - " + formattedMessage);
  8955. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8956. Tools._AddLogEntry(entry);
  8957. };
  8958. Tools._WarnDisabled = function (message) {
  8959. // nothing to do
  8960. };
  8961. Tools._WarnEnabled = function (message) {
  8962. var formattedMessage = Tools._FormatMessage(message);
  8963. console.warn("BJS - " + formattedMessage);
  8964. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8965. Tools._AddLogEntry(entry);
  8966. };
  8967. Tools._ErrorDisabled = function (message) {
  8968. // nothing to do
  8969. };
  8970. Tools._ErrorEnabled = function (message) {
  8971. Tools.errorsCount++;
  8972. var formattedMessage = Tools._FormatMessage(message);
  8973. console.error("BJS - " + formattedMessage);
  8974. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8975. Tools._AddLogEntry(entry);
  8976. };
  8977. Object.defineProperty(Tools, "LogCache", {
  8978. get: function () {
  8979. return Tools._LogCache;
  8980. },
  8981. enumerable: true,
  8982. configurable: true
  8983. });
  8984. Tools.ClearLogCache = function () {
  8985. Tools._LogCache = "";
  8986. Tools.errorsCount = 0;
  8987. };
  8988. Object.defineProperty(Tools, "LogLevels", {
  8989. set: function (level) {
  8990. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8991. Tools.Log = Tools._LogEnabled;
  8992. }
  8993. else {
  8994. Tools.Log = Tools._LogDisabled;
  8995. }
  8996. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8997. Tools.Warn = Tools._WarnEnabled;
  8998. }
  8999. else {
  9000. Tools.Warn = Tools._WarnDisabled;
  9001. }
  9002. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9003. Tools.Error = Tools._ErrorEnabled;
  9004. }
  9005. else {
  9006. Tools.Error = Tools._ErrorDisabled;
  9007. }
  9008. },
  9009. enumerable: true,
  9010. configurable: true
  9011. });
  9012. Tools.IsWindowObjectExist = function () {
  9013. return (typeof window) !== "undefined";
  9014. };
  9015. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9016. get: function () {
  9017. return Tools._PerformanceNoneLogLevel;
  9018. },
  9019. enumerable: true,
  9020. configurable: true
  9021. });
  9022. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9023. get: function () {
  9024. return Tools._PerformanceUserMarkLogLevel;
  9025. },
  9026. enumerable: true,
  9027. configurable: true
  9028. });
  9029. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9030. get: function () {
  9031. return Tools._PerformanceConsoleLogLevel;
  9032. },
  9033. enumerable: true,
  9034. configurable: true
  9035. });
  9036. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9037. set: function (level) {
  9038. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9039. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9040. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9041. return;
  9042. }
  9043. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9044. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9045. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9046. return;
  9047. }
  9048. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9049. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9050. },
  9051. enumerable: true,
  9052. configurable: true
  9053. });
  9054. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9055. };
  9056. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9057. };
  9058. Tools._StartUserMark = function (counterName, condition) {
  9059. if (condition === void 0) { condition = true; }
  9060. if (!Tools._performance) {
  9061. if (!Tools.IsWindowObjectExist()) {
  9062. return;
  9063. }
  9064. Tools._performance = window.performance;
  9065. }
  9066. if (!condition || !Tools._performance.mark) {
  9067. return;
  9068. }
  9069. Tools._performance.mark(counterName + "-Begin");
  9070. };
  9071. Tools._EndUserMark = function (counterName, condition) {
  9072. if (condition === void 0) { condition = true; }
  9073. if (!condition || !Tools._performance.mark) {
  9074. return;
  9075. }
  9076. Tools._performance.mark(counterName + "-End");
  9077. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9078. };
  9079. Tools._StartPerformanceConsole = function (counterName, condition) {
  9080. if (condition === void 0) { condition = true; }
  9081. if (!condition) {
  9082. return;
  9083. }
  9084. Tools._StartUserMark(counterName, condition);
  9085. if (console.time) {
  9086. console.time(counterName);
  9087. }
  9088. };
  9089. Tools._EndPerformanceConsole = function (counterName, condition) {
  9090. if (condition === void 0) { condition = true; }
  9091. if (!condition) {
  9092. return;
  9093. }
  9094. Tools._EndUserMark(counterName, condition);
  9095. if (console.time) {
  9096. console.timeEnd(counterName);
  9097. }
  9098. };
  9099. Object.defineProperty(Tools, "Now", {
  9100. get: function () {
  9101. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9102. return window.performance.now();
  9103. }
  9104. return new Date().getTime();
  9105. },
  9106. enumerable: true,
  9107. configurable: true
  9108. });
  9109. /**
  9110. * This method will return the name of the class used to create the instance of the given object.
  9111. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9112. * @param object the object to get the class name from
  9113. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9114. */
  9115. Tools.GetClassName = function (object, isType) {
  9116. if (isType === void 0) { isType = false; }
  9117. var name = null;
  9118. if (!isType && object.getClassName) {
  9119. name = object.getClassName();
  9120. }
  9121. else {
  9122. if (object instanceof Object) {
  9123. var classObj = isType ? object : Object.getPrototypeOf(object);
  9124. name = classObj.constructor["__bjsclassName__"];
  9125. }
  9126. if (!name) {
  9127. name = typeof object;
  9128. }
  9129. }
  9130. return name;
  9131. };
  9132. Tools.First = function (array, predicate) {
  9133. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9134. var el = array_1[_i];
  9135. if (predicate(el)) {
  9136. return el;
  9137. }
  9138. }
  9139. return null;
  9140. };
  9141. /**
  9142. * This method will return the name of the full name of the class, including its owning module (if any).
  9143. * 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).
  9144. * @param object the object to get the class name from
  9145. * @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.
  9146. */
  9147. Tools.getFullClassName = function (object, isType) {
  9148. if (isType === void 0) { isType = false; }
  9149. var className = null;
  9150. var moduleName = null;
  9151. if (!isType && object.getClassName) {
  9152. className = object.getClassName();
  9153. }
  9154. else {
  9155. if (object instanceof Object) {
  9156. var classObj = isType ? object : Object.getPrototypeOf(object);
  9157. className = classObj.constructor["__bjsclassName__"];
  9158. moduleName = classObj.constructor["__bjsmoduleName__"];
  9159. }
  9160. if (!className) {
  9161. className = typeof object;
  9162. }
  9163. }
  9164. if (!className) {
  9165. return null;
  9166. }
  9167. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9168. };
  9169. /**
  9170. * 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.
  9171. * @param array
  9172. */
  9173. Tools.arrayOrStringFeeder = function (array) {
  9174. return function (index) {
  9175. if (index >= array.length) {
  9176. return null;
  9177. }
  9178. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9179. if (val && val.getHashCode) {
  9180. val = val.getHashCode();
  9181. }
  9182. if (typeof val === "string") {
  9183. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9184. }
  9185. return val;
  9186. };
  9187. };
  9188. /**
  9189. * Compute the hashCode of a stream of number
  9190. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9191. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9192. * @return the hash code computed
  9193. */
  9194. Tools.hashCodeFromStream = function (feeder) {
  9195. // Based from here: http://stackoverflow.com/a/7616484/802124
  9196. var hash = 0;
  9197. var index = 0;
  9198. var chr = feeder(index++);
  9199. while (chr != null) {
  9200. hash = ((hash << 5) - hash) + chr;
  9201. hash |= 0; // Convert to 32bit integer
  9202. chr = feeder(index++);
  9203. }
  9204. return hash;
  9205. };
  9206. /**
  9207. * Returns a promise that resolves after the given amount of time.
  9208. * @param delay Number of milliseconds to delay
  9209. * @returns Promise that resolves after the given amount of time
  9210. */
  9211. Tools.DelayAsync = function (delay) {
  9212. return new Promise(function (resolve) {
  9213. setTimeout(function () {
  9214. resolve();
  9215. }, delay);
  9216. });
  9217. };
  9218. Tools.BaseUrl = "";
  9219. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9220. /**
  9221. * Default behaviour for cors in the application.
  9222. * It can be a string if the expected behavior is identical in the entire app.
  9223. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9224. */
  9225. Tools.CorsBehavior = "anonymous";
  9226. Tools.UseFallbackTexture = true;
  9227. /**
  9228. * Use this object to register external classes like custom textures or material
  9229. * to allow the laoders to instantiate them
  9230. */
  9231. Tools.RegisteredExternalClasses = {};
  9232. // Used in case of a texture loading problem
  9233. 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";
  9234. Tools.PreprocessUrl = function (url) {
  9235. return url;
  9236. };
  9237. // Logs
  9238. Tools._NoneLogLevel = 0;
  9239. Tools._MessageLogLevel = 1;
  9240. Tools._WarningLogLevel = 2;
  9241. Tools._ErrorLogLevel = 4;
  9242. Tools._LogCache = "";
  9243. Tools.errorsCount = 0;
  9244. Tools.Log = Tools._LogEnabled;
  9245. Tools.Warn = Tools._WarnEnabled;
  9246. Tools.Error = Tools._ErrorEnabled;
  9247. // Performances
  9248. Tools._PerformanceNoneLogLevel = 0;
  9249. Tools._PerformanceUserMarkLogLevel = 1;
  9250. Tools._PerformanceConsoleLogLevel = 2;
  9251. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9252. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9253. return Tools;
  9254. }());
  9255. BABYLON.Tools = Tools;
  9256. /**
  9257. * This class is used to track a performance counter which is number based.
  9258. * The user has access to many properties which give statistics of different nature
  9259. *
  9260. * The implementer can track two kinds of Performance Counter: time and count
  9261. * 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.
  9262. * 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.
  9263. */
  9264. var PerfCounter = /** @class */ (function () {
  9265. function PerfCounter() {
  9266. this._startMonitoringTime = 0;
  9267. this._min = 0;
  9268. this._max = 0;
  9269. this._average = 0;
  9270. this._lastSecAverage = 0;
  9271. this._current = 0;
  9272. this._totalValueCount = 0;
  9273. this._totalAccumulated = 0;
  9274. this._lastSecAccumulated = 0;
  9275. this._lastSecTime = 0;
  9276. this._lastSecValueCount = 0;
  9277. }
  9278. Object.defineProperty(PerfCounter.prototype, "min", {
  9279. /**
  9280. * Returns the smallest value ever
  9281. */
  9282. get: function () {
  9283. return this._min;
  9284. },
  9285. enumerable: true,
  9286. configurable: true
  9287. });
  9288. Object.defineProperty(PerfCounter.prototype, "max", {
  9289. /**
  9290. * Returns the biggest value ever
  9291. */
  9292. get: function () {
  9293. return this._max;
  9294. },
  9295. enumerable: true,
  9296. configurable: true
  9297. });
  9298. Object.defineProperty(PerfCounter.prototype, "average", {
  9299. /**
  9300. * Returns the average value since the performance counter is running
  9301. */
  9302. get: function () {
  9303. return this._average;
  9304. },
  9305. enumerable: true,
  9306. configurable: true
  9307. });
  9308. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9309. /**
  9310. * Returns the average value of the last second the counter was monitored
  9311. */
  9312. get: function () {
  9313. return this._lastSecAverage;
  9314. },
  9315. enumerable: true,
  9316. configurable: true
  9317. });
  9318. Object.defineProperty(PerfCounter.prototype, "current", {
  9319. /**
  9320. * Returns the current value
  9321. */
  9322. get: function () {
  9323. return this._current;
  9324. },
  9325. enumerable: true,
  9326. configurable: true
  9327. });
  9328. Object.defineProperty(PerfCounter.prototype, "total", {
  9329. get: function () {
  9330. return this._totalAccumulated;
  9331. },
  9332. enumerable: true,
  9333. configurable: true
  9334. });
  9335. Object.defineProperty(PerfCounter.prototype, "count", {
  9336. get: function () {
  9337. return this._totalValueCount;
  9338. },
  9339. enumerable: true,
  9340. configurable: true
  9341. });
  9342. /**
  9343. * Call this method to start monitoring a new frame.
  9344. * 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.
  9345. */
  9346. PerfCounter.prototype.fetchNewFrame = function () {
  9347. this._totalValueCount++;
  9348. this._current = 0;
  9349. this._lastSecValueCount++;
  9350. };
  9351. /**
  9352. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9353. * @param newCount the count value to add to the monitored count
  9354. * @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.
  9355. */
  9356. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9357. if (!PerfCounter.Enabled) {
  9358. return;
  9359. }
  9360. this._current += newCount;
  9361. if (fetchResult) {
  9362. this._fetchResult();
  9363. }
  9364. };
  9365. /**
  9366. * Start monitoring this performance counter
  9367. */
  9368. PerfCounter.prototype.beginMonitoring = function () {
  9369. if (!PerfCounter.Enabled) {
  9370. return;
  9371. }
  9372. this._startMonitoringTime = Tools.Now;
  9373. };
  9374. /**
  9375. * Compute the time lapsed since the previous beginMonitoring() call.
  9376. * @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
  9377. */
  9378. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9379. if (newFrame === void 0) { newFrame = true; }
  9380. if (!PerfCounter.Enabled) {
  9381. return;
  9382. }
  9383. if (newFrame) {
  9384. this.fetchNewFrame();
  9385. }
  9386. var currentTime = Tools.Now;
  9387. this._current = currentTime - this._startMonitoringTime;
  9388. if (newFrame) {
  9389. this._fetchResult();
  9390. }
  9391. };
  9392. PerfCounter.prototype._fetchResult = function () {
  9393. this._totalAccumulated += this._current;
  9394. this._lastSecAccumulated += this._current;
  9395. // Min/Max update
  9396. this._min = Math.min(this._min, this._current);
  9397. this._max = Math.max(this._max, this._current);
  9398. this._average = this._totalAccumulated / this._totalValueCount;
  9399. // Reset last sec?
  9400. var now = Tools.Now;
  9401. if ((now - this._lastSecTime) > 1000) {
  9402. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9403. this._lastSecTime = now;
  9404. this._lastSecAccumulated = 0;
  9405. this._lastSecValueCount = 0;
  9406. }
  9407. };
  9408. PerfCounter.Enabled = true;
  9409. return PerfCounter;
  9410. }());
  9411. BABYLON.PerfCounter = PerfCounter;
  9412. /**
  9413. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9414. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9415. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9416. * @param name The name of the class, case should be preserved
  9417. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9418. */
  9419. function className(name, module) {
  9420. return function (target) {
  9421. target["__bjsclassName__"] = name;
  9422. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9423. };
  9424. }
  9425. BABYLON.className = className;
  9426. /**
  9427. * An implementation of a loop for asynchronous functions.
  9428. */
  9429. var AsyncLoop = /** @class */ (function () {
  9430. /**
  9431. * Constroctor.
  9432. * @param iterations the number of iterations.
  9433. * @param _fn the function to run each iteration
  9434. * @param _successCallback the callback that will be called upon succesful execution
  9435. * @param offset starting offset.
  9436. */
  9437. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9438. if (offset === void 0) { offset = 0; }
  9439. this.iterations = iterations;
  9440. this._fn = _fn;
  9441. this._successCallback = _successCallback;
  9442. this.index = offset - 1;
  9443. this._done = false;
  9444. }
  9445. /**
  9446. * Execute the next iteration. Must be called after the last iteration was finished.
  9447. */
  9448. AsyncLoop.prototype.executeNext = function () {
  9449. if (!this._done) {
  9450. if (this.index + 1 < this.iterations) {
  9451. ++this.index;
  9452. this._fn(this);
  9453. }
  9454. else {
  9455. this.breakLoop();
  9456. }
  9457. }
  9458. };
  9459. /**
  9460. * Break the loop and run the success callback.
  9461. */
  9462. AsyncLoop.prototype.breakLoop = function () {
  9463. this._done = true;
  9464. this._successCallback();
  9465. };
  9466. /**
  9467. * Helper function
  9468. */
  9469. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9470. if (offset === void 0) { offset = 0; }
  9471. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9472. loop.executeNext();
  9473. return loop;
  9474. };
  9475. /**
  9476. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9477. * @param iterations total number of iterations
  9478. * @param syncedIterations number of synchronous iterations in each async iteration.
  9479. * @param fn the function to call each iteration.
  9480. * @param callback a success call back that will be called when iterating stops.
  9481. * @param breakFunction a break condition (optional)
  9482. * @param timeout timeout settings for the setTimeout function. default - 0.
  9483. * @constructor
  9484. */
  9485. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9486. if (timeout === void 0) { timeout = 0; }
  9487. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9488. if (breakFunction && breakFunction())
  9489. loop.breakLoop();
  9490. else {
  9491. setTimeout(function () {
  9492. for (var i = 0; i < syncedIterations; ++i) {
  9493. var iteration = (loop.index * syncedIterations) + i;
  9494. if (iteration >= iterations)
  9495. break;
  9496. fn(iteration);
  9497. if (breakFunction && breakFunction()) {
  9498. loop.breakLoop();
  9499. break;
  9500. }
  9501. }
  9502. loop.executeNext();
  9503. }, timeout);
  9504. }
  9505. }, callback);
  9506. };
  9507. return AsyncLoop;
  9508. }());
  9509. BABYLON.AsyncLoop = AsyncLoop;
  9510. })(BABYLON || (BABYLON = {}));
  9511. //# sourceMappingURL=babylon.tools.js.map
  9512. "use strict";
  9513. var BABYLON;
  9514. (function (BABYLON) {
  9515. var PromiseStates;
  9516. (function (PromiseStates) {
  9517. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9518. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9519. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9520. })(PromiseStates || (PromiseStates = {}));
  9521. var FulFillmentAgregator = /** @class */ (function () {
  9522. function FulFillmentAgregator() {
  9523. this.count = 0;
  9524. this.target = 0;
  9525. this.results = [];
  9526. }
  9527. return FulFillmentAgregator;
  9528. }());
  9529. var InternalPromise = /** @class */ (function () {
  9530. function InternalPromise(resolver) {
  9531. var _this = this;
  9532. this._state = PromiseStates.Pending;
  9533. this._children = new Array();
  9534. this._rejectWasConsumed = false;
  9535. if (!resolver) {
  9536. return;
  9537. }
  9538. try {
  9539. resolver(function (value) {
  9540. _this._resolve(value);
  9541. }, function (reason) {
  9542. _this._reject(reason);
  9543. });
  9544. }
  9545. catch (e) {
  9546. this._reject(e);
  9547. }
  9548. }
  9549. InternalPromise.prototype.catch = function (onRejected) {
  9550. return this.then(undefined, onRejected);
  9551. };
  9552. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9553. var _this = this;
  9554. var newPromise = new InternalPromise();
  9555. newPromise._onFulfilled = onFulfilled;
  9556. newPromise._onRejected = onRejected;
  9557. // Composition
  9558. this._children.push(newPromise);
  9559. if (this._state !== PromiseStates.Pending) {
  9560. BABYLON.Tools.SetImmediate(function () {
  9561. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9562. var returnedValue = newPromise._resolve(_this._result);
  9563. if (returnedValue !== undefined && returnedValue !== null) {
  9564. if (returnedValue._state !== undefined) {
  9565. var returnedPromise = returnedValue;
  9566. newPromise._children.push(returnedPromise);
  9567. newPromise = returnedPromise;
  9568. }
  9569. else {
  9570. newPromise._result = returnedValue;
  9571. }
  9572. }
  9573. }
  9574. else {
  9575. newPromise._reject(_this._reason);
  9576. }
  9577. });
  9578. }
  9579. return newPromise;
  9580. };
  9581. InternalPromise.prototype._moveChildren = function (children) {
  9582. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9583. if (this._state === PromiseStates.Fulfilled) {
  9584. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9585. var child = _b[_i];
  9586. child._resolve(this._result);
  9587. }
  9588. }
  9589. else if (this._state === PromiseStates.Rejected) {
  9590. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9591. var child = _d[_c];
  9592. child._reject(this._reason);
  9593. }
  9594. }
  9595. var _a;
  9596. };
  9597. InternalPromise.prototype._resolve = function (value) {
  9598. try {
  9599. this._state = PromiseStates.Fulfilled;
  9600. this._result = value;
  9601. var returnedValue = null;
  9602. if (this._onFulfilled) {
  9603. returnedValue = this._onFulfilled(value);
  9604. }
  9605. if (returnedValue !== undefined && returnedValue !== null) {
  9606. if (returnedValue._state !== undefined) {
  9607. // Transmit children
  9608. var returnedPromise = returnedValue;
  9609. returnedPromise._moveChildren(this._children);
  9610. }
  9611. else {
  9612. value = returnedValue;
  9613. }
  9614. }
  9615. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9616. var child = _a[_i];
  9617. child._resolve(value);
  9618. }
  9619. this._children.length = 0;
  9620. delete this._onFulfilled;
  9621. delete this._onRejected;
  9622. return returnedValue;
  9623. }
  9624. catch (e) {
  9625. this._reject(e, true);
  9626. }
  9627. return null;
  9628. };
  9629. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9630. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9631. this._state = PromiseStates.Rejected;
  9632. this._reason = reason;
  9633. if (this._onRejected && !onLocalThrow) {
  9634. try {
  9635. this._onRejected(reason);
  9636. this._rejectWasConsumed = true;
  9637. }
  9638. catch (e) {
  9639. reason = e;
  9640. }
  9641. }
  9642. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9643. var child = _a[_i];
  9644. if (this._rejectWasConsumed) {
  9645. child._resolve(null);
  9646. }
  9647. else {
  9648. child._reject(reason);
  9649. }
  9650. }
  9651. this._children.length = 0;
  9652. delete this._onFulfilled;
  9653. delete this._onRejected;
  9654. };
  9655. InternalPromise.resolve = function (value) {
  9656. var newPromise = new InternalPromise();
  9657. newPromise._resolve(value);
  9658. return newPromise;
  9659. };
  9660. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9661. promise.then(function (value) {
  9662. agregator.results[index] = value;
  9663. agregator.count++;
  9664. if (agregator.count === agregator.target) {
  9665. agregator.rootPromise._resolve(agregator.results);
  9666. }
  9667. return null;
  9668. }, function (reason) {
  9669. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9670. agregator.rootPromise._reject(reason);
  9671. }
  9672. });
  9673. };
  9674. InternalPromise.all = function (promises) {
  9675. var newPromise = new InternalPromise();
  9676. var agregator = new FulFillmentAgregator();
  9677. agregator.target = promises.length;
  9678. agregator.rootPromise = newPromise;
  9679. if (promises.length) {
  9680. for (var index = 0; index < promises.length; index++) {
  9681. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9682. }
  9683. }
  9684. else {
  9685. newPromise._resolve([]);
  9686. }
  9687. return newPromise;
  9688. };
  9689. InternalPromise.race = function (promises) {
  9690. var newPromise = new InternalPromise();
  9691. if (promises.length) {
  9692. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9693. var promise = promises_1[_i];
  9694. promise.then(function (value) {
  9695. if (newPromise) {
  9696. newPromise._resolve(value);
  9697. newPromise = null;
  9698. }
  9699. return null;
  9700. }, function (reason) {
  9701. if (newPromise) {
  9702. newPromise._reject(reason);
  9703. newPromise = null;
  9704. }
  9705. });
  9706. }
  9707. }
  9708. return newPromise;
  9709. };
  9710. return InternalPromise;
  9711. }());
  9712. /**
  9713. * Helper class that provides a small promise polyfill
  9714. */
  9715. var PromisePolyfill = /** @class */ (function () {
  9716. function PromisePolyfill() {
  9717. }
  9718. /**
  9719. * Static function used to check if the polyfill is required
  9720. * If this is the case then the function will inject the polyfill to window.Promise
  9721. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9722. */
  9723. PromisePolyfill.Apply = function (force) {
  9724. if (force === void 0) { force = false; }
  9725. if (force || typeof Promise === 'undefined') {
  9726. var root = window;
  9727. root.Promise = InternalPromise;
  9728. }
  9729. };
  9730. return PromisePolyfill;
  9731. }());
  9732. BABYLON.PromisePolyfill = PromisePolyfill;
  9733. })(BABYLON || (BABYLON = {}));
  9734. //# sourceMappingURL=babylon.promise.js.map
  9735. "use strict";
  9736. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9737. var BABYLON;
  9738. (function (BABYLON) {
  9739. /**
  9740. * Helper class to push actions to a pool of workers.
  9741. */
  9742. var WorkerPool = /** @class */ (function () {
  9743. /**
  9744. * Constructor
  9745. * @param workers Array of workers to use for actions
  9746. */
  9747. function WorkerPool(workers) {
  9748. this._pendingActions = new Array();
  9749. this._workerInfos = workers.map(function (worker) { return ({
  9750. worker: worker,
  9751. active: false
  9752. }); });
  9753. }
  9754. /**
  9755. * Terminates all workers and clears any pending actions.
  9756. */
  9757. WorkerPool.prototype.dispose = function () {
  9758. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9759. var workerInfo = _a[_i];
  9760. workerInfo.worker.terminate();
  9761. }
  9762. delete this._workerInfos;
  9763. delete this._pendingActions;
  9764. };
  9765. /**
  9766. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9767. * pended until a worker has completed its action.
  9768. * @param action The action to perform. Call onComplete when the action is complete.
  9769. */
  9770. WorkerPool.prototype.push = function (action) {
  9771. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9772. var workerInfo = _a[_i];
  9773. if (!workerInfo.active) {
  9774. this._execute(workerInfo, action);
  9775. return;
  9776. }
  9777. }
  9778. this._pendingActions.push(action);
  9779. };
  9780. WorkerPool.prototype._execute = function (workerInfo, action) {
  9781. var _this = this;
  9782. workerInfo.active = true;
  9783. action(workerInfo.worker, function () {
  9784. workerInfo.active = false;
  9785. var nextAction = _this._pendingActions.shift();
  9786. if (nextAction) {
  9787. _this._execute(workerInfo, nextAction);
  9788. }
  9789. });
  9790. };
  9791. return WorkerPool;
  9792. }());
  9793. BABYLON.WorkerPool = WorkerPool;
  9794. })(BABYLON || (BABYLON = {}));
  9795. //# sourceMappingURL=babylon.workerPool.js.map
  9796. "use strict";
  9797. var BABYLON;
  9798. (function (BABYLON) {
  9799. var _AlphaState = /** @class */ (function () {
  9800. /**
  9801. * Initializes the state.
  9802. */
  9803. function _AlphaState() {
  9804. this._isAlphaBlendDirty = false;
  9805. this._isBlendFunctionParametersDirty = false;
  9806. this._isBlendEquationParametersDirty = false;
  9807. this._isBlendConstantsDirty = false;
  9808. this._alphaBlend = false;
  9809. this._blendFunctionParameters = new Array(4);
  9810. this._blendEquationParameters = new Array(2);
  9811. this._blendConstants = new Array(4);
  9812. this.reset();
  9813. }
  9814. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9815. get: function () {
  9816. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9817. },
  9818. enumerable: true,
  9819. configurable: true
  9820. });
  9821. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9822. get: function () {
  9823. return this._alphaBlend;
  9824. },
  9825. set: function (value) {
  9826. if (this._alphaBlend === value) {
  9827. return;
  9828. }
  9829. this._alphaBlend = value;
  9830. this._isAlphaBlendDirty = true;
  9831. },
  9832. enumerable: true,
  9833. configurable: true
  9834. });
  9835. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9836. if (this._blendConstants[0] === r &&
  9837. this._blendConstants[1] === g &&
  9838. this._blendConstants[2] === b &&
  9839. this._blendConstants[3] === a) {
  9840. return;
  9841. }
  9842. this._blendConstants[0] = r;
  9843. this._blendConstants[1] = g;
  9844. this._blendConstants[2] = b;
  9845. this._blendConstants[3] = a;
  9846. this._isBlendConstantsDirty = true;
  9847. };
  9848. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9849. if (this._blendFunctionParameters[0] === value0 &&
  9850. this._blendFunctionParameters[1] === value1 &&
  9851. this._blendFunctionParameters[2] === value2 &&
  9852. this._blendFunctionParameters[3] === value3) {
  9853. return;
  9854. }
  9855. this._blendFunctionParameters[0] = value0;
  9856. this._blendFunctionParameters[1] = value1;
  9857. this._blendFunctionParameters[2] = value2;
  9858. this._blendFunctionParameters[3] = value3;
  9859. this._isBlendFunctionParametersDirty = true;
  9860. };
  9861. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9862. if (this._blendEquationParameters[0] === rgb &&
  9863. this._blendEquationParameters[1] === alpha) {
  9864. return;
  9865. }
  9866. this._blendEquationParameters[0] = rgb;
  9867. this._blendEquationParameters[1] = alpha;
  9868. this._isBlendEquationParametersDirty = true;
  9869. };
  9870. _AlphaState.prototype.reset = function () {
  9871. this._alphaBlend = false;
  9872. this._blendFunctionParameters[0] = null;
  9873. this._blendFunctionParameters[1] = null;
  9874. this._blendFunctionParameters[2] = null;
  9875. this._blendFunctionParameters[3] = null;
  9876. this._blendEquationParameters[0] = null;
  9877. this._blendEquationParameters[1] = null;
  9878. this._blendConstants[0] = null;
  9879. this._blendConstants[1] = null;
  9880. this._blendConstants[2] = null;
  9881. this._blendConstants[3] = null;
  9882. this._isAlphaBlendDirty = true;
  9883. this._isBlendFunctionParametersDirty = false;
  9884. this._isBlendEquationParametersDirty = false;
  9885. this._isBlendConstantsDirty = false;
  9886. };
  9887. _AlphaState.prototype.apply = function (gl) {
  9888. if (!this.isDirty) {
  9889. return;
  9890. }
  9891. // Alpha blend
  9892. if (this._isAlphaBlendDirty) {
  9893. if (this._alphaBlend) {
  9894. gl.enable(gl.BLEND);
  9895. }
  9896. else {
  9897. gl.disable(gl.BLEND);
  9898. }
  9899. this._isAlphaBlendDirty = false;
  9900. }
  9901. // Alpha function
  9902. if (this._isBlendFunctionParametersDirty) {
  9903. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9904. this._isBlendFunctionParametersDirty = false;
  9905. }
  9906. // Alpha equation
  9907. if (this._isBlendEquationParametersDirty) {
  9908. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9909. this._isBlendEquationParametersDirty = false;
  9910. }
  9911. // Constants
  9912. if (this._isBlendConstantsDirty) {
  9913. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9914. this._isBlendConstantsDirty = false;
  9915. }
  9916. };
  9917. return _AlphaState;
  9918. }());
  9919. BABYLON._AlphaState = _AlphaState;
  9920. })(BABYLON || (BABYLON = {}));
  9921. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9922. "use strict";
  9923. var BABYLON;
  9924. (function (BABYLON) {
  9925. var _DepthCullingState = /** @class */ (function () {
  9926. /**
  9927. * Initializes the state.
  9928. */
  9929. function _DepthCullingState() {
  9930. this._isDepthTestDirty = false;
  9931. this._isDepthMaskDirty = false;
  9932. this._isDepthFuncDirty = false;
  9933. this._isCullFaceDirty = false;
  9934. this._isCullDirty = false;
  9935. this._isZOffsetDirty = false;
  9936. this._isFrontFaceDirty = false;
  9937. this.reset();
  9938. }
  9939. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9940. get: function () {
  9941. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9942. },
  9943. enumerable: true,
  9944. configurable: true
  9945. });
  9946. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9947. get: function () {
  9948. return this._zOffset;
  9949. },
  9950. set: function (value) {
  9951. if (this._zOffset === value) {
  9952. return;
  9953. }
  9954. this._zOffset = value;
  9955. this._isZOffsetDirty = true;
  9956. },
  9957. enumerable: true,
  9958. configurable: true
  9959. });
  9960. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9961. get: function () {
  9962. return this._cullFace;
  9963. },
  9964. set: function (value) {
  9965. if (this._cullFace === value) {
  9966. return;
  9967. }
  9968. this._cullFace = value;
  9969. this._isCullFaceDirty = true;
  9970. },
  9971. enumerable: true,
  9972. configurable: true
  9973. });
  9974. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9975. get: function () {
  9976. return this._cull;
  9977. },
  9978. set: function (value) {
  9979. if (this._cull === value) {
  9980. return;
  9981. }
  9982. this._cull = value;
  9983. this._isCullDirty = true;
  9984. },
  9985. enumerable: true,
  9986. configurable: true
  9987. });
  9988. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9989. get: function () {
  9990. return this._depthFunc;
  9991. },
  9992. set: function (value) {
  9993. if (this._depthFunc === value) {
  9994. return;
  9995. }
  9996. this._depthFunc = value;
  9997. this._isDepthFuncDirty = true;
  9998. },
  9999. enumerable: true,
  10000. configurable: true
  10001. });
  10002. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10003. get: function () {
  10004. return this._depthMask;
  10005. },
  10006. set: function (value) {
  10007. if (this._depthMask === value) {
  10008. return;
  10009. }
  10010. this._depthMask = value;
  10011. this._isDepthMaskDirty = true;
  10012. },
  10013. enumerable: true,
  10014. configurable: true
  10015. });
  10016. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10017. get: function () {
  10018. return this._depthTest;
  10019. },
  10020. set: function (value) {
  10021. if (this._depthTest === value) {
  10022. return;
  10023. }
  10024. this._depthTest = value;
  10025. this._isDepthTestDirty = true;
  10026. },
  10027. enumerable: true,
  10028. configurable: true
  10029. });
  10030. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10031. get: function () {
  10032. return this._frontFace;
  10033. },
  10034. set: function (value) {
  10035. if (this._frontFace === value) {
  10036. return;
  10037. }
  10038. this._frontFace = value;
  10039. this._isFrontFaceDirty = true;
  10040. },
  10041. enumerable: true,
  10042. configurable: true
  10043. });
  10044. _DepthCullingState.prototype.reset = function () {
  10045. this._depthMask = true;
  10046. this._depthTest = true;
  10047. this._depthFunc = null;
  10048. this._cullFace = null;
  10049. this._cull = null;
  10050. this._zOffset = 0;
  10051. this._frontFace = null;
  10052. this._isDepthTestDirty = true;
  10053. this._isDepthMaskDirty = true;
  10054. this._isDepthFuncDirty = false;
  10055. this._isCullFaceDirty = false;
  10056. this._isCullDirty = false;
  10057. this._isZOffsetDirty = false;
  10058. this._isFrontFaceDirty = false;
  10059. };
  10060. _DepthCullingState.prototype.apply = function (gl) {
  10061. if (!this.isDirty) {
  10062. return;
  10063. }
  10064. // Cull
  10065. if (this._isCullDirty) {
  10066. if (this.cull) {
  10067. gl.enable(gl.CULL_FACE);
  10068. }
  10069. else {
  10070. gl.disable(gl.CULL_FACE);
  10071. }
  10072. this._isCullDirty = false;
  10073. }
  10074. // Cull face
  10075. if (this._isCullFaceDirty) {
  10076. gl.cullFace(this.cullFace);
  10077. this._isCullFaceDirty = false;
  10078. }
  10079. // Depth mask
  10080. if (this._isDepthMaskDirty) {
  10081. gl.depthMask(this.depthMask);
  10082. this._isDepthMaskDirty = false;
  10083. }
  10084. // Depth test
  10085. if (this._isDepthTestDirty) {
  10086. if (this.depthTest) {
  10087. gl.enable(gl.DEPTH_TEST);
  10088. }
  10089. else {
  10090. gl.disable(gl.DEPTH_TEST);
  10091. }
  10092. this._isDepthTestDirty = false;
  10093. }
  10094. // Depth func
  10095. if (this._isDepthFuncDirty) {
  10096. gl.depthFunc(this.depthFunc);
  10097. this._isDepthFuncDirty = false;
  10098. }
  10099. // zOffset
  10100. if (this._isZOffsetDirty) {
  10101. if (this.zOffset) {
  10102. gl.enable(gl.POLYGON_OFFSET_FILL);
  10103. gl.polygonOffset(this.zOffset, 0);
  10104. }
  10105. else {
  10106. gl.disable(gl.POLYGON_OFFSET_FILL);
  10107. }
  10108. this._isZOffsetDirty = false;
  10109. }
  10110. // Front face
  10111. if (this._isFrontFaceDirty) {
  10112. gl.frontFace(this.frontFace);
  10113. this._isFrontFaceDirty = false;
  10114. }
  10115. };
  10116. return _DepthCullingState;
  10117. }());
  10118. BABYLON._DepthCullingState = _DepthCullingState;
  10119. })(BABYLON || (BABYLON = {}));
  10120. //# sourceMappingURL=babylon.depthCullingState.js.map
  10121. "use strict";
  10122. var BABYLON;
  10123. (function (BABYLON) {
  10124. var _StencilState = /** @class */ (function () {
  10125. function _StencilState() {
  10126. this._isStencilTestDirty = false;
  10127. this._isStencilMaskDirty = false;
  10128. this._isStencilFuncDirty = false;
  10129. this._isStencilOpDirty = false;
  10130. this.reset();
  10131. }
  10132. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10133. get: function () {
  10134. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10135. },
  10136. enumerable: true,
  10137. configurable: true
  10138. });
  10139. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10140. get: function () {
  10141. return this._stencilFunc;
  10142. },
  10143. set: function (value) {
  10144. if (this._stencilFunc === value) {
  10145. return;
  10146. }
  10147. this._stencilFunc = value;
  10148. this._isStencilFuncDirty = true;
  10149. },
  10150. enumerable: true,
  10151. configurable: true
  10152. });
  10153. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10154. get: function () {
  10155. return this._stencilFuncRef;
  10156. },
  10157. set: function (value) {
  10158. if (this._stencilFuncRef === value) {
  10159. return;
  10160. }
  10161. this._stencilFuncRef = value;
  10162. this._isStencilFuncDirty = true;
  10163. },
  10164. enumerable: true,
  10165. configurable: true
  10166. });
  10167. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10168. get: function () {
  10169. return this._stencilFuncMask;
  10170. },
  10171. set: function (value) {
  10172. if (this._stencilFuncMask === value) {
  10173. return;
  10174. }
  10175. this._stencilFuncMask = value;
  10176. this._isStencilFuncDirty = true;
  10177. },
  10178. enumerable: true,
  10179. configurable: true
  10180. });
  10181. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10182. get: function () {
  10183. return this._stencilOpStencilFail;
  10184. },
  10185. set: function (value) {
  10186. if (this._stencilOpStencilFail === value) {
  10187. return;
  10188. }
  10189. this._stencilOpStencilFail = value;
  10190. this._isStencilOpDirty = true;
  10191. },
  10192. enumerable: true,
  10193. configurable: true
  10194. });
  10195. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10196. get: function () {
  10197. return this._stencilOpDepthFail;
  10198. },
  10199. set: function (value) {
  10200. if (this._stencilOpDepthFail === value) {
  10201. return;
  10202. }
  10203. this._stencilOpDepthFail = value;
  10204. this._isStencilOpDirty = true;
  10205. },
  10206. enumerable: true,
  10207. configurable: true
  10208. });
  10209. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10210. get: function () {
  10211. return this._stencilOpStencilDepthPass;
  10212. },
  10213. set: function (value) {
  10214. if (this._stencilOpStencilDepthPass === value) {
  10215. return;
  10216. }
  10217. this._stencilOpStencilDepthPass = value;
  10218. this._isStencilOpDirty = true;
  10219. },
  10220. enumerable: true,
  10221. configurable: true
  10222. });
  10223. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10224. get: function () {
  10225. return this._stencilMask;
  10226. },
  10227. set: function (value) {
  10228. if (this._stencilMask === value) {
  10229. return;
  10230. }
  10231. this._stencilMask = value;
  10232. this._isStencilMaskDirty = true;
  10233. },
  10234. enumerable: true,
  10235. configurable: true
  10236. });
  10237. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10238. get: function () {
  10239. return this._stencilTest;
  10240. },
  10241. set: function (value) {
  10242. if (this._stencilTest === value) {
  10243. return;
  10244. }
  10245. this._stencilTest = value;
  10246. this._isStencilTestDirty = true;
  10247. },
  10248. enumerable: true,
  10249. configurable: true
  10250. });
  10251. _StencilState.prototype.reset = function () {
  10252. this._stencilTest = false;
  10253. this._stencilMask = 0xFF;
  10254. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10255. this._stencilFuncRef = 1;
  10256. this._stencilFuncMask = 0xFF;
  10257. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10258. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10259. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10260. this._isStencilTestDirty = true;
  10261. this._isStencilMaskDirty = true;
  10262. this._isStencilFuncDirty = true;
  10263. this._isStencilOpDirty = true;
  10264. };
  10265. _StencilState.prototype.apply = function (gl) {
  10266. if (!this.isDirty) {
  10267. return;
  10268. }
  10269. // Stencil test
  10270. if (this._isStencilTestDirty) {
  10271. if (this.stencilTest) {
  10272. gl.enable(gl.STENCIL_TEST);
  10273. }
  10274. else {
  10275. gl.disable(gl.STENCIL_TEST);
  10276. }
  10277. this._isStencilTestDirty = false;
  10278. }
  10279. // Stencil mask
  10280. if (this._isStencilMaskDirty) {
  10281. gl.stencilMask(this.stencilMask);
  10282. this._isStencilMaskDirty = false;
  10283. }
  10284. // Stencil func
  10285. if (this._isStencilFuncDirty) {
  10286. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10287. this._isStencilFuncDirty = false;
  10288. }
  10289. // Stencil op
  10290. if (this._isStencilOpDirty) {
  10291. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10292. this._isStencilOpDirty = false;
  10293. }
  10294. };
  10295. return _StencilState;
  10296. }());
  10297. BABYLON._StencilState = _StencilState;
  10298. })(BABYLON || (BABYLON = {}));
  10299. //# sourceMappingURL=babylon.stencilState.js.map
  10300. "use strict";
  10301. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10302. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10303. s = arguments[i];
  10304. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10305. t[p] = s[p];
  10306. }
  10307. return t;
  10308. };
  10309. var BABYLON;
  10310. (function (BABYLON) {
  10311. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10312. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10313. };
  10314. var compileRawShader = function (gl, source, type) {
  10315. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10316. gl.shaderSource(shader, source);
  10317. gl.compileShader(shader);
  10318. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10319. var log = gl.getShaderInfoLog(shader);
  10320. if (log) {
  10321. throw new Error(log);
  10322. }
  10323. }
  10324. if (!shader) {
  10325. throw new Error("Something went wrong while compile the shader.");
  10326. }
  10327. return shader;
  10328. };
  10329. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10330. var magFilter = gl.NEAREST;
  10331. var minFilter = gl.NEAREST;
  10332. switch (samplingMode) {
  10333. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10334. magFilter = gl.LINEAR;
  10335. if (generateMipMaps) {
  10336. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10337. }
  10338. else {
  10339. minFilter = gl.LINEAR;
  10340. }
  10341. break;
  10342. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10343. magFilter = gl.LINEAR;
  10344. if (generateMipMaps) {
  10345. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10346. }
  10347. else {
  10348. minFilter = gl.LINEAR;
  10349. }
  10350. break;
  10351. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10352. magFilter = gl.NEAREST;
  10353. if (generateMipMaps) {
  10354. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10355. }
  10356. else {
  10357. minFilter = gl.NEAREST;
  10358. }
  10359. break;
  10360. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10361. magFilter = gl.NEAREST;
  10362. if (generateMipMaps) {
  10363. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10364. }
  10365. else {
  10366. minFilter = gl.NEAREST;
  10367. }
  10368. break;
  10369. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10370. magFilter = gl.NEAREST;
  10371. if (generateMipMaps) {
  10372. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10373. }
  10374. else {
  10375. minFilter = gl.LINEAR;
  10376. }
  10377. break;
  10378. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10379. magFilter = gl.NEAREST;
  10380. if (generateMipMaps) {
  10381. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10382. }
  10383. else {
  10384. minFilter = gl.LINEAR;
  10385. }
  10386. break;
  10387. case BABYLON.Texture.NEAREST_LINEAR:
  10388. magFilter = gl.NEAREST;
  10389. minFilter = gl.LINEAR;
  10390. break;
  10391. case BABYLON.Texture.NEAREST_NEAREST:
  10392. magFilter = gl.NEAREST;
  10393. minFilter = gl.NEAREST;
  10394. break;
  10395. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10396. magFilter = gl.LINEAR;
  10397. if (generateMipMaps) {
  10398. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10399. }
  10400. else {
  10401. minFilter = gl.NEAREST;
  10402. }
  10403. break;
  10404. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10405. magFilter = gl.LINEAR;
  10406. if (generateMipMaps) {
  10407. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10408. }
  10409. else {
  10410. minFilter = gl.NEAREST;
  10411. }
  10412. break;
  10413. case BABYLON.Texture.LINEAR_LINEAR:
  10414. magFilter = gl.LINEAR;
  10415. minFilter = gl.LINEAR;
  10416. break;
  10417. case BABYLON.Texture.LINEAR_NEAREST:
  10418. magFilter = gl.LINEAR;
  10419. minFilter = gl.NEAREST;
  10420. break;
  10421. }
  10422. return {
  10423. min: minFilter,
  10424. mag: magFilter
  10425. };
  10426. };
  10427. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10428. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10429. var img;
  10430. var onload = function () {
  10431. loadedImages[index] = img;
  10432. loadedImages._internalCount++;
  10433. if (scene) {
  10434. scene._removePendingData(img);
  10435. }
  10436. if (loadedImages._internalCount === 6) {
  10437. onfinish(loadedImages);
  10438. }
  10439. };
  10440. var onerror = function (message, exception) {
  10441. if (scene) {
  10442. scene._removePendingData(img);
  10443. }
  10444. if (onErrorCallBack) {
  10445. onErrorCallBack(message, exception);
  10446. }
  10447. };
  10448. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10449. if (scene) {
  10450. scene._addPendingData(img);
  10451. }
  10452. };
  10453. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10454. if (onError === void 0) { onError = null; }
  10455. var loadedImages = [];
  10456. loadedImages._internalCount = 0;
  10457. for (var index = 0; index < 6; index++) {
  10458. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10459. }
  10460. };
  10461. var BufferPointer = /** @class */ (function () {
  10462. function BufferPointer() {
  10463. }
  10464. return BufferPointer;
  10465. }());
  10466. var InstancingAttributeInfo = /** @class */ (function () {
  10467. function InstancingAttributeInfo() {
  10468. }
  10469. return InstancingAttributeInfo;
  10470. }());
  10471. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10472. /**
  10473. * Define options used to create a render target texture
  10474. */
  10475. var RenderTargetCreationOptions = /** @class */ (function () {
  10476. function RenderTargetCreationOptions() {
  10477. }
  10478. return RenderTargetCreationOptions;
  10479. }());
  10480. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10481. /**
  10482. * Define options used to create a depth texture
  10483. */
  10484. var DepthTextureCreationOptions = /** @class */ (function () {
  10485. function DepthTextureCreationOptions() {
  10486. }
  10487. return DepthTextureCreationOptions;
  10488. }());
  10489. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10490. /**
  10491. * Regroup several parameters relative to the browser in use
  10492. */
  10493. var EngineCapabilities = /** @class */ (function () {
  10494. function EngineCapabilities() {
  10495. }
  10496. return EngineCapabilities;
  10497. }());
  10498. BABYLON.EngineCapabilities = EngineCapabilities;
  10499. /**
  10500. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10501. */
  10502. var Engine = /** @class */ (function () {
  10503. /**
  10504. * @constructor
  10505. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10506. * @param antialias defines enable antialiasing (default: false)
  10507. * @param options defines further options to be sent to the getContext() function
  10508. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10509. */
  10510. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10511. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10512. var _this = this;
  10513. // Public members
  10514. this.forcePOTTextures = false;
  10515. this.isFullscreen = false;
  10516. this.isPointerLock = false;
  10517. this.cullBackFaces = true;
  10518. this.renderEvenInBackground = true;
  10519. this.preventCacheWipeBetweenFrames = false;
  10520. // To enable/disable IDB support and avoid XHR on .manifest
  10521. this.enableOfflineSupport = false;
  10522. this.scenes = new Array();
  10523. this.postProcesses = new Array();
  10524. // Observables
  10525. /**
  10526. * Observable event triggered each time the rendering canvas is resized
  10527. */
  10528. this.onResizeObservable = new BABYLON.Observable();
  10529. /**
  10530. * Observable event triggered each time the canvas loses focus
  10531. */
  10532. this.onCanvasBlurObservable = new BABYLON.Observable();
  10533. /**
  10534. * Observable event triggered each time the canvas gains focus
  10535. */
  10536. this.onCanvasFocusObservable = new BABYLON.Observable();
  10537. /**
  10538. * Observable event triggered each time the canvas receives pointerout event
  10539. */
  10540. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10541. /**
  10542. * Observable event triggered before each texture is initialized
  10543. */
  10544. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10545. //WebVR
  10546. this._vrDisplay = undefined;
  10547. this._vrSupported = false;
  10548. this._vrExclusivePointerMode = false;
  10549. // Uniform buffers list
  10550. this.disableUniformBuffers = false;
  10551. this._uniformBuffers = new Array();
  10552. // Observables
  10553. /**
  10554. * Observable raised when the engine begins a new frame
  10555. */
  10556. this.onBeginFrameObservable = new BABYLON.Observable();
  10557. /**
  10558. * Observable raised when the engine ends the current frame
  10559. */
  10560. this.onEndFrameObservable = new BABYLON.Observable();
  10561. /**
  10562. * Observable raised when the engine is about to compile a shader
  10563. */
  10564. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10565. /**
  10566. * Observable raised when the engine has jsut compiled a shader
  10567. */
  10568. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10569. this._windowIsBackground = false;
  10570. this._webGLVersion = 1.0;
  10571. this._badOS = false;
  10572. this._badDesktopOS = false;
  10573. /**
  10574. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10575. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10576. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10577. */
  10578. this.disableTextureBindingOptimization = false;
  10579. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10580. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10581. this.onVRRequestPresentStart = new BABYLON.Observable();
  10582. this._colorWrite = true;
  10583. this._drawCalls = new BABYLON.PerfCounter();
  10584. this._textureCollisions = new BABYLON.PerfCounter();
  10585. this._renderingQueueLaunched = false;
  10586. this._activeRenderLoops = new Array();
  10587. // Deterministic lockstepMaxSteps
  10588. this._deterministicLockstep = false;
  10589. this._lockstepMaxSteps = 4;
  10590. // Lost context
  10591. this.onContextLostObservable = new BABYLON.Observable();
  10592. this.onContextRestoredObservable = new BABYLON.Observable();
  10593. this._contextWasLost = false;
  10594. this._doNotHandleContextLost = false;
  10595. // FPS
  10596. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10597. this._fps = 60;
  10598. this._deltaTime = 0;
  10599. /**
  10600. * Turn this value on if you want to pause FPS computation when in background
  10601. */
  10602. this.disablePerformanceMonitorInBackground = false;
  10603. // States
  10604. this._depthCullingState = new BABYLON._DepthCullingState();
  10605. this._stencilState = new BABYLON._StencilState();
  10606. this._alphaState = new BABYLON._AlphaState();
  10607. this._alphaMode = Engine.ALPHA_DISABLE;
  10608. // Cache
  10609. this._internalTexturesCache = new Array();
  10610. this._activeChannel = 0;
  10611. this._currentTextureChannel = -1;
  10612. this._boundTexturesCache = {};
  10613. this._compiledEffects = {};
  10614. this._vertexAttribArraysEnabled = [];
  10615. this._uintIndicesCurrentlySet = false;
  10616. this._currentBoundBuffer = new Array();
  10617. this._currentBufferPointers = new Array();
  10618. this._currentInstanceLocations = new Array();
  10619. this._currentInstanceBuffers = new Array();
  10620. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10621. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10622. this._vaoRecordInProgress = false;
  10623. this._mustWipeVertexAttributes = false;
  10624. this._nextFreeTextureSlots = new Array();
  10625. this._maxSimultaneousTextures = 0;
  10626. this._activeRequests = new Array();
  10627. // Hardware supported Compressed Textures
  10628. this._texturesSupported = new Array();
  10629. this._onVRFullScreenTriggered = function () {
  10630. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10631. //get the old size before we change
  10632. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10633. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10634. //get the width and height, change the render size
  10635. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10636. _this.setHardwareScalingLevel(1);
  10637. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10638. }
  10639. else {
  10640. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10641. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10642. }
  10643. };
  10644. this._boundUniforms = {};
  10645. // Register promises
  10646. BABYLON.PromisePolyfill.Apply();
  10647. var canvas = null;
  10648. Engine.Instances.push(this);
  10649. if (!canvasOrContext) {
  10650. return;
  10651. }
  10652. options = options || {};
  10653. if (canvasOrContext.getContext) {
  10654. canvas = canvasOrContext;
  10655. this._renderingCanvas = canvas;
  10656. if (antialias != null) {
  10657. options.antialias = antialias;
  10658. }
  10659. if (options.deterministicLockstep === undefined) {
  10660. options.deterministicLockstep = false;
  10661. }
  10662. if (options.lockstepMaxSteps === undefined) {
  10663. options.lockstepMaxSteps = 4;
  10664. }
  10665. if (options.preserveDrawingBuffer === undefined) {
  10666. options.preserveDrawingBuffer = false;
  10667. }
  10668. if (options.audioEngine === undefined) {
  10669. options.audioEngine = true;
  10670. }
  10671. if (options.stencil === undefined) {
  10672. options.stencil = true;
  10673. }
  10674. this._deterministicLockstep = options.deterministicLockstep;
  10675. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10676. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10677. // Exceptions
  10678. if (navigator && navigator.userAgent) {
  10679. var ua = navigator.userAgent;
  10680. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10681. var exception = _a[_i];
  10682. var key = exception.key;
  10683. var targets = exception.targets;
  10684. if (ua.indexOf(key) > -1) {
  10685. if (exception.capture && exception.captureConstraint) {
  10686. var capture = exception.capture;
  10687. var constraint = exception.captureConstraint;
  10688. var regex = new RegExp(capture);
  10689. var matches = regex.exec(ua);
  10690. if (matches && matches.length > 0) {
  10691. var capturedValue = parseInt(matches[matches.length - 1]);
  10692. if (capturedValue >= constraint) {
  10693. continue;
  10694. }
  10695. }
  10696. }
  10697. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10698. var target = targets_1[_b];
  10699. switch (target) {
  10700. case "uniformBuffer":
  10701. this.disableUniformBuffers = true;
  10702. break;
  10703. case "textureBindingOptimization":
  10704. this.disableTextureBindingOptimization = true;
  10705. break;
  10706. }
  10707. }
  10708. }
  10709. }
  10710. }
  10711. // GL
  10712. if (!options.disableWebGL2Support) {
  10713. try {
  10714. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10715. if (this._gl) {
  10716. this._webGLVersion = 2.0;
  10717. }
  10718. }
  10719. catch (e) {
  10720. // Do nothing
  10721. }
  10722. }
  10723. if (!this._gl) {
  10724. if (!canvas) {
  10725. throw new Error("The provided canvas is null or undefined.");
  10726. }
  10727. try {
  10728. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10729. }
  10730. catch (e) {
  10731. throw new Error("WebGL not supported");
  10732. }
  10733. }
  10734. if (!this._gl) {
  10735. throw new Error("WebGL not supported");
  10736. }
  10737. this._onCanvasFocus = function () {
  10738. _this.onCanvasFocusObservable.notifyObservers(_this);
  10739. };
  10740. this._onCanvasBlur = function () {
  10741. _this.onCanvasBlurObservable.notifyObservers(_this);
  10742. };
  10743. canvas.addEventListener("focus", this._onCanvasFocus);
  10744. canvas.addEventListener("blur", this._onCanvasBlur);
  10745. this._onBlur = function () {
  10746. if (_this.disablePerformanceMonitorInBackground) {
  10747. _this._performanceMonitor.disable();
  10748. }
  10749. _this._windowIsBackground = true;
  10750. };
  10751. this._onFocus = function () {
  10752. if (_this.disablePerformanceMonitorInBackground) {
  10753. _this._performanceMonitor.enable();
  10754. }
  10755. _this._windowIsBackground = false;
  10756. };
  10757. this._onCanvasPointerOut = function (ev) {
  10758. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10759. };
  10760. window.addEventListener("blur", this._onBlur);
  10761. window.addEventListener("focus", this._onFocus);
  10762. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10763. // Context lost
  10764. if (!this._doNotHandleContextLost) {
  10765. this._onContextLost = function (evt) {
  10766. evt.preventDefault();
  10767. _this._contextWasLost = true;
  10768. BABYLON.Tools.Warn("WebGL context lost.");
  10769. _this.onContextLostObservable.notifyObservers(_this);
  10770. };
  10771. this._onContextRestored = function (evt) {
  10772. // Adding a timeout to avoid race condition at browser level
  10773. setTimeout(function () {
  10774. // Rebuild gl context
  10775. _this._initGLContext();
  10776. // Rebuild effects
  10777. _this._rebuildEffects();
  10778. // Rebuild textures
  10779. _this._rebuildInternalTextures();
  10780. // Rebuild buffers
  10781. _this._rebuildBuffers();
  10782. // Cache
  10783. _this.wipeCaches(true);
  10784. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10785. _this.onContextRestoredObservable.notifyObservers(_this);
  10786. _this._contextWasLost = false;
  10787. }, 0);
  10788. };
  10789. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10790. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10791. }
  10792. }
  10793. else {
  10794. this._gl = canvasOrContext;
  10795. this._renderingCanvas = this._gl.canvas;
  10796. if (this._gl.renderbufferStorageMultisample) {
  10797. this._webGLVersion = 2.0;
  10798. }
  10799. options.stencil = this._gl.getContextAttributes().stencil;
  10800. }
  10801. // Viewport
  10802. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10803. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10804. this.resize();
  10805. this._isStencilEnable = options.stencil ? true : false;
  10806. this._initGLContext();
  10807. if (canvas) {
  10808. // Fullscreen
  10809. this._onFullscreenChange = function () {
  10810. if (document.fullscreen !== undefined) {
  10811. _this.isFullscreen = document.fullscreen;
  10812. }
  10813. else if (document.mozFullScreen !== undefined) {
  10814. _this.isFullscreen = document.mozFullScreen;
  10815. }
  10816. else if (document.webkitIsFullScreen !== undefined) {
  10817. _this.isFullscreen = document.webkitIsFullScreen;
  10818. }
  10819. else if (document.msIsFullScreen !== undefined) {
  10820. _this.isFullscreen = document.msIsFullScreen;
  10821. }
  10822. // Pointer lock
  10823. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10824. canvas.requestPointerLock = canvas.requestPointerLock ||
  10825. canvas.msRequestPointerLock ||
  10826. canvas.mozRequestPointerLock ||
  10827. canvas.webkitRequestPointerLock;
  10828. if (canvas.requestPointerLock) {
  10829. canvas.requestPointerLock();
  10830. }
  10831. }
  10832. };
  10833. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10834. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10835. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10836. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10837. // Pointer lock
  10838. this._onPointerLockChange = function () {
  10839. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10840. document.webkitPointerLockElement === canvas ||
  10841. document.msPointerLockElement === canvas ||
  10842. document.pointerLockElement === canvas);
  10843. };
  10844. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10845. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10846. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10847. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10848. this._onVRDisplayPointerRestricted = function () {
  10849. if (canvas) {
  10850. canvas.requestPointerLock();
  10851. }
  10852. };
  10853. this._onVRDisplayPointerUnrestricted = function () {
  10854. document.exitPointerLock();
  10855. };
  10856. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10857. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10858. }
  10859. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10860. Engine.audioEngine = new BABYLON.AudioEngine();
  10861. }
  10862. // Prepare buffer pointers
  10863. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10864. this._currentBufferPointers[i] = new BufferPointer();
  10865. }
  10866. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10867. // Load WebVR Devices
  10868. if (options.autoEnableWebVR) {
  10869. this.initWebVR();
  10870. }
  10871. // Detect if we are running on a faulty buggy OS.
  10872. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10873. // Detect if we are running on a faulty buggy desktop OS.
  10874. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10875. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10876. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10877. }
  10878. Object.defineProperty(Engine, "LastCreatedEngine", {
  10879. get: function () {
  10880. if (Engine.Instances.length === 0) {
  10881. return null;
  10882. }
  10883. return Engine.Instances[Engine.Instances.length - 1];
  10884. },
  10885. enumerable: true,
  10886. configurable: true
  10887. });
  10888. Object.defineProperty(Engine, "LastCreatedScene", {
  10889. get: function () {
  10890. var lastCreatedEngine = Engine.LastCreatedEngine;
  10891. if (!lastCreatedEngine) {
  10892. return null;
  10893. }
  10894. if (lastCreatedEngine.scenes.length === 0) {
  10895. return null;
  10896. }
  10897. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10898. },
  10899. enumerable: true,
  10900. configurable: true
  10901. });
  10902. /**
  10903. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10904. */
  10905. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10906. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10907. var engine = Engine.Instances[engineIndex];
  10908. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10909. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10910. }
  10911. }
  10912. };
  10913. Object.defineProperty(Engine, "NEVER", {
  10914. get: function () {
  10915. return Engine._NEVER;
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. Object.defineProperty(Engine, "ALWAYS", {
  10921. get: function () {
  10922. return Engine._ALWAYS;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(Engine, "LESS", {
  10928. get: function () {
  10929. return Engine._LESS;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. Object.defineProperty(Engine, "EQUAL", {
  10935. get: function () {
  10936. return Engine._EQUAL;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. Object.defineProperty(Engine, "LEQUAL", {
  10942. get: function () {
  10943. return Engine._LEQUAL;
  10944. },
  10945. enumerable: true,
  10946. configurable: true
  10947. });
  10948. Object.defineProperty(Engine, "GREATER", {
  10949. get: function () {
  10950. return Engine._GREATER;
  10951. },
  10952. enumerable: true,
  10953. configurable: true
  10954. });
  10955. Object.defineProperty(Engine, "GEQUAL", {
  10956. get: function () {
  10957. return Engine._GEQUAL;
  10958. },
  10959. enumerable: true,
  10960. configurable: true
  10961. });
  10962. Object.defineProperty(Engine, "NOTEQUAL", {
  10963. get: function () {
  10964. return Engine._NOTEQUAL;
  10965. },
  10966. enumerable: true,
  10967. configurable: true
  10968. });
  10969. Object.defineProperty(Engine, "KEEP", {
  10970. get: function () {
  10971. return Engine._KEEP;
  10972. },
  10973. enumerable: true,
  10974. configurable: true
  10975. });
  10976. Object.defineProperty(Engine, "REPLACE", {
  10977. get: function () {
  10978. return Engine._REPLACE;
  10979. },
  10980. enumerable: true,
  10981. configurable: true
  10982. });
  10983. Object.defineProperty(Engine, "INCR", {
  10984. get: function () {
  10985. return Engine._INCR;
  10986. },
  10987. enumerable: true,
  10988. configurable: true
  10989. });
  10990. Object.defineProperty(Engine, "DECR", {
  10991. get: function () {
  10992. return Engine._DECR;
  10993. },
  10994. enumerable: true,
  10995. configurable: true
  10996. });
  10997. Object.defineProperty(Engine, "INVERT", {
  10998. get: function () {
  10999. return Engine._INVERT;
  11000. },
  11001. enumerable: true,
  11002. configurable: true
  11003. });
  11004. Object.defineProperty(Engine, "INCR_WRAP", {
  11005. get: function () {
  11006. return Engine._INCR_WRAP;
  11007. },
  11008. enumerable: true,
  11009. configurable: true
  11010. });
  11011. Object.defineProperty(Engine, "DECR_WRAP", {
  11012. get: function () {
  11013. return Engine._DECR_WRAP;
  11014. },
  11015. enumerable: true,
  11016. configurable: true
  11017. });
  11018. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11019. get: function () {
  11020. return Engine._ALPHA_DISABLE;
  11021. },
  11022. enumerable: true,
  11023. configurable: true
  11024. });
  11025. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11026. get: function () {
  11027. return Engine._ALPHA_ONEONE;
  11028. },
  11029. enumerable: true,
  11030. configurable: true
  11031. });
  11032. Object.defineProperty(Engine, "ALPHA_ADD", {
  11033. get: function () {
  11034. return Engine._ALPHA_ADD;
  11035. },
  11036. enumerable: true,
  11037. configurable: true
  11038. });
  11039. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11040. get: function () {
  11041. return Engine._ALPHA_COMBINE;
  11042. },
  11043. enumerable: true,
  11044. configurable: true
  11045. });
  11046. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11047. get: function () {
  11048. return Engine._ALPHA_SUBTRACT;
  11049. },
  11050. enumerable: true,
  11051. configurable: true
  11052. });
  11053. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11054. get: function () {
  11055. return Engine._ALPHA_MULTIPLY;
  11056. },
  11057. enumerable: true,
  11058. configurable: true
  11059. });
  11060. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11061. get: function () {
  11062. return Engine._ALPHA_MAXIMIZED;
  11063. },
  11064. enumerable: true,
  11065. configurable: true
  11066. });
  11067. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11068. get: function () {
  11069. return Engine._ALPHA_PREMULTIPLIED;
  11070. },
  11071. enumerable: true,
  11072. configurable: true
  11073. });
  11074. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11075. get: function () {
  11076. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11077. },
  11078. enumerable: true,
  11079. configurable: true
  11080. });
  11081. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11082. get: function () {
  11083. return Engine._ALPHA_INTERPOLATE;
  11084. },
  11085. enumerable: true,
  11086. configurable: true
  11087. });
  11088. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11089. get: function () {
  11090. return Engine._ALPHA_SCREENMODE;
  11091. },
  11092. enumerable: true,
  11093. configurable: true
  11094. });
  11095. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11096. get: function () {
  11097. return Engine._DELAYLOADSTATE_NONE;
  11098. },
  11099. enumerable: true,
  11100. configurable: true
  11101. });
  11102. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11103. get: function () {
  11104. return Engine._DELAYLOADSTATE_LOADED;
  11105. },
  11106. enumerable: true,
  11107. configurable: true
  11108. });
  11109. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11110. get: function () {
  11111. return Engine._DELAYLOADSTATE_LOADING;
  11112. },
  11113. enumerable: true,
  11114. configurable: true
  11115. });
  11116. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11117. get: function () {
  11118. return Engine._DELAYLOADSTATE_NOTLOADED;
  11119. },
  11120. enumerable: true,
  11121. configurable: true
  11122. });
  11123. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11124. get: function () {
  11125. return Engine._TEXTUREFORMAT_ALPHA;
  11126. },
  11127. enumerable: true,
  11128. configurable: true
  11129. });
  11130. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11131. get: function () {
  11132. return Engine._TEXTUREFORMAT_LUMINANCE;
  11133. },
  11134. enumerable: true,
  11135. configurable: true
  11136. });
  11137. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11138. /**
  11139. * R32F
  11140. */
  11141. get: function () {
  11142. return Engine._TEXTUREFORMAT_R32F;
  11143. },
  11144. enumerable: true,
  11145. configurable: true
  11146. });
  11147. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11148. /**
  11149. * RG32F
  11150. */
  11151. get: function () {
  11152. return Engine._TEXTUREFORMAT_RG32F;
  11153. },
  11154. enumerable: true,
  11155. configurable: true
  11156. });
  11157. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11158. /**
  11159. * RGB32F
  11160. */
  11161. get: function () {
  11162. return Engine._TEXTUREFORMAT_RGB32F;
  11163. },
  11164. enumerable: true,
  11165. configurable: true
  11166. });
  11167. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11168. /**
  11169. * RGBA32F
  11170. */
  11171. get: function () {
  11172. return Engine._TEXTUREFORMAT_RGBA32F;
  11173. },
  11174. enumerable: true,
  11175. configurable: true
  11176. });
  11177. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11178. get: function () {
  11179. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11180. },
  11181. enumerable: true,
  11182. configurable: true
  11183. });
  11184. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11185. get: function () {
  11186. return Engine._TEXTUREFORMAT_RGB;
  11187. },
  11188. enumerable: true,
  11189. configurable: true
  11190. });
  11191. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11192. get: function () {
  11193. return Engine._TEXTUREFORMAT_RGBA;
  11194. },
  11195. enumerable: true,
  11196. configurable: true
  11197. });
  11198. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11199. get: function () {
  11200. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11201. },
  11202. enumerable: true,
  11203. configurable: true
  11204. });
  11205. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11206. get: function () {
  11207. return Engine._TEXTURETYPE_FLOAT;
  11208. },
  11209. enumerable: true,
  11210. configurable: true
  11211. });
  11212. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11213. get: function () {
  11214. return Engine._TEXTURETYPE_HALF_FLOAT;
  11215. },
  11216. enumerable: true,
  11217. configurable: true
  11218. });
  11219. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11220. get: function () {
  11221. return Engine._SCALEMODE_FLOOR;
  11222. },
  11223. enumerable: true,
  11224. configurable: true
  11225. });
  11226. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11227. get: function () {
  11228. return Engine._SCALEMODE_NEAREST;
  11229. },
  11230. enumerable: true,
  11231. configurable: true
  11232. });
  11233. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11234. get: function () {
  11235. return Engine._SCALEMODE_CEILING;
  11236. },
  11237. enumerable: true,
  11238. configurable: true
  11239. });
  11240. Object.defineProperty(Engine, "Version", {
  11241. get: function () {
  11242. return "3.2.0-beta.1";
  11243. },
  11244. enumerable: true,
  11245. configurable: true
  11246. });
  11247. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11248. get: function () {
  11249. return this._vrExclusivePointerMode;
  11250. },
  11251. enumerable: true,
  11252. configurable: true
  11253. });
  11254. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11255. get: function () {
  11256. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11257. },
  11258. enumerable: true,
  11259. configurable: true
  11260. });
  11261. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11262. get: function () {
  11263. return this._webGLVersion < 2 || this.forcePOTTextures;
  11264. },
  11265. enumerable: true,
  11266. configurable: true
  11267. });
  11268. Object.defineProperty(Engine.prototype, "badOS", {
  11269. get: function () {
  11270. return this._badOS;
  11271. },
  11272. enumerable: true,
  11273. configurable: true
  11274. });
  11275. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11276. get: function () {
  11277. return this._badDesktopOS;
  11278. },
  11279. enumerable: true,
  11280. configurable: true
  11281. });
  11282. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11283. get: function () {
  11284. return this._performanceMonitor;
  11285. },
  11286. enumerable: true,
  11287. configurable: true
  11288. });
  11289. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11290. get: function () {
  11291. return this._texturesSupported;
  11292. },
  11293. enumerable: true,
  11294. configurable: true
  11295. });
  11296. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11297. get: function () {
  11298. return this._textureFormatInUse;
  11299. },
  11300. enumerable: true,
  11301. configurable: true
  11302. });
  11303. Object.defineProperty(Engine.prototype, "currentViewport", {
  11304. get: function () {
  11305. return this._cachedViewport;
  11306. },
  11307. enumerable: true,
  11308. configurable: true
  11309. });
  11310. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11311. // Empty texture
  11312. get: function () {
  11313. if (!this._emptyTexture) {
  11314. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11315. }
  11316. return this._emptyTexture;
  11317. },
  11318. enumerable: true,
  11319. configurable: true
  11320. });
  11321. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11322. get: function () {
  11323. if (!this._emptyTexture3D) {
  11324. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11325. }
  11326. return this._emptyTexture3D;
  11327. },
  11328. enumerable: true,
  11329. configurable: true
  11330. });
  11331. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11332. get: function () {
  11333. if (!this._emptyCubeTexture) {
  11334. var faceData = new Uint8Array(4);
  11335. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11336. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11337. }
  11338. return this._emptyCubeTexture;
  11339. },
  11340. enumerable: true,
  11341. configurable: true
  11342. });
  11343. Engine.prototype._rebuildInternalTextures = function () {
  11344. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11345. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11346. var internalTexture = currentState_1[_i];
  11347. internalTexture._rebuild();
  11348. }
  11349. };
  11350. Engine.prototype._rebuildEffects = function () {
  11351. for (var key in this._compiledEffects) {
  11352. var effect = this._compiledEffects[key];
  11353. effect._prepareEffect();
  11354. }
  11355. BABYLON.Effect.ResetCache();
  11356. };
  11357. Engine.prototype._rebuildBuffers = function () {
  11358. // Index / Vertex
  11359. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11360. var scene = _a[_i];
  11361. scene.resetCachedMaterial();
  11362. scene._rebuildGeometries();
  11363. scene._rebuildTextures();
  11364. }
  11365. // Uniforms
  11366. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11367. var uniformBuffer = _c[_b];
  11368. uniformBuffer._rebuild();
  11369. }
  11370. };
  11371. Engine.prototype._initGLContext = function () {
  11372. // Caps
  11373. this._caps = new EngineCapabilities();
  11374. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11375. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11376. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11377. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11378. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11379. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11380. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11381. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11382. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11383. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11384. // Infos
  11385. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11386. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11387. if (rendererInfo != null) {
  11388. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11389. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11390. }
  11391. if (!this._glVendor) {
  11392. this._glVendor = "Unknown vendor";
  11393. }
  11394. if (!this._glRenderer) {
  11395. this._glRenderer = "Unknown renderer";
  11396. }
  11397. // Constants
  11398. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11399. if (this._gl.RGBA16F !== 0x881A) {
  11400. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11401. }
  11402. if (this._gl.RGBA32F !== 0x8814) {
  11403. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11404. }
  11405. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11406. this._gl.DEPTH24_STENCIL8 = 35056;
  11407. }
  11408. // Extensions
  11409. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11410. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11411. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11412. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11413. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11414. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11415. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11416. 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');
  11417. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11418. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11419. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11420. this._caps.highPrecisionShaderSupported = true;
  11421. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11422. if (this._caps.timerQuery) {
  11423. if (this._webGLVersion === 1) {
  11424. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11425. }
  11426. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11427. }
  11428. // Checks if some of the format renders first to allow the use of webgl inspector.
  11429. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11430. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11431. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11432. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11433. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11434. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11435. if (this._webGLVersion > 1) {
  11436. this._gl.HALF_FLOAT_OES = 0x140B;
  11437. }
  11438. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11439. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11440. // Draw buffers
  11441. if (this._webGLVersion > 1) {
  11442. this._caps.drawBuffersExtension = true;
  11443. }
  11444. else {
  11445. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11446. if (drawBuffersExtension !== null) {
  11447. this._caps.drawBuffersExtension = true;
  11448. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11449. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11450. for (var i = 0; i < 16; i++) {
  11451. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11452. }
  11453. }
  11454. else {
  11455. this._caps.drawBuffersExtension = false;
  11456. }
  11457. }
  11458. // Depth Texture
  11459. if (this._webGLVersion > 1) {
  11460. this._caps.depthTextureExtension = true;
  11461. }
  11462. else {
  11463. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11464. if (depthTextureExtension != null) {
  11465. this._caps.depthTextureExtension = true;
  11466. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11467. }
  11468. }
  11469. // Vertex array object
  11470. if (this._webGLVersion > 1) {
  11471. this._caps.vertexArrayObject = true;
  11472. }
  11473. else {
  11474. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11475. if (vertexArrayObjectExtension != null) {
  11476. this._caps.vertexArrayObject = true;
  11477. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11478. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11479. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11480. }
  11481. else {
  11482. this._caps.vertexArrayObject = false;
  11483. }
  11484. }
  11485. // Instances count
  11486. if (this._webGLVersion > 1) {
  11487. this._caps.instancedArrays = true;
  11488. }
  11489. else {
  11490. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11491. if (instanceExtension != null) {
  11492. this._caps.instancedArrays = true;
  11493. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11494. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11495. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11496. }
  11497. else {
  11498. this._caps.instancedArrays = false;
  11499. }
  11500. }
  11501. // Intelligently add supported compressed formats in order to check for.
  11502. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11503. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11504. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11505. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11506. if (this._caps.astc)
  11507. this.texturesSupported.push('-astc.ktx');
  11508. if (this._caps.s3tc)
  11509. this.texturesSupported.push('-dxt.ktx');
  11510. if (this._caps.pvrtc)
  11511. this.texturesSupported.push('-pvrtc.ktx');
  11512. if (this._caps.etc2)
  11513. this.texturesSupported.push('-etc2.ktx');
  11514. if (this._caps.etc1)
  11515. this.texturesSupported.push('-etc1.ktx');
  11516. if (this._gl.getShaderPrecisionFormat) {
  11517. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11518. if (highp) {
  11519. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11520. }
  11521. }
  11522. // Depth buffer
  11523. this.setDepthBuffer(true);
  11524. this.setDepthFunctionToLessOrEqual();
  11525. this.setDepthWrite(true);
  11526. // Texture maps
  11527. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11528. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11529. this._nextFreeTextureSlots.push(slot);
  11530. }
  11531. };
  11532. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11533. get: function () {
  11534. return this._webGLVersion;
  11535. },
  11536. enumerable: true,
  11537. configurable: true
  11538. });
  11539. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11540. /**
  11541. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11542. */
  11543. get: function () {
  11544. return this._isStencilEnable;
  11545. },
  11546. enumerable: true,
  11547. configurable: true
  11548. });
  11549. Engine.prototype._prepareWorkingCanvas = function () {
  11550. if (this._workingCanvas) {
  11551. return;
  11552. }
  11553. this._workingCanvas = document.createElement("canvas");
  11554. var context = this._workingCanvas.getContext("2d");
  11555. if (context) {
  11556. this._workingContext = context;
  11557. }
  11558. };
  11559. Engine.prototype.resetTextureCache = function () {
  11560. for (var key in this._boundTexturesCache) {
  11561. var boundTexture = this._boundTexturesCache[key];
  11562. if (boundTexture) {
  11563. this._removeDesignatedSlot(boundTexture);
  11564. }
  11565. this._boundTexturesCache[key] = null;
  11566. }
  11567. if (!this.disableTextureBindingOptimization) {
  11568. this._nextFreeTextureSlots = [];
  11569. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11570. this._nextFreeTextureSlots.push(slot);
  11571. }
  11572. }
  11573. this._currentTextureChannel = -1;
  11574. };
  11575. Engine.prototype.isDeterministicLockStep = function () {
  11576. return this._deterministicLockstep;
  11577. };
  11578. Engine.prototype.getLockstepMaxSteps = function () {
  11579. return this._lockstepMaxSteps;
  11580. };
  11581. Engine.prototype.getGlInfo = function () {
  11582. return {
  11583. vendor: this._glVendor,
  11584. renderer: this._glRenderer,
  11585. version: this._glVersion
  11586. };
  11587. };
  11588. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11589. if (useScreen === void 0) { useScreen = false; }
  11590. var viewport = camera.viewport;
  11591. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11592. };
  11593. Engine.prototype.getRenderWidth = function (useScreen) {
  11594. if (useScreen === void 0) { useScreen = false; }
  11595. if (!useScreen && this._currentRenderTarget) {
  11596. return this._currentRenderTarget.width;
  11597. }
  11598. return this._gl.drawingBufferWidth;
  11599. };
  11600. Engine.prototype.getRenderHeight = function (useScreen) {
  11601. if (useScreen === void 0) { useScreen = false; }
  11602. if (!useScreen && this._currentRenderTarget) {
  11603. return this._currentRenderTarget.height;
  11604. }
  11605. return this._gl.drawingBufferHeight;
  11606. };
  11607. Engine.prototype.getRenderingCanvas = function () {
  11608. return this._renderingCanvas;
  11609. };
  11610. Engine.prototype.getRenderingCanvasClientRect = function () {
  11611. if (!this._renderingCanvas) {
  11612. return null;
  11613. }
  11614. return this._renderingCanvas.getBoundingClientRect();
  11615. };
  11616. Engine.prototype.setHardwareScalingLevel = function (level) {
  11617. this._hardwareScalingLevel = level;
  11618. this.resize();
  11619. };
  11620. Engine.prototype.getHardwareScalingLevel = function () {
  11621. return this._hardwareScalingLevel;
  11622. };
  11623. Engine.prototype.getLoadedTexturesCache = function () {
  11624. return this._internalTexturesCache;
  11625. };
  11626. Engine.prototype.getCaps = function () {
  11627. return this._caps;
  11628. };
  11629. Object.defineProperty(Engine.prototype, "drawCalls", {
  11630. /** The number of draw calls submitted last frame */
  11631. get: function () {
  11632. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11633. return 0;
  11634. },
  11635. enumerable: true,
  11636. configurable: true
  11637. });
  11638. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11639. get: function () {
  11640. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11641. return null;
  11642. },
  11643. enumerable: true,
  11644. configurable: true
  11645. });
  11646. Engine.prototype.getDepthFunction = function () {
  11647. return this._depthCullingState.depthFunc;
  11648. };
  11649. Engine.prototype.setDepthFunction = function (depthFunc) {
  11650. this._depthCullingState.depthFunc = depthFunc;
  11651. };
  11652. Engine.prototype.setDepthFunctionToGreater = function () {
  11653. this._depthCullingState.depthFunc = this._gl.GREATER;
  11654. };
  11655. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11656. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11657. };
  11658. Engine.prototype.setDepthFunctionToLess = function () {
  11659. this._depthCullingState.depthFunc = this._gl.LESS;
  11660. };
  11661. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11662. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11663. };
  11664. Engine.prototype.getStencilBuffer = function () {
  11665. return this._stencilState.stencilTest;
  11666. };
  11667. Engine.prototype.setStencilBuffer = function (enable) {
  11668. this._stencilState.stencilTest = enable;
  11669. };
  11670. Engine.prototype.getStencilMask = function () {
  11671. return this._stencilState.stencilMask;
  11672. };
  11673. Engine.prototype.setStencilMask = function (mask) {
  11674. this._stencilState.stencilMask = mask;
  11675. };
  11676. Engine.prototype.getStencilFunction = function () {
  11677. return this._stencilState.stencilFunc;
  11678. };
  11679. Engine.prototype.getStencilFunctionReference = function () {
  11680. return this._stencilState.stencilFuncRef;
  11681. };
  11682. Engine.prototype.getStencilFunctionMask = function () {
  11683. return this._stencilState.stencilFuncMask;
  11684. };
  11685. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11686. this._stencilState.stencilFunc = stencilFunc;
  11687. };
  11688. Engine.prototype.setStencilFunctionReference = function (reference) {
  11689. this._stencilState.stencilFuncRef = reference;
  11690. };
  11691. Engine.prototype.setStencilFunctionMask = function (mask) {
  11692. this._stencilState.stencilFuncMask = mask;
  11693. };
  11694. Engine.prototype.getStencilOperationFail = function () {
  11695. return this._stencilState.stencilOpStencilFail;
  11696. };
  11697. Engine.prototype.getStencilOperationDepthFail = function () {
  11698. return this._stencilState.stencilOpDepthFail;
  11699. };
  11700. Engine.prototype.getStencilOperationPass = function () {
  11701. return this._stencilState.stencilOpStencilDepthPass;
  11702. };
  11703. Engine.prototype.setStencilOperationFail = function (operation) {
  11704. this._stencilState.stencilOpStencilFail = operation;
  11705. };
  11706. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11707. this._stencilState.stencilOpDepthFail = operation;
  11708. };
  11709. Engine.prototype.setStencilOperationPass = function (operation) {
  11710. this._stencilState.stencilOpStencilDepthPass = operation;
  11711. };
  11712. Engine.prototype.setDitheringState = function (value) {
  11713. if (value) {
  11714. this._gl.enable(this._gl.DITHER);
  11715. }
  11716. else {
  11717. this._gl.disable(this._gl.DITHER);
  11718. }
  11719. };
  11720. Engine.prototype.setRasterizerState = function (value) {
  11721. if (value) {
  11722. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11723. }
  11724. else {
  11725. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11726. }
  11727. };
  11728. /**
  11729. * stop executing a render loop function and remove it from the execution array
  11730. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11731. */
  11732. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11733. if (!renderFunction) {
  11734. this._activeRenderLoops = [];
  11735. return;
  11736. }
  11737. var index = this._activeRenderLoops.indexOf(renderFunction);
  11738. if (index >= 0) {
  11739. this._activeRenderLoops.splice(index, 1);
  11740. }
  11741. };
  11742. Engine.prototype._renderLoop = function () {
  11743. if (!this._contextWasLost) {
  11744. var shouldRender = true;
  11745. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11746. shouldRender = false;
  11747. }
  11748. if (shouldRender) {
  11749. // Start new frame
  11750. this.beginFrame();
  11751. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11752. var renderFunction = this._activeRenderLoops[index];
  11753. renderFunction();
  11754. }
  11755. // Present
  11756. this.endFrame();
  11757. }
  11758. }
  11759. if (this._activeRenderLoops.length > 0) {
  11760. // Register new frame
  11761. var requester = null;
  11762. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11763. requester = this._vrDisplay;
  11764. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11765. }
  11766. else {
  11767. this._renderingQueueLaunched = false;
  11768. }
  11769. };
  11770. /**
  11771. * Register and execute a render loop. The engine can have more than one render function.
  11772. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11773. * @example
  11774. * engine.runRenderLoop(function () {
  11775. * scene.render()
  11776. * })
  11777. */
  11778. Engine.prototype.runRenderLoop = function (renderFunction) {
  11779. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11780. return;
  11781. }
  11782. this._activeRenderLoops.push(renderFunction);
  11783. if (!this._renderingQueueLaunched) {
  11784. this._renderingQueueLaunched = true;
  11785. this._bindedRenderFunction = this._renderLoop.bind(this);
  11786. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11787. }
  11788. };
  11789. /**
  11790. * Toggle full screen mode.
  11791. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11792. * @param {any} options - an options object to be sent to the requestFullscreen function
  11793. */
  11794. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11795. if (this.isFullscreen) {
  11796. BABYLON.Tools.ExitFullscreen();
  11797. }
  11798. else {
  11799. this._pointerLockRequested = requestPointerLock;
  11800. if (this._renderingCanvas) {
  11801. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11802. }
  11803. }
  11804. };
  11805. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11806. if (stencil === void 0) { stencil = false; }
  11807. this.applyStates();
  11808. var mode = 0;
  11809. if (backBuffer && color) {
  11810. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11811. mode |= this._gl.COLOR_BUFFER_BIT;
  11812. }
  11813. if (depth) {
  11814. this._gl.clearDepth(1.0);
  11815. mode |= this._gl.DEPTH_BUFFER_BIT;
  11816. }
  11817. if (stencil) {
  11818. this._gl.clearStencil(0);
  11819. mode |= this._gl.STENCIL_BUFFER_BIT;
  11820. }
  11821. this._gl.clear(mode);
  11822. };
  11823. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11824. var gl = this._gl;
  11825. // Save state
  11826. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11827. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11828. // Change state
  11829. gl.enable(gl.SCISSOR_TEST);
  11830. gl.scissor(x, y, width, height);
  11831. // Clear
  11832. this.clear(clearColor, true, true, true);
  11833. // Restore state
  11834. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11835. if (curScissor === true) {
  11836. gl.enable(gl.SCISSOR_TEST);
  11837. }
  11838. else {
  11839. gl.disable(gl.SCISSOR_TEST);
  11840. }
  11841. };
  11842. /**
  11843. * Set the WebGL's viewport
  11844. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11845. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11846. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11847. */
  11848. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11849. var width = requiredWidth || this.getRenderWidth();
  11850. var height = requiredHeight || this.getRenderHeight();
  11851. var x = viewport.x || 0;
  11852. var y = viewport.y || 0;
  11853. this._cachedViewport = viewport;
  11854. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11855. };
  11856. /**
  11857. * Directly set the WebGL Viewport
  11858. * The x, y, width & height are directly passed to the WebGL call
  11859. * @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.
  11860. */
  11861. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11862. var currentViewport = this._cachedViewport;
  11863. this._cachedViewport = null;
  11864. this._gl.viewport(x, y, width, height);
  11865. return currentViewport;
  11866. };
  11867. Engine.prototype.beginFrame = function () {
  11868. this.onBeginFrameObservable.notifyObservers(this);
  11869. this._measureFps();
  11870. };
  11871. Engine.prototype.endFrame = function () {
  11872. //force a flush in case we are using a bad OS.
  11873. if (this._badOS) {
  11874. this.flushFramebuffer();
  11875. }
  11876. //submit frame to the vr device, if enabled
  11877. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11878. // TODO: We should only submit the frame if we read frameData successfully.
  11879. this._vrDisplay.submitFrame();
  11880. }
  11881. this.onEndFrameObservable.notifyObservers(this);
  11882. };
  11883. /**
  11884. * resize the view according to the canvas' size.
  11885. * @example
  11886. * window.addEventListener("resize", function () {
  11887. * engine.resize();
  11888. * });
  11889. */
  11890. Engine.prototype.resize = function () {
  11891. // We're not resizing the size of the canvas while in VR mode & presenting
  11892. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11893. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11894. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11895. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11896. }
  11897. };
  11898. /**
  11899. * force a specific size of the canvas
  11900. * @param {number} width - the new canvas' width
  11901. * @param {number} height - the new canvas' height
  11902. */
  11903. Engine.prototype.setSize = function (width, height) {
  11904. if (!this._renderingCanvas) {
  11905. return;
  11906. }
  11907. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11908. return;
  11909. }
  11910. this._renderingCanvas.width = width;
  11911. this._renderingCanvas.height = height;
  11912. for (var index = 0; index < this.scenes.length; index++) {
  11913. var scene = this.scenes[index];
  11914. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11915. var cam = scene.cameras[camIndex];
  11916. cam._currentRenderId = 0;
  11917. }
  11918. }
  11919. if (this.onResizeObservable.hasObservers) {
  11920. this.onResizeObservable.notifyObservers(this);
  11921. }
  11922. };
  11923. // WebVR functions
  11924. Engine.prototype.isVRDevicePresent = function () {
  11925. return !!this._vrDisplay;
  11926. };
  11927. Engine.prototype.getVRDevice = function () {
  11928. return this._vrDisplay;
  11929. };
  11930. /**
  11931. * Initializes a webVR display and starts listening to display change events.
  11932. * The onVRDisplayChangedObservable will be notified upon these changes.
  11933. * @returns The onVRDisplayChangedObservable.
  11934. */
  11935. Engine.prototype.initWebVR = function () {
  11936. this.initWebVRAsync();
  11937. return this.onVRDisplayChangedObservable;
  11938. };
  11939. /**
  11940. * Initializes a webVR display and starts listening to display change events.
  11941. * The onVRDisplayChangedObservable will be notified upon these changes.
  11942. * @returns A promise containing a VRDisplay and if vr is supported.
  11943. */
  11944. Engine.prototype.initWebVRAsync = function () {
  11945. var _this = this;
  11946. var notifyObservers = function () {
  11947. var eventArgs = {
  11948. vrDisplay: _this._vrDisplay,
  11949. vrSupported: _this._vrSupported
  11950. };
  11951. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11952. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11953. };
  11954. if (!this._onVrDisplayConnect) {
  11955. this._onVrDisplayConnect = function (event) {
  11956. _this._vrDisplay = event.display;
  11957. notifyObservers();
  11958. };
  11959. this._onVrDisplayDisconnect = function () {
  11960. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11961. _this._vrDisplay = undefined;
  11962. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11963. notifyObservers();
  11964. };
  11965. this._onVrDisplayPresentChange = function () {
  11966. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11967. };
  11968. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11969. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11970. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11971. }
  11972. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11973. this._webVRInitPromise.then(notifyObservers);
  11974. return this._webVRInitPromise;
  11975. };
  11976. Engine.prototype.enableVR = function () {
  11977. var _this = this;
  11978. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11979. var onResolved = function () {
  11980. _this.onVRRequestPresentComplete.notifyObservers(true);
  11981. _this._onVRFullScreenTriggered();
  11982. };
  11983. var onRejected = function () {
  11984. _this.onVRRequestPresentComplete.notifyObservers(false);
  11985. };
  11986. this.onVRRequestPresentStart.notifyObservers(this);
  11987. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11988. }
  11989. };
  11990. Engine.prototype.disableVR = function () {
  11991. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11992. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11993. }
  11994. };
  11995. Engine.prototype._getVRDisplaysAsync = function () {
  11996. var _this = this;
  11997. return new Promise(function (res, rej) {
  11998. if (navigator.getVRDisplays) {
  11999. navigator.getVRDisplays().then(function (devices) {
  12000. _this._vrSupported = true;
  12001. // note that devices may actually be an empty array. This is fine;
  12002. // we expect this._vrDisplay to be undefined in this case.
  12003. _this._vrDisplay = devices[0];
  12004. res({
  12005. vrDisplay: _this._vrDisplay,
  12006. vrSupported: _this._vrSupported
  12007. });
  12008. });
  12009. }
  12010. else {
  12011. _this._vrDisplay = undefined;
  12012. _this._vrSupported = false;
  12013. res({
  12014. vrDisplay: _this._vrDisplay,
  12015. vrSupported: _this._vrSupported
  12016. });
  12017. }
  12018. });
  12019. };
  12020. /**
  12021. * Binds the frame buffer to the specified texture.
  12022. * @param texture The texture to render to or null for the default canvas
  12023. * @param faceIndex The face of the texture to render to in case of cube texture
  12024. * @param requiredWidth The width of the target to render to
  12025. * @param requiredHeight The height of the target to render to
  12026. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12027. * @param depthStencilTexture The depth stencil texture to use to render
  12028. */
  12029. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12030. if (this._currentRenderTarget) {
  12031. this.unBindFramebuffer(this._currentRenderTarget);
  12032. }
  12033. this._currentRenderTarget = texture;
  12034. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12035. var gl = this._gl;
  12036. if (texture.isCube) {
  12037. if (faceIndex === undefined) {
  12038. faceIndex = 0;
  12039. }
  12040. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12041. if (depthStencilTexture) {
  12042. if (depthStencilTexture._generateStencilBuffer) {
  12043. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12044. }
  12045. else {
  12046. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12047. }
  12048. }
  12049. }
  12050. if (this._cachedViewport && !forceFullscreenViewport) {
  12051. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12052. }
  12053. else {
  12054. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12055. }
  12056. this.wipeCaches();
  12057. };
  12058. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12059. if (this._currentFramebuffer !== framebuffer) {
  12060. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12061. this._currentFramebuffer = framebuffer;
  12062. }
  12063. };
  12064. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12065. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12066. this._currentRenderTarget = null;
  12067. // If MSAA, we need to bitblt back to main texture
  12068. var gl = this._gl;
  12069. if (texture._MSAAFramebuffer) {
  12070. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12071. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12072. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12073. }
  12074. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12075. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12076. gl.generateMipmap(gl.TEXTURE_2D);
  12077. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12078. }
  12079. if (onBeforeUnbind) {
  12080. if (texture._MSAAFramebuffer) {
  12081. // Bind the correct framebuffer
  12082. this.bindUnboundFramebuffer(texture._framebuffer);
  12083. }
  12084. onBeforeUnbind();
  12085. }
  12086. this.bindUnboundFramebuffer(null);
  12087. };
  12088. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12089. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12090. this._currentRenderTarget = null;
  12091. // If MSAA, we need to bitblt back to main texture
  12092. var gl = this._gl;
  12093. if (textures[0]._MSAAFramebuffer) {
  12094. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12095. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12096. var attachments = textures[0]._attachments;
  12097. if (!attachments) {
  12098. attachments = new Array(textures.length);
  12099. textures[0]._attachments = attachments;
  12100. }
  12101. for (var i = 0; i < textures.length; i++) {
  12102. var texture = textures[i];
  12103. for (var j = 0; j < attachments.length; j++) {
  12104. attachments[j] = gl.NONE;
  12105. }
  12106. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12107. gl.readBuffer(attachments[i]);
  12108. gl.drawBuffers(attachments);
  12109. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12110. }
  12111. for (var i = 0; i < attachments.length; i++) {
  12112. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12113. }
  12114. gl.drawBuffers(attachments);
  12115. }
  12116. for (var i = 0; i < textures.length; i++) {
  12117. var texture = textures[i];
  12118. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12119. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12120. gl.generateMipmap(gl.TEXTURE_2D);
  12121. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12122. }
  12123. }
  12124. if (onBeforeUnbind) {
  12125. if (textures[0]._MSAAFramebuffer) {
  12126. // Bind the correct framebuffer
  12127. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12128. }
  12129. onBeforeUnbind();
  12130. }
  12131. this.bindUnboundFramebuffer(null);
  12132. };
  12133. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12134. if (texture.generateMipMaps) {
  12135. var gl = this._gl;
  12136. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12137. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12138. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12139. }
  12140. };
  12141. Engine.prototype.flushFramebuffer = function () {
  12142. this._gl.flush();
  12143. };
  12144. Engine.prototype.restoreDefaultFramebuffer = function () {
  12145. if (this._currentRenderTarget) {
  12146. this.unBindFramebuffer(this._currentRenderTarget);
  12147. }
  12148. else {
  12149. this.bindUnboundFramebuffer(null);
  12150. }
  12151. if (this._cachedViewport) {
  12152. this.setViewport(this._cachedViewport);
  12153. }
  12154. this.wipeCaches();
  12155. };
  12156. // UBOs
  12157. Engine.prototype.createUniformBuffer = function (elements) {
  12158. var ubo = this._gl.createBuffer();
  12159. if (!ubo) {
  12160. throw new Error("Unable to create uniform buffer");
  12161. }
  12162. this.bindUniformBuffer(ubo);
  12163. if (elements instanceof Float32Array) {
  12164. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12165. }
  12166. else {
  12167. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12168. }
  12169. this.bindUniformBuffer(null);
  12170. ubo.references = 1;
  12171. return ubo;
  12172. };
  12173. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12174. var ubo = this._gl.createBuffer();
  12175. if (!ubo) {
  12176. throw new Error("Unable to create dynamic uniform buffer");
  12177. }
  12178. this.bindUniformBuffer(ubo);
  12179. if (elements instanceof Float32Array) {
  12180. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12181. }
  12182. else {
  12183. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12184. }
  12185. this.bindUniformBuffer(null);
  12186. ubo.references = 1;
  12187. return ubo;
  12188. };
  12189. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12190. this.bindUniformBuffer(uniformBuffer);
  12191. if (offset === undefined) {
  12192. offset = 0;
  12193. }
  12194. if (count === undefined) {
  12195. if (elements instanceof Float32Array) {
  12196. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12197. }
  12198. else {
  12199. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12200. }
  12201. }
  12202. else {
  12203. if (elements instanceof Float32Array) {
  12204. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12205. }
  12206. else {
  12207. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12208. }
  12209. }
  12210. this.bindUniformBuffer(null);
  12211. };
  12212. // VBOs
  12213. Engine.prototype._resetVertexBufferBinding = function () {
  12214. this.bindArrayBuffer(null);
  12215. this._cachedVertexBuffers = null;
  12216. };
  12217. Engine.prototype.createVertexBuffer = function (vertices) {
  12218. var vbo = this._gl.createBuffer();
  12219. if (!vbo) {
  12220. throw new Error("Unable to create vertex buffer");
  12221. }
  12222. this.bindArrayBuffer(vbo);
  12223. if (vertices instanceof Float32Array) {
  12224. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12225. }
  12226. else {
  12227. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12228. }
  12229. this._resetVertexBufferBinding();
  12230. vbo.references = 1;
  12231. return vbo;
  12232. };
  12233. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12234. var vbo = this._gl.createBuffer();
  12235. if (!vbo) {
  12236. throw new Error("Unable to create dynamic vertex buffer");
  12237. }
  12238. this.bindArrayBuffer(vbo);
  12239. if (vertices instanceof Float32Array) {
  12240. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12241. }
  12242. else {
  12243. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12244. }
  12245. this._resetVertexBufferBinding();
  12246. vbo.references = 1;
  12247. return vbo;
  12248. };
  12249. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12250. if (offset === void 0) { offset = 0; }
  12251. // Force cache update
  12252. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12253. this.bindIndexBuffer(indexBuffer);
  12254. var arrayBuffer;
  12255. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12256. arrayBuffer = indices;
  12257. }
  12258. else {
  12259. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12260. }
  12261. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12262. this._resetIndexBufferBinding();
  12263. };
  12264. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12265. this.bindArrayBuffer(vertexBuffer);
  12266. if (offset === undefined) {
  12267. offset = 0;
  12268. }
  12269. if (count === undefined) {
  12270. if (vertices instanceof Float32Array) {
  12271. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12272. }
  12273. else {
  12274. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12275. }
  12276. }
  12277. else {
  12278. if (vertices instanceof Float32Array) {
  12279. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12280. }
  12281. else {
  12282. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12283. }
  12284. }
  12285. this._resetVertexBufferBinding();
  12286. };
  12287. Engine.prototype._resetIndexBufferBinding = function () {
  12288. this.bindIndexBuffer(null);
  12289. this._cachedIndexBuffer = null;
  12290. };
  12291. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12292. var vbo = this._gl.createBuffer();
  12293. if (!vbo) {
  12294. throw new Error("Unable to create index buffer");
  12295. }
  12296. this.bindIndexBuffer(vbo);
  12297. // Check for 32 bits indices
  12298. var arrayBuffer;
  12299. var need32Bits = false;
  12300. if (indices instanceof Uint16Array) {
  12301. arrayBuffer = indices;
  12302. }
  12303. else {
  12304. //check 32 bit support
  12305. if (this._caps.uintIndices) {
  12306. if (indices instanceof Uint32Array) {
  12307. arrayBuffer = indices;
  12308. need32Bits = true;
  12309. }
  12310. else {
  12311. //number[] or Int32Array, check if 32 bit is necessary
  12312. for (var index = 0; index < indices.length; index++) {
  12313. if (indices[index] > 65535) {
  12314. need32Bits = true;
  12315. break;
  12316. }
  12317. }
  12318. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12319. }
  12320. }
  12321. else {
  12322. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12323. arrayBuffer = new Uint16Array(indices);
  12324. }
  12325. }
  12326. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12327. this._resetIndexBufferBinding();
  12328. vbo.references = 1;
  12329. vbo.is32Bits = need32Bits;
  12330. return vbo;
  12331. };
  12332. Engine.prototype.bindArrayBuffer = function (buffer) {
  12333. if (!this._vaoRecordInProgress) {
  12334. this._unbindVertexArrayObject();
  12335. }
  12336. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12337. };
  12338. Engine.prototype.bindUniformBuffer = function (buffer) {
  12339. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12340. };
  12341. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12342. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12343. };
  12344. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12345. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12346. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12347. };
  12348. ;
  12349. Engine.prototype.bindIndexBuffer = function (buffer) {
  12350. if (!this._vaoRecordInProgress) {
  12351. this._unbindVertexArrayObject();
  12352. }
  12353. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12354. };
  12355. Engine.prototype.bindBuffer = function (buffer, target) {
  12356. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12357. this._gl.bindBuffer(target, buffer);
  12358. this._currentBoundBuffer[target] = buffer;
  12359. }
  12360. };
  12361. Engine.prototype.updateArrayBuffer = function (data) {
  12362. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12363. };
  12364. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12365. var pointer = this._currentBufferPointers[indx];
  12366. var changed = false;
  12367. if (!pointer.active) {
  12368. changed = true;
  12369. pointer.active = true;
  12370. pointer.index = indx;
  12371. pointer.size = size;
  12372. pointer.type = type;
  12373. pointer.normalized = normalized;
  12374. pointer.stride = stride;
  12375. pointer.offset = offset;
  12376. pointer.buffer = buffer;
  12377. }
  12378. else {
  12379. if (pointer.buffer !== buffer) {
  12380. pointer.buffer = buffer;
  12381. changed = true;
  12382. }
  12383. if (pointer.size !== size) {
  12384. pointer.size = size;
  12385. changed = true;
  12386. }
  12387. if (pointer.type !== type) {
  12388. pointer.type = type;
  12389. changed = true;
  12390. }
  12391. if (pointer.normalized !== normalized) {
  12392. pointer.normalized = normalized;
  12393. changed = true;
  12394. }
  12395. if (pointer.stride !== stride) {
  12396. pointer.stride = stride;
  12397. changed = true;
  12398. }
  12399. if (pointer.offset !== offset) {
  12400. pointer.offset = offset;
  12401. changed = true;
  12402. }
  12403. }
  12404. if (changed || this._vaoRecordInProgress) {
  12405. this.bindArrayBuffer(buffer);
  12406. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12407. }
  12408. };
  12409. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12410. if (indexBuffer == null) {
  12411. return;
  12412. }
  12413. if (this._cachedIndexBuffer !== indexBuffer) {
  12414. this._cachedIndexBuffer = indexBuffer;
  12415. this.bindIndexBuffer(indexBuffer);
  12416. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12417. }
  12418. };
  12419. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12420. var attributes = effect.getAttributesNames();
  12421. if (!this._vaoRecordInProgress) {
  12422. this._unbindVertexArrayObject();
  12423. }
  12424. this.unbindAllAttributes();
  12425. for (var index = 0; index < attributes.length; index++) {
  12426. var order = effect.getAttributeLocation(index);
  12427. if (order >= 0) {
  12428. var vertexBuffer = vertexBuffers[attributes[index]];
  12429. if (!vertexBuffer) {
  12430. continue;
  12431. }
  12432. this._gl.enableVertexAttribArray(order);
  12433. if (!this._vaoRecordInProgress) {
  12434. this._vertexAttribArraysEnabled[order] = true;
  12435. }
  12436. var buffer = vertexBuffer.getBuffer();
  12437. if (buffer) {
  12438. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12439. if (vertexBuffer.getIsInstanced()) {
  12440. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12441. if (!this._vaoRecordInProgress) {
  12442. this._currentInstanceLocations.push(order);
  12443. this._currentInstanceBuffers.push(buffer);
  12444. }
  12445. }
  12446. }
  12447. }
  12448. }
  12449. };
  12450. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12451. var vao = this._gl.createVertexArray();
  12452. this._vaoRecordInProgress = true;
  12453. this._gl.bindVertexArray(vao);
  12454. this._mustWipeVertexAttributes = true;
  12455. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12456. this.bindIndexBuffer(indexBuffer);
  12457. this._vaoRecordInProgress = false;
  12458. this._gl.bindVertexArray(null);
  12459. return vao;
  12460. };
  12461. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12462. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12463. this._cachedVertexArrayObject = vertexArrayObject;
  12464. this._gl.bindVertexArray(vertexArrayObject);
  12465. this._cachedVertexBuffers = null;
  12466. this._cachedIndexBuffer = null;
  12467. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12468. this._mustWipeVertexAttributes = true;
  12469. }
  12470. };
  12471. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12472. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12473. this._cachedVertexBuffers = vertexBuffer;
  12474. this._cachedEffectForVertexBuffers = effect;
  12475. var attributesCount = effect.getAttributesCount();
  12476. this._unbindVertexArrayObject();
  12477. this.unbindAllAttributes();
  12478. var offset = 0;
  12479. for (var index = 0; index < attributesCount; index++) {
  12480. if (index < vertexDeclaration.length) {
  12481. var order = effect.getAttributeLocation(index);
  12482. if (order >= 0) {
  12483. this._gl.enableVertexAttribArray(order);
  12484. this._vertexAttribArraysEnabled[order] = true;
  12485. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12486. }
  12487. offset += vertexDeclaration[index] * 4;
  12488. }
  12489. }
  12490. }
  12491. this._bindIndexBufferWithCache(indexBuffer);
  12492. };
  12493. Engine.prototype._unbindVertexArrayObject = function () {
  12494. if (!this._cachedVertexArrayObject) {
  12495. return;
  12496. }
  12497. this._cachedVertexArrayObject = null;
  12498. this._gl.bindVertexArray(null);
  12499. };
  12500. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12501. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12502. this._cachedVertexBuffers = vertexBuffers;
  12503. this._cachedEffectForVertexBuffers = effect;
  12504. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12505. }
  12506. this._bindIndexBufferWithCache(indexBuffer);
  12507. };
  12508. Engine.prototype.unbindInstanceAttributes = function () {
  12509. var boundBuffer;
  12510. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12511. var instancesBuffer = this._currentInstanceBuffers[i];
  12512. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12513. boundBuffer = instancesBuffer;
  12514. this.bindArrayBuffer(instancesBuffer);
  12515. }
  12516. var offsetLocation = this._currentInstanceLocations[i];
  12517. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12518. }
  12519. this._currentInstanceBuffers.length = 0;
  12520. this._currentInstanceLocations.length = 0;
  12521. };
  12522. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12523. this._gl.deleteVertexArray(vao);
  12524. };
  12525. Engine.prototype._releaseBuffer = function (buffer) {
  12526. buffer.references--;
  12527. if (buffer.references === 0) {
  12528. this._gl.deleteBuffer(buffer);
  12529. return true;
  12530. }
  12531. return false;
  12532. };
  12533. Engine.prototype.createInstancesBuffer = function (capacity) {
  12534. var buffer = this._gl.createBuffer();
  12535. if (!buffer) {
  12536. throw new Error("Unable to create instance buffer");
  12537. }
  12538. buffer.capacity = capacity;
  12539. this.bindArrayBuffer(buffer);
  12540. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12541. return buffer;
  12542. };
  12543. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12544. this._gl.deleteBuffer(buffer);
  12545. };
  12546. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12547. this.bindArrayBuffer(instancesBuffer);
  12548. if (data) {
  12549. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12550. }
  12551. if (offsetLocations[0].index !== undefined) {
  12552. var stride = 0;
  12553. for (var i = 0; i < offsetLocations.length; i++) {
  12554. var ai = offsetLocations[i];
  12555. stride += ai.attributeSize * 4;
  12556. }
  12557. for (var i = 0; i < offsetLocations.length; i++) {
  12558. var ai = offsetLocations[i];
  12559. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12560. this._gl.enableVertexAttribArray(ai.index);
  12561. this._vertexAttribArraysEnabled[ai.index] = true;
  12562. }
  12563. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12564. this._gl.vertexAttribDivisor(ai.index, 1);
  12565. this._currentInstanceLocations.push(ai.index);
  12566. this._currentInstanceBuffers.push(instancesBuffer);
  12567. }
  12568. }
  12569. else {
  12570. for (var index = 0; index < 4; index++) {
  12571. var offsetLocation = offsetLocations[index];
  12572. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12573. this._gl.enableVertexAttribArray(offsetLocation);
  12574. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12575. }
  12576. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12577. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12578. this._currentInstanceLocations.push(offsetLocation);
  12579. this._currentInstanceBuffers.push(instancesBuffer);
  12580. }
  12581. }
  12582. };
  12583. Engine.prototype.applyStates = function () {
  12584. this._depthCullingState.apply(this._gl);
  12585. this._stencilState.apply(this._gl);
  12586. this._alphaState.apply(this._gl);
  12587. };
  12588. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12589. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12590. };
  12591. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12592. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12593. };
  12594. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12595. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12596. };
  12597. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12598. // Apply states
  12599. this.applyStates();
  12600. this._drawCalls.addCount(1, false);
  12601. // Render
  12602. var drawMode = this._drawMode(fillMode);
  12603. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12604. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12605. if (instancesCount) {
  12606. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12607. }
  12608. else {
  12609. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12610. }
  12611. };
  12612. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12613. // Apply states
  12614. this.applyStates();
  12615. this._drawCalls.addCount(1, false);
  12616. var drawMode = this._drawMode(fillMode);
  12617. if (instancesCount) {
  12618. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12619. }
  12620. else {
  12621. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12622. }
  12623. };
  12624. Engine.prototype._drawMode = function (fillMode) {
  12625. switch (fillMode) {
  12626. // Triangle views
  12627. case BABYLON.Material.TriangleFillMode:
  12628. return this._gl.TRIANGLES;
  12629. case BABYLON.Material.PointFillMode:
  12630. return this._gl.POINTS;
  12631. case BABYLON.Material.WireFrameFillMode:
  12632. return this._gl.LINES;
  12633. // Draw modes
  12634. case BABYLON.Material.PointListDrawMode:
  12635. return this._gl.POINTS;
  12636. case BABYLON.Material.LineListDrawMode:
  12637. return this._gl.LINES;
  12638. case BABYLON.Material.LineLoopDrawMode:
  12639. return this._gl.LINE_LOOP;
  12640. case BABYLON.Material.LineStripDrawMode:
  12641. return this._gl.LINE_STRIP;
  12642. case BABYLON.Material.TriangleStripDrawMode:
  12643. return this._gl.TRIANGLE_STRIP;
  12644. case BABYLON.Material.TriangleFanDrawMode:
  12645. return this._gl.TRIANGLE_FAN;
  12646. default:
  12647. return this._gl.TRIANGLES;
  12648. }
  12649. };
  12650. // Shaders
  12651. Engine.prototype._releaseEffect = function (effect) {
  12652. if (this._compiledEffects[effect._key]) {
  12653. delete this._compiledEffects[effect._key];
  12654. this._deleteProgram(effect.getProgram());
  12655. }
  12656. };
  12657. Engine.prototype._deleteProgram = function (program) {
  12658. if (program) {
  12659. program.__SPECTOR_rebuildProgram = null;
  12660. if (program.transformFeedback) {
  12661. this.deleteTransformFeedback(program.transformFeedback);
  12662. program.transformFeedback = null;
  12663. }
  12664. this._gl.deleteProgram(program);
  12665. }
  12666. };
  12667. /**
  12668. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12669. * @param samplers An array of string used to represent textures
  12670. */
  12671. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12672. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12673. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12674. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12675. if (this._compiledEffects[name]) {
  12676. var compiledEffect = this._compiledEffects[name];
  12677. if (onCompiled && compiledEffect.isReady()) {
  12678. onCompiled(compiledEffect);
  12679. }
  12680. return compiledEffect;
  12681. }
  12682. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12683. effect._key = name;
  12684. this._compiledEffects[name] = effect;
  12685. return effect;
  12686. };
  12687. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12688. if (uniformsNames === void 0) { uniformsNames = []; }
  12689. if (samplers === void 0) { samplers = []; }
  12690. if (defines === void 0) { defines = ""; }
  12691. return this.createEffect({
  12692. vertex: "particles",
  12693. fragmentElement: fragmentName
  12694. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12695. };
  12696. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12697. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12698. context = context || this._gl;
  12699. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12700. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12701. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12702. };
  12703. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12704. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12705. context = context || this._gl;
  12706. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12707. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12708. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12709. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12710. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12711. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12712. return program;
  12713. };
  12714. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12715. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12716. var shaderProgram = context.createProgram();
  12717. if (!shaderProgram) {
  12718. throw new Error("Unable to create program");
  12719. }
  12720. context.attachShader(shaderProgram, vertexShader);
  12721. context.attachShader(shaderProgram, fragmentShader);
  12722. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12723. var transformFeedback = this.createTransformFeedback();
  12724. this.bindTransformFeedback(transformFeedback);
  12725. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12726. shaderProgram.transformFeedback = transformFeedback;
  12727. }
  12728. context.linkProgram(shaderProgram);
  12729. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12730. this.bindTransformFeedback(null);
  12731. }
  12732. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12733. if (!linked) {
  12734. context.validateProgram(shaderProgram);
  12735. var error = context.getProgramInfoLog(shaderProgram);
  12736. if (error) {
  12737. throw new Error(error);
  12738. }
  12739. }
  12740. context.deleteShader(vertexShader);
  12741. context.deleteShader(fragmentShader);
  12742. return shaderProgram;
  12743. };
  12744. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12745. var results = new Array();
  12746. for (var index = 0; index < uniformsNames.length; index++) {
  12747. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12748. }
  12749. return results;
  12750. };
  12751. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12752. var results = [];
  12753. for (var index = 0; index < attributesNames.length; index++) {
  12754. try {
  12755. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12756. }
  12757. catch (e) {
  12758. results.push(-1);
  12759. }
  12760. }
  12761. return results;
  12762. };
  12763. Engine.prototype.enableEffect = function (effect) {
  12764. if (!effect) {
  12765. return;
  12766. }
  12767. // Use program
  12768. this.bindSamplers(effect);
  12769. this._currentEffect = effect;
  12770. if (effect.onBind) {
  12771. effect.onBind(effect);
  12772. }
  12773. effect.onBindObservable.notifyObservers(effect);
  12774. };
  12775. Engine.prototype.setIntArray = function (uniform, array) {
  12776. if (!uniform)
  12777. return;
  12778. this._gl.uniform1iv(uniform, array);
  12779. };
  12780. Engine.prototype.setIntArray2 = function (uniform, array) {
  12781. if (!uniform || array.length % 2 !== 0)
  12782. return;
  12783. this._gl.uniform2iv(uniform, array);
  12784. };
  12785. Engine.prototype.setIntArray3 = function (uniform, array) {
  12786. if (!uniform || array.length % 3 !== 0)
  12787. return;
  12788. this._gl.uniform3iv(uniform, array);
  12789. };
  12790. Engine.prototype.setIntArray4 = function (uniform, array) {
  12791. if (!uniform || array.length % 4 !== 0)
  12792. return;
  12793. this._gl.uniform4iv(uniform, array);
  12794. };
  12795. Engine.prototype.setFloatArray = function (uniform, array) {
  12796. if (!uniform)
  12797. return;
  12798. this._gl.uniform1fv(uniform, array);
  12799. };
  12800. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12801. if (!uniform || array.length % 2 !== 0)
  12802. return;
  12803. this._gl.uniform2fv(uniform, array);
  12804. };
  12805. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12806. if (!uniform || array.length % 3 !== 0)
  12807. return;
  12808. this._gl.uniform3fv(uniform, array);
  12809. };
  12810. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12811. if (!uniform || array.length % 4 !== 0)
  12812. return;
  12813. this._gl.uniform4fv(uniform, array);
  12814. };
  12815. Engine.prototype.setArray = function (uniform, array) {
  12816. if (!uniform)
  12817. return;
  12818. this._gl.uniform1fv(uniform, array);
  12819. };
  12820. Engine.prototype.setArray2 = function (uniform, array) {
  12821. if (!uniform || array.length % 2 !== 0)
  12822. return;
  12823. this._gl.uniform2fv(uniform, array);
  12824. };
  12825. Engine.prototype.setArray3 = function (uniform, array) {
  12826. if (!uniform || array.length % 3 !== 0)
  12827. return;
  12828. this._gl.uniform3fv(uniform, array);
  12829. };
  12830. Engine.prototype.setArray4 = function (uniform, array) {
  12831. if (!uniform || array.length % 4 !== 0)
  12832. return;
  12833. this._gl.uniform4fv(uniform, array);
  12834. };
  12835. Engine.prototype.setMatrices = function (uniform, matrices) {
  12836. if (!uniform)
  12837. return;
  12838. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12839. };
  12840. Engine.prototype.setMatrix = function (uniform, matrix) {
  12841. if (!uniform)
  12842. return;
  12843. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12844. };
  12845. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12846. if (!uniform)
  12847. return;
  12848. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12849. };
  12850. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12851. if (!uniform)
  12852. return;
  12853. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12854. };
  12855. Engine.prototype.setInt = function (uniform, value) {
  12856. if (!uniform)
  12857. return;
  12858. this._gl.uniform1i(uniform, value);
  12859. };
  12860. Engine.prototype.setFloat = function (uniform, value) {
  12861. if (!uniform)
  12862. return;
  12863. this._gl.uniform1f(uniform, value);
  12864. };
  12865. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12866. if (!uniform)
  12867. return;
  12868. this._gl.uniform2f(uniform, x, y);
  12869. };
  12870. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12871. if (!uniform)
  12872. return;
  12873. this._gl.uniform3f(uniform, x, y, z);
  12874. };
  12875. Engine.prototype.setBool = function (uniform, bool) {
  12876. if (!uniform)
  12877. return;
  12878. this._gl.uniform1i(uniform, bool);
  12879. };
  12880. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12881. if (!uniform)
  12882. return;
  12883. this._gl.uniform4f(uniform, x, y, z, w);
  12884. };
  12885. Engine.prototype.setColor3 = function (uniform, color3) {
  12886. if (!uniform)
  12887. return;
  12888. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12889. };
  12890. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12891. if (!uniform)
  12892. return;
  12893. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12894. };
  12895. /**
  12896. * Sets a Color4 on a uniform variable
  12897. * @param uniform defines the uniform location
  12898. * @param color4 defines the value to be set
  12899. */
  12900. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12901. if (!uniform)
  12902. return;
  12903. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12904. };
  12905. // States
  12906. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12907. if (zOffset === void 0) { zOffset = 0; }
  12908. if (reverseSide === void 0) { reverseSide = false; }
  12909. // Culling
  12910. if (this._depthCullingState.cull !== culling || force) {
  12911. this._depthCullingState.cull = culling;
  12912. }
  12913. // Cull face
  12914. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12915. if (this._depthCullingState.cullFace !== cullFace || force) {
  12916. this._depthCullingState.cullFace = cullFace;
  12917. }
  12918. // Z offset
  12919. this.setZOffset(zOffset);
  12920. // Front face
  12921. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12922. if (this._depthCullingState.frontFace !== frontFace || force) {
  12923. this._depthCullingState.frontFace = frontFace;
  12924. }
  12925. };
  12926. Engine.prototype.setZOffset = function (value) {
  12927. this._depthCullingState.zOffset = value;
  12928. };
  12929. Engine.prototype.getZOffset = function () {
  12930. return this._depthCullingState.zOffset;
  12931. };
  12932. Engine.prototype.setDepthBuffer = function (enable) {
  12933. this._depthCullingState.depthTest = enable;
  12934. };
  12935. Engine.prototype.getDepthWrite = function () {
  12936. return this._depthCullingState.depthMask;
  12937. };
  12938. Engine.prototype.setDepthWrite = function (enable) {
  12939. this._depthCullingState.depthMask = enable;
  12940. };
  12941. Engine.prototype.setColorWrite = function (enable) {
  12942. this._gl.colorMask(enable, enable, enable, enable);
  12943. this._colorWrite = enable;
  12944. };
  12945. Engine.prototype.getColorWrite = function () {
  12946. return this._colorWrite;
  12947. };
  12948. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12949. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12950. };
  12951. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12952. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12953. if (this._alphaMode === mode) {
  12954. return;
  12955. }
  12956. switch (mode) {
  12957. case Engine.ALPHA_DISABLE:
  12958. this._alphaState.alphaBlend = false;
  12959. break;
  12960. case Engine.ALPHA_PREMULTIPLIED:
  12961. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12962. this._alphaState.alphaBlend = true;
  12963. break;
  12964. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12965. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12966. this._alphaState.alphaBlend = true;
  12967. break;
  12968. case Engine.ALPHA_COMBINE:
  12969. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12970. this._alphaState.alphaBlend = true;
  12971. break;
  12972. case Engine.ALPHA_ONEONE:
  12973. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12974. this._alphaState.alphaBlend = true;
  12975. break;
  12976. case Engine.ALPHA_ADD:
  12977. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12978. this._alphaState.alphaBlend = true;
  12979. break;
  12980. case Engine.ALPHA_SUBTRACT:
  12981. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12982. this._alphaState.alphaBlend = true;
  12983. break;
  12984. case Engine.ALPHA_MULTIPLY:
  12985. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12986. this._alphaState.alphaBlend = true;
  12987. break;
  12988. case Engine.ALPHA_MAXIMIZED:
  12989. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12990. this._alphaState.alphaBlend = true;
  12991. break;
  12992. case Engine.ALPHA_INTERPOLATE:
  12993. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12994. this._alphaState.alphaBlend = true;
  12995. break;
  12996. case Engine.ALPHA_SCREENMODE:
  12997. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12998. this._alphaState.alphaBlend = true;
  12999. break;
  13000. }
  13001. if (!noDepthWriteChange) {
  13002. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  13003. }
  13004. this._alphaMode = mode;
  13005. };
  13006. Engine.prototype.getAlphaMode = function () {
  13007. return this._alphaMode;
  13008. };
  13009. // Textures
  13010. Engine.prototype.wipeCaches = function (bruteForce) {
  13011. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  13012. return;
  13013. }
  13014. this._currentEffect = null;
  13015. // 6/8/2017: deltakosh: Should not be required anymore.
  13016. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  13017. if (bruteForce) {
  13018. this.resetTextureCache();
  13019. this._currentProgram = null;
  13020. this._stencilState.reset();
  13021. this._depthCullingState.reset();
  13022. this.setDepthFunctionToLessOrEqual();
  13023. this._alphaState.reset();
  13024. }
  13025. this._resetVertexBufferBinding();
  13026. this._cachedIndexBuffer = null;
  13027. this._cachedEffectForVertexBuffers = null;
  13028. this._unbindVertexArrayObject();
  13029. this.bindIndexBuffer(null);
  13030. };
  13031. /**
  13032. * Set the compressed texture format to use, based on the formats you have, and the formats
  13033. * supported by the hardware / browser.
  13034. *
  13035. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  13036. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  13037. * to API arguments needed to compressed textures. This puts the burden on the container
  13038. * generator to house the arcane code for determining these for current & future formats.
  13039. *
  13040. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  13041. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13042. *
  13043. * Note: The result of this call is not taken into account when a texture is base64.
  13044. *
  13045. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13046. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13047. *
  13048. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13049. * @returns The extension selected.
  13050. */
  13051. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13052. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13053. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13054. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13055. return this._textureFormatInUse = this._texturesSupported[i];
  13056. }
  13057. }
  13058. }
  13059. // actively set format to nothing, to allow this to be called more than once
  13060. // and possibly fail the 2nd time
  13061. this._textureFormatInUse = null;
  13062. return null;
  13063. };
  13064. Engine.prototype._createTexture = function () {
  13065. var texture = this._gl.createTexture();
  13066. if (!texture) {
  13067. throw new Error("Unable to create texture");
  13068. }
  13069. return texture;
  13070. };
  13071. /**
  13072. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13073. * @param {string} urlArg- This contains one of the following:
  13074. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13075. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13076. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13077. *
  13078. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13079. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13080. * @param {Scene} scene- Needed for loading to the correct scene.
  13081. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13082. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13083. * @param {callback} onError- Optional callback to be called upon failure.
  13084. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13085. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13086. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13087. *
  13088. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13089. */
  13090. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13091. var _this = this;
  13092. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13093. if (onLoad === void 0) { onLoad = null; }
  13094. if (onError === void 0) { onError = null; }
  13095. if (buffer === void 0) { buffer = null; }
  13096. if (fallBack === void 0) { fallBack = null; }
  13097. if (format === void 0) { format = null; }
  13098. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13099. var fromData = url.substr(0, 5) === "data:";
  13100. var fromBlob = url.substr(0, 5) === "blob:";
  13101. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13102. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13103. // establish the file extension, if possible
  13104. var lastDot = url.lastIndexOf('.');
  13105. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13106. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13107. var isTGA = (extension.indexOf(".tga") === 0);
  13108. // determine if a ktx file should be substituted
  13109. var isKTX = false;
  13110. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13111. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13112. isKTX = true;
  13113. }
  13114. if (scene) {
  13115. scene._addPendingData(texture);
  13116. }
  13117. texture.url = url;
  13118. texture.generateMipMaps = !noMipmap;
  13119. texture.samplingMode = samplingMode;
  13120. texture.invertY = invertY;
  13121. if (!this._doNotHandleContextLost) {
  13122. // Keep a link to the buffer only if we plan to handle context lost
  13123. texture._buffer = buffer;
  13124. }
  13125. var onLoadObserver = null;
  13126. if (onLoad && !fallBack) {
  13127. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13128. }
  13129. if (!fallBack)
  13130. this._internalTexturesCache.push(texture);
  13131. var onerror = function (message, exception) {
  13132. if (scene) {
  13133. scene._removePendingData(texture);
  13134. }
  13135. if (onLoadObserver) {
  13136. texture.onLoadedObservable.remove(onLoadObserver);
  13137. }
  13138. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13139. if (isKTX) {
  13140. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13141. }
  13142. else if (BABYLON.Tools.UseFallbackTexture) {
  13143. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13144. }
  13145. if (onError) {
  13146. onError(message || "Unknown error", exception);
  13147. }
  13148. };
  13149. var callback = null;
  13150. // processing for non-image formats
  13151. if (isKTX || isTGA || isDDS) {
  13152. if (isKTX) {
  13153. callback = function (data) {
  13154. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13155. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13156. ktx.uploadLevels(_this._gl, !noMipmap);
  13157. return false;
  13158. }, samplingMode);
  13159. };
  13160. }
  13161. else if (isTGA) {
  13162. callback = function (arrayBuffer) {
  13163. var data = new Uint8Array(arrayBuffer);
  13164. var header = BABYLON.TGATools.GetTGAHeader(data);
  13165. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13166. BABYLON.TGATools.UploadContent(_this._gl, data);
  13167. return false;
  13168. }, samplingMode);
  13169. };
  13170. }
  13171. else if (isDDS) {
  13172. callback = function (data) {
  13173. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13174. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13175. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13176. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13177. return false;
  13178. }, samplingMode);
  13179. };
  13180. }
  13181. if (!buffer) {
  13182. this._loadFile(url, function (data) {
  13183. if (callback) {
  13184. callback(data);
  13185. }
  13186. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13187. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13188. });
  13189. }
  13190. else {
  13191. if (callback) {
  13192. callback(buffer);
  13193. }
  13194. }
  13195. // image format processing
  13196. }
  13197. else {
  13198. var onload = function (img) {
  13199. if (fromBlob && !_this._doNotHandleContextLost) {
  13200. // We need to store the image if we need to rebuild the texture
  13201. // in case of a webgl context lost
  13202. texture._buffer = img;
  13203. }
  13204. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13205. var gl = _this._gl;
  13206. var isPot = (img.width === potWidth && img.height === potHeight);
  13207. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13208. if (isPot) {
  13209. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13210. return false;
  13211. }
  13212. // Using shaders to rescale because canvas.drawImage is lossy
  13213. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13214. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13215. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13216. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13219. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13220. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13221. _this._releaseTexture(source);
  13222. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13223. continuationCallback();
  13224. });
  13225. return true;
  13226. }, samplingMode);
  13227. };
  13228. if (!fromData || isBase64)
  13229. if (buffer instanceof HTMLImageElement) {
  13230. onload(buffer);
  13231. }
  13232. else {
  13233. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13234. }
  13235. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13236. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13237. else
  13238. onload(buffer);
  13239. }
  13240. return texture;
  13241. };
  13242. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13243. var _this = this;
  13244. var rtt = this.createRenderTargetTexture({
  13245. width: destination.width,
  13246. height: destination.height,
  13247. }, {
  13248. generateMipMaps: false,
  13249. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13250. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13251. generateDepthBuffer: false,
  13252. generateStencilBuffer: false
  13253. });
  13254. if (!this._rescalePostProcess) {
  13255. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13256. }
  13257. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13258. _this._rescalePostProcess.onApply = function (effect) {
  13259. effect._bindTexture("textureSampler", source);
  13260. };
  13261. var hostingScene = scene;
  13262. if (!hostingScene) {
  13263. hostingScene = _this.scenes[_this.scenes.length - 1];
  13264. }
  13265. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13266. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13267. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13268. _this.unBindFramebuffer(rtt);
  13269. _this._releaseTexture(rtt);
  13270. if (onComplete) {
  13271. onComplete();
  13272. }
  13273. });
  13274. };
  13275. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13276. if (compression === void 0) { compression = null; }
  13277. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13278. if (!texture) {
  13279. return;
  13280. }
  13281. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13282. var internalFormat = this._getInternalFormat(format);
  13283. var textureType = this._getWebGLTextureType(type);
  13284. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13285. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13286. if (!this._doNotHandleContextLost) {
  13287. texture._bufferView = data;
  13288. texture.format = format;
  13289. texture.type = type;
  13290. texture.invertY = invertY;
  13291. texture._compression = compression;
  13292. }
  13293. if (texture.width % 4 !== 0) {
  13294. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13295. }
  13296. if (compression && data) {
  13297. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13298. }
  13299. else {
  13300. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13301. }
  13302. if (texture.generateMipMaps) {
  13303. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13304. }
  13305. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13306. // this.resetTextureCache();
  13307. texture.isReady = true;
  13308. };
  13309. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13310. if (compression === void 0) { compression = null; }
  13311. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13312. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13313. texture.baseWidth = width;
  13314. texture.baseHeight = height;
  13315. texture.width = width;
  13316. texture.height = height;
  13317. texture.format = format;
  13318. texture.generateMipMaps = generateMipMaps;
  13319. texture.samplingMode = samplingMode;
  13320. texture.invertY = invertY;
  13321. texture._compression = compression;
  13322. texture.type = type;
  13323. if (!this._doNotHandleContextLost) {
  13324. texture._bufferView = data;
  13325. }
  13326. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13327. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13328. // Filters
  13329. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13330. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13332. if (generateMipMaps) {
  13333. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13334. }
  13335. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13336. this._internalTexturesCache.push(texture);
  13337. return texture;
  13338. };
  13339. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13340. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13341. texture.baseWidth = width;
  13342. texture.baseHeight = height;
  13343. if (generateMipMaps) {
  13344. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13345. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13346. }
  13347. // this.resetTextureCache();
  13348. texture.width = width;
  13349. texture.height = height;
  13350. texture.isReady = false;
  13351. texture.generateMipMaps = generateMipMaps;
  13352. texture.samplingMode = samplingMode;
  13353. this.updateTextureSamplingMode(samplingMode, texture);
  13354. this._internalTexturesCache.push(texture);
  13355. return texture;
  13356. };
  13357. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13358. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13359. if (texture.isCube) {
  13360. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13361. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13362. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13363. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13364. }
  13365. else if (texture.is3D) {
  13366. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13367. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13368. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13369. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13370. }
  13371. else {
  13372. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13373. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13374. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13375. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13376. }
  13377. texture.samplingMode = samplingMode;
  13378. };
  13379. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13380. if (premulAlpha === void 0) { premulAlpha = false; }
  13381. if (!texture) {
  13382. return;
  13383. }
  13384. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13385. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13386. if (premulAlpha) {
  13387. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13388. }
  13389. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13390. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13391. if (texture.generateMipMaps) {
  13392. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13393. }
  13394. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13395. if (premulAlpha) {
  13396. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13397. }
  13398. texture.isReady = true;
  13399. };
  13400. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13401. if (!texture || texture._isDisabled) {
  13402. return;
  13403. }
  13404. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13405. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13406. try {
  13407. // Testing video texture support
  13408. if (this._videoTextureSupported === undefined) {
  13409. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13410. if (this._gl.getError() !== 0) {
  13411. this._videoTextureSupported = false;
  13412. }
  13413. else {
  13414. this._videoTextureSupported = true;
  13415. }
  13416. }
  13417. // Copy video through the current working canvas if video texture is not supported
  13418. if (!this._videoTextureSupported) {
  13419. if (!texture._workingCanvas) {
  13420. texture._workingCanvas = document.createElement("canvas");
  13421. var context = texture._workingCanvas.getContext("2d");
  13422. if (!context) {
  13423. throw new Error("Unable to get 2d context");
  13424. }
  13425. texture._workingContext = context;
  13426. texture._workingCanvas.width = texture.width;
  13427. texture._workingCanvas.height = texture.height;
  13428. }
  13429. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13430. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13431. }
  13432. else {
  13433. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13434. }
  13435. if (texture.generateMipMaps) {
  13436. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13437. }
  13438. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13439. // this.resetTextureCache();
  13440. texture.isReady = true;
  13441. }
  13442. catch (ex) {
  13443. // Something unexpected
  13444. // Let's disable the texture
  13445. texture._isDisabled = true;
  13446. }
  13447. };
  13448. /**
  13449. * Updates a depth texture Comparison Mode and Function.
  13450. * If the comparison Function is equal to 0, the mode will be set to none.
  13451. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13452. * @param texture The texture to set the comparison function for
  13453. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13454. */
  13455. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13456. if (this.webGLVersion === 1) {
  13457. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13458. return;
  13459. }
  13460. var gl = this._gl;
  13461. if (texture.isCube) {
  13462. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13463. if (comparisonFunction === 0) {
  13464. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13465. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13466. }
  13467. else {
  13468. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13469. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13470. }
  13471. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13472. }
  13473. else {
  13474. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13475. if (comparisonFunction === 0) {
  13476. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13477. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13478. }
  13479. else {
  13480. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13481. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13482. }
  13483. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13484. }
  13485. texture._comparisonFunction = comparisonFunction;
  13486. };
  13487. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13488. var width = size.width || size;
  13489. var height = size.height || size;
  13490. internalTexture.baseWidth = width;
  13491. internalTexture.baseHeight = height;
  13492. internalTexture.width = width;
  13493. internalTexture.height = height;
  13494. internalTexture.isReady = true;
  13495. internalTexture.samples = 1;
  13496. internalTexture.generateMipMaps = false;
  13497. internalTexture._generateDepthBuffer = true;
  13498. internalTexture._generateStencilBuffer = generateStencil;
  13499. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13500. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13501. internalTexture._comparisonFunction = comparisonFunction;
  13502. var gl = this._gl;
  13503. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13504. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13505. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13506. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13507. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13508. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13509. if (comparisonFunction === 0) {
  13510. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13511. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13512. }
  13513. else {
  13514. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13515. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13516. }
  13517. };
  13518. /**
  13519. * Creates a depth stencil texture.
  13520. * This is only available in WebGL 2 or with the depth texture extension available.
  13521. * @param size The size of face edge in the texture.
  13522. * @param options The options defining the texture.
  13523. * @returns The texture
  13524. */
  13525. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13526. if (options.isCube) {
  13527. var width = size.width || size;
  13528. return this._createDepthStencilCubeTexture(width, options);
  13529. }
  13530. else {
  13531. return this._createDepthStencilTexture(size, options);
  13532. }
  13533. };
  13534. /**
  13535. * Creates a depth stencil texture.
  13536. * This is only available in WebGL 2 or with the depth texture extension available.
  13537. * @param size The size of face edge in the texture.
  13538. * @param options The options defining the texture.
  13539. * @returns The texture
  13540. */
  13541. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13542. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13543. if (!this._caps.depthTextureExtension) {
  13544. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13545. return internalTexture;
  13546. }
  13547. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13548. var gl = this._gl;
  13549. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13550. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13551. if (this.webGLVersion > 1) {
  13552. if (internalOptions.generateStencil) {
  13553. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13554. }
  13555. else {
  13556. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13557. }
  13558. }
  13559. else {
  13560. if (internalOptions.generateStencil) {
  13561. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13562. }
  13563. else {
  13564. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13565. }
  13566. }
  13567. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13568. return internalTexture;
  13569. };
  13570. /**
  13571. * Creates a depth stencil cube texture.
  13572. * This is only available in WebGL 2.
  13573. * @param size The size of face edge in the cube texture.
  13574. * @param options The options defining the cube texture.
  13575. * @returns The cube texture
  13576. */
  13577. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13578. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13579. internalTexture.isCube = true;
  13580. if (this.webGLVersion === 1) {
  13581. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13582. return internalTexture;
  13583. }
  13584. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13585. var gl = this._gl;
  13586. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13587. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13588. // Create the depth/stencil buffer
  13589. for (var face = 0; face < 6; face++) {
  13590. if (internalOptions.generateStencil) {
  13591. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13592. }
  13593. else {
  13594. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13595. }
  13596. }
  13597. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13598. return internalTexture;
  13599. };
  13600. /**
  13601. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13602. * @param renderTarget The render target to set the frame buffer for
  13603. */
  13604. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13605. // Create the framebuffer
  13606. var internalTexture = renderTarget.getInternalTexture();
  13607. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13608. return;
  13609. }
  13610. var gl = this._gl;
  13611. var depthStencilTexture = renderTarget.depthStencilTexture;
  13612. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13613. if (depthStencilTexture.isCube) {
  13614. if (depthStencilTexture._generateStencilBuffer) {
  13615. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13616. }
  13617. else {
  13618. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13619. }
  13620. }
  13621. else {
  13622. if (depthStencilTexture._generateStencilBuffer) {
  13623. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13624. }
  13625. else {
  13626. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13627. }
  13628. }
  13629. this.bindUnboundFramebuffer(null);
  13630. };
  13631. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13632. var fullOptions = new RenderTargetCreationOptions();
  13633. if (options !== undefined && typeof options === "object") {
  13634. fullOptions.generateMipMaps = options.generateMipMaps;
  13635. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13636. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13637. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13638. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13639. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13640. }
  13641. else {
  13642. fullOptions.generateMipMaps = options;
  13643. fullOptions.generateDepthBuffer = true;
  13644. fullOptions.generateStencilBuffer = false;
  13645. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13646. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13647. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13648. }
  13649. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13650. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13651. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13652. }
  13653. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13654. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13655. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13656. }
  13657. var gl = this._gl;
  13658. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13659. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13660. var width = size.width || size;
  13661. var height = size.height || size;
  13662. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13663. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13664. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13665. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13666. }
  13667. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13668. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13669. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13670. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13671. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13672. // Create the framebuffer
  13673. var framebuffer = gl.createFramebuffer();
  13674. this.bindUnboundFramebuffer(framebuffer);
  13675. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13676. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13677. if (fullOptions.generateMipMaps) {
  13678. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13679. }
  13680. // Unbind
  13681. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13682. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13683. this.bindUnboundFramebuffer(null);
  13684. texture._framebuffer = framebuffer;
  13685. texture.baseWidth = width;
  13686. texture.baseHeight = height;
  13687. texture.width = width;
  13688. texture.height = height;
  13689. texture.isReady = true;
  13690. texture.samples = 1;
  13691. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13692. texture.samplingMode = fullOptions.samplingMode;
  13693. texture.type = fullOptions.type;
  13694. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13695. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13696. // this.resetTextureCache();
  13697. this._internalTexturesCache.push(texture);
  13698. return texture;
  13699. };
  13700. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13701. var generateMipMaps = false;
  13702. var generateDepthBuffer = true;
  13703. var generateStencilBuffer = false;
  13704. var generateDepthTexture = false;
  13705. var textureCount = 1;
  13706. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13707. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13708. var types = [], samplingModes = [];
  13709. if (options !== undefined) {
  13710. generateMipMaps = options.generateMipMaps;
  13711. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13712. generateStencilBuffer = options.generateStencilBuffer;
  13713. generateDepthTexture = options.generateDepthTexture;
  13714. textureCount = options.textureCount || 1;
  13715. if (options.types) {
  13716. types = options.types;
  13717. }
  13718. if (options.samplingModes) {
  13719. samplingModes = options.samplingModes;
  13720. }
  13721. }
  13722. var gl = this._gl;
  13723. // Create the framebuffer
  13724. var framebuffer = gl.createFramebuffer();
  13725. this.bindUnboundFramebuffer(framebuffer);
  13726. var width = size.width || size;
  13727. var height = size.height || size;
  13728. var textures = [];
  13729. var attachments = [];
  13730. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13731. for (var i = 0; i < textureCount; i++) {
  13732. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13733. var type = types[i] || defaultType;
  13734. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13735. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13736. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13737. }
  13738. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13739. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13740. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13741. }
  13742. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13743. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13744. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13745. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13746. }
  13747. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13748. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13749. textures.push(texture);
  13750. attachments.push(attachment);
  13751. gl.activeTexture(gl["TEXTURE" + i]);
  13752. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13753. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13754. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13755. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13756. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13757. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13758. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13759. if (generateMipMaps) {
  13760. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13761. }
  13762. // Unbind
  13763. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13764. texture._framebuffer = framebuffer;
  13765. texture._depthStencilBuffer = depthStencilBuffer;
  13766. texture.baseWidth = width;
  13767. texture.baseHeight = height;
  13768. texture.width = width;
  13769. texture.height = height;
  13770. texture.isReady = true;
  13771. texture.samples = 1;
  13772. texture.generateMipMaps = generateMipMaps;
  13773. texture.samplingMode = samplingMode;
  13774. texture.type = type;
  13775. texture._generateDepthBuffer = generateDepthBuffer;
  13776. texture._generateStencilBuffer = generateStencilBuffer;
  13777. texture._attachments = attachments;
  13778. this._internalTexturesCache.push(texture);
  13779. }
  13780. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13781. // Depth texture
  13782. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13783. gl.activeTexture(gl.TEXTURE0);
  13784. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13785. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13786. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13787. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13788. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13789. 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);
  13790. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13791. depthTexture._framebuffer = framebuffer;
  13792. depthTexture.baseWidth = width;
  13793. depthTexture.baseHeight = height;
  13794. depthTexture.width = width;
  13795. depthTexture.height = height;
  13796. depthTexture.isReady = true;
  13797. depthTexture.samples = 1;
  13798. depthTexture.generateMipMaps = generateMipMaps;
  13799. depthTexture.samplingMode = gl.NEAREST;
  13800. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13801. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13802. textures.push(depthTexture);
  13803. this._internalTexturesCache.push(depthTexture);
  13804. }
  13805. gl.drawBuffers(attachments);
  13806. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13807. this.bindUnboundFramebuffer(null);
  13808. this.resetTextureCache();
  13809. return textures;
  13810. };
  13811. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13812. if (samples === void 0) { samples = 1; }
  13813. var depthStencilBuffer = null;
  13814. var gl = this._gl;
  13815. // Create the depth/stencil buffer
  13816. if (generateStencilBuffer) {
  13817. depthStencilBuffer = gl.createRenderbuffer();
  13818. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13819. if (samples > 1) {
  13820. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13821. }
  13822. else {
  13823. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13824. }
  13825. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13826. }
  13827. else if (generateDepthBuffer) {
  13828. depthStencilBuffer = gl.createRenderbuffer();
  13829. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13830. if (samples > 1) {
  13831. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13832. }
  13833. else {
  13834. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13835. }
  13836. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13837. }
  13838. return depthStencilBuffer;
  13839. };
  13840. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13841. if (this.webGLVersion < 2 || !texture) {
  13842. return 1;
  13843. }
  13844. if (texture.samples === samples) {
  13845. return samples;
  13846. }
  13847. var gl = this._gl;
  13848. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13849. // Dispose previous render buffers
  13850. if (texture._depthStencilBuffer) {
  13851. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13852. texture._depthStencilBuffer = null;
  13853. }
  13854. if (texture._MSAAFramebuffer) {
  13855. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13856. texture._MSAAFramebuffer = null;
  13857. }
  13858. if (texture._MSAARenderBuffer) {
  13859. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13860. texture._MSAARenderBuffer = null;
  13861. }
  13862. if (samples > 1) {
  13863. var framebuffer = gl.createFramebuffer();
  13864. if (!framebuffer) {
  13865. throw new Error("Unable to create multi sampled framebuffer");
  13866. }
  13867. texture._MSAAFramebuffer = framebuffer;
  13868. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13869. var colorRenderbuffer = gl.createRenderbuffer();
  13870. if (!colorRenderbuffer) {
  13871. throw new Error("Unable to create multi sampled framebuffer");
  13872. }
  13873. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13874. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13875. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13876. texture._MSAARenderBuffer = colorRenderbuffer;
  13877. }
  13878. else {
  13879. this.bindUnboundFramebuffer(texture._framebuffer);
  13880. }
  13881. texture.samples = samples;
  13882. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13883. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13884. this.bindUnboundFramebuffer(null);
  13885. return samples;
  13886. };
  13887. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13888. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13889. return 1;
  13890. }
  13891. if (textures[0].samples === samples) {
  13892. return samples;
  13893. }
  13894. var gl = this._gl;
  13895. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13896. // Dispose previous render buffers
  13897. if (textures[0]._depthStencilBuffer) {
  13898. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13899. textures[0]._depthStencilBuffer = null;
  13900. }
  13901. if (textures[0]._MSAAFramebuffer) {
  13902. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13903. textures[0]._MSAAFramebuffer = null;
  13904. }
  13905. for (var i = 0; i < textures.length; i++) {
  13906. if (textures[i]._MSAARenderBuffer) {
  13907. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13908. textures[i]._MSAARenderBuffer = null;
  13909. }
  13910. }
  13911. if (samples > 1) {
  13912. var framebuffer = gl.createFramebuffer();
  13913. if (!framebuffer) {
  13914. throw new Error("Unable to create multi sampled framebuffer");
  13915. }
  13916. this.bindUnboundFramebuffer(framebuffer);
  13917. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13918. var attachments = [];
  13919. for (var i = 0; i < textures.length; i++) {
  13920. var texture = textures[i];
  13921. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13922. var colorRenderbuffer = gl.createRenderbuffer();
  13923. if (!colorRenderbuffer) {
  13924. throw new Error("Unable to create multi sampled framebuffer");
  13925. }
  13926. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13927. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13928. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13929. texture._MSAAFramebuffer = framebuffer;
  13930. texture._MSAARenderBuffer = colorRenderbuffer;
  13931. texture.samples = samples;
  13932. texture._depthStencilBuffer = depthStencilBuffer;
  13933. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13934. attachments.push(attachment);
  13935. }
  13936. gl.drawBuffers(attachments);
  13937. }
  13938. else {
  13939. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13940. }
  13941. this.bindUnboundFramebuffer(null);
  13942. return samples;
  13943. };
  13944. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13945. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13946. };
  13947. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13948. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13949. };
  13950. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13951. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13952. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13953. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13954. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13955. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13956. }
  13957. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13958. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13959. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13960. }
  13961. var gl = this._gl;
  13962. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13963. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13964. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13965. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13966. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13967. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13968. }
  13969. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13970. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13971. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13972. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13973. for (var face = 0; face < 6; face++) {
  13974. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13975. }
  13976. // Create the framebuffer
  13977. var framebuffer = gl.createFramebuffer();
  13978. this.bindUnboundFramebuffer(framebuffer);
  13979. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13980. // MipMaps
  13981. if (fullOptions.generateMipMaps) {
  13982. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13983. }
  13984. // Unbind
  13985. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13986. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13987. this.bindUnboundFramebuffer(null);
  13988. texture._framebuffer = framebuffer;
  13989. texture.width = size;
  13990. texture.height = size;
  13991. texture.isReady = true;
  13992. texture.isCube = true;
  13993. texture.samples = 1;
  13994. texture.generateMipMaps = fullOptions.generateMipMaps;
  13995. texture.samplingMode = fullOptions.samplingMode;
  13996. texture.type = fullOptions.type;
  13997. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13998. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13999. this._internalTexturesCache.push(texture);
  14000. return texture;
  14001. };
  14002. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  14003. var _this = this;
  14004. if (onLoad === void 0) { onLoad = null; }
  14005. if (onError === void 0) { onError = null; }
  14006. if (forcedExtension === void 0) { forcedExtension = null; }
  14007. var callback = function (loadData) {
  14008. if (!loadData) {
  14009. if (onLoad) {
  14010. onLoad(null);
  14011. }
  14012. return;
  14013. }
  14014. var texture = loadData.texture;
  14015. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  14016. texture._lodGenerationScale = scale;
  14017. texture._lodGenerationOffset = offset;
  14018. if (_this._caps.textureLOD) {
  14019. // Do not add extra process if texture lod is supported.
  14020. if (onLoad) {
  14021. onLoad(texture);
  14022. }
  14023. return;
  14024. }
  14025. var mipSlices = 3;
  14026. var gl = _this._gl;
  14027. var width = loadData.width;
  14028. if (!width) {
  14029. return;
  14030. }
  14031. var textures = [];
  14032. for (var i = 0; i < mipSlices; i++) {
  14033. //compute LOD from even spacing in smoothness (matching shader calculation)
  14034. var smoothness = i / (mipSlices - 1);
  14035. var roughness = 1 - smoothness;
  14036. var minLODIndex = offset; // roughness = 0
  14037. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  14038. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  14039. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  14040. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14041. glTextureFromLod.isCube = true;
  14042. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14043. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14044. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14045. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14046. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14047. if (loadData.isDDS) {
  14048. var info = loadData.info;
  14049. var data = loadData.data;
  14050. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14051. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14052. }
  14053. else {
  14054. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14055. }
  14056. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14057. // Wrap in a base texture for easy binding.
  14058. var lodTexture = new BABYLON.BaseTexture(scene);
  14059. lodTexture.isCube = true;
  14060. lodTexture._texture = glTextureFromLod;
  14061. glTextureFromLod.isReady = true;
  14062. textures.push(lodTexture);
  14063. }
  14064. texture._lodTextureHigh = textures[2];
  14065. texture._lodTextureMid = textures[1];
  14066. texture._lodTextureLow = textures[0];
  14067. if (onLoad) {
  14068. onLoad(texture);
  14069. }
  14070. };
  14071. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14072. };
  14073. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14074. var _this = this;
  14075. if (onLoad === void 0) { onLoad = null; }
  14076. if (onError === void 0) { onError = null; }
  14077. if (forcedExtension === void 0) { forcedExtension = null; }
  14078. var gl = this._gl;
  14079. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14080. texture.isCube = true;
  14081. texture.url = rootUrl;
  14082. texture.generateMipMaps = !noMipmap;
  14083. if (!this._doNotHandleContextLost) {
  14084. texture._extension = forcedExtension;
  14085. texture._files = files;
  14086. }
  14087. var isKTX = false;
  14088. var isDDS = false;
  14089. var lastDot = rootUrl.lastIndexOf('.');
  14090. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14091. if (this._textureFormatInUse) {
  14092. extension = this._textureFormatInUse;
  14093. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14094. isKTX = true;
  14095. }
  14096. else {
  14097. isDDS = (extension === ".dds");
  14098. }
  14099. var onerror = function (request, exception) {
  14100. if (onError && request) {
  14101. onError(request.status + " " + request.statusText, exception);
  14102. }
  14103. };
  14104. if (isKTX) {
  14105. this._loadFile(rootUrl, function (data) {
  14106. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14107. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14108. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14109. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14110. ktx.uploadLevels(_this._gl, !noMipmap);
  14111. _this.setCubeMapTextureParams(gl, loadMipmap);
  14112. texture.width = ktx.pixelWidth;
  14113. texture.height = ktx.pixelHeight;
  14114. texture.isReady = true;
  14115. }, undefined, undefined, true, onerror);
  14116. }
  14117. else if (isDDS) {
  14118. if (files && files.length === 6) {
  14119. this._cascadeLoadFiles(scene, function (imgs) {
  14120. var info;
  14121. var loadMipmap = false;
  14122. var width = 0;
  14123. for (var index = 0; index < imgs.length; index++) {
  14124. var data = imgs[index];
  14125. info = BABYLON.DDSTools.GetDDSInfo(data);
  14126. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14127. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14128. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14129. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14130. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14131. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14132. }
  14133. texture.width = info.width;
  14134. texture.height = info.height;
  14135. texture.type = info.textureType;
  14136. width = info.width;
  14137. }
  14138. _this.setCubeMapTextureParams(gl, loadMipmap);
  14139. texture.isReady = true;
  14140. if (onLoad) {
  14141. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14142. }
  14143. }, files, onError);
  14144. }
  14145. else {
  14146. this._loadFile(rootUrl, function (data) {
  14147. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14148. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14149. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14150. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14151. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14152. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14153. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14154. }
  14155. _this.setCubeMapTextureParams(gl, loadMipmap);
  14156. texture.width = info.width;
  14157. texture.height = info.height;
  14158. texture.isReady = true;
  14159. texture.type = info.textureType;
  14160. if (onLoad) {
  14161. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14162. }
  14163. }, undefined, undefined, true, onerror);
  14164. }
  14165. }
  14166. else {
  14167. if (!files) {
  14168. throw new Error("Cannot load cubemap because files were not defined");
  14169. }
  14170. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14171. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14172. var height = width;
  14173. _this._prepareWorkingCanvas();
  14174. if (!_this._workingCanvas || !_this._workingContext) {
  14175. return;
  14176. }
  14177. _this._workingCanvas.width = width;
  14178. _this._workingCanvas.height = height;
  14179. var faces = [
  14180. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14181. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14182. ];
  14183. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14184. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14185. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14186. for (var index = 0; index < faces.length; index++) {
  14187. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14188. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14189. }
  14190. if (!noMipmap) {
  14191. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14192. }
  14193. _this.setCubeMapTextureParams(gl, !noMipmap);
  14194. texture.width = width;
  14195. texture.height = height;
  14196. texture.isReady = true;
  14197. if (format) {
  14198. texture.format = format;
  14199. }
  14200. texture.onLoadedObservable.notifyObservers(texture);
  14201. texture.onLoadedObservable.clear();
  14202. if (onLoad) {
  14203. onLoad();
  14204. }
  14205. }, files, onError);
  14206. }
  14207. this._internalTexturesCache.push(texture);
  14208. return texture;
  14209. };
  14210. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14211. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14212. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14213. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14214. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14215. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14216. // this.resetTextureCache();
  14217. };
  14218. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14219. if (compression === void 0) { compression = null; }
  14220. if (level === void 0) { level = 0; }
  14221. texture._bufferViewArray = data;
  14222. texture.format = format;
  14223. texture.type = type;
  14224. texture.invertY = invertY;
  14225. texture._compression = compression;
  14226. var gl = this._gl;
  14227. var textureType = this._getWebGLTextureType(type);
  14228. var internalFormat = this._getInternalFormat(format);
  14229. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14230. var needConversion = false;
  14231. if (internalFormat === gl.RGB) {
  14232. internalFormat = gl.RGBA;
  14233. needConversion = true;
  14234. }
  14235. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14236. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14237. if (texture.width % 4 !== 0) {
  14238. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14239. }
  14240. // Data are known to be in +X +Y +Z -X -Y -Z
  14241. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14242. var faceData = data[faceIndex];
  14243. if (compression) {
  14244. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14245. }
  14246. else {
  14247. if (needConversion) {
  14248. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14249. }
  14250. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14251. }
  14252. }
  14253. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14254. if (isPot && texture.generateMipMaps && level === 0) {
  14255. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14256. }
  14257. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14258. // this.resetTextureCache();
  14259. texture.isReady = true;
  14260. };
  14261. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14262. if (compression === void 0) { compression = null; }
  14263. var gl = this._gl;
  14264. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14265. texture.isCube = true;
  14266. texture.generateMipMaps = generateMipMaps;
  14267. texture.format = format;
  14268. texture.type = type;
  14269. if (!this._doNotHandleContextLost) {
  14270. texture._bufferViewArray = data;
  14271. }
  14272. var textureType = this._getWebGLTextureType(type);
  14273. var internalFormat = this._getInternalFormat(format);
  14274. if (internalFormat === gl.RGB) {
  14275. internalFormat = gl.RGBA;
  14276. }
  14277. var width = size;
  14278. var height = width;
  14279. texture.width = width;
  14280. texture.height = height;
  14281. // Double check on POT to generate Mips.
  14282. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14283. if (!isPot) {
  14284. generateMipMaps = false;
  14285. }
  14286. // Upload data if needed. The texture won't be ready until then.
  14287. if (data) {
  14288. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14289. }
  14290. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14291. // Filters
  14292. if (data && generateMipMaps) {
  14293. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14294. }
  14295. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14296. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14297. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14298. }
  14299. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14300. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14301. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14302. }
  14303. else {
  14304. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14305. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14306. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14307. }
  14308. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14309. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14310. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14311. return texture;
  14312. };
  14313. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14314. var _this = this;
  14315. if (onLoad === void 0) { onLoad = null; }
  14316. if (onError === void 0) { onError = null; }
  14317. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14318. if (invertY === void 0) { invertY = false; }
  14319. var gl = this._gl;
  14320. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14321. scene._addPendingData(texture);
  14322. texture.url = url;
  14323. this._internalTexturesCache.push(texture);
  14324. var onerror = function (request, exception) {
  14325. scene._removePendingData(texture);
  14326. if (onError && request) {
  14327. onError(request.status + " " + request.statusText, exception);
  14328. }
  14329. };
  14330. var internalCallback = function (data) {
  14331. var width = texture.width;
  14332. var faceDataArrays = callback(data);
  14333. if (!faceDataArrays) {
  14334. return;
  14335. }
  14336. if (mipmmapGenerator) {
  14337. var textureType = _this._getWebGLTextureType(type);
  14338. var internalFormat = _this._getInternalFormat(format);
  14339. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14340. var needConversion = false;
  14341. if (internalFormat === gl.RGB) {
  14342. internalFormat = gl.RGBA;
  14343. needConversion = true;
  14344. }
  14345. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14346. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14347. var mipData = mipmmapGenerator(faceDataArrays);
  14348. for (var level = 0; level < mipData.length; level++) {
  14349. var mipSize = width >> level;
  14350. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14351. var mipFaceData = mipData[level][faceIndex];
  14352. if (needConversion) {
  14353. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14354. }
  14355. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14356. }
  14357. }
  14358. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14359. }
  14360. else {
  14361. texture.generateMipMaps = !noMipmap;
  14362. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14363. }
  14364. texture.isReady = true;
  14365. // this.resetTextureCache();
  14366. scene._removePendingData(texture);
  14367. if (onLoad) {
  14368. onLoad();
  14369. }
  14370. };
  14371. this._loadFile(url, function (data) {
  14372. internalCallback(data);
  14373. }, undefined, scene.database, true, onerror);
  14374. return texture;
  14375. };
  14376. ;
  14377. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14378. if (compression === void 0) { compression = null; }
  14379. var internalFormat = this._getInternalFormat(format);
  14380. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14381. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14382. if (!this._doNotHandleContextLost) {
  14383. texture._bufferView = data;
  14384. texture.format = format;
  14385. texture.invertY = invertY;
  14386. texture._compression = compression;
  14387. }
  14388. if (texture.width % 4 !== 0) {
  14389. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14390. }
  14391. if (compression && data) {
  14392. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14393. }
  14394. else {
  14395. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14396. }
  14397. if (texture.generateMipMaps) {
  14398. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14399. }
  14400. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14401. // this.resetTextureCache();
  14402. texture.isReady = true;
  14403. };
  14404. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14405. if (compression === void 0) { compression = null; }
  14406. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14407. texture.baseWidth = width;
  14408. texture.baseHeight = height;
  14409. texture.baseDepth = depth;
  14410. texture.width = width;
  14411. texture.height = height;
  14412. texture.depth = depth;
  14413. texture.format = format;
  14414. texture.generateMipMaps = generateMipMaps;
  14415. texture.samplingMode = samplingMode;
  14416. texture.is3D = true;
  14417. if (!this._doNotHandleContextLost) {
  14418. texture._bufferView = data;
  14419. }
  14420. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14421. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14422. // Filters
  14423. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14424. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14425. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14426. if (generateMipMaps) {
  14427. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14428. }
  14429. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14430. this._internalTexturesCache.push(texture);
  14431. return texture;
  14432. };
  14433. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14434. var gl = this._gl;
  14435. if (!gl) {
  14436. return;
  14437. }
  14438. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14439. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14440. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14441. if (!noMipmap && !isCompressed) {
  14442. gl.generateMipmap(gl.TEXTURE_2D);
  14443. }
  14444. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14445. // this.resetTextureCache();
  14446. if (scene) {
  14447. scene._removePendingData(texture);
  14448. }
  14449. texture.onLoadedObservable.notifyObservers(texture);
  14450. texture.onLoadedObservable.clear();
  14451. };
  14452. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14453. var _this = this;
  14454. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14455. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14456. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14457. var gl = this._gl;
  14458. if (!gl) {
  14459. return;
  14460. }
  14461. if (!texture._webGLTexture) {
  14462. // this.resetTextureCache();
  14463. if (scene) {
  14464. scene._removePendingData(texture);
  14465. }
  14466. return;
  14467. }
  14468. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14469. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14470. texture.baseWidth = width;
  14471. texture.baseHeight = height;
  14472. texture.width = potWidth;
  14473. texture.height = potHeight;
  14474. texture.isReady = true;
  14475. if (processFunction(potWidth, potHeight, function () {
  14476. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14477. })) {
  14478. // Returning as texture needs extra async steps
  14479. return;
  14480. }
  14481. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14482. };
  14483. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14484. // Create new RGBA data container.
  14485. var rgbaData;
  14486. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14487. rgbaData = new Float32Array(width * height * 4);
  14488. }
  14489. else {
  14490. rgbaData = new Uint32Array(width * height * 4);
  14491. }
  14492. // Convert each pixel.
  14493. for (var x = 0; x < width; x++) {
  14494. for (var y = 0; y < height; y++) {
  14495. var index = (y * width + x) * 3;
  14496. var newIndex = (y * width + x) * 4;
  14497. // Map Old Value to new value.
  14498. rgbaData[newIndex + 0] = rgbData[index + 0];
  14499. rgbaData[newIndex + 1] = rgbData[index + 1];
  14500. rgbaData[newIndex + 2] = rgbData[index + 2];
  14501. // Add fully opaque alpha channel.
  14502. rgbaData[newIndex + 3] = 1;
  14503. }
  14504. }
  14505. return rgbaData;
  14506. };
  14507. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14508. var gl = this._gl;
  14509. if (texture._framebuffer) {
  14510. gl.deleteFramebuffer(texture._framebuffer);
  14511. texture._framebuffer = null;
  14512. }
  14513. if (texture._depthStencilBuffer) {
  14514. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14515. texture._depthStencilBuffer = null;
  14516. }
  14517. if (texture._MSAAFramebuffer) {
  14518. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14519. texture._MSAAFramebuffer = null;
  14520. }
  14521. if (texture._MSAARenderBuffer) {
  14522. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14523. texture._MSAARenderBuffer = null;
  14524. }
  14525. };
  14526. Engine.prototype._releaseTexture = function (texture) {
  14527. var gl = this._gl;
  14528. this._releaseFramebufferObjects(texture);
  14529. gl.deleteTexture(texture._webGLTexture);
  14530. // Unbind channels
  14531. this.unbindAllTextures();
  14532. var index = this._internalTexturesCache.indexOf(texture);
  14533. if (index !== -1) {
  14534. this._internalTexturesCache.splice(index, 1);
  14535. }
  14536. // Integrated fixed lod samplers.
  14537. if (texture._lodTextureHigh) {
  14538. texture._lodTextureHigh.dispose();
  14539. }
  14540. if (texture._lodTextureMid) {
  14541. texture._lodTextureMid.dispose();
  14542. }
  14543. if (texture._lodTextureLow) {
  14544. texture._lodTextureLow.dispose();
  14545. }
  14546. // Set output texture of post process to null if the texture has been released/disposed
  14547. this.scenes.forEach(function (scene) {
  14548. scene.postProcesses.forEach(function (postProcess) {
  14549. if (postProcess._outputTexture == texture) {
  14550. postProcess._outputTexture = null;
  14551. }
  14552. });
  14553. scene.cameras.forEach(function (camera) {
  14554. camera._postProcesses.forEach(function (postProcess) {
  14555. if (postProcess) {
  14556. if (postProcess._outputTexture == texture) {
  14557. postProcess._outputTexture = null;
  14558. }
  14559. }
  14560. });
  14561. });
  14562. });
  14563. };
  14564. Engine.prototype.setProgram = function (program) {
  14565. if (this._currentProgram !== program) {
  14566. this._gl.useProgram(program);
  14567. this._currentProgram = program;
  14568. }
  14569. };
  14570. Engine.prototype.bindSamplers = function (effect) {
  14571. this.setProgram(effect.getProgram());
  14572. var samplers = effect.getSamplers();
  14573. for (var index = 0; index < samplers.length; index++) {
  14574. var uniform = effect.getUniform(samplers[index]);
  14575. if (uniform) {
  14576. this._boundUniforms[index] = uniform;
  14577. }
  14578. }
  14579. this._currentEffect = null;
  14580. };
  14581. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14582. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14583. return;
  14584. }
  14585. // Remove
  14586. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14587. // Bind last to it
  14588. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14589. // Bind to dummy
  14590. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14591. };
  14592. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14593. if (!internalTexture) {
  14594. return -1;
  14595. }
  14596. internalTexture._initialSlot = channel;
  14597. if (this.disableTextureBindingOptimization) {
  14598. if (channel !== internalTexture._designatedSlot) {
  14599. this._textureCollisions.addCount(1, false);
  14600. }
  14601. }
  14602. else {
  14603. if (channel !== internalTexture._designatedSlot) {
  14604. if (internalTexture._designatedSlot > -1) {
  14605. return internalTexture._designatedSlot;
  14606. }
  14607. else {
  14608. // No slot for this texture, let's pick a new one (if we find a free slot)
  14609. if (this._nextFreeTextureSlots.length) {
  14610. return this._nextFreeTextureSlots[0];
  14611. }
  14612. // We need to recycle the oldest bound texture, sorry.
  14613. this._textureCollisions.addCount(1, false);
  14614. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14615. }
  14616. }
  14617. }
  14618. return channel;
  14619. };
  14620. Engine.prototype._linkTrackers = function (previous, next) {
  14621. previous.next = next;
  14622. next.previous = previous;
  14623. };
  14624. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14625. var currentSlot = internalTexture._designatedSlot;
  14626. if (currentSlot === -1) {
  14627. return -1;
  14628. }
  14629. internalTexture._designatedSlot = -1;
  14630. if (this.disableTextureBindingOptimization) {
  14631. return -1;
  14632. }
  14633. // Remove from bound list
  14634. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14635. // Free the slot
  14636. this._boundTexturesCache[currentSlot] = null;
  14637. this._nextFreeTextureSlots.push(currentSlot);
  14638. return currentSlot;
  14639. };
  14640. Engine.prototype._activateCurrentTexture = function () {
  14641. if (this._currentTextureChannel !== this._activeChannel) {
  14642. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14643. this._currentTextureChannel = this._activeChannel;
  14644. }
  14645. };
  14646. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14647. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14648. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14649. this._activeChannel = texture._designatedSlot;
  14650. }
  14651. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14652. var isTextureForRendering = texture && texture._initialSlot > -1;
  14653. if (currentTextureBound !== texture) {
  14654. if (currentTextureBound) {
  14655. this._removeDesignatedSlot(currentTextureBound);
  14656. }
  14657. this._activateCurrentTexture();
  14658. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14659. this._boundTexturesCache[this._activeChannel] = texture;
  14660. if (texture) {
  14661. if (!this.disableTextureBindingOptimization) {
  14662. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14663. if (slotIndex > -1) {
  14664. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14665. }
  14666. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14667. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14668. }
  14669. texture._designatedSlot = this._activeChannel;
  14670. }
  14671. }
  14672. else if (forTextureDataUpdate) {
  14673. this._activateCurrentTexture();
  14674. }
  14675. if (isTextureForRendering && !forTextureDataUpdate) {
  14676. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14677. }
  14678. };
  14679. Engine.prototype._bindTexture = function (channel, texture) {
  14680. if (channel < 0) {
  14681. return;
  14682. }
  14683. if (texture) {
  14684. channel = this._getCorrectTextureChannel(channel, texture);
  14685. }
  14686. this._activeChannel = channel;
  14687. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14688. };
  14689. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14690. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14691. };
  14692. /**
  14693. * Binds the output of the passed in post process to the texture channel specified
  14694. * @param channel The channel the texture should be bound to
  14695. * @param postProcess The post process which's output should be bound
  14696. */
  14697. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14698. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14699. };
  14700. Engine.prototype.unbindAllTextures = function () {
  14701. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14702. this._activeChannel = channel;
  14703. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14704. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14705. if (this.webGLVersion > 1) {
  14706. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14707. }
  14708. }
  14709. };
  14710. /**
  14711. * Sets a texture to the according uniform.
  14712. * @param channel The texture channel
  14713. * @param uniform The uniform to set
  14714. * @param texture The texture to apply
  14715. */
  14716. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14717. if (channel < 0) {
  14718. return;
  14719. }
  14720. if (uniform) {
  14721. this._boundUniforms[channel] = uniform;
  14722. }
  14723. this._setTexture(channel, texture);
  14724. };
  14725. /**
  14726. * Sets a depth stencil texture from a render target to the according uniform.
  14727. * @param channel The texture channel
  14728. * @param uniform The uniform to set
  14729. * @param texture The render target texture containing the depth stencil texture to apply
  14730. */
  14731. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14732. if (channel < 0) {
  14733. return;
  14734. }
  14735. if (uniform) {
  14736. this._boundUniforms[channel] = uniform;
  14737. }
  14738. if (!texture || !texture.depthStencilTexture) {
  14739. this._setTexture(channel, null);
  14740. }
  14741. else {
  14742. this._setTexture(channel, texture, false, true);
  14743. }
  14744. };
  14745. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14746. var uniform = this._boundUniforms[sourceSlot];
  14747. if (uniform._currentState === destination) {
  14748. return;
  14749. }
  14750. this._gl.uniform1i(uniform, destination);
  14751. uniform._currentState = destination;
  14752. };
  14753. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14754. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14755. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14756. // Not ready?
  14757. if (!texture) {
  14758. if (this._boundTexturesCache[channel] != null) {
  14759. this._activeChannel = channel;
  14760. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14761. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14762. if (this.webGLVersion > 1) {
  14763. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14764. }
  14765. }
  14766. return false;
  14767. }
  14768. // Video
  14769. if (texture.video) {
  14770. this._activeChannel = channel;
  14771. texture.update();
  14772. }
  14773. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14774. texture.delayLoad();
  14775. return false;
  14776. }
  14777. var internalTexture;
  14778. if (depthStencilTexture) {
  14779. internalTexture = texture.depthStencilTexture;
  14780. }
  14781. else if (texture.isReady()) {
  14782. internalTexture = texture.getInternalTexture();
  14783. }
  14784. else if (texture.isCube) {
  14785. internalTexture = this.emptyCubeTexture;
  14786. }
  14787. else if (texture.is3D) {
  14788. internalTexture = this.emptyTexture3D;
  14789. }
  14790. else {
  14791. internalTexture = this.emptyTexture;
  14792. }
  14793. if (!isPartOfTextureArray) {
  14794. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14795. }
  14796. if (this._boundTexturesCache[channel] === internalTexture) {
  14797. this._moveBoundTextureOnTop(internalTexture);
  14798. if (!isPartOfTextureArray) {
  14799. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14800. }
  14801. return false;
  14802. }
  14803. this._activeChannel = channel;
  14804. if (internalTexture && internalTexture.is3D) {
  14805. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14806. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14807. internalTexture._cachedWrapU = texture.wrapU;
  14808. switch (texture.wrapU) {
  14809. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14810. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14811. break;
  14812. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14813. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14814. break;
  14815. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14816. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14817. break;
  14818. }
  14819. }
  14820. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14821. internalTexture._cachedWrapV = texture.wrapV;
  14822. switch (texture.wrapV) {
  14823. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14824. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14825. break;
  14826. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14827. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14828. break;
  14829. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14830. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14831. break;
  14832. }
  14833. }
  14834. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14835. internalTexture._cachedWrapR = texture.wrapR;
  14836. switch (texture.wrapR) {
  14837. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14838. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14839. break;
  14840. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14841. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14842. break;
  14843. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14844. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14845. break;
  14846. }
  14847. }
  14848. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14849. }
  14850. else if (internalTexture && internalTexture.isCube) {
  14851. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14852. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14853. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14854. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14855. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14856. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14857. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14858. }
  14859. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14860. }
  14861. else {
  14862. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14863. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14864. internalTexture._cachedWrapU = texture.wrapU;
  14865. switch (texture.wrapU) {
  14866. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14867. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14868. break;
  14869. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14870. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14871. break;
  14872. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14873. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14874. break;
  14875. }
  14876. }
  14877. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14878. internalTexture._cachedWrapV = texture.wrapV;
  14879. switch (texture.wrapV) {
  14880. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14881. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14882. break;
  14883. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14884. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14885. break;
  14886. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14887. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14888. break;
  14889. }
  14890. }
  14891. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14892. }
  14893. return true;
  14894. };
  14895. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14896. if (channel < 0 || !uniform) {
  14897. return;
  14898. }
  14899. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14900. this._textureUnits = new Int32Array(textures.length);
  14901. }
  14902. for (var i = 0; i < textures.length; i++) {
  14903. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14904. }
  14905. this._gl.uniform1iv(uniform, this._textureUnits);
  14906. for (var index = 0; index < textures.length; index++) {
  14907. this._setTexture(this._textureUnits[index], textures[index], true);
  14908. }
  14909. };
  14910. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14911. var internalTexture = texture.getInternalTexture();
  14912. if (!internalTexture) {
  14913. return;
  14914. }
  14915. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14916. var value = texture.anisotropicFilteringLevel;
  14917. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14918. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14919. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14920. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14921. }
  14922. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14923. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14924. internalTexture._cachedAnisotropicFilteringLevel = value;
  14925. }
  14926. };
  14927. Engine.prototype.readPixels = function (x, y, width, height) {
  14928. var data = new Uint8Array(height * width * 4);
  14929. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14930. return data;
  14931. };
  14932. /**
  14933. * Add an externaly attached data from its key.
  14934. * This method call will fail and return false, if such key already exists.
  14935. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14936. * @param key the unique key that identifies the data
  14937. * @param data the data object to associate to the key for this Engine instance
  14938. * @return true if no such key were already present and the data was added successfully, false otherwise
  14939. */
  14940. Engine.prototype.addExternalData = function (key, data) {
  14941. if (!this._externalData) {
  14942. this._externalData = new BABYLON.StringDictionary();
  14943. }
  14944. return this._externalData.add(key, data);
  14945. };
  14946. /**
  14947. * Get an externaly attached data from its key
  14948. * @param key the unique key that identifies the data
  14949. * @return the associated data, if present (can be null), or undefined if not present
  14950. */
  14951. Engine.prototype.getExternalData = function (key) {
  14952. if (!this._externalData) {
  14953. this._externalData = new BABYLON.StringDictionary();
  14954. }
  14955. return this._externalData.get(key);
  14956. };
  14957. /**
  14958. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14959. * @param key the unique key that identifies the data
  14960. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14961. * @return the associated data, can be null if the factory returned null.
  14962. */
  14963. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14964. if (!this._externalData) {
  14965. this._externalData = new BABYLON.StringDictionary();
  14966. }
  14967. return this._externalData.getOrAddWithFactory(key, factory);
  14968. };
  14969. /**
  14970. * Remove an externaly attached data from the Engine instance
  14971. * @param key the unique key that identifies the data
  14972. * @return true if the data was successfully removed, false if it doesn't exist
  14973. */
  14974. Engine.prototype.removeExternalData = function (key) {
  14975. if (!this._externalData) {
  14976. this._externalData = new BABYLON.StringDictionary();
  14977. }
  14978. return this._externalData.remove(key);
  14979. };
  14980. Engine.prototype.unbindAllAttributes = function () {
  14981. if (this._mustWipeVertexAttributes) {
  14982. this._mustWipeVertexAttributes = false;
  14983. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14984. this._gl.disableVertexAttribArray(i);
  14985. this._vertexAttribArraysEnabled[i] = false;
  14986. this._currentBufferPointers[i].active = false;
  14987. }
  14988. return;
  14989. }
  14990. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14991. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14992. continue;
  14993. }
  14994. this._gl.disableVertexAttribArray(i);
  14995. this._vertexAttribArraysEnabled[i] = false;
  14996. this._currentBufferPointers[i].active = false;
  14997. }
  14998. };
  14999. Engine.prototype.releaseEffects = function () {
  15000. for (var name in this._compiledEffects) {
  15001. this._deleteProgram(this._compiledEffects[name]._program);
  15002. }
  15003. this._compiledEffects = {};
  15004. };
  15005. // Dispose
  15006. Engine.prototype.dispose = function () {
  15007. this.hideLoadingUI();
  15008. this.stopRenderLoop();
  15009. // Release postProcesses
  15010. while (this.postProcesses.length) {
  15011. this.postProcesses[0].dispose();
  15012. }
  15013. // Empty texture
  15014. if (this._emptyTexture) {
  15015. this._releaseTexture(this._emptyTexture);
  15016. this._emptyTexture = null;
  15017. }
  15018. if (this._emptyCubeTexture) {
  15019. this._releaseTexture(this._emptyCubeTexture);
  15020. this._emptyCubeTexture = null;
  15021. }
  15022. // Rescale PP
  15023. if (this._rescalePostProcess) {
  15024. this._rescalePostProcess.dispose();
  15025. }
  15026. // Release scenes
  15027. while (this.scenes.length) {
  15028. this.scenes[0].dispose();
  15029. }
  15030. // Release audio engine
  15031. if (Engine.audioEngine) {
  15032. Engine.audioEngine.dispose();
  15033. }
  15034. // Release effects
  15035. this.releaseEffects();
  15036. // Unbind
  15037. this.unbindAllAttributes();
  15038. if (this._dummyFramebuffer) {
  15039. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  15040. }
  15041. //WebVR
  15042. this.disableVR();
  15043. // Events
  15044. if (BABYLON.Tools.IsWindowObjectExist()) {
  15045. window.removeEventListener("blur", this._onBlur);
  15046. window.removeEventListener("focus", this._onFocus);
  15047. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15048. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15049. if (this._renderingCanvas) {
  15050. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15051. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15052. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15053. if (!this._doNotHandleContextLost) {
  15054. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15055. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15056. }
  15057. }
  15058. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15059. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15060. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15061. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15062. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15063. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15064. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15065. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15066. if (this._onVrDisplayConnect) {
  15067. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15068. if (this._onVrDisplayDisconnect) {
  15069. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15070. }
  15071. if (this._onVrDisplayPresentChange) {
  15072. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15073. }
  15074. this._onVrDisplayConnect = null;
  15075. this._onVrDisplayDisconnect = null;
  15076. }
  15077. }
  15078. // Remove from Instances
  15079. var index = Engine.Instances.indexOf(this);
  15080. if (index >= 0) {
  15081. Engine.Instances.splice(index, 1);
  15082. }
  15083. this._workingCanvas = null;
  15084. this._workingContext = null;
  15085. this._currentBufferPointers = [];
  15086. this._renderingCanvas = null;
  15087. this._currentProgram = null;
  15088. this._bindedRenderFunction = null;
  15089. this.onResizeObservable.clear();
  15090. this.onCanvasBlurObservable.clear();
  15091. this.onCanvasFocusObservable.clear();
  15092. this.onCanvasPointerOutObservable.clear();
  15093. this.onBeginFrameObservable.clear();
  15094. this.onEndFrameObservable.clear();
  15095. BABYLON.Effect.ResetCache();
  15096. // Abort active requests
  15097. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15098. var request = _a[_i];
  15099. request.abort();
  15100. }
  15101. };
  15102. // Loading screen
  15103. Engine.prototype.displayLoadingUI = function () {
  15104. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15105. return;
  15106. }
  15107. var loadingScreen = this.loadingScreen;
  15108. if (loadingScreen) {
  15109. loadingScreen.displayLoadingUI();
  15110. }
  15111. };
  15112. Engine.prototype.hideLoadingUI = function () {
  15113. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15114. return;
  15115. }
  15116. var loadingScreen = this.loadingScreen;
  15117. if (loadingScreen) {
  15118. loadingScreen.hideLoadingUI();
  15119. }
  15120. };
  15121. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15122. get: function () {
  15123. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15124. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15125. return this._loadingScreen;
  15126. },
  15127. set: function (loadingScreen) {
  15128. this._loadingScreen = loadingScreen;
  15129. },
  15130. enumerable: true,
  15131. configurable: true
  15132. });
  15133. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15134. set: function (text) {
  15135. this.loadingScreen.loadingUIText = text;
  15136. },
  15137. enumerable: true,
  15138. configurable: true
  15139. });
  15140. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15141. set: function (color) {
  15142. this.loadingScreen.loadingUIBackgroundColor = color;
  15143. },
  15144. enumerable: true,
  15145. configurable: true
  15146. });
  15147. Engine.prototype.attachContextLostEvent = function (callback) {
  15148. if (this._renderingCanvas) {
  15149. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15150. }
  15151. };
  15152. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15153. if (this._renderingCanvas) {
  15154. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15155. }
  15156. };
  15157. Engine.prototype.getVertexShaderSource = function (program) {
  15158. var shaders = this._gl.getAttachedShaders(program);
  15159. if (!shaders) {
  15160. return null;
  15161. }
  15162. return this._gl.getShaderSource(shaders[0]);
  15163. };
  15164. Engine.prototype.getFragmentShaderSource = function (program) {
  15165. var shaders = this._gl.getAttachedShaders(program);
  15166. if (!shaders) {
  15167. return null;
  15168. }
  15169. return this._gl.getShaderSource(shaders[1]);
  15170. };
  15171. Engine.prototype.getError = function () {
  15172. return this._gl.getError();
  15173. };
  15174. // FPS
  15175. Engine.prototype.getFps = function () {
  15176. return this._fps;
  15177. };
  15178. Engine.prototype.getDeltaTime = function () {
  15179. return this._deltaTime;
  15180. };
  15181. Engine.prototype._measureFps = function () {
  15182. this._performanceMonitor.sampleFrame();
  15183. this._fps = this._performanceMonitor.averageFPS;
  15184. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15185. };
  15186. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15187. if (faceIndex === void 0) { faceIndex = -1; }
  15188. var gl = this._gl;
  15189. if (!this._dummyFramebuffer) {
  15190. var dummy = gl.createFramebuffer();
  15191. if (!dummy) {
  15192. throw new Error("Unable to create dummy framebuffer");
  15193. }
  15194. this._dummyFramebuffer = dummy;
  15195. }
  15196. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15197. if (faceIndex > -1) {
  15198. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15199. }
  15200. else {
  15201. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15202. }
  15203. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15204. var buffer;
  15205. switch (readType) {
  15206. case gl.UNSIGNED_BYTE:
  15207. buffer = new Uint8Array(4 * width * height);
  15208. readType = gl.UNSIGNED_BYTE;
  15209. break;
  15210. default:
  15211. buffer = new Float32Array(4 * width * height);
  15212. readType = gl.FLOAT;
  15213. break;
  15214. }
  15215. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15216. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15217. return buffer;
  15218. };
  15219. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15220. if (this._webGLVersion > 1) {
  15221. return this._caps.colorBufferFloat;
  15222. }
  15223. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15224. };
  15225. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15226. if (this._webGLVersion > 1) {
  15227. return this._caps.colorBufferFloat;
  15228. }
  15229. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15230. };
  15231. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15232. Engine.prototype._canRenderToFramebuffer = function (type) {
  15233. var gl = this._gl;
  15234. //clear existing errors
  15235. while (gl.getError() !== gl.NO_ERROR) { }
  15236. var successful = true;
  15237. var texture = gl.createTexture();
  15238. gl.bindTexture(gl.TEXTURE_2D, texture);
  15239. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15240. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15241. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15242. var fb = gl.createFramebuffer();
  15243. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15244. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15245. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15246. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15247. successful = successful && (gl.getError() === gl.NO_ERROR);
  15248. //try render by clearing frame buffer's color buffer
  15249. if (successful) {
  15250. gl.clear(gl.COLOR_BUFFER_BIT);
  15251. successful = successful && (gl.getError() === gl.NO_ERROR);
  15252. }
  15253. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15254. if (successful) {
  15255. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15256. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15257. var readFormat = gl.RGBA;
  15258. var readType = gl.UNSIGNED_BYTE;
  15259. var buffer = new Uint8Array(4);
  15260. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15261. successful = successful && (gl.getError() === gl.NO_ERROR);
  15262. }
  15263. //clean up
  15264. gl.deleteTexture(texture);
  15265. gl.deleteFramebuffer(fb);
  15266. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15267. //clear accumulated errors
  15268. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15269. return successful;
  15270. };
  15271. Engine.prototype._getWebGLTextureType = function (type) {
  15272. if (type === Engine.TEXTURETYPE_FLOAT) {
  15273. return this._gl.FLOAT;
  15274. }
  15275. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15276. // Add Half Float Constant.
  15277. return this._gl.HALF_FLOAT_OES;
  15278. }
  15279. return this._gl.UNSIGNED_BYTE;
  15280. };
  15281. ;
  15282. Engine.prototype._getInternalFormat = function (format) {
  15283. var internalFormat = this._gl.RGBA;
  15284. switch (format) {
  15285. case Engine.TEXTUREFORMAT_ALPHA:
  15286. internalFormat = this._gl.ALPHA;
  15287. break;
  15288. case Engine.TEXTUREFORMAT_LUMINANCE:
  15289. internalFormat = this._gl.LUMINANCE;
  15290. break;
  15291. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15292. internalFormat = this._gl.LUMINANCE_ALPHA;
  15293. break;
  15294. case Engine.TEXTUREFORMAT_RGB:
  15295. case Engine.TEXTUREFORMAT_RGB32F:
  15296. internalFormat = this._gl.RGB;
  15297. break;
  15298. case Engine.TEXTUREFORMAT_RGBA:
  15299. case Engine.TEXTUREFORMAT_RGBA32F:
  15300. internalFormat = this._gl.RGBA;
  15301. break;
  15302. case Engine.TEXTUREFORMAT_R32F:
  15303. internalFormat = this._gl.RED;
  15304. break;
  15305. case Engine.TEXTUREFORMAT_RG32F:
  15306. internalFormat = this._gl.RG;
  15307. break;
  15308. }
  15309. return internalFormat;
  15310. };
  15311. /** @ignore */
  15312. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15313. if (this._webGLVersion === 1) {
  15314. if (format) {
  15315. switch (format) {
  15316. case Engine.TEXTUREFORMAT_LUMINANCE:
  15317. return this._gl.LUMINANCE;
  15318. }
  15319. }
  15320. return this._gl.RGBA;
  15321. }
  15322. if (type === Engine.TEXTURETYPE_FLOAT) {
  15323. if (format) {
  15324. switch (format) {
  15325. case Engine.TEXTUREFORMAT_R32F:
  15326. return this._gl.R32F;
  15327. case Engine.TEXTUREFORMAT_RG32F:
  15328. return this._gl.RG32F;
  15329. case Engine.TEXTUREFORMAT_RGB32F:
  15330. return this._gl.RGB32F;
  15331. }
  15332. }
  15333. return this._gl.RGBA32F;
  15334. }
  15335. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15336. return this._gl.RGBA16F;
  15337. }
  15338. if (format) {
  15339. switch (format) {
  15340. case Engine.TEXTUREFORMAT_LUMINANCE:
  15341. return this._gl.LUMINANCE;
  15342. }
  15343. }
  15344. return this._gl.RGBA;
  15345. };
  15346. ;
  15347. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15348. if (type === Engine.TEXTURETYPE_FLOAT) {
  15349. return this._gl.RGBA32F;
  15350. }
  15351. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15352. return this._gl.RGBA16F;
  15353. }
  15354. return this._gl.RGBA8;
  15355. };
  15356. ;
  15357. Engine.prototype.createQuery = function () {
  15358. return this._gl.createQuery();
  15359. };
  15360. Engine.prototype.deleteQuery = function (query) {
  15361. this._gl.deleteQuery(query);
  15362. return this;
  15363. };
  15364. Engine.prototype.isQueryResultAvailable = function (query) {
  15365. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15366. };
  15367. Engine.prototype.getQueryResult = function (query) {
  15368. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15369. };
  15370. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15371. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15372. this._gl.beginQuery(glAlgorithm, query);
  15373. return this;
  15374. };
  15375. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15376. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15377. this._gl.endQuery(glAlgorithm);
  15378. return this;
  15379. };
  15380. /* Time queries */
  15381. Engine.prototype._createTimeQuery = function () {
  15382. var timerQuery = this._caps.timerQuery;
  15383. if (timerQuery.createQueryEXT) {
  15384. return timerQuery.createQueryEXT();
  15385. }
  15386. return this.createQuery();
  15387. };
  15388. Engine.prototype._deleteTimeQuery = function (query) {
  15389. var timerQuery = this._caps.timerQuery;
  15390. if (timerQuery.deleteQueryEXT) {
  15391. timerQuery.deleteQueryEXT(query);
  15392. return;
  15393. }
  15394. this.deleteQuery(query);
  15395. };
  15396. Engine.prototype._getTimeQueryResult = function (query) {
  15397. var timerQuery = this._caps.timerQuery;
  15398. if (timerQuery.getQueryObjectEXT) {
  15399. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15400. }
  15401. return this.getQueryResult(query);
  15402. };
  15403. Engine.prototype._getTimeQueryAvailability = function (query) {
  15404. var timerQuery = this._caps.timerQuery;
  15405. if (timerQuery.getQueryObjectEXT) {
  15406. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15407. }
  15408. return this.isQueryResultAvailable(query);
  15409. };
  15410. Engine.prototype.startTimeQuery = function () {
  15411. var timerQuery = this._caps.timerQuery;
  15412. if (!timerQuery) {
  15413. return null;
  15414. }
  15415. var token = new BABYLON._TimeToken();
  15416. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15417. if (this._caps.canUseTimestampForTimerQuery) {
  15418. token._startTimeQuery = this._createTimeQuery();
  15419. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15420. }
  15421. else {
  15422. if (this._currentNonTimestampToken) {
  15423. return this._currentNonTimestampToken;
  15424. }
  15425. token._timeElapsedQuery = this._createTimeQuery();
  15426. if (timerQuery.beginQueryEXT) {
  15427. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15428. }
  15429. else {
  15430. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15431. }
  15432. this._currentNonTimestampToken = token;
  15433. }
  15434. return token;
  15435. };
  15436. Engine.prototype.endTimeQuery = function (token) {
  15437. var timerQuery = this._caps.timerQuery;
  15438. if (!timerQuery || !token) {
  15439. return -1;
  15440. }
  15441. if (this._caps.canUseTimestampForTimerQuery) {
  15442. if (!token._startTimeQuery) {
  15443. return -1;
  15444. }
  15445. if (!token._endTimeQuery) {
  15446. token._endTimeQuery = this._createTimeQuery();
  15447. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15448. }
  15449. }
  15450. else if (!token._timeElapsedQueryEnded) {
  15451. if (!token._timeElapsedQuery) {
  15452. return -1;
  15453. }
  15454. if (timerQuery.endQueryEXT) {
  15455. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15456. }
  15457. else {
  15458. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15459. }
  15460. token._timeElapsedQueryEnded = true;
  15461. }
  15462. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15463. var available = false;
  15464. if (token._endTimeQuery) {
  15465. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15466. }
  15467. else if (token._timeElapsedQuery) {
  15468. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15469. }
  15470. if (available && !disjoint) {
  15471. var result = 0;
  15472. if (this._caps.canUseTimestampForTimerQuery) {
  15473. if (!token._startTimeQuery || !token._endTimeQuery) {
  15474. return -1;
  15475. }
  15476. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15477. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15478. result = timeEnd - timeStart;
  15479. this._deleteTimeQuery(token._startTimeQuery);
  15480. this._deleteTimeQuery(token._endTimeQuery);
  15481. token._startTimeQuery = null;
  15482. token._endTimeQuery = null;
  15483. }
  15484. else {
  15485. if (!token._timeElapsedQuery) {
  15486. return -1;
  15487. }
  15488. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15489. this._deleteTimeQuery(token._timeElapsedQuery);
  15490. token._timeElapsedQuery = null;
  15491. token._timeElapsedQueryEnded = false;
  15492. this._currentNonTimestampToken = null;
  15493. }
  15494. return result;
  15495. }
  15496. return -1;
  15497. };
  15498. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15499. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15500. };
  15501. // Transform feedback
  15502. Engine.prototype.createTransformFeedback = function () {
  15503. return this._gl.createTransformFeedback();
  15504. };
  15505. Engine.prototype.deleteTransformFeedback = function (value) {
  15506. this._gl.deleteTransformFeedback(value);
  15507. };
  15508. Engine.prototype.bindTransformFeedback = function (value) {
  15509. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15510. };
  15511. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15512. if (usePoints === void 0) { usePoints = true; }
  15513. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15514. };
  15515. Engine.prototype.endTransformFeedback = function () {
  15516. this._gl.endTransformFeedback();
  15517. };
  15518. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15519. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15520. };
  15521. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15522. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15523. };
  15524. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15525. var _this = this;
  15526. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15527. this._activeRequests.push(request);
  15528. request.onCompleteObservable.add(function (request) {
  15529. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15530. });
  15531. return request;
  15532. };
  15533. /** @ignore */
  15534. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15535. var _this = this;
  15536. return new Promise(function (resolve, reject) {
  15537. _this._loadFile(url, function (data) {
  15538. resolve(data);
  15539. }, undefined, database, useArrayBuffer, function (request, exception) {
  15540. reject(exception);
  15541. });
  15542. });
  15543. };
  15544. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15545. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15546. var onload = function (data) {
  15547. loadedFiles[index] = data;
  15548. loadedFiles._internalCount++;
  15549. if (loadedFiles._internalCount === 6) {
  15550. onfinish(loadedFiles);
  15551. }
  15552. };
  15553. var onerror = function (request, exception) {
  15554. if (onErrorCallBack && request) {
  15555. onErrorCallBack(request.status + " " + request.statusText, exception);
  15556. }
  15557. };
  15558. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15559. };
  15560. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15561. if (onError === void 0) { onError = null; }
  15562. var loadedFiles = [];
  15563. loadedFiles._internalCount = 0;
  15564. for (var index = 0; index < 6; index++) {
  15565. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15566. }
  15567. };
  15568. // Statics
  15569. Engine.isSupported = function () {
  15570. try {
  15571. var tempcanvas = document.createElement("canvas");
  15572. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15573. return gl != null && !!window.WebGLRenderingContext;
  15574. }
  15575. catch (e) {
  15576. return false;
  15577. }
  15578. };
  15579. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15580. Engine.ExceptionList = [
  15581. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15582. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15583. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15584. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15585. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15586. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15587. ];
  15588. Engine.Instances = new Array();
  15589. // Const statics
  15590. Engine._ALPHA_DISABLE = 0;
  15591. Engine._ALPHA_ADD = 1;
  15592. Engine._ALPHA_COMBINE = 2;
  15593. Engine._ALPHA_SUBTRACT = 3;
  15594. Engine._ALPHA_MULTIPLY = 4;
  15595. Engine._ALPHA_MAXIMIZED = 5;
  15596. Engine._ALPHA_ONEONE = 6;
  15597. Engine._ALPHA_PREMULTIPLIED = 7;
  15598. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15599. Engine._ALPHA_INTERPOLATE = 9;
  15600. Engine._ALPHA_SCREENMODE = 10;
  15601. Engine._DELAYLOADSTATE_NONE = 0;
  15602. Engine._DELAYLOADSTATE_LOADED = 1;
  15603. Engine._DELAYLOADSTATE_LOADING = 2;
  15604. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15605. Engine._TEXTUREFORMAT_ALPHA = 0;
  15606. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15607. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15608. Engine._TEXTUREFORMAT_RGB = 4;
  15609. Engine._TEXTUREFORMAT_RGBA = 5;
  15610. Engine._TEXTUREFORMAT_R32F = 6;
  15611. Engine._TEXTUREFORMAT_RG32F = 7;
  15612. Engine._TEXTUREFORMAT_RGB32F = 8;
  15613. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15614. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15615. Engine._TEXTURETYPE_FLOAT = 1;
  15616. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15617. // Depht or Stencil test Constants.
  15618. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15619. 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.
  15620. 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.
  15621. 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.
  15622. 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.
  15623. 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.
  15624. 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.
  15625. 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.
  15626. // Stencil Actions Constants.
  15627. Engine._KEEP = 0x1E00;
  15628. Engine._REPLACE = 0x1E01;
  15629. Engine._INCR = 0x1E02;
  15630. Engine._DECR = 0x1E03;
  15631. Engine._INVERT = 0x150A;
  15632. Engine._INCR_WRAP = 0x8507;
  15633. Engine._DECR_WRAP = 0x8508;
  15634. // Texture rescaling mode
  15635. Engine._SCALEMODE_FLOOR = 1;
  15636. Engine._SCALEMODE_NEAREST = 2;
  15637. Engine._SCALEMODE_CEILING = 3;
  15638. // Updatable statics so stick with vars here
  15639. Engine.CollisionsEpsilon = 0.001;
  15640. Engine.CodeRepository = "src/";
  15641. Engine.ShadersRepository = "src/Shaders/";
  15642. return Engine;
  15643. }());
  15644. BABYLON.Engine = Engine;
  15645. })(BABYLON || (BABYLON = {}));
  15646. //# sourceMappingURL=babylon.engine.js.map
  15647. "use strict";
  15648. var BABYLON;
  15649. (function (BABYLON) {
  15650. /**
  15651. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15652. */
  15653. var Node = /** @class */ (function () {
  15654. /**
  15655. * Creates a new Node
  15656. * @param {string} name - the name and id to be given to this node
  15657. * @param {BABYLON.Scene} the scene this node will be added to
  15658. */
  15659. function Node(name, scene) {
  15660. if (scene === void 0) { scene = null; }
  15661. /**
  15662. * Gets or sets a string used to store user defined state for the node
  15663. */
  15664. this.state = "";
  15665. /**
  15666. * Gets or sets an object used to store user defined information for the node
  15667. */
  15668. this.metadata = null;
  15669. /**
  15670. * Gets or sets a boolean used to define if the node must be serialized
  15671. */
  15672. this.doNotSerialize = false;
  15673. /** @ignore */
  15674. this._isDisposed = false;
  15675. /**
  15676. * Gets a list of {BABYLON.Animation} associated with the node
  15677. */
  15678. this.animations = new Array();
  15679. this._ranges = {};
  15680. this._isEnabled = true;
  15681. this._isReady = true;
  15682. /** @ignore */
  15683. this._currentRenderId = -1;
  15684. this._parentRenderId = -1;
  15685. this._animationPropertiesOverride = null;
  15686. /**
  15687. * An event triggered when the mesh is disposed
  15688. * @type {BABYLON.Observable}
  15689. */
  15690. this.onDisposeObservable = new BABYLON.Observable();
  15691. // Behaviors
  15692. this._behaviors = new Array();
  15693. this.name = name;
  15694. this.id = name;
  15695. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15696. this.uniqueId = this._scene.getUniqueId();
  15697. this._initCache();
  15698. }
  15699. /**
  15700. * Gets a boolean indicating if the node has been disposed
  15701. * @returns true if the node was disposed
  15702. */
  15703. Node.prototype.isDisposed = function () {
  15704. return this._isDisposed;
  15705. };
  15706. Object.defineProperty(Node.prototype, "parent", {
  15707. get: function () {
  15708. return this._parentNode;
  15709. },
  15710. /**
  15711. * Gets or sets the parent of the node
  15712. */
  15713. set: function (parent) {
  15714. if (this._parentNode === parent) {
  15715. return;
  15716. }
  15717. // Remove self from list of children of parent
  15718. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15719. var index = this._parentNode._children.indexOf(this);
  15720. if (index !== -1) {
  15721. this._parentNode._children.splice(index, 1);
  15722. }
  15723. }
  15724. // Store new parent
  15725. this._parentNode = parent;
  15726. // Add as child to new parent
  15727. if (this._parentNode) {
  15728. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15729. this._parentNode._children = new Array();
  15730. }
  15731. this._parentNode._children.push(this);
  15732. }
  15733. },
  15734. enumerable: true,
  15735. configurable: true
  15736. });
  15737. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15738. /**
  15739. * Gets or sets the animation properties override
  15740. */
  15741. get: function () {
  15742. return this._animationPropertiesOverride;
  15743. },
  15744. set: function (value) {
  15745. this._animationPropertiesOverride = value;
  15746. },
  15747. enumerable: true,
  15748. configurable: true
  15749. });
  15750. /**
  15751. * Gets a string idenfifying the name of the class
  15752. * @returns "Node" string
  15753. */
  15754. Node.prototype.getClassName = function () {
  15755. return "Node";
  15756. };
  15757. Object.defineProperty(Node.prototype, "onDispose", {
  15758. /**
  15759. * Sets a callback that will be raised when the node will be disposed
  15760. */
  15761. set: function (callback) {
  15762. if (this._onDisposeObserver) {
  15763. this.onDisposeObservable.remove(this._onDisposeObserver);
  15764. }
  15765. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15766. },
  15767. enumerable: true,
  15768. configurable: true
  15769. });
  15770. /**
  15771. * Gets the scene of the node
  15772. * @returns a {BABYLON.Scene}
  15773. */
  15774. Node.prototype.getScene = function () {
  15775. return this._scene;
  15776. };
  15777. /**
  15778. * Gets the engine of the node
  15779. * @returns a {BABYLON.Engine}
  15780. */
  15781. Node.prototype.getEngine = function () {
  15782. return this._scene.getEngine();
  15783. };
  15784. /**
  15785. * Attach a behavior to the node
  15786. * @see http://doc.babylonjs.com/features/behaviour
  15787. * @param behavior defines the behavior to attach
  15788. * @returns the current Node
  15789. */
  15790. Node.prototype.addBehavior = function (behavior) {
  15791. var _this = this;
  15792. var index = this._behaviors.indexOf(behavior);
  15793. if (index !== -1) {
  15794. return this;
  15795. }
  15796. behavior.init();
  15797. if (this._scene.isLoading) {
  15798. // We defer the attach when the scene will be loaded
  15799. var observer = this._scene.onDataLoadedObservable.add(function () {
  15800. behavior.attach(_this);
  15801. setTimeout(function () {
  15802. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15803. _this._scene.onDataLoadedObservable.remove(observer);
  15804. }, 0);
  15805. });
  15806. }
  15807. else {
  15808. behavior.attach(this);
  15809. }
  15810. this._behaviors.push(behavior);
  15811. return this;
  15812. };
  15813. /**
  15814. * Remove an attached behavior
  15815. * @see http://doc.babylonjs.com/features/behaviour
  15816. * @param behavior defines the behavior to attach
  15817. * @returns the current Node
  15818. */
  15819. Node.prototype.removeBehavior = function (behavior) {
  15820. var index = this._behaviors.indexOf(behavior);
  15821. if (index === -1) {
  15822. return this;
  15823. }
  15824. this._behaviors[index].detach();
  15825. this._behaviors.splice(index, 1);
  15826. return this;
  15827. };
  15828. Object.defineProperty(Node.prototype, "behaviors", {
  15829. /**
  15830. * Gets the list of attached behaviors
  15831. * @see http://doc.babylonjs.com/features/behaviour
  15832. */
  15833. get: function () {
  15834. return this._behaviors;
  15835. },
  15836. enumerable: true,
  15837. configurable: true
  15838. });
  15839. /**
  15840. * Gets an attached behavior by name
  15841. * @param name defines the name of the behavior to look for
  15842. * @see http://doc.babylonjs.com/features/behaviour
  15843. * @returns null if behavior was not found else the requested behavior
  15844. */
  15845. Node.prototype.getBehaviorByName = function (name) {
  15846. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15847. var behavior = _a[_i];
  15848. if (behavior.name === name) {
  15849. return behavior;
  15850. }
  15851. }
  15852. return null;
  15853. };
  15854. /**
  15855. * Returns the world matrix of the node
  15856. * @returns a matrix containing the node's world matrix
  15857. */
  15858. Node.prototype.getWorldMatrix = function () {
  15859. return BABYLON.Matrix.Identity();
  15860. };
  15861. // override it in derived class if you add new variables to the cache
  15862. // and call the parent class method
  15863. /** @ignore */
  15864. Node.prototype._initCache = function () {
  15865. this._cache = {};
  15866. this._cache.parent = undefined;
  15867. };
  15868. /** @ignore */
  15869. Node.prototype.updateCache = function (force) {
  15870. if (!force && this.isSynchronized())
  15871. return;
  15872. this._cache.parent = this.parent;
  15873. this._updateCache();
  15874. };
  15875. // override it in derived class if you add new variables to the cache
  15876. // and call the parent class method if !ignoreParentClass
  15877. /** @ignore */
  15878. Node.prototype._updateCache = function (ignoreParentClass) {
  15879. };
  15880. // override it in derived class if you add new variables to the cache
  15881. /** @ignore */
  15882. Node.prototype._isSynchronized = function () {
  15883. return true;
  15884. };
  15885. /** @ignore */
  15886. Node.prototype._markSyncedWithParent = function () {
  15887. if (this.parent) {
  15888. this._parentRenderId = this.parent._currentRenderId;
  15889. }
  15890. };
  15891. /** @ignore */
  15892. Node.prototype.isSynchronizedWithParent = function () {
  15893. if (!this.parent) {
  15894. return true;
  15895. }
  15896. if (this._parentRenderId !== this.parent._currentRenderId) {
  15897. return false;
  15898. }
  15899. return this.parent.isSynchronized();
  15900. };
  15901. /** @ignore */
  15902. Node.prototype.isSynchronized = function (updateCache) {
  15903. var check = this.hasNewParent();
  15904. check = check || !this.isSynchronizedWithParent();
  15905. check = check || !this._isSynchronized();
  15906. if (updateCache)
  15907. this.updateCache(true);
  15908. return !check;
  15909. };
  15910. /** @ignore */
  15911. Node.prototype.hasNewParent = function (update) {
  15912. if (this._cache.parent === this.parent)
  15913. return false;
  15914. if (update)
  15915. this._cache.parent = this.parent;
  15916. return true;
  15917. };
  15918. /**
  15919. * Is this node ready to be used/rendered
  15920. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15921. * @return true if the node is ready
  15922. */
  15923. Node.prototype.isReady = function (completeCheck) {
  15924. if (completeCheck === void 0) { completeCheck = false; }
  15925. return this._isReady;
  15926. };
  15927. /**
  15928. * Is this node enabled?
  15929. * 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
  15930. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  15931. * @return whether this node (and its parent) is enabled
  15932. * @see setEnabled
  15933. */
  15934. Node.prototype.isEnabled = function (checkAncestors) {
  15935. if (checkAncestors === void 0) { checkAncestors = true; }
  15936. if (checkAncestors === false) {
  15937. return this._isEnabled;
  15938. }
  15939. if (this._isEnabled === false) {
  15940. return false;
  15941. }
  15942. if (this.parent !== undefined && this.parent !== null) {
  15943. return this.parent.isEnabled(checkAncestors);
  15944. }
  15945. return true;
  15946. };
  15947. /**
  15948. * Set the enabled state of this node
  15949. * @param value defines the new enabled state
  15950. * @see isEnabled
  15951. */
  15952. Node.prototype.setEnabled = function (value) {
  15953. this._isEnabled = value;
  15954. };
  15955. /**
  15956. * Is this node a descendant of the given node?
  15957. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15958. * @param ancestor defines the parent node to inspect
  15959. * @see parent
  15960. * @returns a boolean indicating if this node is a descendant of the given node
  15961. */
  15962. Node.prototype.isDescendantOf = function (ancestor) {
  15963. if (this.parent) {
  15964. if (this.parent === ancestor) {
  15965. return true;
  15966. }
  15967. return this.parent.isDescendantOf(ancestor);
  15968. }
  15969. return false;
  15970. };
  15971. /** @ignore */
  15972. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15973. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15974. if (!this._children) {
  15975. return;
  15976. }
  15977. for (var index = 0; index < this._children.length; index++) {
  15978. var item = this._children[index];
  15979. if (!predicate || predicate(item)) {
  15980. results.push(item);
  15981. }
  15982. if (!directDescendantsOnly) {
  15983. item._getDescendants(results, false, predicate);
  15984. }
  15985. }
  15986. };
  15987. /**
  15988. * Will return all nodes that have this node as ascendant
  15989. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15990. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15991. * @return all children nodes of all types
  15992. */
  15993. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15994. var results = new Array();
  15995. this._getDescendants(results, directDescendantsOnly, predicate);
  15996. return results;
  15997. };
  15998. /**
  15999. * Get all child-meshes of this node
  16000. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  16001. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  16002. * @returns an array of {BABYLON.AbstractMesh}
  16003. */
  16004. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  16005. var results = [];
  16006. this._getDescendants(results, directDescendantsOnly, function (node) {
  16007. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  16008. });
  16009. return results;
  16010. };
  16011. /**
  16012. * Get all child-transformNodes of this node
  16013. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  16014. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  16015. * @returns an array of {BABYLON.TransformNode}
  16016. */
  16017. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  16018. var results = [];
  16019. this._getDescendants(results, directDescendantsOnly, function (node) {
  16020. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  16021. });
  16022. return results;
  16023. };
  16024. /**
  16025. * Get all direct children of this node
  16026. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  16027. * @returns an array of {BABYLON.Node}
  16028. */
  16029. Node.prototype.getChildren = function (predicate) {
  16030. return this.getDescendants(true, predicate);
  16031. };
  16032. /** @ignore */
  16033. Node.prototype._setReady = function (state) {
  16034. if (state === this._isReady) {
  16035. return;
  16036. }
  16037. if (!state) {
  16038. this._isReady = false;
  16039. return;
  16040. }
  16041. if (this.onReady) {
  16042. this.onReady(this);
  16043. }
  16044. this._isReady = true;
  16045. };
  16046. /**
  16047. * Get an animation by name
  16048. * @param name defines the name of the animation to look for
  16049. * @returns null if not found else the requested animation
  16050. */
  16051. Node.prototype.getAnimationByName = function (name) {
  16052. for (var i = 0; i < this.animations.length; i++) {
  16053. var animation = this.animations[i];
  16054. if (animation.name === name) {
  16055. return animation;
  16056. }
  16057. }
  16058. return null;
  16059. };
  16060. /**
  16061. * Creates an animation range for this node
  16062. * @param name defines the name of the range
  16063. * @param from defines the starting key
  16064. * @param to defines the end key
  16065. */
  16066. Node.prototype.createAnimationRange = function (name, from, to) {
  16067. // check name not already in use
  16068. if (!this._ranges[name]) {
  16069. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16070. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16071. if (this.animations[i]) {
  16072. this.animations[i].createRange(name, from, to);
  16073. }
  16074. }
  16075. }
  16076. };
  16077. /**
  16078. * Delete a specific animation range
  16079. * @param name defines the name of the range to delete
  16080. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16081. */
  16082. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16083. if (deleteFrames === void 0) { deleteFrames = true; }
  16084. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16085. if (this.animations[i]) {
  16086. this.animations[i].deleteRange(name, deleteFrames);
  16087. }
  16088. }
  16089. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16090. };
  16091. /**
  16092. * Get an animation range by name
  16093. * @param name defines the name of the animation range to look for
  16094. * @returns null if not found else the requested animation range
  16095. */
  16096. Node.prototype.getAnimationRange = function (name) {
  16097. return this._ranges[name];
  16098. };
  16099. /**
  16100. * Will start the animation sequence
  16101. * @param name defines the range frames for animation sequence
  16102. * @param loop defines if the animation should loop (false by default)
  16103. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16104. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16105. * @returns the object created for this animation. If range does not exist, it will return null
  16106. */
  16107. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16108. var range = this.getAnimationRange(name);
  16109. if (!range) {
  16110. return null;
  16111. }
  16112. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16113. };
  16114. /**
  16115. * Serialize animation ranges into a JSON compatible object
  16116. * @returns serialization object
  16117. */
  16118. Node.prototype.serializeAnimationRanges = function () {
  16119. var serializationRanges = [];
  16120. for (var name in this._ranges) {
  16121. var localRange = this._ranges[name];
  16122. if (!localRange) {
  16123. continue;
  16124. }
  16125. var range = {};
  16126. range.name = name;
  16127. range.from = localRange.from;
  16128. range.to = localRange.to;
  16129. serializationRanges.push(range);
  16130. }
  16131. return serializationRanges;
  16132. };
  16133. /**
  16134. * Computes the world matrix of the node
  16135. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16136. * @returns the world matrix
  16137. */
  16138. Node.prototype.computeWorldMatrix = function (force) {
  16139. return BABYLON.Matrix.Identity();
  16140. };
  16141. /**
  16142. * Releases resources associated with this node.
  16143. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16144. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16145. */
  16146. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16147. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16148. if (!doNotRecurse) {
  16149. var nodes = this.getDescendants(true);
  16150. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16151. var node = nodes_1[_i];
  16152. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16153. }
  16154. }
  16155. else {
  16156. var transformNodes = this.getChildTransformNodes(true);
  16157. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16158. var transformNode = transformNodes_1[_a];
  16159. transformNode.parent = null;
  16160. transformNode.computeWorldMatrix(true);
  16161. }
  16162. }
  16163. this.parent = null;
  16164. // Callback
  16165. this.onDisposeObservable.notifyObservers(this);
  16166. this.onDisposeObservable.clear();
  16167. // Behaviors
  16168. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16169. var behavior = _c[_b];
  16170. behavior.detach();
  16171. }
  16172. this._behaviors = [];
  16173. this._isDisposed = true;
  16174. };
  16175. /**
  16176. * Parse animation range data from a serialization object and store them into a given node
  16177. * @param node defines where to store the animation ranges
  16178. * @param parsedNode defines the serialization object to read data from
  16179. * @param scene defines the hosting scene
  16180. */
  16181. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16182. if (parsedNode.ranges) {
  16183. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16184. var data = parsedNode.ranges[index];
  16185. node.createAnimationRange(data.name, data.from, data.to);
  16186. }
  16187. }
  16188. };
  16189. __decorate([
  16190. BABYLON.serialize()
  16191. ], Node.prototype, "name", void 0);
  16192. __decorate([
  16193. BABYLON.serialize()
  16194. ], Node.prototype, "id", void 0);
  16195. __decorate([
  16196. BABYLON.serialize()
  16197. ], Node.prototype, "uniqueId", void 0);
  16198. __decorate([
  16199. BABYLON.serialize()
  16200. ], Node.prototype, "state", void 0);
  16201. __decorate([
  16202. BABYLON.serialize()
  16203. ], Node.prototype, "metadata", void 0);
  16204. return Node;
  16205. }());
  16206. BABYLON.Node = Node;
  16207. })(BABYLON || (BABYLON = {}));
  16208. //# sourceMappingURL=babylon.node.js.map
  16209. "use strict";
  16210. var BABYLON;
  16211. (function (BABYLON) {
  16212. var BoundingSphere = /** @class */ (function () {
  16213. function BoundingSphere(minimum, maximum) {
  16214. this.minimum = minimum;
  16215. this.maximum = maximum;
  16216. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16217. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16218. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16219. this.radius = distance * 0.5;
  16220. this.centerWorld = BABYLON.Vector3.Zero();
  16221. this._update(BABYLON.Matrix.Identity());
  16222. }
  16223. // Methods
  16224. BoundingSphere.prototype._update = function (world) {
  16225. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16226. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16227. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16228. };
  16229. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16230. for (var i = 0; i < 6; i++) {
  16231. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16232. return false;
  16233. }
  16234. return true;
  16235. };
  16236. BoundingSphere.prototype.intersectsPoint = function (point) {
  16237. var x = this.centerWorld.x - point.x;
  16238. var y = this.centerWorld.y - point.y;
  16239. var z = this.centerWorld.z - point.z;
  16240. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16241. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16242. return false;
  16243. return true;
  16244. };
  16245. // Statics
  16246. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16247. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16248. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16249. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16250. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16251. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16252. return false;
  16253. return true;
  16254. };
  16255. return BoundingSphere;
  16256. }());
  16257. BABYLON.BoundingSphere = BoundingSphere;
  16258. })(BABYLON || (BABYLON = {}));
  16259. //# sourceMappingURL=babylon.boundingSphere.js.map
  16260. "use strict";
  16261. var BABYLON;
  16262. (function (BABYLON) {
  16263. var BoundingBox = /** @class */ (function () {
  16264. function BoundingBox(minimum, maximum) {
  16265. this.minimum = minimum;
  16266. this.maximum = maximum;
  16267. this.vectors = new Array();
  16268. this.vectorsWorld = new Array();
  16269. // Bounding vectors
  16270. this.vectors.push(this.minimum.clone());
  16271. this.vectors.push(this.maximum.clone());
  16272. this.vectors.push(this.minimum.clone());
  16273. this.vectors[2].x = this.maximum.x;
  16274. this.vectors.push(this.minimum.clone());
  16275. this.vectors[3].y = this.maximum.y;
  16276. this.vectors.push(this.minimum.clone());
  16277. this.vectors[4].z = this.maximum.z;
  16278. this.vectors.push(this.maximum.clone());
  16279. this.vectors[5].z = this.minimum.z;
  16280. this.vectors.push(this.maximum.clone());
  16281. this.vectors[6].x = this.minimum.x;
  16282. this.vectors.push(this.maximum.clone());
  16283. this.vectors[7].y = this.minimum.y;
  16284. // OBB
  16285. this.center = this.maximum.add(this.minimum).scale(0.5);
  16286. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16287. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16288. // World
  16289. for (var index = 0; index < this.vectors.length; index++) {
  16290. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16291. }
  16292. this.minimumWorld = BABYLON.Vector3.Zero();
  16293. this.maximumWorld = BABYLON.Vector3.Zero();
  16294. this.centerWorld = BABYLON.Vector3.Zero();
  16295. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16296. this._update(BABYLON.Matrix.Identity());
  16297. }
  16298. // Methods
  16299. BoundingBox.prototype.getWorldMatrix = function () {
  16300. return this._worldMatrix;
  16301. };
  16302. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16303. this._worldMatrix.copyFrom(matrix);
  16304. return this;
  16305. };
  16306. BoundingBox.prototype._update = function (world) {
  16307. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16308. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16309. for (var index = 0; index < this.vectors.length; index++) {
  16310. var v = this.vectorsWorld[index];
  16311. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16312. if (v.x < this.minimumWorld.x)
  16313. this.minimumWorld.x = v.x;
  16314. if (v.y < this.minimumWorld.y)
  16315. this.minimumWorld.y = v.y;
  16316. if (v.z < this.minimumWorld.z)
  16317. this.minimumWorld.z = v.z;
  16318. if (v.x > this.maximumWorld.x)
  16319. this.maximumWorld.x = v.x;
  16320. if (v.y > this.maximumWorld.y)
  16321. this.maximumWorld.y = v.y;
  16322. if (v.z > this.maximumWorld.z)
  16323. this.maximumWorld.z = v.z;
  16324. }
  16325. // Extend
  16326. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16327. this.extendSizeWorld.scaleInPlace(0.5);
  16328. // OBB
  16329. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16330. this.centerWorld.scaleInPlace(0.5);
  16331. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16332. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16333. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16334. this._worldMatrix = world;
  16335. };
  16336. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16337. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16338. };
  16339. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16340. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16341. };
  16342. BoundingBox.prototype.intersectsPoint = function (point) {
  16343. var delta = -BABYLON.Epsilon;
  16344. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16345. return false;
  16346. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16347. return false;
  16348. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16349. return false;
  16350. return true;
  16351. };
  16352. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16353. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16354. };
  16355. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16356. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16357. return false;
  16358. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16359. return false;
  16360. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16361. return false;
  16362. return true;
  16363. };
  16364. // Statics
  16365. BoundingBox.Intersects = function (box0, box1) {
  16366. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16367. return false;
  16368. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16369. return false;
  16370. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16371. return false;
  16372. return true;
  16373. };
  16374. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16375. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16376. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16377. return (num <= (sphereRadius * sphereRadius));
  16378. };
  16379. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16380. for (var p = 0; p < 6; p++) {
  16381. for (var i = 0; i < 8; i++) {
  16382. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16383. return false;
  16384. }
  16385. }
  16386. }
  16387. return true;
  16388. };
  16389. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16390. for (var p = 0; p < 6; p++) {
  16391. var inCount = 8;
  16392. for (var i = 0; i < 8; i++) {
  16393. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16394. --inCount;
  16395. }
  16396. else {
  16397. break;
  16398. }
  16399. }
  16400. if (inCount === 0)
  16401. return false;
  16402. }
  16403. return true;
  16404. };
  16405. return BoundingBox;
  16406. }());
  16407. BABYLON.BoundingBox = BoundingBox;
  16408. })(BABYLON || (BABYLON = {}));
  16409. //# sourceMappingURL=babylon.boundingBox.js.map
  16410. "use strict";
  16411. var BABYLON;
  16412. (function (BABYLON) {
  16413. var computeBoxExtents = function (axis, box) {
  16414. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16415. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16416. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16417. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16418. var r = r0 + r1 + r2;
  16419. return {
  16420. min: p - r,
  16421. max: p + r
  16422. };
  16423. };
  16424. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16425. var axisOverlap = function (axis, box0, box1) {
  16426. var result0 = computeBoxExtents(axis, box0);
  16427. var result1 = computeBoxExtents(axis, box1);
  16428. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16429. };
  16430. var BoundingInfo = /** @class */ (function () {
  16431. function BoundingInfo(minimum, maximum) {
  16432. this.minimum = minimum;
  16433. this.maximum = maximum;
  16434. this._isLocked = false;
  16435. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16436. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16437. }
  16438. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16439. get: function () {
  16440. return this._isLocked;
  16441. },
  16442. set: function (value) {
  16443. this._isLocked = value;
  16444. },
  16445. enumerable: true,
  16446. configurable: true
  16447. });
  16448. // Methods
  16449. BoundingInfo.prototype.update = function (world) {
  16450. if (this._isLocked) {
  16451. return;
  16452. }
  16453. this.boundingBox._update(world);
  16454. this.boundingSphere._update(world);
  16455. };
  16456. /**
  16457. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16458. * @param center New center of the bounding info
  16459. * @param extend New extend of the bounding info
  16460. */
  16461. BoundingInfo.prototype.centerOn = function (center, extend) {
  16462. this.minimum = center.subtract(extend);
  16463. this.maximum = center.add(extend);
  16464. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16465. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16466. return this;
  16467. };
  16468. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16469. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16470. return false;
  16471. return this.boundingBox.isInFrustum(frustumPlanes);
  16472. };
  16473. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16474. /**
  16475. * Gets the world distance between the min and max points of the bounding box
  16476. */
  16477. get: function () {
  16478. var boundingBox = this.boundingBox;
  16479. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16480. return size.length();
  16481. },
  16482. enumerable: true,
  16483. configurable: true
  16484. });
  16485. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16486. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16487. };
  16488. BoundingInfo.prototype._checkCollision = function (collider) {
  16489. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16490. };
  16491. BoundingInfo.prototype.intersectsPoint = function (point) {
  16492. if (!this.boundingSphere.centerWorld) {
  16493. return false;
  16494. }
  16495. if (!this.boundingSphere.intersectsPoint(point)) {
  16496. return false;
  16497. }
  16498. if (!this.boundingBox.intersectsPoint(point)) {
  16499. return false;
  16500. }
  16501. return true;
  16502. };
  16503. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16504. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16505. return false;
  16506. }
  16507. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16508. return false;
  16509. }
  16510. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16511. return false;
  16512. }
  16513. if (!precise) {
  16514. return true;
  16515. }
  16516. var box0 = this.boundingBox;
  16517. var box1 = boundingInfo.boundingBox;
  16518. if (!axisOverlap(box0.directions[0], box0, box1))
  16519. return false;
  16520. if (!axisOverlap(box0.directions[1], box0, box1))
  16521. return false;
  16522. if (!axisOverlap(box0.directions[2], box0, box1))
  16523. return false;
  16524. if (!axisOverlap(box1.directions[0], box0, box1))
  16525. return false;
  16526. if (!axisOverlap(box1.directions[1], box0, box1))
  16527. return false;
  16528. if (!axisOverlap(box1.directions[2], box0, box1))
  16529. return false;
  16530. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16531. return false;
  16532. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16533. return false;
  16534. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16535. return false;
  16536. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16537. return false;
  16538. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16539. return false;
  16540. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16541. return false;
  16542. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16543. return false;
  16544. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16545. return false;
  16546. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16547. return false;
  16548. return true;
  16549. };
  16550. return BoundingInfo;
  16551. }());
  16552. BABYLON.BoundingInfo = BoundingInfo;
  16553. })(BABYLON || (BABYLON = {}));
  16554. //# sourceMappingURL=babylon.boundingInfo.js.map
  16555. "use strict";
  16556. var BABYLON;
  16557. (function (BABYLON) {
  16558. var TransformNode = /** @class */ (function (_super) {
  16559. __extends(TransformNode, _super);
  16560. function TransformNode(name, scene, isPure) {
  16561. if (scene === void 0) { scene = null; }
  16562. if (isPure === void 0) { isPure = true; }
  16563. var _this = _super.call(this, name, scene) || this;
  16564. // Properties
  16565. _this._rotation = BABYLON.Vector3.Zero();
  16566. _this._scaling = BABYLON.Vector3.One();
  16567. _this._isDirty = false;
  16568. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16569. _this.scalingDeterminant = 1;
  16570. _this.infiniteDistance = false;
  16571. _this.position = BABYLON.Vector3.Zero();
  16572. _this._localWorld = BABYLON.Matrix.Zero();
  16573. _this._worldMatrix = BABYLON.Matrix.Zero();
  16574. _this._worldMatrixDeterminant = 0;
  16575. _this._absolutePosition = BABYLON.Vector3.Zero();
  16576. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16577. _this._postMultiplyPivotMatrix = false;
  16578. _this._isWorldMatrixFrozen = false;
  16579. /**
  16580. * An event triggered after the world matrix is updated
  16581. * @type {BABYLON.Observable}
  16582. */
  16583. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16584. _this._nonUniformScaling = false;
  16585. if (isPure) {
  16586. _this.getScene().addTransformNode(_this);
  16587. }
  16588. return _this;
  16589. }
  16590. /**
  16591. * Gets a string idenfifying the name of the class
  16592. * @returns "TransformNode" string
  16593. */
  16594. TransformNode.prototype.getClassName = function () {
  16595. return "TransformNode";
  16596. };
  16597. Object.defineProperty(TransformNode.prototype, "rotation", {
  16598. /**
  16599. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16600. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16601. * Default : (0.0, 0.0, 0.0)
  16602. */
  16603. get: function () {
  16604. return this._rotation;
  16605. },
  16606. set: function (newRotation) {
  16607. this._rotation = newRotation;
  16608. },
  16609. enumerable: true,
  16610. configurable: true
  16611. });
  16612. Object.defineProperty(TransformNode.prototype, "scaling", {
  16613. /**
  16614. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16615. * Default : (1.0, 1.0, 1.0)
  16616. */
  16617. get: function () {
  16618. return this._scaling;
  16619. },
  16620. /**
  16621. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16622. * Default : (1.0, 1.0, 1.0)
  16623. */
  16624. set: function (newScaling) {
  16625. this._scaling = newScaling;
  16626. },
  16627. enumerable: true,
  16628. configurable: true
  16629. });
  16630. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16631. /**
  16632. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16633. * It's null by default.
  16634. * 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)
  16635. */
  16636. get: function () {
  16637. return this._rotationQuaternion;
  16638. },
  16639. set: function (quaternion) {
  16640. this._rotationQuaternion = quaternion;
  16641. //reset the rotation vector.
  16642. if (quaternion && this.rotation.length()) {
  16643. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16644. }
  16645. },
  16646. enumerable: true,
  16647. configurable: true
  16648. });
  16649. /**
  16650. * Returns the latest update of the World matrix
  16651. * Returns a Matrix.
  16652. */
  16653. TransformNode.prototype.getWorldMatrix = function () {
  16654. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16655. this.computeWorldMatrix();
  16656. }
  16657. return this._worldMatrix;
  16658. };
  16659. /**
  16660. * Returns the latest update of the World matrix determinant.
  16661. */
  16662. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16663. return this._worldMatrixDeterminant;
  16664. };
  16665. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16666. /**
  16667. * Returns directly the latest state of the mesh World matrix.
  16668. * A Matrix is returned.
  16669. */
  16670. get: function () {
  16671. return this._worldMatrix;
  16672. },
  16673. enumerable: true,
  16674. configurable: true
  16675. });
  16676. /**
  16677. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16678. * Returns the AbstractMesh.
  16679. */
  16680. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16681. this._poseMatrix.copyFrom(matrix);
  16682. return this;
  16683. };
  16684. /**
  16685. * Returns the mesh Pose matrix.
  16686. * Returned object : Matrix
  16687. */
  16688. TransformNode.prototype.getPoseMatrix = function () {
  16689. return this._poseMatrix;
  16690. };
  16691. TransformNode.prototype._isSynchronized = function () {
  16692. if (this._isDirty) {
  16693. return false;
  16694. }
  16695. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16696. return false;
  16697. if (this._cache.pivotMatrixUpdated) {
  16698. return false;
  16699. }
  16700. if (this.infiniteDistance) {
  16701. return false;
  16702. }
  16703. if (!this._cache.position.equals(this.position))
  16704. return false;
  16705. if (this.rotationQuaternion) {
  16706. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16707. return false;
  16708. }
  16709. if (!this._cache.rotation.equals(this.rotation))
  16710. return false;
  16711. if (!this._cache.scaling.equals(this.scaling))
  16712. return false;
  16713. return true;
  16714. };
  16715. TransformNode.prototype._initCache = function () {
  16716. _super.prototype._initCache.call(this);
  16717. this._cache.localMatrixUpdated = false;
  16718. this._cache.position = BABYLON.Vector3.Zero();
  16719. this._cache.scaling = BABYLON.Vector3.Zero();
  16720. this._cache.rotation = BABYLON.Vector3.Zero();
  16721. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16722. this._cache.billboardMode = -1;
  16723. };
  16724. TransformNode.prototype.markAsDirty = function (property) {
  16725. if (property === "rotation") {
  16726. this.rotationQuaternion = null;
  16727. }
  16728. this._currentRenderId = Number.MAX_VALUE;
  16729. this._isDirty = true;
  16730. return this;
  16731. };
  16732. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16733. /**
  16734. * Returns the current mesh absolute position.
  16735. * Retuns a Vector3.
  16736. */
  16737. get: function () {
  16738. return this._absolutePosition;
  16739. },
  16740. enumerable: true,
  16741. configurable: true
  16742. });
  16743. /**
  16744. * Sets a new matrix to apply before all other transformation
  16745. * @param matrix defines the transform matrix
  16746. * @returns the current TransformNode
  16747. */
  16748. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16749. return this.setPivotMatrix(matrix, false);
  16750. };
  16751. /**
  16752. * Sets a new pivot matrix to the current node
  16753. * @param matrix defines the new pivot matrix to use
  16754. * @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
  16755. * @returns the current TransformNode
  16756. */
  16757. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16758. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16759. this._pivotMatrix = matrix.clone();
  16760. this._cache.pivotMatrixUpdated = true;
  16761. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16762. if (this._postMultiplyPivotMatrix) {
  16763. if (!this._pivotMatrixInverse) {
  16764. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16765. }
  16766. else {
  16767. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16768. }
  16769. }
  16770. return this;
  16771. };
  16772. /**
  16773. * Returns the mesh pivot matrix.
  16774. * Default : Identity.
  16775. * A Matrix is returned.
  16776. */
  16777. TransformNode.prototype.getPivotMatrix = function () {
  16778. return this._pivotMatrix;
  16779. };
  16780. /**
  16781. * Prevents the World matrix to be computed any longer.
  16782. * Returns the AbstractMesh.
  16783. */
  16784. TransformNode.prototype.freezeWorldMatrix = function () {
  16785. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16786. this.computeWorldMatrix(true);
  16787. this._isWorldMatrixFrozen = true;
  16788. return this;
  16789. };
  16790. /**
  16791. * Allows back the World matrix computation.
  16792. * Returns the AbstractMesh.
  16793. */
  16794. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16795. this._isWorldMatrixFrozen = false;
  16796. this.computeWorldMatrix(true);
  16797. return this;
  16798. };
  16799. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16800. /**
  16801. * True if the World matrix has been frozen.
  16802. * Returns a boolean.
  16803. */
  16804. get: function () {
  16805. return this._isWorldMatrixFrozen;
  16806. },
  16807. enumerable: true,
  16808. configurable: true
  16809. });
  16810. /**
  16811. * Retuns the mesh absolute position in the World.
  16812. * Returns a Vector3.
  16813. */
  16814. TransformNode.prototype.getAbsolutePosition = function () {
  16815. this.computeWorldMatrix();
  16816. return this._absolutePosition;
  16817. };
  16818. /**
  16819. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16820. * Returns the AbstractMesh.
  16821. */
  16822. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16823. if (!absolutePosition) {
  16824. return this;
  16825. }
  16826. var absolutePositionX;
  16827. var absolutePositionY;
  16828. var absolutePositionZ;
  16829. if (absolutePosition.x === undefined) {
  16830. if (arguments.length < 3) {
  16831. return this;
  16832. }
  16833. absolutePositionX = arguments[0];
  16834. absolutePositionY = arguments[1];
  16835. absolutePositionZ = arguments[2];
  16836. }
  16837. else {
  16838. absolutePositionX = absolutePosition.x;
  16839. absolutePositionY = absolutePosition.y;
  16840. absolutePositionZ = absolutePosition.z;
  16841. }
  16842. if (this.parent) {
  16843. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16844. invertParentWorldMatrix.invert();
  16845. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16846. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16847. }
  16848. else {
  16849. this.position.x = absolutePositionX;
  16850. this.position.y = absolutePositionY;
  16851. this.position.z = absolutePositionZ;
  16852. }
  16853. return this;
  16854. };
  16855. /**
  16856. * Sets the mesh position in its local space.
  16857. * Returns the AbstractMesh.
  16858. */
  16859. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16860. this.computeWorldMatrix();
  16861. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16862. return this;
  16863. };
  16864. /**
  16865. * Returns the mesh position in the local space from the current World matrix values.
  16866. * Returns a new Vector3.
  16867. */
  16868. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16869. this.computeWorldMatrix();
  16870. var invLocalWorldMatrix = this._localWorld.clone();
  16871. invLocalWorldMatrix.invert();
  16872. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16873. };
  16874. /**
  16875. * Translates the mesh along the passed Vector3 in its local space.
  16876. * Returns the AbstractMesh.
  16877. */
  16878. TransformNode.prototype.locallyTranslate = function (vector3) {
  16879. this.computeWorldMatrix(true);
  16880. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16881. return this;
  16882. };
  16883. /**
  16884. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16885. * @param targetPoint the position (must be in same space as current mesh) to look at
  16886. * @param yawCor optional yaw (y-axis) correction in radians
  16887. * @param pitchCor optional pitch (x-axis) correction in radians
  16888. * @param rollCor optional roll (z-axis) correction in radians
  16889. * @param space the choosen space of the target
  16890. * @returns the TransformNode.
  16891. */
  16892. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16893. if (yawCor === void 0) { yawCor = 0; }
  16894. if (pitchCor === void 0) { pitchCor = 0; }
  16895. if (rollCor === void 0) { rollCor = 0; }
  16896. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16897. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16898. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16899. targetPoint.subtractToRef(pos, dv);
  16900. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16901. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16902. var pitch = Math.atan2(dv.y, len);
  16903. if (this.rotationQuaternion) {
  16904. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16905. }
  16906. else {
  16907. this.rotation.x = pitch + pitchCor;
  16908. this.rotation.y = yaw + yawCor;
  16909. this.rotation.z = rollCor;
  16910. }
  16911. return this;
  16912. };
  16913. /**
  16914. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16915. * This Vector3 is expressed in the World space.
  16916. */
  16917. TransformNode.prototype.getDirection = function (localAxis) {
  16918. var result = BABYLON.Vector3.Zero();
  16919. this.getDirectionToRef(localAxis, result);
  16920. return result;
  16921. };
  16922. /**
  16923. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16924. * localAxis is expressed in the mesh local space.
  16925. * result is computed in the Wordl space from the mesh World matrix.
  16926. * Returns the AbstractMesh.
  16927. */
  16928. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16929. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16930. return this;
  16931. };
  16932. /**
  16933. * Sets a new pivot point to the current node
  16934. * @param point defines the new pivot point to use
  16935. * @param space defines if the point is in world or local space (local by default)
  16936. * @returns the current TransformNode
  16937. */
  16938. TransformNode.prototype.setPivotPoint = function (point, space) {
  16939. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16940. if (this.getScene().getRenderId() == 0) {
  16941. this.computeWorldMatrix(true);
  16942. }
  16943. var wm = this.getWorldMatrix();
  16944. if (space == BABYLON.Space.WORLD) {
  16945. var tmat = BABYLON.Tmp.Matrix[0];
  16946. wm.invertToRef(tmat);
  16947. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16948. }
  16949. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16950. };
  16951. /**
  16952. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16953. */
  16954. TransformNode.prototype.getPivotPoint = function () {
  16955. var point = BABYLON.Vector3.Zero();
  16956. this.getPivotPointToRef(point);
  16957. return point;
  16958. };
  16959. /**
  16960. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16961. * Returns the AbstractMesh.
  16962. */
  16963. TransformNode.prototype.getPivotPointToRef = function (result) {
  16964. result.x = -this._pivotMatrix.m[12];
  16965. result.y = -this._pivotMatrix.m[13];
  16966. result.z = -this._pivotMatrix.m[14];
  16967. return this;
  16968. };
  16969. /**
  16970. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16971. */
  16972. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16973. var point = BABYLON.Vector3.Zero();
  16974. this.getAbsolutePivotPointToRef(point);
  16975. return point;
  16976. };
  16977. /**
  16978. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16979. * Returns the AbstractMesh.
  16980. */
  16981. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16982. result.x = this._pivotMatrix.m[12];
  16983. result.y = this._pivotMatrix.m[13];
  16984. result.z = this._pivotMatrix.m[14];
  16985. this.getPivotPointToRef(result);
  16986. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16987. return this;
  16988. };
  16989. /**
  16990. * Defines the passed node as the parent of the current node.
  16991. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16992. * Returns the TransformNode.
  16993. */
  16994. TransformNode.prototype.setParent = function (node) {
  16995. if (node === null) {
  16996. var rotation = BABYLON.Tmp.Quaternion[0];
  16997. var position = BABYLON.Tmp.Vector3[0];
  16998. var scale = BABYLON.Tmp.Vector3[1];
  16999. if (this.parent && this.parent.computeWorldMatrix) {
  17000. this.parent.computeWorldMatrix(true);
  17001. }
  17002. this.computeWorldMatrix(true);
  17003. this.getWorldMatrix().decompose(scale, rotation, position);
  17004. if (this.rotationQuaternion) {
  17005. this.rotationQuaternion.copyFrom(rotation);
  17006. }
  17007. else {
  17008. rotation.toEulerAnglesToRef(this.rotation);
  17009. }
  17010. this.scaling.x = scale.x;
  17011. this.scaling.y = scale.y;
  17012. this.scaling.z = scale.z;
  17013. this.position.x = position.x;
  17014. this.position.y = position.y;
  17015. this.position.z = position.z;
  17016. }
  17017. else {
  17018. var rotation = BABYLON.Tmp.Quaternion[0];
  17019. var position = BABYLON.Tmp.Vector3[0];
  17020. var scale = BABYLON.Tmp.Vector3[1];
  17021. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17022. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17023. this.computeWorldMatrix(true);
  17024. node.computeWorldMatrix(true);
  17025. node.getWorldMatrix().invertToRef(invParentMatrix);
  17026. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17027. diffMatrix.decompose(scale, rotation, position);
  17028. if (this.rotationQuaternion) {
  17029. this.rotationQuaternion.copyFrom(rotation);
  17030. }
  17031. else {
  17032. rotation.toEulerAnglesToRef(this.rotation);
  17033. }
  17034. this.position.x = position.x;
  17035. this.position.y = position.y;
  17036. this.position.z = position.z;
  17037. this.scaling.x = scale.x;
  17038. this.scaling.y = scale.y;
  17039. this.scaling.z = scale.z;
  17040. }
  17041. this.parent = node;
  17042. return this;
  17043. };
  17044. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17045. get: function () {
  17046. return this._nonUniformScaling;
  17047. },
  17048. enumerable: true,
  17049. configurable: true
  17050. });
  17051. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17052. if (this._nonUniformScaling === value) {
  17053. return false;
  17054. }
  17055. this._nonUniformScaling = true;
  17056. return true;
  17057. };
  17058. /**
  17059. * Attach the current TransformNode to another TransformNode associated with a bone
  17060. * @param bone Bone affecting the TransformNode
  17061. * @param affectedTransformNode TransformNode associated with the bone
  17062. */
  17063. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17064. this._transformToBoneReferal = affectedTransformNode;
  17065. this.parent = bone;
  17066. if (bone.getWorldMatrix().determinant() < 0) {
  17067. this.scalingDeterminant *= -1;
  17068. }
  17069. return this;
  17070. };
  17071. TransformNode.prototype.detachFromBone = function () {
  17072. if (!this.parent) {
  17073. return this;
  17074. }
  17075. if (this.parent.getWorldMatrix().determinant() < 0) {
  17076. this.scalingDeterminant *= -1;
  17077. }
  17078. this._transformToBoneReferal = null;
  17079. this.parent = null;
  17080. return this;
  17081. };
  17082. /**
  17083. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17084. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17085. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17086. * The passed axis is also normalized.
  17087. * Returns the AbstractMesh.
  17088. */
  17089. TransformNode.prototype.rotate = function (axis, amount, space) {
  17090. axis.normalize();
  17091. if (!this.rotationQuaternion) {
  17092. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17093. this.rotation = BABYLON.Vector3.Zero();
  17094. }
  17095. var rotationQuaternion;
  17096. if (!space || space === BABYLON.Space.LOCAL) {
  17097. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17098. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17099. }
  17100. else {
  17101. if (this.parent) {
  17102. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17103. invertParentWorldMatrix.invert();
  17104. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17105. }
  17106. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17107. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17108. }
  17109. return this;
  17110. };
  17111. /**
  17112. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17113. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17114. * The passed axis is also normalized.
  17115. * Returns the AbstractMesh.
  17116. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17117. */
  17118. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17119. axis.normalize();
  17120. if (!this.rotationQuaternion) {
  17121. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17122. this.rotation.copyFromFloats(0, 0, 0);
  17123. }
  17124. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17125. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17126. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17127. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17128. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17129. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17130. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17131. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17132. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17133. return this;
  17134. };
  17135. /**
  17136. * Translates the mesh along the axis vector for the passed distance in the given space.
  17137. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17138. * Returns the AbstractMesh.
  17139. */
  17140. TransformNode.prototype.translate = function (axis, distance, space) {
  17141. var displacementVector = axis.scale(distance);
  17142. if (!space || space === BABYLON.Space.LOCAL) {
  17143. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17144. this.setPositionWithLocalVector(tempV3);
  17145. }
  17146. else {
  17147. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17148. }
  17149. return this;
  17150. };
  17151. /**
  17152. * Adds a rotation step to the mesh current rotation.
  17153. * x, y, z are Euler angles expressed in radians.
  17154. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17155. * This means this rotation is made in the mesh local space only.
  17156. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17157. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17158. * ```javascript
  17159. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17160. * ```
  17161. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17162. * 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.
  17163. * Returns the AbstractMesh.
  17164. */
  17165. TransformNode.prototype.addRotation = function (x, y, z) {
  17166. var rotationQuaternion;
  17167. if (this.rotationQuaternion) {
  17168. rotationQuaternion = this.rotationQuaternion;
  17169. }
  17170. else {
  17171. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17172. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17173. }
  17174. var accumulation = BABYLON.Tmp.Quaternion[0];
  17175. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17176. rotationQuaternion.multiplyInPlace(accumulation);
  17177. if (!this.rotationQuaternion) {
  17178. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17179. }
  17180. return this;
  17181. };
  17182. /**
  17183. * Computes the mesh World matrix and returns it.
  17184. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17185. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17186. * If the parameter `force`is set to `true`, the actual computation is done.
  17187. * Returns the mesh World Matrix.
  17188. */
  17189. TransformNode.prototype.computeWorldMatrix = function (force) {
  17190. if (this._isWorldMatrixFrozen) {
  17191. return this._worldMatrix;
  17192. }
  17193. if (!force && this.isSynchronized(true)) {
  17194. return this._worldMatrix;
  17195. }
  17196. this._cache.position.copyFrom(this.position);
  17197. this._cache.scaling.copyFrom(this.scaling);
  17198. this._cache.pivotMatrixUpdated = false;
  17199. this._cache.billboardMode = this.billboardMode;
  17200. this._currentRenderId = this.getScene().getRenderId();
  17201. this._isDirty = false;
  17202. // Scaling
  17203. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17204. // Rotation
  17205. //rotate, if quaternion is set and rotation was used
  17206. if (this.rotationQuaternion) {
  17207. var len = this.rotation.length();
  17208. if (len) {
  17209. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17210. this.rotation.copyFromFloats(0, 0, 0);
  17211. }
  17212. }
  17213. if (this.rotationQuaternion) {
  17214. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17215. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17216. }
  17217. else {
  17218. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17219. this._cache.rotation.copyFrom(this.rotation);
  17220. }
  17221. // Translation
  17222. var camera = this.getScene().activeCamera;
  17223. if (this.infiniteDistance && !this.parent && camera) {
  17224. var cameraWorldMatrix = camera.getWorldMatrix();
  17225. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17226. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17227. }
  17228. else {
  17229. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17230. }
  17231. // Composing transformations
  17232. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17233. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17234. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17235. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  17236. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  17237. // Need to decompose each rotation here
  17238. var currentPosition = BABYLON.Tmp.Vector3[3];
  17239. if (this.parent && this.parent.getWorldMatrix) {
  17240. if (this._transformToBoneReferal) {
  17241. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17242. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17243. }
  17244. else {
  17245. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17246. }
  17247. }
  17248. else {
  17249. currentPosition.copyFrom(this.position);
  17250. }
  17251. currentPosition.subtractInPlace(camera.globalPosition);
  17252. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17253. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17254. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17255. }
  17256. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17257. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17258. }
  17259. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17260. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17261. }
  17262. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17263. }
  17264. else {
  17265. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17266. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17267. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17268. }
  17269. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17270. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17271. }
  17272. // Local world
  17273. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17274. // Parent
  17275. if (this.parent && this.parent.getWorldMatrix) {
  17276. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17277. if (this._transformToBoneReferal) {
  17278. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17279. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17280. }
  17281. else {
  17282. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17283. }
  17284. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17285. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17286. this._worldMatrix.copyFrom(this._localWorld);
  17287. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17288. }
  17289. else {
  17290. if (this._transformToBoneReferal) {
  17291. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17292. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17293. }
  17294. else {
  17295. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17296. }
  17297. }
  17298. this._markSyncedWithParent();
  17299. }
  17300. else {
  17301. this._worldMatrix.copyFrom(this._localWorld);
  17302. }
  17303. // Post multiply inverse of pivotMatrix
  17304. if (this._postMultiplyPivotMatrix) {
  17305. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17306. }
  17307. // Normal matrix
  17308. if (this.scaling.isNonUniform) {
  17309. this._updateNonUniformScalingState(true);
  17310. }
  17311. else if (this.parent && this.parent._nonUniformScaling) {
  17312. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17313. }
  17314. else {
  17315. this._updateNonUniformScalingState(false);
  17316. }
  17317. this._afterComputeWorldMatrix();
  17318. // Absolute position
  17319. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17320. // Callbacks
  17321. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17322. if (!this._poseMatrix) {
  17323. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17324. }
  17325. // Cache the determinant
  17326. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17327. return this._worldMatrix;
  17328. };
  17329. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17330. };
  17331. /**
  17332. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17333. * @param func: callback function to add
  17334. *
  17335. * Returns the TransformNode.
  17336. */
  17337. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17338. this.onAfterWorldMatrixUpdateObservable.add(func);
  17339. return this;
  17340. };
  17341. /**
  17342. * Removes a registered callback function.
  17343. * Returns the TransformNode.
  17344. */
  17345. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17346. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17347. return this;
  17348. };
  17349. /**
  17350. * Clone the current transform node
  17351. * Returns the new transform node
  17352. * @param name Name of the new clone
  17353. * @param newParent New parent for the clone
  17354. * @param doNotCloneChildren Do not clone children hierarchy
  17355. */
  17356. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17357. var _this = this;
  17358. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17359. result.name = name;
  17360. result.id = name;
  17361. if (newParent) {
  17362. result.parent = newParent;
  17363. }
  17364. if (!doNotCloneChildren) {
  17365. // Children
  17366. var directDescendants = this.getDescendants(true);
  17367. for (var index = 0; index < directDescendants.length; index++) {
  17368. var child = directDescendants[index];
  17369. if (child.clone) {
  17370. child.clone(name + "." + child.name, result);
  17371. }
  17372. }
  17373. }
  17374. return result;
  17375. };
  17376. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17377. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17378. serializationObject.type = this.getClassName();
  17379. // Parent
  17380. if (this.parent) {
  17381. serializationObject.parentId = this.parent.id;
  17382. }
  17383. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17384. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17385. }
  17386. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17387. serializationObject.isEnabled = this.isEnabled();
  17388. // Parent
  17389. if (this.parent) {
  17390. serializationObject.parentId = this.parent.id;
  17391. }
  17392. return serializationObject;
  17393. };
  17394. // Statics
  17395. /**
  17396. * Returns a new TransformNode object parsed from the source provided.
  17397. * The parameter `parsedMesh` is the source.
  17398. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17399. */
  17400. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17401. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17402. if (BABYLON.Tags) {
  17403. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17404. }
  17405. if (parsedTransformNode.localMatrix) {
  17406. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17407. }
  17408. else if (parsedTransformNode.pivotMatrix) {
  17409. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17410. }
  17411. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17412. // Parent
  17413. if (parsedTransformNode.parentId) {
  17414. transformNode._waitingParentId = parsedTransformNode.parentId;
  17415. }
  17416. return transformNode;
  17417. };
  17418. /**
  17419. * Releases resources associated with this transform node.
  17420. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17421. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17422. */
  17423. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17424. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17425. // Animations
  17426. this.getScene().stopAnimation(this);
  17427. // Remove from scene
  17428. this.getScene().removeTransformNode(this);
  17429. this.onAfterWorldMatrixUpdateObservable.clear();
  17430. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17431. };
  17432. // Statics
  17433. TransformNode.BILLBOARDMODE_NONE = 0;
  17434. TransformNode.BILLBOARDMODE_X = 1;
  17435. TransformNode.BILLBOARDMODE_Y = 2;
  17436. TransformNode.BILLBOARDMODE_Z = 4;
  17437. TransformNode.BILLBOARDMODE_ALL = 7;
  17438. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17439. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17440. __decorate([
  17441. BABYLON.serializeAsVector3()
  17442. ], TransformNode.prototype, "_rotation", void 0);
  17443. __decorate([
  17444. BABYLON.serializeAsQuaternion()
  17445. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17446. __decorate([
  17447. BABYLON.serializeAsVector3()
  17448. ], TransformNode.prototype, "_scaling", void 0);
  17449. __decorate([
  17450. BABYLON.serialize()
  17451. ], TransformNode.prototype, "billboardMode", void 0);
  17452. __decorate([
  17453. BABYLON.serialize()
  17454. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17455. __decorate([
  17456. BABYLON.serialize()
  17457. ], TransformNode.prototype, "infiniteDistance", void 0);
  17458. __decorate([
  17459. BABYLON.serializeAsVector3()
  17460. ], TransformNode.prototype, "position", void 0);
  17461. return TransformNode;
  17462. }(BABYLON.Node));
  17463. BABYLON.TransformNode = TransformNode;
  17464. })(BABYLON || (BABYLON = {}));
  17465. //# sourceMappingURL=babylon.transformNode.js.map
  17466. "use strict";
  17467. var BABYLON;
  17468. (function (BABYLON) {
  17469. var AbstractMesh = /** @class */ (function (_super) {
  17470. __extends(AbstractMesh, _super);
  17471. // Constructor
  17472. function AbstractMesh(name, scene) {
  17473. if (scene === void 0) { scene = null; }
  17474. var _this = _super.call(this, name, scene, false) || this;
  17475. _this._facetNb = 0; // facet number
  17476. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17477. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17478. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17479. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17480. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17481. _this._subDiv = {
  17482. max: 1,
  17483. X: 1,
  17484. Y: 1,
  17485. Z: 1
  17486. };
  17487. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17488. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17489. // Events
  17490. /**
  17491. * An event triggered when this mesh collides with another one
  17492. * @type {BABYLON.Observable}
  17493. */
  17494. _this.onCollideObservable = new BABYLON.Observable();
  17495. /**
  17496. * An event triggered when the collision's position changes
  17497. * @type {BABYLON.Observable}
  17498. */
  17499. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17500. /**
  17501. * An event triggered when material is changed
  17502. * @type {BABYLON.Observable}
  17503. */
  17504. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17505. // Properties
  17506. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17507. /**
  17508. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17509. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17510. * or
  17511. * 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.
  17512. * for more info check WebGl documentations
  17513. */
  17514. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17515. /**
  17516. * 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:
  17517. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17518. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17519. * 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.
  17520. */
  17521. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17522. /**
  17523. * 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.
  17524. * The default value is -1 which means don't break the query and wait till the result.
  17525. */
  17526. _this.occlusionRetryCount = -1;
  17527. _this._occlusionInternalRetryCounter = 0;
  17528. _this._isOccluded = false;
  17529. _this._isOcclusionQueryInProgress = false;
  17530. _this._visibility = 1.0;
  17531. _this.alphaIndex = Number.MAX_VALUE;
  17532. _this.isVisible = true;
  17533. _this.isPickable = true;
  17534. _this.showBoundingBox = false;
  17535. _this.showSubMeshesBoundingBox = false;
  17536. _this.isBlocker = false;
  17537. _this.enablePointerMoveEvents = false;
  17538. _this.renderingGroupId = 0;
  17539. _this._receiveShadows = false;
  17540. _this.renderOutline = false;
  17541. _this.outlineColor = BABYLON.Color3.Red();
  17542. _this.outlineWidth = 0.02;
  17543. _this.renderOverlay = false;
  17544. _this.overlayColor = BABYLON.Color3.Red();
  17545. _this.overlayAlpha = 0.5;
  17546. _this._hasVertexAlpha = false;
  17547. _this._useVertexColors = true;
  17548. _this._computeBonesUsingShaders = true;
  17549. _this._numBoneInfluencers = 4;
  17550. _this._applyFog = true;
  17551. _this.useOctreeForRenderingSelection = true;
  17552. _this.useOctreeForPicking = true;
  17553. _this.useOctreeForCollisions = true;
  17554. _this._layerMask = 0x0FFFFFFF;
  17555. /**
  17556. * True if the mesh must be rendered in any case.
  17557. */
  17558. _this.alwaysSelectAsActiveMesh = false;
  17559. /**
  17560. * This scene's action manager
  17561. * @type {BABYLON.ActionManager}
  17562. */
  17563. _this.actionManager = null;
  17564. // Physics
  17565. _this.physicsImpostor = null;
  17566. // Collisions
  17567. _this._checkCollisions = false;
  17568. _this._collisionMask = -1;
  17569. _this._collisionGroup = -1;
  17570. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17571. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17572. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17573. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17574. // Edges
  17575. _this.edgesWidth = 1;
  17576. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17577. // Cache
  17578. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17579. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17580. _this._renderId = 0;
  17581. _this._intersectionsInProgress = new Array();
  17582. _this._unIndexed = false;
  17583. _this._lightSources = new Array();
  17584. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17585. if (collidedMesh === void 0) { collidedMesh = null; }
  17586. //TODO move this to the collision coordinator!
  17587. if (_this.getScene().workerCollisions)
  17588. newPosition.multiplyInPlace(_this._collider._radius);
  17589. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17590. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17591. _this.position.addInPlace(_this._diffPositionForCollisions);
  17592. }
  17593. if (collidedMesh) {
  17594. _this.onCollideObservable.notifyObservers(collidedMesh);
  17595. }
  17596. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17597. };
  17598. _this.getScene().addMesh(_this);
  17599. _this._resyncLightSources();
  17600. return _this;
  17601. }
  17602. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17603. get: function () {
  17604. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17605. },
  17606. enumerable: true,
  17607. configurable: true
  17608. });
  17609. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17610. get: function () {
  17611. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17612. },
  17613. enumerable: true,
  17614. configurable: true
  17615. });
  17616. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17617. get: function () {
  17618. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17619. },
  17620. enumerable: true,
  17621. configurable: true
  17622. });
  17623. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17624. get: function () {
  17625. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17626. },
  17627. enumerable: true,
  17628. configurable: true
  17629. });
  17630. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17631. get: function () {
  17632. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17633. },
  17634. enumerable: true,
  17635. configurable: true
  17636. });
  17637. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17638. /**
  17639. * Read-only : the number of facets in the mesh
  17640. */
  17641. get: function () {
  17642. return this._facetNb;
  17643. },
  17644. enumerable: true,
  17645. configurable: true
  17646. });
  17647. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17648. /**
  17649. * The number (integer) of subdivisions per axis in the partioning space
  17650. */
  17651. get: function () {
  17652. return this._partitioningSubdivisions;
  17653. },
  17654. set: function (nb) {
  17655. this._partitioningSubdivisions = nb;
  17656. },
  17657. enumerable: true,
  17658. configurable: true
  17659. });
  17660. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17661. /**
  17662. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17663. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17664. */
  17665. get: function () {
  17666. return this._partitioningBBoxRatio;
  17667. },
  17668. set: function (ratio) {
  17669. this._partitioningBBoxRatio = ratio;
  17670. },
  17671. enumerable: true,
  17672. configurable: true
  17673. });
  17674. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17675. /**
  17676. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17677. * Works only for updatable meshes.
  17678. * Doesn't work with multi-materials.
  17679. */
  17680. get: function () {
  17681. return this._facetDepthSort;
  17682. },
  17683. set: function (sort) {
  17684. this._facetDepthSort = sort;
  17685. },
  17686. enumerable: true,
  17687. configurable: true
  17688. });
  17689. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17690. /**
  17691. * The location (Vector3) where the facet depth sort must be computed from.
  17692. * By default, the active camera position.
  17693. * Used only when facet depth sort is enabled.
  17694. */
  17695. get: function () {
  17696. return this._facetDepthSortFrom;
  17697. },
  17698. set: function (location) {
  17699. this._facetDepthSortFrom = location;
  17700. },
  17701. enumerable: true,
  17702. configurable: true
  17703. });
  17704. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17705. /**
  17706. * Read-only boolean : is the feature facetData enabled ?
  17707. */
  17708. get: function () {
  17709. return this._facetDataEnabled;
  17710. },
  17711. enumerable: true,
  17712. configurable: true
  17713. });
  17714. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17715. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17716. return false;
  17717. }
  17718. this._markSubMeshesAsMiscDirty();
  17719. return true;
  17720. };
  17721. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17722. set: function (callback) {
  17723. if (this._onCollideObserver) {
  17724. this.onCollideObservable.remove(this._onCollideObserver);
  17725. }
  17726. this._onCollideObserver = this.onCollideObservable.add(callback);
  17727. },
  17728. enumerable: true,
  17729. configurable: true
  17730. });
  17731. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17732. set: function (callback) {
  17733. if (this._onCollisionPositionChangeObserver) {
  17734. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17735. }
  17736. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17737. },
  17738. enumerable: true,
  17739. configurable: true
  17740. });
  17741. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17742. /**
  17743. * 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.
  17744. */
  17745. get: function () {
  17746. return this._isOccluded;
  17747. },
  17748. set: function (value) {
  17749. this._isOccluded = value;
  17750. },
  17751. enumerable: true,
  17752. configurable: true
  17753. });
  17754. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17755. /**
  17756. * Flag to check the progress status of the query
  17757. */
  17758. get: function () {
  17759. return this._isOcclusionQueryInProgress;
  17760. },
  17761. enumerable: true,
  17762. configurable: true
  17763. });
  17764. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17765. /**
  17766. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17767. */
  17768. get: function () {
  17769. return this._visibility;
  17770. },
  17771. /**
  17772. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17773. */
  17774. set: function (value) {
  17775. if (this._visibility === value) {
  17776. return;
  17777. }
  17778. this._visibility = value;
  17779. this._markSubMeshesAsMiscDirty();
  17780. },
  17781. enumerable: true,
  17782. configurable: true
  17783. });
  17784. Object.defineProperty(AbstractMesh.prototype, "material", {
  17785. get: function () {
  17786. return this._material;
  17787. },
  17788. set: function (value) {
  17789. if (this._material === value) {
  17790. return;
  17791. }
  17792. this._material = value;
  17793. if (this.onMaterialChangedObservable.hasObservers) {
  17794. this.onMaterialChangedObservable.notifyObservers(this);
  17795. }
  17796. if (!this.subMeshes) {
  17797. return;
  17798. }
  17799. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17800. var subMesh = _a[_i];
  17801. subMesh.setEffect(null);
  17802. }
  17803. },
  17804. enumerable: true,
  17805. configurable: true
  17806. });
  17807. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17808. get: function () {
  17809. return this._receiveShadows;
  17810. },
  17811. set: function (value) {
  17812. if (this._receiveShadows === value) {
  17813. return;
  17814. }
  17815. this._receiveShadows = value;
  17816. this._markSubMeshesAsLightDirty();
  17817. },
  17818. enumerable: true,
  17819. configurable: true
  17820. });
  17821. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17822. get: function () {
  17823. return this._hasVertexAlpha;
  17824. },
  17825. set: function (value) {
  17826. if (this._hasVertexAlpha === value) {
  17827. return;
  17828. }
  17829. this._hasVertexAlpha = value;
  17830. this._markSubMeshesAsAttributesDirty();
  17831. this._markSubMeshesAsMiscDirty();
  17832. },
  17833. enumerable: true,
  17834. configurable: true
  17835. });
  17836. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17837. get: function () {
  17838. return this._useVertexColors;
  17839. },
  17840. set: function (value) {
  17841. if (this._useVertexColors === value) {
  17842. return;
  17843. }
  17844. this._useVertexColors = value;
  17845. this._markSubMeshesAsAttributesDirty();
  17846. },
  17847. enumerable: true,
  17848. configurable: true
  17849. });
  17850. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17851. get: function () {
  17852. return this._computeBonesUsingShaders;
  17853. },
  17854. set: function (value) {
  17855. if (this._computeBonesUsingShaders === value) {
  17856. return;
  17857. }
  17858. this._computeBonesUsingShaders = value;
  17859. this._markSubMeshesAsAttributesDirty();
  17860. },
  17861. enumerable: true,
  17862. configurable: true
  17863. });
  17864. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17865. get: function () {
  17866. return this._numBoneInfluencers;
  17867. },
  17868. set: function (value) {
  17869. if (this._numBoneInfluencers === value) {
  17870. return;
  17871. }
  17872. this._numBoneInfluencers = value;
  17873. this._markSubMeshesAsAttributesDirty();
  17874. },
  17875. enumerable: true,
  17876. configurable: true
  17877. });
  17878. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17879. get: function () {
  17880. return this._applyFog;
  17881. },
  17882. set: function (value) {
  17883. if (this._applyFog === value) {
  17884. return;
  17885. }
  17886. this._applyFog = value;
  17887. this._markSubMeshesAsMiscDirty();
  17888. },
  17889. enumerable: true,
  17890. configurable: true
  17891. });
  17892. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17893. get: function () {
  17894. return this._layerMask;
  17895. },
  17896. set: function (value) {
  17897. if (value === this._layerMask) {
  17898. return;
  17899. }
  17900. this._layerMask = value;
  17901. this._resyncLightSources();
  17902. },
  17903. enumerable: true,
  17904. configurable: true
  17905. });
  17906. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17907. get: function () {
  17908. return this._collisionMask;
  17909. },
  17910. set: function (mask) {
  17911. this._collisionMask = !isNaN(mask) ? mask : -1;
  17912. },
  17913. enumerable: true,
  17914. configurable: true
  17915. });
  17916. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17917. get: function () {
  17918. return this._collisionGroup;
  17919. },
  17920. set: function (mask) {
  17921. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17922. },
  17923. enumerable: true,
  17924. configurable: true
  17925. });
  17926. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17927. get: function () {
  17928. return null;
  17929. },
  17930. enumerable: true,
  17931. configurable: true
  17932. });
  17933. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17934. get: function () {
  17935. return this._skeleton;
  17936. },
  17937. set: function (value) {
  17938. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17939. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17940. }
  17941. if (value && value.needInitialSkinMatrix) {
  17942. value._registerMeshWithPoseMatrix(this);
  17943. }
  17944. this._skeleton = value;
  17945. if (!this._skeleton) {
  17946. this._bonesTransformMatrices = null;
  17947. }
  17948. this._markSubMeshesAsAttributesDirty();
  17949. },
  17950. enumerable: true,
  17951. configurable: true
  17952. });
  17953. /**
  17954. * Returns the string "AbstractMesh"
  17955. */
  17956. AbstractMesh.prototype.getClassName = function () {
  17957. return "AbstractMesh";
  17958. };
  17959. /**
  17960. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17961. */
  17962. AbstractMesh.prototype.toString = function (fullDetails) {
  17963. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17964. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17965. if (this._skeleton) {
  17966. ret += ", skeleton: " + this._skeleton.name;
  17967. }
  17968. if (fullDetails) {
  17969. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17970. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17971. }
  17972. return ret;
  17973. };
  17974. AbstractMesh.prototype._rebuild = function () {
  17975. if (this._occlusionQuery) {
  17976. this._occlusionQuery = null;
  17977. }
  17978. if (this._edgesRenderer) {
  17979. this._edgesRenderer._rebuild();
  17980. }
  17981. if (!this.subMeshes) {
  17982. return;
  17983. }
  17984. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17985. var subMesh = _a[_i];
  17986. subMesh._rebuild();
  17987. }
  17988. };
  17989. AbstractMesh.prototype._resyncLightSources = function () {
  17990. this._lightSources.length = 0;
  17991. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17992. var light = _a[_i];
  17993. if (!light.isEnabled()) {
  17994. continue;
  17995. }
  17996. if (light.canAffectMesh(this)) {
  17997. this._lightSources.push(light);
  17998. }
  17999. }
  18000. this._markSubMeshesAsLightDirty();
  18001. };
  18002. AbstractMesh.prototype._resyncLighSource = function (light) {
  18003. var isIn = light.isEnabled() && light.canAffectMesh(this);
  18004. var index = this._lightSources.indexOf(light);
  18005. if (index === -1) {
  18006. if (!isIn) {
  18007. return;
  18008. }
  18009. this._lightSources.push(light);
  18010. }
  18011. else {
  18012. if (isIn) {
  18013. return;
  18014. }
  18015. this._lightSources.splice(index, 1);
  18016. }
  18017. this._markSubMeshesAsLightDirty();
  18018. };
  18019. AbstractMesh.prototype._removeLightSource = function (light) {
  18020. var index = this._lightSources.indexOf(light);
  18021. if (index === -1) {
  18022. return;
  18023. }
  18024. this._lightSources.splice(index, 1);
  18025. this._markSubMeshesAsLightDirty();
  18026. };
  18027. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18028. if (!this.subMeshes) {
  18029. return;
  18030. }
  18031. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18032. var subMesh = _a[_i];
  18033. if (subMesh._materialDefines) {
  18034. func(subMesh._materialDefines);
  18035. }
  18036. }
  18037. };
  18038. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18039. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18040. };
  18041. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18042. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18043. };
  18044. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18045. if (!this.subMeshes) {
  18046. return;
  18047. }
  18048. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18049. var subMesh = _a[_i];
  18050. var material = subMesh.getMaterial();
  18051. if (material) {
  18052. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18053. }
  18054. }
  18055. };
  18056. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18057. /**
  18058. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18059. * Default : (1.0, 1.0, 1.0)
  18060. */
  18061. get: function () {
  18062. return this._scaling;
  18063. },
  18064. /**
  18065. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18066. * Default : (1.0, 1.0, 1.0)
  18067. */
  18068. set: function (newScaling) {
  18069. this._scaling = newScaling;
  18070. if (this.physicsImpostor) {
  18071. this.physicsImpostor.forceUpdate();
  18072. }
  18073. },
  18074. enumerable: true,
  18075. configurable: true
  18076. });
  18077. // Methods
  18078. /**
  18079. * Disables the mesh edger rendering mode.
  18080. * Returns the AbstractMesh.
  18081. */
  18082. AbstractMesh.prototype.disableEdgesRendering = function () {
  18083. if (this._edgesRenderer) {
  18084. this._edgesRenderer.dispose();
  18085. this._edgesRenderer = null;
  18086. }
  18087. return this;
  18088. };
  18089. /**
  18090. * Enables the edge rendering mode on the mesh.
  18091. * This mode makes the mesh edges visible.
  18092. * Returns the AbstractMesh.
  18093. */
  18094. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18095. if (epsilon === void 0) { epsilon = 0.95; }
  18096. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18097. this.disableEdgesRendering();
  18098. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18099. return this;
  18100. };
  18101. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18102. /**
  18103. * Returns true if the mesh is blocked. Used by the class Mesh.
  18104. * Returns the boolean `false` by default.
  18105. */
  18106. get: function () {
  18107. return false;
  18108. },
  18109. enumerable: true,
  18110. configurable: true
  18111. });
  18112. /**
  18113. * Returns the mesh itself by default, used by the class Mesh.
  18114. * Returned type : AbstractMesh
  18115. */
  18116. AbstractMesh.prototype.getLOD = function (camera) {
  18117. return this;
  18118. };
  18119. /**
  18120. * Returns 0 by default, used by the class Mesh.
  18121. * Returns an integer.
  18122. */
  18123. AbstractMesh.prototype.getTotalVertices = function () {
  18124. return 0;
  18125. };
  18126. /**
  18127. * Returns null by default, used by the class Mesh.
  18128. * Returned type : integer array
  18129. */
  18130. AbstractMesh.prototype.getIndices = function () {
  18131. return null;
  18132. };
  18133. /**
  18134. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18135. * Returned type : float array or Float32Array
  18136. */
  18137. AbstractMesh.prototype.getVerticesData = function (kind) {
  18138. return null;
  18139. };
  18140. /**
  18141. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18142. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18143. * The `data` are either a numeric array either a Float32Array.
  18144. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18145. * 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).
  18146. * Note that a new underlying VertexBuffer object is created each call.
  18147. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18148. *
  18149. * Possible `kind` values :
  18150. * - BABYLON.VertexBuffer.PositionKind
  18151. * - BABYLON.VertexBuffer.UVKind
  18152. * - BABYLON.VertexBuffer.UV2Kind
  18153. * - BABYLON.VertexBuffer.UV3Kind
  18154. * - BABYLON.VertexBuffer.UV4Kind
  18155. * - BABYLON.VertexBuffer.UV5Kind
  18156. * - BABYLON.VertexBuffer.UV6Kind
  18157. * - BABYLON.VertexBuffer.ColorKind
  18158. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18159. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18160. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18161. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18162. *
  18163. * Returns the Mesh.
  18164. */
  18165. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18166. return this;
  18167. };
  18168. /**
  18169. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18170. * If the mesh has no geometry, it is simply returned as it is.
  18171. * The `data` are either a numeric array either a Float32Array.
  18172. * No new underlying VertexBuffer object is created.
  18173. * 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.
  18174. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18175. *
  18176. * Possible `kind` values :
  18177. * - BABYLON.VertexBuffer.PositionKind
  18178. * - BABYLON.VertexBuffer.UVKind
  18179. * - BABYLON.VertexBuffer.UV2Kind
  18180. * - BABYLON.VertexBuffer.UV3Kind
  18181. * - BABYLON.VertexBuffer.UV4Kind
  18182. * - BABYLON.VertexBuffer.UV5Kind
  18183. * - BABYLON.VertexBuffer.UV6Kind
  18184. * - BABYLON.VertexBuffer.ColorKind
  18185. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18186. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18187. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18188. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18189. *
  18190. * Returns the Mesh.
  18191. */
  18192. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18193. return this;
  18194. };
  18195. /**
  18196. * Sets the mesh indices.
  18197. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18198. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18199. * This method creates a new index buffer each call.
  18200. * Returns the Mesh.
  18201. */
  18202. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18203. return this;
  18204. };
  18205. /** Returns false by default, used by the class Mesh.
  18206. * Returns a boolean
  18207. */
  18208. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18209. return false;
  18210. };
  18211. /**
  18212. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18213. * Returns a BoundingInfo
  18214. */
  18215. AbstractMesh.prototype.getBoundingInfo = function () {
  18216. if (this._masterMesh) {
  18217. return this._masterMesh.getBoundingInfo();
  18218. }
  18219. if (!this._boundingInfo) {
  18220. // this._boundingInfo is being created here
  18221. this._updateBoundingInfo();
  18222. }
  18223. // cannot be null.
  18224. return this._boundingInfo;
  18225. };
  18226. /**
  18227. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18228. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18229. */
  18230. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18231. if (includeDescendants === void 0) { includeDescendants = true; }
  18232. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18233. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18234. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18235. if (maxDimension === 0) {
  18236. return this;
  18237. }
  18238. var scale = 1 / maxDimension;
  18239. this.scaling.scaleInPlace(scale);
  18240. return this;
  18241. };
  18242. /**
  18243. * Sets a mesh new object BoundingInfo.
  18244. * Returns the AbstractMesh.
  18245. */
  18246. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18247. this._boundingInfo = boundingInfo;
  18248. return this;
  18249. };
  18250. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18251. get: function () {
  18252. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18253. },
  18254. enumerable: true,
  18255. configurable: true
  18256. });
  18257. AbstractMesh.prototype._preActivate = function () {
  18258. };
  18259. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18260. };
  18261. AbstractMesh.prototype._activate = function (renderId) {
  18262. this._renderId = renderId;
  18263. };
  18264. /**
  18265. * Returns the latest update of the World matrix
  18266. * Returns a Matrix.
  18267. */
  18268. AbstractMesh.prototype.getWorldMatrix = function () {
  18269. if (this._masterMesh) {
  18270. return this._masterMesh.getWorldMatrix();
  18271. }
  18272. return _super.prototype.getWorldMatrix.call(this);
  18273. };
  18274. /**
  18275. * Returns the latest update of the World matrix determinant.
  18276. */
  18277. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18278. if (this._masterMesh) {
  18279. return this._masterMesh._getWorldMatrixDeterminant();
  18280. }
  18281. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18282. };
  18283. // ================================== Point of View Movement =================================
  18284. /**
  18285. * Perform relative position change from the point of view of behind the front of the mesh.
  18286. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18287. * Supports definition of mesh facing forward or backward.
  18288. * @param {number} amountRight
  18289. * @param {number} amountUp
  18290. * @param {number} amountForward
  18291. *
  18292. * Returns the AbstractMesh.
  18293. */
  18294. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18295. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18296. return this;
  18297. };
  18298. /**
  18299. * Calculate relative position change from the point of view of behind the front of the mesh.
  18300. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18301. * Supports definition of mesh facing forward or backward.
  18302. * @param {number} amountRight
  18303. * @param {number} amountUp
  18304. * @param {number} amountForward
  18305. *
  18306. * Returns a new Vector3.
  18307. */
  18308. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18309. var rotMatrix = new BABYLON.Matrix();
  18310. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18311. rotQuaternion.toRotationMatrix(rotMatrix);
  18312. var translationDelta = BABYLON.Vector3.Zero();
  18313. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18314. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18315. return translationDelta;
  18316. };
  18317. // ================================== Point of View Rotation =================================
  18318. /**
  18319. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18320. * Supports definition of mesh facing forward or backward.
  18321. * @param {number} flipBack
  18322. * @param {number} twirlClockwise
  18323. * @param {number} tiltRight
  18324. *
  18325. * Returns the AbstractMesh.
  18326. */
  18327. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18328. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18329. return this;
  18330. };
  18331. /**
  18332. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18333. * Supports definition of mesh facing forward or backward.
  18334. * @param {number} flipBack
  18335. * @param {number} twirlClockwise
  18336. * @param {number} tiltRight
  18337. *
  18338. * Returns a new Vector3.
  18339. */
  18340. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18341. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18342. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18343. };
  18344. /**
  18345. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18346. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18347. */
  18348. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18349. if (includeDescendants === void 0) { includeDescendants = true; }
  18350. this.computeWorldMatrix(true);
  18351. var min;
  18352. var max;
  18353. var boundingInfo = this.getBoundingInfo();
  18354. if (!this.subMeshes) {
  18355. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18356. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18357. }
  18358. else {
  18359. min = boundingInfo.boundingBox.minimumWorld;
  18360. max = boundingInfo.boundingBox.maximumWorld;
  18361. }
  18362. if (includeDescendants) {
  18363. var descendants = this.getDescendants(false);
  18364. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18365. var descendant = descendants_1[_i];
  18366. var childMesh = descendant;
  18367. childMesh.computeWorldMatrix(true);
  18368. //make sure we have the needed params to get mix and max
  18369. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18370. continue;
  18371. }
  18372. var childBoundingInfo = childMesh.getBoundingInfo();
  18373. var boundingBox = childBoundingInfo.boundingBox;
  18374. var minBox = boundingBox.minimumWorld;
  18375. var maxBox = boundingBox.maximumWorld;
  18376. BABYLON.Tools.CheckExtends(minBox, min, max);
  18377. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18378. }
  18379. }
  18380. return {
  18381. min: min,
  18382. max: max
  18383. };
  18384. };
  18385. /**
  18386. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18387. * Returns the AbstractMesh.
  18388. */
  18389. AbstractMesh.prototype._updateBoundingInfo = function () {
  18390. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18391. this._boundingInfo.update(this.worldMatrixFromCache);
  18392. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18393. return this;
  18394. };
  18395. /**
  18396. * Update a mesh's children BoundingInfo objects only.
  18397. * Returns the AbstractMesh.
  18398. */
  18399. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18400. if (!this.subMeshes) {
  18401. return this;
  18402. }
  18403. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18404. var subMesh = this.subMeshes[subIndex];
  18405. if (!subMesh.IsGlobal) {
  18406. subMesh.updateBoundingInfo(matrix);
  18407. }
  18408. }
  18409. return this;
  18410. };
  18411. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18412. // Bounding info
  18413. this._updateBoundingInfo();
  18414. };
  18415. /**
  18416. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18417. * A mesh is in the frustum if its bounding box intersects the frustum.
  18418. * Boolean returned.
  18419. */
  18420. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18421. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18422. };
  18423. /**
  18424. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18425. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18426. * Boolean returned.
  18427. */
  18428. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18429. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18430. ;
  18431. };
  18432. /**
  18433. * True if the mesh intersects another mesh or a SolidParticle object.
  18434. * 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)
  18435. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18436. * Returns a boolean.
  18437. */
  18438. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18439. if (precise === void 0) { precise = false; }
  18440. if (!this._boundingInfo || !mesh._boundingInfo) {
  18441. return false;
  18442. }
  18443. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18444. return true;
  18445. }
  18446. if (includeDescendants) {
  18447. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18448. var child = _a[_i];
  18449. if (child.intersectsMesh(mesh, precise, true)) {
  18450. return true;
  18451. }
  18452. }
  18453. }
  18454. return false;
  18455. };
  18456. /**
  18457. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18458. * Returns a boolean.
  18459. */
  18460. AbstractMesh.prototype.intersectsPoint = function (point) {
  18461. if (!this._boundingInfo) {
  18462. return false;
  18463. }
  18464. return this._boundingInfo.intersectsPoint(point);
  18465. };
  18466. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18467. return this.physicsImpostor;
  18468. };
  18469. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18470. if (camera === void 0) { camera = null; }
  18471. if (!camera) {
  18472. camera = this.getScene().activeCamera;
  18473. }
  18474. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18475. };
  18476. /**
  18477. * Returns the distance from the mesh to the active camera.
  18478. * Returns a float.
  18479. */
  18480. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18481. if (camera === void 0) { camera = null; }
  18482. if (!camera) {
  18483. camera = this.getScene().activeCamera;
  18484. }
  18485. return this.absolutePosition.subtract(camera.position).length();
  18486. };
  18487. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18488. if (!this.physicsImpostor) {
  18489. return this;
  18490. }
  18491. this.physicsImpostor.applyImpulse(force, contactPoint);
  18492. return this;
  18493. };
  18494. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18495. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18496. return this;
  18497. }
  18498. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18499. mainPivot: pivot1,
  18500. connectedPivot: pivot2,
  18501. nativeParams: options
  18502. });
  18503. return this;
  18504. };
  18505. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18506. // Collisions
  18507. /**
  18508. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18509. * Default `false`.
  18510. */
  18511. get: function () {
  18512. return this._checkCollisions;
  18513. },
  18514. set: function (collisionEnabled) {
  18515. this._checkCollisions = collisionEnabled;
  18516. if (this.getScene().workerCollisions) {
  18517. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18518. }
  18519. },
  18520. enumerable: true,
  18521. configurable: true
  18522. });
  18523. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18524. /**
  18525. * Gets Collider object used to compute collisions (not physics)
  18526. */
  18527. get: function () {
  18528. return this._collider;
  18529. },
  18530. enumerable: true,
  18531. configurable: true
  18532. });
  18533. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18534. var globalPosition = this.getAbsolutePosition();
  18535. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18536. if (!this._collider) {
  18537. this._collider = new BABYLON.Collider();
  18538. }
  18539. this._collider._radius = this.ellipsoid;
  18540. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18541. return this;
  18542. };
  18543. // Submeshes octree
  18544. /**
  18545. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18546. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18547. * Returns an Octree of submeshes.
  18548. */
  18549. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18550. if (maxCapacity === void 0) { maxCapacity = 64; }
  18551. if (maxDepth === void 0) { maxDepth = 2; }
  18552. if (!this._submeshesOctree) {
  18553. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18554. }
  18555. this.computeWorldMatrix(true);
  18556. var boundingInfo = this.getBoundingInfo();
  18557. // Update octree
  18558. var bbox = boundingInfo.boundingBox;
  18559. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18560. return this._submeshesOctree;
  18561. };
  18562. // Collisions
  18563. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18564. this._generatePointsArray();
  18565. if (!this._positions) {
  18566. return this;
  18567. }
  18568. // Transformation
  18569. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18570. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18571. subMesh._lastColliderWorldVertices = [];
  18572. subMesh._trianglePlanes = [];
  18573. var start = subMesh.verticesStart;
  18574. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18575. for (var i = start; i < end; i++) {
  18576. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18577. }
  18578. }
  18579. // Collide
  18580. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18581. if (collider.collisionFound) {
  18582. collider.collidedMesh = this;
  18583. }
  18584. return this;
  18585. };
  18586. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18587. var subMeshes;
  18588. var len;
  18589. // Octrees
  18590. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18591. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18592. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18593. len = intersections.length;
  18594. subMeshes = intersections.data;
  18595. }
  18596. else {
  18597. subMeshes = this.subMeshes;
  18598. len = subMeshes.length;
  18599. }
  18600. for (var index = 0; index < len; index++) {
  18601. var subMesh = subMeshes[index];
  18602. // Bounding test
  18603. if (len > 1 && !subMesh._checkCollision(collider))
  18604. continue;
  18605. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18606. }
  18607. return this;
  18608. };
  18609. AbstractMesh.prototype._checkCollision = function (collider) {
  18610. // Bounding box test
  18611. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18612. return this;
  18613. // Transformation matrix
  18614. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18615. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18616. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18617. return this;
  18618. };
  18619. // Picking
  18620. AbstractMesh.prototype._generatePointsArray = function () {
  18621. return false;
  18622. };
  18623. /**
  18624. * Checks if the passed Ray intersects with the mesh.
  18625. * Returns an object PickingInfo.
  18626. */
  18627. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18628. var pickingInfo = new BABYLON.PickingInfo();
  18629. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18630. return pickingInfo;
  18631. }
  18632. if (!this._generatePointsArray()) {
  18633. return pickingInfo;
  18634. }
  18635. var intersectInfo = null;
  18636. // Octrees
  18637. var subMeshes;
  18638. var len;
  18639. if (this._submeshesOctree && this.useOctreeForPicking) {
  18640. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18641. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18642. len = intersections.length;
  18643. subMeshes = intersections.data;
  18644. }
  18645. else {
  18646. subMeshes = this.subMeshes;
  18647. len = subMeshes.length;
  18648. }
  18649. for (var index = 0; index < len; index++) {
  18650. var subMesh = subMeshes[index];
  18651. // Bounding test
  18652. if (len > 1 && !subMesh.canIntersects(ray))
  18653. continue;
  18654. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18655. if (currentIntersectInfo) {
  18656. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18657. intersectInfo = currentIntersectInfo;
  18658. intersectInfo.subMeshId = index;
  18659. if (fastCheck) {
  18660. break;
  18661. }
  18662. }
  18663. }
  18664. }
  18665. if (intersectInfo) {
  18666. // Get picked point
  18667. var world = this.getWorldMatrix();
  18668. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18669. var direction = ray.direction.clone();
  18670. direction = direction.scale(intersectInfo.distance);
  18671. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18672. var pickedPoint = worldOrigin.add(worldDirection);
  18673. // Return result
  18674. pickingInfo.hit = true;
  18675. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18676. pickingInfo.pickedPoint = pickedPoint;
  18677. pickingInfo.pickedMesh = this;
  18678. pickingInfo.bu = intersectInfo.bu || 0;
  18679. pickingInfo.bv = intersectInfo.bv || 0;
  18680. pickingInfo.faceId = intersectInfo.faceId;
  18681. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18682. return pickingInfo;
  18683. }
  18684. return pickingInfo;
  18685. };
  18686. /**
  18687. * Clones the mesh, used by the class Mesh.
  18688. * Just returns `null` for an AbstractMesh.
  18689. */
  18690. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18691. return null;
  18692. };
  18693. /**
  18694. * Disposes all the mesh submeshes.
  18695. * Returns the AbstractMesh.
  18696. */
  18697. AbstractMesh.prototype.releaseSubMeshes = function () {
  18698. if (this.subMeshes) {
  18699. while (this.subMeshes.length) {
  18700. this.subMeshes[0].dispose();
  18701. }
  18702. }
  18703. else {
  18704. this.subMeshes = new Array();
  18705. }
  18706. return this;
  18707. };
  18708. /**
  18709. * Releases resources associated with this abstract mesh.
  18710. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18711. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18712. */
  18713. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18714. var _this = this;
  18715. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18716. var index;
  18717. // Smart Array Retainers.
  18718. this.getScene().freeActiveMeshes();
  18719. this.getScene().freeRenderingGroups();
  18720. // Action manager
  18721. if (this.actionManager !== undefined && this.actionManager !== null) {
  18722. this.actionManager.dispose();
  18723. this.actionManager = null;
  18724. }
  18725. // Skeleton
  18726. this._skeleton = null;
  18727. // Physics
  18728. if (this.physicsImpostor) {
  18729. this.physicsImpostor.dispose();
  18730. }
  18731. // Intersections in progress
  18732. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18733. var other = this._intersectionsInProgress[index];
  18734. var pos = other._intersectionsInProgress.indexOf(this);
  18735. other._intersectionsInProgress.splice(pos, 1);
  18736. }
  18737. this._intersectionsInProgress = [];
  18738. // Lights
  18739. var lights = this.getScene().lights;
  18740. lights.forEach(function (light) {
  18741. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18742. if (meshIndex !== -1) {
  18743. light.includedOnlyMeshes.splice(meshIndex, 1);
  18744. }
  18745. meshIndex = light.excludedMeshes.indexOf(_this);
  18746. if (meshIndex !== -1) {
  18747. light.excludedMeshes.splice(meshIndex, 1);
  18748. }
  18749. // Shadow generators
  18750. var generator = light.getShadowGenerator();
  18751. if (generator) {
  18752. var shadowMap = generator.getShadowMap();
  18753. if (shadowMap && shadowMap.renderList) {
  18754. meshIndex = shadowMap.renderList.indexOf(_this);
  18755. if (meshIndex !== -1) {
  18756. shadowMap.renderList.splice(meshIndex, 1);
  18757. }
  18758. }
  18759. }
  18760. });
  18761. // Edges
  18762. if (this._edgesRenderer) {
  18763. this._edgesRenderer.dispose();
  18764. this._edgesRenderer = null;
  18765. }
  18766. // SubMeshes
  18767. if (this.getClassName() !== "InstancedMesh") {
  18768. this.releaseSubMeshes();
  18769. }
  18770. // Octree
  18771. var sceneOctree = this.getScene().selectionOctree;
  18772. if (sceneOctree !== undefined && sceneOctree !== null) {
  18773. var index = sceneOctree.dynamicContent.indexOf(this);
  18774. if (index !== -1) {
  18775. sceneOctree.dynamicContent.splice(index, 1);
  18776. }
  18777. }
  18778. // Query
  18779. var engine = this.getScene().getEngine();
  18780. if (this._occlusionQuery) {
  18781. this._isOcclusionQueryInProgress = false;
  18782. engine.deleteQuery(this._occlusionQuery);
  18783. this._occlusionQuery = null;
  18784. }
  18785. // Engine
  18786. engine.wipeCaches();
  18787. // Remove from scene
  18788. this.getScene().removeMesh(this);
  18789. if (disposeMaterialAndTextures) {
  18790. if (this.material) {
  18791. this.material.dispose(false, true);
  18792. }
  18793. }
  18794. if (!doNotRecurse) {
  18795. // Particles
  18796. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18797. if (this.getScene().particleSystems[index].emitter === this) {
  18798. this.getScene().particleSystems[index].dispose();
  18799. index--;
  18800. }
  18801. }
  18802. }
  18803. // facet data
  18804. if (this._facetDataEnabled) {
  18805. this.disableFacetData();
  18806. }
  18807. this.onAfterWorldMatrixUpdateObservable.clear();
  18808. this.onCollideObservable.clear();
  18809. this.onCollisionPositionChangeObservable.clear();
  18810. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18811. };
  18812. /**
  18813. * Adds the passed mesh as a child to the current mesh.
  18814. * Returns the AbstractMesh.
  18815. */
  18816. AbstractMesh.prototype.addChild = function (mesh) {
  18817. mesh.setParent(this);
  18818. return this;
  18819. };
  18820. /**
  18821. * Removes the passed mesh from the current mesh children list.
  18822. * Returns the AbstractMesh.
  18823. */
  18824. AbstractMesh.prototype.removeChild = function (mesh) {
  18825. mesh.setParent(null);
  18826. return this;
  18827. };
  18828. // Facet data
  18829. /**
  18830. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18831. * Returns the AbstractMesh.
  18832. */
  18833. AbstractMesh.prototype._initFacetData = function () {
  18834. if (!this._facetNormals) {
  18835. this._facetNormals = new Array();
  18836. }
  18837. if (!this._facetPositions) {
  18838. this._facetPositions = new Array();
  18839. }
  18840. if (!this._facetPartitioning) {
  18841. this._facetPartitioning = new Array();
  18842. }
  18843. this._facetNb = (this.getIndices().length / 3) | 0;
  18844. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18845. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18846. for (var f = 0; f < this._facetNb; f++) {
  18847. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18848. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18849. }
  18850. this._facetDataEnabled = true;
  18851. return this;
  18852. };
  18853. /**
  18854. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18855. * This method can be called within the render loop.
  18856. * 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.
  18857. * Returns the AbstractMesh.
  18858. */
  18859. AbstractMesh.prototype.updateFacetData = function () {
  18860. if (!this._facetDataEnabled) {
  18861. this._initFacetData();
  18862. }
  18863. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18864. var indices = this.getIndices();
  18865. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18866. var bInfo = this.getBoundingInfo();
  18867. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18868. // init arrays, matrix and sort function on first call
  18869. this._facetDepthSortEnabled = true;
  18870. if (indices instanceof Uint16Array) {
  18871. this._depthSortedIndices = new Uint16Array(indices);
  18872. }
  18873. else if (indices instanceof Uint32Array) {
  18874. this._depthSortedIndices = new Uint32Array(indices);
  18875. }
  18876. else {
  18877. var needs32bits = false;
  18878. for (var i = 0; i < indices.length; i++) {
  18879. if (indices[i] > 65535) {
  18880. needs32bits = true;
  18881. break;
  18882. }
  18883. }
  18884. if (needs32bits) {
  18885. this._depthSortedIndices = new Uint32Array(indices);
  18886. }
  18887. else {
  18888. this._depthSortedIndices = new Uint16Array(indices);
  18889. }
  18890. }
  18891. this._facetDepthSortFunction = function (f1, f2) {
  18892. return (f2.sqDistance - f1.sqDistance);
  18893. };
  18894. if (!this._facetDepthSortFrom) {
  18895. var camera = this.getScene().activeCamera;
  18896. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18897. }
  18898. this._depthSortedFacets = [];
  18899. for (var f = 0; f < this._facetNb; f++) {
  18900. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18901. this._depthSortedFacets.push(depthSortedFacet);
  18902. }
  18903. this._invertedMatrix = BABYLON.Matrix.Identity();
  18904. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18905. }
  18906. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18907. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18908. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18909. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18910. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18911. this._subDiv.max = this._partitioningSubdivisions;
  18912. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18913. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18914. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18915. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18916. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18917. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18918. // set the parameters for ComputeNormals()
  18919. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18920. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18921. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18922. this._facetParameters.bInfo = bInfo;
  18923. this._facetParameters.bbSize = this._bbSize;
  18924. this._facetParameters.subDiv = this._subDiv;
  18925. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18926. this._facetParameters.depthSort = this._facetDepthSort;
  18927. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18928. this.computeWorldMatrix(true);
  18929. this._worldMatrix.invertToRef(this._invertedMatrix);
  18930. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18931. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18932. }
  18933. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18934. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18935. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18936. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18937. var l = (this._depthSortedIndices.length / 3) | 0;
  18938. for (var f = 0; f < l; f++) {
  18939. var sind = this._depthSortedFacets[f].ind;
  18940. this._depthSortedIndices[f * 3] = indices[sind];
  18941. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18942. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18943. }
  18944. this.updateIndices(this._depthSortedIndices);
  18945. }
  18946. return this;
  18947. };
  18948. /**
  18949. * Returns the facetLocalNormals array.
  18950. * The normals are expressed in the mesh local space.
  18951. */
  18952. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18953. if (!this._facetNormals) {
  18954. this.updateFacetData();
  18955. }
  18956. return this._facetNormals;
  18957. };
  18958. /**
  18959. * Returns the facetLocalPositions array.
  18960. * The facet positions are expressed in the mesh local space.
  18961. */
  18962. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18963. if (!this._facetPositions) {
  18964. this.updateFacetData();
  18965. }
  18966. return this._facetPositions;
  18967. };
  18968. /**
  18969. * Returns the facetLocalPartioning array.
  18970. */
  18971. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18972. if (!this._facetPartitioning) {
  18973. this.updateFacetData();
  18974. }
  18975. return this._facetPartitioning;
  18976. };
  18977. /**
  18978. * Returns the i-th facet position in the world system.
  18979. * This method allocates a new Vector3 per call.
  18980. */
  18981. AbstractMesh.prototype.getFacetPosition = function (i) {
  18982. var pos = BABYLON.Vector3.Zero();
  18983. this.getFacetPositionToRef(i, pos);
  18984. return pos;
  18985. };
  18986. /**
  18987. * Sets the reference Vector3 with the i-th facet position in the world system.
  18988. * Returns the AbstractMesh.
  18989. */
  18990. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18991. var localPos = (this.getFacetLocalPositions())[i];
  18992. var world = this.getWorldMatrix();
  18993. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18994. return this;
  18995. };
  18996. /**
  18997. * Returns the i-th facet normal in the world system.
  18998. * This method allocates a new Vector3 per call.
  18999. */
  19000. AbstractMesh.prototype.getFacetNormal = function (i) {
  19001. var norm = BABYLON.Vector3.Zero();
  19002. this.getFacetNormalToRef(i, norm);
  19003. return norm;
  19004. };
  19005. /**
  19006. * Sets the reference Vector3 with the i-th facet normal in the world system.
  19007. * Returns the AbstractMesh.
  19008. */
  19009. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  19010. var localNorm = (this.getFacetLocalNormals())[i];
  19011. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19012. return this;
  19013. };
  19014. /**
  19015. * 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).
  19016. */
  19017. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19018. var bInfo = this.getBoundingInfo();
  19019. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19020. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19021. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19022. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19023. return null;
  19024. }
  19025. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19026. };
  19027. /**
  19028. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19029. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19030. * 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.
  19031. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19032. * 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.
  19033. */
  19034. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19035. if (checkFace === void 0) { checkFace = false; }
  19036. if (facing === void 0) { facing = true; }
  19037. var world = this.getWorldMatrix();
  19038. var invMat = BABYLON.Tmp.Matrix[5];
  19039. world.invertToRef(invMat);
  19040. var invVect = BABYLON.Tmp.Vector3[8];
  19041. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19042. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19043. if (projected) {
  19044. // tranform the local computed projected vector to world coordinates
  19045. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19046. }
  19047. return closest;
  19048. };
  19049. /**
  19050. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19051. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19052. * 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.
  19053. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19054. * 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.
  19055. */
  19056. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19057. if (checkFace === void 0) { checkFace = false; }
  19058. if (facing === void 0) { facing = true; }
  19059. var closest = null;
  19060. var tmpx = 0.0;
  19061. var tmpy = 0.0;
  19062. var tmpz = 0.0;
  19063. var d = 0.0; // tmp dot facet normal * facet position
  19064. var t0 = 0.0;
  19065. var projx = 0.0;
  19066. var projy = 0.0;
  19067. var projz = 0.0;
  19068. // Get all the facets in the same partitioning block than (x, y, z)
  19069. var facetPositions = this.getFacetLocalPositions();
  19070. var facetNormals = this.getFacetLocalNormals();
  19071. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19072. if (!facetsInBlock) {
  19073. return null;
  19074. }
  19075. // Get the closest facet to (x, y, z)
  19076. var shortest = Number.MAX_VALUE; // init distance vars
  19077. var tmpDistance = shortest;
  19078. var fib; // current facet in the block
  19079. var norm; // current facet normal
  19080. var p0; // current facet barycenter position
  19081. // loop on all the facets in the current partitioning block
  19082. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19083. fib = facetsInBlock[idx];
  19084. norm = facetNormals[fib];
  19085. p0 = facetPositions[fib];
  19086. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19087. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19088. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19089. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19090. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19091. projx = x + norm.x * t0;
  19092. projy = y + norm.y * t0;
  19093. projz = z + norm.z * t0;
  19094. tmpx = projx - x;
  19095. tmpy = projy - y;
  19096. tmpz = projz - z;
  19097. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19098. if (tmpDistance < shortest) {
  19099. shortest = tmpDistance;
  19100. closest = fib;
  19101. if (projected) {
  19102. projected.x = projx;
  19103. projected.y = projy;
  19104. projected.z = projz;
  19105. }
  19106. }
  19107. }
  19108. }
  19109. return closest;
  19110. };
  19111. /**
  19112. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19113. */
  19114. AbstractMesh.prototype.getFacetDataParameters = function () {
  19115. return this._facetParameters;
  19116. };
  19117. /**
  19118. * Disables the feature FacetData and frees the related memory.
  19119. * Returns the AbstractMesh.
  19120. */
  19121. AbstractMesh.prototype.disableFacetData = function () {
  19122. if (this._facetDataEnabled) {
  19123. this._facetDataEnabled = false;
  19124. this._facetPositions = new Array();
  19125. this._facetNormals = new Array();
  19126. this._facetPartitioning = new Array();
  19127. this._facetParameters = null;
  19128. this._depthSortedIndices = new Uint32Array(0);
  19129. }
  19130. return this;
  19131. };
  19132. /**
  19133. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19134. * Returns the mesh.
  19135. */
  19136. AbstractMesh.prototype.updateIndices = function (indices) {
  19137. return this;
  19138. };
  19139. /**
  19140. * The mesh Geometry. Actually used by the Mesh object.
  19141. * Returns a blank geometry object.
  19142. */
  19143. /**
  19144. * Creates new normals data for the mesh.
  19145. * @param updatable.
  19146. */
  19147. AbstractMesh.prototype.createNormals = function (updatable) {
  19148. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19149. var indices = this.getIndices();
  19150. var normals;
  19151. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19152. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19153. }
  19154. else {
  19155. normals = [];
  19156. }
  19157. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19158. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19159. };
  19160. /**
  19161. * Align the mesh with a normal.
  19162. * Returns the mesh.
  19163. */
  19164. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19165. if (!upDirection) {
  19166. upDirection = BABYLON.Axis.Y;
  19167. }
  19168. var axisX = BABYLON.Tmp.Vector3[0];
  19169. var axisZ = BABYLON.Tmp.Vector3[1];
  19170. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19171. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19172. if (this.rotationQuaternion) {
  19173. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19174. }
  19175. else {
  19176. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19177. }
  19178. return this;
  19179. };
  19180. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19181. var engine = this.getEngine();
  19182. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19183. this._isOccluded = false;
  19184. return;
  19185. }
  19186. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19187. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19188. if (isOcclusionQueryAvailable) {
  19189. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19190. this._isOcclusionQueryInProgress = false;
  19191. this._occlusionInternalRetryCounter = 0;
  19192. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19193. }
  19194. else {
  19195. this._occlusionInternalRetryCounter++;
  19196. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19197. this._isOcclusionQueryInProgress = false;
  19198. this._occlusionInternalRetryCounter = 0;
  19199. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19200. // if strict continue the last state of the object.
  19201. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19202. }
  19203. else {
  19204. return;
  19205. }
  19206. }
  19207. }
  19208. var scene = this.getScene();
  19209. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19210. if (!this._occlusionQuery) {
  19211. this._occlusionQuery = engine.createQuery();
  19212. }
  19213. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19214. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19215. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19216. this._isOcclusionQueryInProgress = true;
  19217. };
  19218. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19219. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19220. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19221. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19222. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19223. return AbstractMesh;
  19224. }(BABYLON.TransformNode));
  19225. BABYLON.AbstractMesh = AbstractMesh;
  19226. })(BABYLON || (BABYLON = {}));
  19227. //# sourceMappingURL=babylon.abstractMesh.js.map
  19228. "use strict";
  19229. var BABYLON;
  19230. (function (BABYLON) {
  19231. /**
  19232. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19233. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19234. * 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.
  19235. */
  19236. var Light = /** @class */ (function (_super) {
  19237. __extends(Light, _super);
  19238. /**
  19239. * Creates a Light object in the scene.
  19240. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19241. * @param name The firendly name of the light
  19242. * @param scene The scene the light belongs too
  19243. */
  19244. function Light(name, scene) {
  19245. var _this = _super.call(this, name, scene) || this;
  19246. /**
  19247. * Diffuse gives the basic color to an object.
  19248. */
  19249. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19250. /**
  19251. * Specular produces a highlight color on an object.
  19252. * Note: This is note affecting PBR materials.
  19253. */
  19254. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19255. /**
  19256. * Strength of the light.
  19257. * Note: By default it is define in the framework own unit.
  19258. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19259. */
  19260. _this.intensity = 1.0;
  19261. /**
  19262. * Defines how far from the source the light is impacting in scene units.
  19263. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19264. */
  19265. _this.range = Number.MAX_VALUE;
  19266. /**
  19267. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19268. * of light.
  19269. */
  19270. _this._photometricScale = 1.0;
  19271. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19272. _this._radius = 0.00001;
  19273. /**
  19274. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19275. * exceeding the number allowed of the materials.
  19276. */
  19277. _this.renderPriority = 0;
  19278. /**
  19279. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19280. * the current shadow generator.
  19281. */
  19282. _this.shadowEnabled = true;
  19283. _this._excludeWithLayerMask = 0;
  19284. _this._includeOnlyWithLayerMask = 0;
  19285. _this._lightmapMode = 0;
  19286. /**
  19287. * @ignore Internal use only.
  19288. */
  19289. _this._excludedMeshesIds = new Array();
  19290. /**
  19291. * @ignore Internal use only.
  19292. */
  19293. _this._includedOnlyMeshesIds = new Array();
  19294. _this.getScene().addLight(_this);
  19295. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19296. _this._buildUniformLayout();
  19297. _this.includedOnlyMeshes = new Array();
  19298. _this.excludedMeshes = new Array();
  19299. _this._resyncMeshes();
  19300. return _this;
  19301. }
  19302. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19303. /**
  19304. * If every light affecting the material is in this lightmapMode,
  19305. * material.lightmapTexture adds or multiplies
  19306. * (depends on material.useLightmapAsShadowmap)
  19307. * after every other light calculations.
  19308. */
  19309. get: function () {
  19310. return Light._LIGHTMAP_DEFAULT;
  19311. },
  19312. enumerable: true,
  19313. configurable: true
  19314. });
  19315. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19316. /**
  19317. * material.lightmapTexture as only diffuse lighting from this light
  19318. * adds only specular lighting from this light
  19319. * adds dynamic shadows
  19320. */
  19321. get: function () {
  19322. return Light._LIGHTMAP_SPECULAR;
  19323. },
  19324. enumerable: true,
  19325. configurable: true
  19326. });
  19327. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19328. /**
  19329. * material.lightmapTexture as only lighting
  19330. * no light calculation from this light
  19331. * only adds dynamic shadows from this light
  19332. */
  19333. get: function () {
  19334. return Light._LIGHTMAP_SHADOWSONLY;
  19335. },
  19336. enumerable: true,
  19337. configurable: true
  19338. });
  19339. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19340. /**
  19341. * Each light type uses the default quantity according to its type:
  19342. * point/spot lights use luminous intensity
  19343. * directional lights use illuminance
  19344. */
  19345. get: function () {
  19346. return Light._INTENSITYMODE_AUTOMATIC;
  19347. },
  19348. enumerable: true,
  19349. configurable: true
  19350. });
  19351. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19352. /**
  19353. * lumen (lm)
  19354. */
  19355. get: function () {
  19356. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19357. },
  19358. enumerable: true,
  19359. configurable: true
  19360. });
  19361. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19362. /**
  19363. * candela (lm/sr)
  19364. */
  19365. get: function () {
  19366. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19367. },
  19368. enumerable: true,
  19369. configurable: true
  19370. });
  19371. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19372. /**
  19373. * lux (lm/m^2)
  19374. */
  19375. get: function () {
  19376. return Light._INTENSITYMODE_ILLUMINANCE;
  19377. },
  19378. enumerable: true,
  19379. configurable: true
  19380. });
  19381. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19382. /**
  19383. * nit (cd/m^2)
  19384. */
  19385. get: function () {
  19386. return Light._INTENSITYMODE_LUMINANCE;
  19387. },
  19388. enumerable: true,
  19389. configurable: true
  19390. });
  19391. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19392. /**
  19393. * Light type const id of the point light.
  19394. */
  19395. get: function () {
  19396. return Light._LIGHTTYPEID_POINTLIGHT;
  19397. },
  19398. enumerable: true,
  19399. configurable: true
  19400. });
  19401. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19402. /**
  19403. * Light type const id of the directional light.
  19404. */
  19405. get: function () {
  19406. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19407. },
  19408. enumerable: true,
  19409. configurable: true
  19410. });
  19411. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19412. /**
  19413. * Light type const id of the spot light.
  19414. */
  19415. get: function () {
  19416. return Light._LIGHTTYPEID_SPOTLIGHT;
  19417. },
  19418. enumerable: true,
  19419. configurable: true
  19420. });
  19421. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19422. /**
  19423. * Light type const id of the hemispheric light.
  19424. */
  19425. get: function () {
  19426. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19427. },
  19428. enumerable: true,
  19429. configurable: true
  19430. });
  19431. Object.defineProperty(Light.prototype, "intensityMode", {
  19432. /**
  19433. * Gets the photometric scale used to interpret the intensity.
  19434. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19435. */
  19436. get: function () {
  19437. return this._intensityMode;
  19438. },
  19439. /**
  19440. * Sets the photometric scale used to interpret the intensity.
  19441. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19442. */
  19443. set: function (value) {
  19444. this._intensityMode = value;
  19445. this._computePhotometricScale();
  19446. },
  19447. enumerable: true,
  19448. configurable: true
  19449. });
  19450. ;
  19451. ;
  19452. Object.defineProperty(Light.prototype, "radius", {
  19453. /**
  19454. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19455. */
  19456. get: function () {
  19457. return this._radius;
  19458. },
  19459. /**
  19460. * sets the light radius used by PBR Materials to simulate soft area lights.
  19461. */
  19462. set: function (value) {
  19463. this._radius = value;
  19464. this._computePhotometricScale();
  19465. },
  19466. enumerable: true,
  19467. configurable: true
  19468. });
  19469. ;
  19470. ;
  19471. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19472. /**
  19473. * Gets the only meshes impacted by this light.
  19474. */
  19475. get: function () {
  19476. return this._includedOnlyMeshes;
  19477. },
  19478. /**
  19479. * Sets the only meshes impacted by this light.
  19480. */
  19481. set: function (value) {
  19482. this._includedOnlyMeshes = value;
  19483. this._hookArrayForIncludedOnly(value);
  19484. },
  19485. enumerable: true,
  19486. configurable: true
  19487. });
  19488. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19489. /**
  19490. * Gets the meshes not impacted by this light.
  19491. */
  19492. get: function () {
  19493. return this._excludedMeshes;
  19494. },
  19495. /**
  19496. * Sets the meshes not impacted by this light.
  19497. */
  19498. set: function (value) {
  19499. this._excludedMeshes = value;
  19500. this._hookArrayForExcluded(value);
  19501. },
  19502. enumerable: true,
  19503. configurable: true
  19504. });
  19505. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19506. /**
  19507. * Gets the layer id use to find what meshes are not impacted by the light.
  19508. * Inactive if 0
  19509. */
  19510. get: function () {
  19511. return this._excludeWithLayerMask;
  19512. },
  19513. /**
  19514. * Sets the layer id use to find what meshes are not impacted by the light.
  19515. * Inactive if 0
  19516. */
  19517. set: function (value) {
  19518. this._excludeWithLayerMask = value;
  19519. this._resyncMeshes();
  19520. },
  19521. enumerable: true,
  19522. configurable: true
  19523. });
  19524. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19525. /**
  19526. * Gets the layer id use to find what meshes are impacted by the light.
  19527. * Inactive if 0
  19528. */
  19529. get: function () {
  19530. return this._includeOnlyWithLayerMask;
  19531. },
  19532. /**
  19533. * Sets the layer id use to find what meshes are impacted by the light.
  19534. * Inactive if 0
  19535. */
  19536. set: function (value) {
  19537. this._includeOnlyWithLayerMask = value;
  19538. this._resyncMeshes();
  19539. },
  19540. enumerable: true,
  19541. configurable: true
  19542. });
  19543. Object.defineProperty(Light.prototype, "lightmapMode", {
  19544. /**
  19545. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19546. */
  19547. get: function () {
  19548. return this._lightmapMode;
  19549. },
  19550. /**
  19551. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19552. */
  19553. set: function (value) {
  19554. if (this._lightmapMode === value) {
  19555. return;
  19556. }
  19557. this._lightmapMode = value;
  19558. this._markMeshesAsLightDirty();
  19559. },
  19560. enumerable: true,
  19561. configurable: true
  19562. });
  19563. /**
  19564. * Returns the string "Light".
  19565. * @returns the class name
  19566. */
  19567. Light.prototype.getClassName = function () {
  19568. return "Light";
  19569. };
  19570. /**
  19571. * Converts the light information to a readable string for debug purpose.
  19572. * @param fullDetails Supports for multiple levels of logging within scene loading
  19573. * @returns the human readable light info
  19574. */
  19575. Light.prototype.toString = function (fullDetails) {
  19576. var ret = "Name: " + this.name;
  19577. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19578. if (this.animations) {
  19579. for (var i = 0; i < this.animations.length; i++) {
  19580. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19581. }
  19582. }
  19583. if (fullDetails) {
  19584. }
  19585. return ret;
  19586. };
  19587. /**
  19588. * Set the enabled state of this node.
  19589. * @param value - the new enabled state
  19590. * @see isEnabled
  19591. */
  19592. Light.prototype.setEnabled = function (value) {
  19593. _super.prototype.setEnabled.call(this, value);
  19594. this._resyncMeshes();
  19595. };
  19596. /**
  19597. * Returns the Light associated shadow generator if any.
  19598. * @return the associated shadow generator.
  19599. */
  19600. Light.prototype.getShadowGenerator = function () {
  19601. return this._shadowGenerator;
  19602. };
  19603. /**
  19604. * Returns a Vector3, the absolute light position in the World.
  19605. * @returns the world space position of the light
  19606. */
  19607. Light.prototype.getAbsolutePosition = function () {
  19608. return BABYLON.Vector3.Zero();
  19609. };
  19610. /**
  19611. * Specifies if the light will affect the passed mesh.
  19612. * @param mesh The mesh to test against the light
  19613. * @return true the mesh is affected otherwise, false.
  19614. */
  19615. Light.prototype.canAffectMesh = function (mesh) {
  19616. if (!mesh) {
  19617. return true;
  19618. }
  19619. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19620. return false;
  19621. }
  19622. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19623. return false;
  19624. }
  19625. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19626. return false;
  19627. }
  19628. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19629. return false;
  19630. }
  19631. return true;
  19632. };
  19633. /**
  19634. * Computes and Returns the light World matrix.
  19635. * @returns the world matrix
  19636. */
  19637. Light.prototype.getWorldMatrix = function () {
  19638. this._currentRenderId = this.getScene().getRenderId();
  19639. var worldMatrix = this._getWorldMatrix();
  19640. if (this.parent && this.parent.getWorldMatrix) {
  19641. if (!this._parentedWorldMatrix) {
  19642. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19643. }
  19644. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19645. this._markSyncedWithParent();
  19646. return this._parentedWorldMatrix;
  19647. }
  19648. return worldMatrix;
  19649. };
  19650. /**
  19651. * Sort function to order lights for rendering.
  19652. * @param a First Light object to compare to second.
  19653. * @param b Second Light object to compare first.
  19654. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19655. */
  19656. Light.CompareLightsPriority = function (a, b) {
  19657. //shadow-casting lights have priority over non-shadow-casting lights
  19658. //the renderPrioirty is a secondary sort criterion
  19659. if (a.shadowEnabled !== b.shadowEnabled) {
  19660. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19661. }
  19662. return b.renderPriority - a.renderPriority;
  19663. };
  19664. /**
  19665. * Releases resources associated with this node.
  19666. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19667. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19668. */
  19669. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19670. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19671. if (this._shadowGenerator) {
  19672. this._shadowGenerator.dispose();
  19673. this._shadowGenerator = null;
  19674. }
  19675. // Animations
  19676. this.getScene().stopAnimation(this);
  19677. // Remove from meshes
  19678. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19679. var mesh = _a[_i];
  19680. mesh._removeLightSource(this);
  19681. }
  19682. this._uniformBuffer.dispose();
  19683. // Remove from scene
  19684. this.getScene().removeLight(this);
  19685. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19686. };
  19687. /**
  19688. * Returns the light type ID (integer).
  19689. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19690. */
  19691. Light.prototype.getTypeID = function () {
  19692. return 0;
  19693. };
  19694. /**
  19695. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19696. * @returns the scaled intensity in intensity mode unit
  19697. */
  19698. Light.prototype.getScaledIntensity = function () {
  19699. return this._photometricScale * this.intensity;
  19700. };
  19701. /**
  19702. * Returns a new Light object, named "name", from the current one.
  19703. * @param name The name of the cloned light
  19704. * @returns the new created light
  19705. */
  19706. Light.prototype.clone = function (name) {
  19707. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19708. if (!constructor) {
  19709. return null;
  19710. }
  19711. return BABYLON.SerializationHelper.Clone(constructor, this);
  19712. };
  19713. /**
  19714. * Serializes the current light into a Serialization object.
  19715. * @returns the serialized object.
  19716. */
  19717. Light.prototype.serialize = function () {
  19718. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19719. // Type
  19720. serializationObject.type = this.getTypeID();
  19721. // Parent
  19722. if (this.parent) {
  19723. serializationObject.parentId = this.parent.id;
  19724. }
  19725. // Inclusion / exclusions
  19726. if (this.excludedMeshes.length > 0) {
  19727. serializationObject.excludedMeshesIds = [];
  19728. this.excludedMeshes.forEach(function (mesh) {
  19729. serializationObject.excludedMeshesIds.push(mesh.id);
  19730. });
  19731. }
  19732. if (this.includedOnlyMeshes.length > 0) {
  19733. serializationObject.includedOnlyMeshesIds = [];
  19734. this.includedOnlyMeshes.forEach(function (mesh) {
  19735. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19736. });
  19737. }
  19738. // Animations
  19739. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19740. serializationObject.ranges = this.serializeAnimationRanges();
  19741. return serializationObject;
  19742. };
  19743. /**
  19744. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19745. * This new light is named "name" and added to the passed scene.
  19746. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19747. * @param name The friendly name of the light
  19748. * @param scene The scene the new light will belong to
  19749. * @returns the constructor function
  19750. */
  19751. Light.GetConstructorFromName = function (type, name, scene) {
  19752. switch (type) {
  19753. case 0:
  19754. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19755. case 1:
  19756. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19757. case 2:
  19758. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19759. case 3:
  19760. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19761. }
  19762. return null;
  19763. };
  19764. /**
  19765. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19766. * @param parsedLight The JSON representation of the light
  19767. * @param scene The scene to create the parsed light in
  19768. * @returns the created light after parsing
  19769. */
  19770. Light.Parse = function (parsedLight, scene) {
  19771. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19772. if (!constructor) {
  19773. return null;
  19774. }
  19775. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19776. // Inclusion / exclusions
  19777. if (parsedLight.excludedMeshesIds) {
  19778. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19779. }
  19780. if (parsedLight.includedOnlyMeshesIds) {
  19781. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19782. }
  19783. // Parent
  19784. if (parsedLight.parentId) {
  19785. light._waitingParentId = parsedLight.parentId;
  19786. }
  19787. // Animations
  19788. if (parsedLight.animations) {
  19789. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19790. var parsedAnimation = parsedLight.animations[animationIndex];
  19791. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19792. }
  19793. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19794. }
  19795. if (parsedLight.autoAnimate) {
  19796. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19797. }
  19798. return light;
  19799. };
  19800. Light.prototype._hookArrayForExcluded = function (array) {
  19801. var _this = this;
  19802. var oldPush = array.push;
  19803. array.push = function () {
  19804. var items = [];
  19805. for (var _i = 0; _i < arguments.length; _i++) {
  19806. items[_i] = arguments[_i];
  19807. }
  19808. var result = oldPush.apply(array, items);
  19809. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19810. var item = items_1[_a];
  19811. item._resyncLighSource(_this);
  19812. }
  19813. return result;
  19814. };
  19815. var oldSplice = array.splice;
  19816. array.splice = function (index, deleteCount) {
  19817. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19818. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19819. var item = deleted_1[_i];
  19820. item._resyncLighSource(_this);
  19821. }
  19822. return deleted;
  19823. };
  19824. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19825. var item = array_1[_i];
  19826. item._resyncLighSource(this);
  19827. }
  19828. };
  19829. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19830. var _this = this;
  19831. var oldPush = array.push;
  19832. array.push = function () {
  19833. var items = [];
  19834. for (var _i = 0; _i < arguments.length; _i++) {
  19835. items[_i] = arguments[_i];
  19836. }
  19837. var result = oldPush.apply(array, items);
  19838. _this._resyncMeshes();
  19839. return result;
  19840. };
  19841. var oldSplice = array.splice;
  19842. array.splice = function (index, deleteCount) {
  19843. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19844. _this._resyncMeshes();
  19845. return deleted;
  19846. };
  19847. this._resyncMeshes();
  19848. };
  19849. Light.prototype._resyncMeshes = function () {
  19850. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19851. var mesh = _a[_i];
  19852. mesh._resyncLighSource(this);
  19853. }
  19854. };
  19855. /**
  19856. * Forces the meshes to update their light related information in their rendering used effects
  19857. * @ignore Internal Use Only
  19858. */
  19859. Light.prototype._markMeshesAsLightDirty = function () {
  19860. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19861. var mesh = _a[_i];
  19862. if (mesh._lightSources.indexOf(this) !== -1) {
  19863. mesh._markSubMeshesAsLightDirty();
  19864. }
  19865. }
  19866. };
  19867. /**
  19868. * Recomputes the cached photometric scale if needed.
  19869. */
  19870. Light.prototype._computePhotometricScale = function () {
  19871. this._photometricScale = this._getPhotometricScale();
  19872. this.getScene().resetCachedMaterial();
  19873. };
  19874. /**
  19875. * Returns the Photometric Scale according to the light type and intensity mode.
  19876. */
  19877. Light.prototype._getPhotometricScale = function () {
  19878. var photometricScale = 0.0;
  19879. var lightTypeID = this.getTypeID();
  19880. //get photometric mode
  19881. var photometricMode = this.intensityMode;
  19882. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19883. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19884. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19885. }
  19886. else {
  19887. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19888. }
  19889. }
  19890. //compute photometric scale
  19891. switch (lightTypeID) {
  19892. case Light.LIGHTTYPEID_POINTLIGHT:
  19893. case Light.LIGHTTYPEID_SPOTLIGHT:
  19894. switch (photometricMode) {
  19895. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19896. photometricScale = 1.0 / (4.0 * Math.PI);
  19897. break;
  19898. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19899. photometricScale = 1.0;
  19900. break;
  19901. case Light.INTENSITYMODE_LUMINANCE:
  19902. photometricScale = this.radius * this.radius;
  19903. break;
  19904. }
  19905. break;
  19906. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19907. switch (photometricMode) {
  19908. case Light.INTENSITYMODE_ILLUMINANCE:
  19909. photometricScale = 1.0;
  19910. break;
  19911. case Light.INTENSITYMODE_LUMINANCE:
  19912. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19913. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19914. var apexAngleRadians = this.radius;
  19915. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19916. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19917. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19918. photometricScale = solidAngle;
  19919. break;
  19920. }
  19921. break;
  19922. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19923. // No fall off in hemisperic light.
  19924. photometricScale = 1.0;
  19925. break;
  19926. }
  19927. return photometricScale;
  19928. };
  19929. /**
  19930. * Reorder the light in the scene according to their defined priority.
  19931. * @ignore Internal Use Only
  19932. */
  19933. Light.prototype._reorderLightsInScene = function () {
  19934. var scene = this.getScene();
  19935. if (this._renderPriority != 0) {
  19936. scene.requireLightSorting = true;
  19937. }
  19938. this.getScene().sortLightsByPriority();
  19939. };
  19940. //lightmapMode Consts
  19941. Light._LIGHTMAP_DEFAULT = 0;
  19942. Light._LIGHTMAP_SPECULAR = 1;
  19943. Light._LIGHTMAP_SHADOWSONLY = 2;
  19944. // Intensity Mode Consts
  19945. Light._INTENSITYMODE_AUTOMATIC = 0;
  19946. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19947. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19948. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19949. Light._INTENSITYMODE_LUMINANCE = 4;
  19950. // Light types ids const.
  19951. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19952. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19953. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19954. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19955. __decorate([
  19956. BABYLON.serializeAsColor3()
  19957. ], Light.prototype, "diffuse", void 0);
  19958. __decorate([
  19959. BABYLON.serializeAsColor3()
  19960. ], Light.prototype, "specular", void 0);
  19961. __decorate([
  19962. BABYLON.serialize()
  19963. ], Light.prototype, "intensity", void 0);
  19964. __decorate([
  19965. BABYLON.serialize()
  19966. ], Light.prototype, "range", void 0);
  19967. __decorate([
  19968. BABYLON.serialize()
  19969. ], Light.prototype, "intensityMode", null);
  19970. __decorate([
  19971. BABYLON.serialize()
  19972. ], Light.prototype, "radius", null);
  19973. __decorate([
  19974. BABYLON.serialize()
  19975. ], Light.prototype, "_renderPriority", void 0);
  19976. __decorate([
  19977. BABYLON.expandToProperty("_reorderLightsInScene")
  19978. ], Light.prototype, "renderPriority", void 0);
  19979. __decorate([
  19980. BABYLON.serialize()
  19981. ], Light.prototype, "shadowEnabled", void 0);
  19982. __decorate([
  19983. BABYLON.serialize("excludeWithLayerMask")
  19984. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19985. __decorate([
  19986. BABYLON.serialize("includeOnlyWithLayerMask")
  19987. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19988. __decorate([
  19989. BABYLON.serialize("lightmapMode")
  19990. ], Light.prototype, "_lightmapMode", void 0);
  19991. return Light;
  19992. }(BABYLON.Node));
  19993. BABYLON.Light = Light;
  19994. })(BABYLON || (BABYLON = {}));
  19995. //# sourceMappingURL=babylon.light.js.map
  19996. "use strict";
  19997. var BABYLON;
  19998. (function (BABYLON) {
  19999. var Camera = /** @class */ (function (_super) {
  20000. __extends(Camera, _super);
  20001. function Camera(name, position, scene) {
  20002. var _this = _super.call(this, name, scene) || this;
  20003. /**
  20004. * The vector the camera should consider as up.
  20005. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  20006. */
  20007. _this.upVector = BABYLON.Vector3.Up();
  20008. _this.orthoLeft = null;
  20009. _this.orthoRight = null;
  20010. _this.orthoBottom = null;
  20011. _this.orthoTop = null;
  20012. /**
  20013. * FOV is set in Radians. (default is 0.8)
  20014. */
  20015. _this.fov = 0.8;
  20016. _this.minZ = 1;
  20017. _this.maxZ = 10000.0;
  20018. _this.inertia = 0.9;
  20019. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20020. _this.isIntermediate = false;
  20021. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20022. /**
  20023. * Restricts the camera to viewing objects with the same layerMask.
  20024. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20025. */
  20026. _this.layerMask = 0x0FFFFFFF;
  20027. /**
  20028. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20029. */
  20030. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20031. // Camera rig members
  20032. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20033. _this._rigCameras = new Array();
  20034. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20035. _this._skipRendering = false;
  20036. _this.customRenderTargets = new Array();
  20037. // Observables
  20038. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20039. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20040. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20041. _this.onRestoreStateObservable = new BABYLON.Observable();
  20042. // Cache
  20043. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20044. _this._projectionMatrix = new BABYLON.Matrix();
  20045. _this._doNotComputeProjectionMatrix = false;
  20046. _this._postProcesses = new Array();
  20047. _this._transformMatrix = BABYLON.Matrix.Zero();
  20048. _this._activeMeshes = new BABYLON.SmartArray(256);
  20049. _this._globalPosition = BABYLON.Vector3.Zero();
  20050. _this._refreshFrustumPlanes = true;
  20051. _this.getScene().addCamera(_this);
  20052. if (!_this.getScene().activeCamera) {
  20053. _this.getScene().activeCamera = _this;
  20054. }
  20055. _this.position = position;
  20056. return _this;
  20057. }
  20058. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20059. get: function () {
  20060. return Camera._PERSPECTIVE_CAMERA;
  20061. },
  20062. enumerable: true,
  20063. configurable: true
  20064. });
  20065. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20066. get: function () {
  20067. return Camera._ORTHOGRAPHIC_CAMERA;
  20068. },
  20069. enumerable: true,
  20070. configurable: true
  20071. });
  20072. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20073. /**
  20074. * This is the default FOV mode for perspective cameras.
  20075. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20076. *
  20077. */
  20078. get: function () {
  20079. return Camera._FOVMODE_VERTICAL_FIXED;
  20080. },
  20081. enumerable: true,
  20082. configurable: true
  20083. });
  20084. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20085. /**
  20086. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20087. *
  20088. */
  20089. get: function () {
  20090. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20091. },
  20092. enumerable: true,
  20093. configurable: true
  20094. });
  20095. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20096. get: function () {
  20097. return Camera._RIG_MODE_NONE;
  20098. },
  20099. enumerable: true,
  20100. configurable: true
  20101. });
  20102. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20103. get: function () {
  20104. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20105. },
  20106. enumerable: true,
  20107. configurable: true
  20108. });
  20109. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20110. get: function () {
  20111. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20112. },
  20113. enumerable: true,
  20114. configurable: true
  20115. });
  20116. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20117. get: function () {
  20118. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20119. },
  20120. enumerable: true,
  20121. configurable: true
  20122. });
  20123. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20124. get: function () {
  20125. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20126. },
  20127. enumerable: true,
  20128. configurable: true
  20129. });
  20130. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20131. get: function () {
  20132. return Camera._RIG_MODE_VR;
  20133. },
  20134. enumerable: true,
  20135. configurable: true
  20136. });
  20137. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20138. get: function () {
  20139. return Camera._RIG_MODE_WEBVR;
  20140. },
  20141. enumerable: true,
  20142. configurable: true
  20143. });
  20144. /**
  20145. * Store current camera state (fov, position, etc..)
  20146. */
  20147. Camera.prototype.storeState = function () {
  20148. this._stateStored = true;
  20149. this._storedFov = this.fov;
  20150. return this;
  20151. };
  20152. /**
  20153. * Restores the camera state values if it has been stored. You must call storeState() first
  20154. */
  20155. Camera.prototype._restoreStateValues = function () {
  20156. if (!this._stateStored) {
  20157. return false;
  20158. }
  20159. this.fov = this._storedFov;
  20160. return true;
  20161. };
  20162. /**
  20163. * Restored camera state. You must call storeState() first
  20164. */
  20165. Camera.prototype.restoreState = function () {
  20166. if (this._restoreStateValues()) {
  20167. this.onRestoreStateObservable.notifyObservers(this);
  20168. return true;
  20169. }
  20170. return false;
  20171. };
  20172. Camera.prototype.getClassName = function () {
  20173. return "Camera";
  20174. };
  20175. /**
  20176. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20177. */
  20178. Camera.prototype.toString = function (fullDetails) {
  20179. var ret = "Name: " + this.name;
  20180. ret += ", type: " + this.getClassName();
  20181. if (this.animations) {
  20182. for (var i = 0; i < this.animations.length; i++) {
  20183. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20184. }
  20185. }
  20186. if (fullDetails) {
  20187. }
  20188. return ret;
  20189. };
  20190. Object.defineProperty(Camera.prototype, "globalPosition", {
  20191. get: function () {
  20192. return this._globalPosition;
  20193. },
  20194. enumerable: true,
  20195. configurable: true
  20196. });
  20197. Camera.prototype.getActiveMeshes = function () {
  20198. return this._activeMeshes;
  20199. };
  20200. Camera.prototype.isActiveMesh = function (mesh) {
  20201. return (this._activeMeshes.indexOf(mesh) !== -1);
  20202. };
  20203. //Cache
  20204. Camera.prototype._initCache = function () {
  20205. _super.prototype._initCache.call(this);
  20206. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20207. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20208. this._cache.mode = undefined;
  20209. this._cache.minZ = undefined;
  20210. this._cache.maxZ = undefined;
  20211. this._cache.fov = undefined;
  20212. this._cache.fovMode = undefined;
  20213. this._cache.aspectRatio = undefined;
  20214. this._cache.orthoLeft = undefined;
  20215. this._cache.orthoRight = undefined;
  20216. this._cache.orthoBottom = undefined;
  20217. this._cache.orthoTop = undefined;
  20218. this._cache.renderWidth = undefined;
  20219. this._cache.renderHeight = undefined;
  20220. };
  20221. Camera.prototype._updateCache = function (ignoreParentClass) {
  20222. if (!ignoreParentClass) {
  20223. _super.prototype._updateCache.call(this);
  20224. }
  20225. this._cache.position.copyFrom(this.position);
  20226. this._cache.upVector.copyFrom(this.upVector);
  20227. };
  20228. // Synchronized
  20229. Camera.prototype._isSynchronized = function () {
  20230. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20231. };
  20232. Camera.prototype._isSynchronizedViewMatrix = function () {
  20233. if (!_super.prototype._isSynchronized.call(this))
  20234. return false;
  20235. return this._cache.position.equals(this.position)
  20236. && this._cache.upVector.equals(this.upVector)
  20237. && this.isSynchronizedWithParent();
  20238. };
  20239. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20240. var check = this._cache.mode === this.mode
  20241. && this._cache.minZ === this.minZ
  20242. && this._cache.maxZ === this.maxZ;
  20243. if (!check) {
  20244. return false;
  20245. }
  20246. var engine = this.getEngine();
  20247. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20248. check = this._cache.fov === this.fov
  20249. && this._cache.fovMode === this.fovMode
  20250. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20251. }
  20252. else {
  20253. check = this._cache.orthoLeft === this.orthoLeft
  20254. && this._cache.orthoRight === this.orthoRight
  20255. && this._cache.orthoBottom === this.orthoBottom
  20256. && this._cache.orthoTop === this.orthoTop
  20257. && this._cache.renderWidth === engine.getRenderWidth()
  20258. && this._cache.renderHeight === engine.getRenderHeight();
  20259. }
  20260. return check;
  20261. };
  20262. // Controls
  20263. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20264. };
  20265. Camera.prototype.detachControl = function (element) {
  20266. };
  20267. Camera.prototype.update = function () {
  20268. this._checkInputs();
  20269. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20270. this._updateRigCameras();
  20271. }
  20272. };
  20273. Camera.prototype._checkInputs = function () {
  20274. this.onAfterCheckInputsObservable.notifyObservers(this);
  20275. };
  20276. Object.defineProperty(Camera.prototype, "rigCameras", {
  20277. get: function () {
  20278. return this._rigCameras;
  20279. },
  20280. enumerable: true,
  20281. configurable: true
  20282. });
  20283. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20284. get: function () {
  20285. return this._rigPostProcess;
  20286. },
  20287. enumerable: true,
  20288. configurable: true
  20289. });
  20290. /**
  20291. * Internal, gets the first post proces.
  20292. * @returns the first post process to be run on this camera.
  20293. */
  20294. Camera.prototype._getFirstPostProcess = function () {
  20295. for (var pp in this._postProcesses) {
  20296. if (this._postProcesses[pp] !== null) {
  20297. return this._postProcesses[pp];
  20298. }
  20299. }
  20300. return null;
  20301. };
  20302. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20303. // invalidate framebuffer
  20304. var firstPostProcess = this._getFirstPostProcess();
  20305. if (firstPostProcess) {
  20306. firstPostProcess.markTextureDirty();
  20307. }
  20308. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20309. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20310. var cam = this._rigCameras[i];
  20311. var rigPostProcess = cam._rigPostProcess;
  20312. // for VR rig, there does not have to be a post process
  20313. if (rigPostProcess) {
  20314. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20315. if (isPass) {
  20316. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20317. cam.isIntermediate = this._postProcesses.length === 0;
  20318. }
  20319. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20320. rigPostProcess.markTextureDirty();
  20321. }
  20322. else {
  20323. cam._postProcesses = this._postProcesses.slice(0);
  20324. }
  20325. }
  20326. };
  20327. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20328. if (insertAt === void 0) { insertAt = null; }
  20329. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20330. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20331. return 0;
  20332. }
  20333. if (insertAt == null || insertAt < 0) {
  20334. this._postProcesses.push(postProcess);
  20335. }
  20336. else if (this._postProcesses[insertAt] === null) {
  20337. this._postProcesses[insertAt] = postProcess;
  20338. }
  20339. else {
  20340. this._postProcesses.splice(insertAt, 0, postProcess);
  20341. }
  20342. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20343. return this._postProcesses.indexOf(postProcess);
  20344. };
  20345. Camera.prototype.detachPostProcess = function (postProcess) {
  20346. var idx = this._postProcesses.indexOf(postProcess);
  20347. if (idx !== -1) {
  20348. this._postProcesses[idx] = null;
  20349. }
  20350. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20351. };
  20352. Camera.prototype.getWorldMatrix = function () {
  20353. if (!this._worldMatrix) {
  20354. this._worldMatrix = BABYLON.Matrix.Identity();
  20355. }
  20356. var viewMatrix = this.getViewMatrix();
  20357. viewMatrix.invertToRef(this._worldMatrix);
  20358. return this._worldMatrix;
  20359. };
  20360. Camera.prototype._getViewMatrix = function () {
  20361. return BABYLON.Matrix.Identity();
  20362. };
  20363. Camera.prototype.getViewMatrix = function (force) {
  20364. if (!force && this._isSynchronizedViewMatrix()) {
  20365. return this._computedViewMatrix;
  20366. }
  20367. this.updateCache();
  20368. this._computedViewMatrix = this._getViewMatrix();
  20369. this._currentRenderId = this.getScene().getRenderId();
  20370. this._refreshFrustumPlanes = true;
  20371. if (!this.parent || !this.parent.getWorldMatrix) {
  20372. this._globalPosition.copyFrom(this.position);
  20373. }
  20374. else {
  20375. if (!this._worldMatrix) {
  20376. this._worldMatrix = BABYLON.Matrix.Identity();
  20377. }
  20378. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20379. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20380. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20381. this._computedViewMatrix.invert();
  20382. this._markSyncedWithParent();
  20383. }
  20384. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20385. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20386. }
  20387. this.onViewMatrixChangedObservable.notifyObservers(this);
  20388. return this._computedViewMatrix;
  20389. };
  20390. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20391. this._doNotComputeProjectionMatrix = true;
  20392. if (projection !== undefined) {
  20393. this._projectionMatrix = projection;
  20394. }
  20395. };
  20396. ;
  20397. Camera.prototype.unfreezeProjectionMatrix = function () {
  20398. this._doNotComputeProjectionMatrix = false;
  20399. };
  20400. ;
  20401. Camera.prototype.getProjectionMatrix = function (force) {
  20402. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20403. return this._projectionMatrix;
  20404. }
  20405. // Cache
  20406. this._cache.mode = this.mode;
  20407. this._cache.minZ = this.minZ;
  20408. this._cache.maxZ = this.maxZ;
  20409. // Matrix
  20410. this._refreshFrustumPlanes = true;
  20411. var engine = this.getEngine();
  20412. var scene = this.getScene();
  20413. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20414. this._cache.fov = this.fov;
  20415. this._cache.fovMode = this.fovMode;
  20416. this._cache.aspectRatio = engine.getAspectRatio(this);
  20417. if (this.minZ <= 0) {
  20418. this.minZ = 0.1;
  20419. }
  20420. if (scene.useRightHandedSystem) {
  20421. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20422. }
  20423. else {
  20424. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20425. }
  20426. }
  20427. else {
  20428. var halfWidth = engine.getRenderWidth() / 2.0;
  20429. var halfHeight = engine.getRenderHeight() / 2.0;
  20430. if (scene.useRightHandedSystem) {
  20431. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20432. }
  20433. else {
  20434. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20435. }
  20436. this._cache.orthoLeft = this.orthoLeft;
  20437. this._cache.orthoRight = this.orthoRight;
  20438. this._cache.orthoBottom = this.orthoBottom;
  20439. this._cache.orthoTop = this.orthoTop;
  20440. this._cache.renderWidth = engine.getRenderWidth();
  20441. this._cache.renderHeight = engine.getRenderHeight();
  20442. }
  20443. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20444. return this._projectionMatrix;
  20445. };
  20446. Camera.prototype.getTranformationMatrix = function () {
  20447. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20448. return this._transformMatrix;
  20449. };
  20450. Camera.prototype.updateFrustumPlanes = function () {
  20451. if (!this._refreshFrustumPlanes) {
  20452. return;
  20453. }
  20454. this.getTranformationMatrix();
  20455. if (!this._frustumPlanes) {
  20456. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20457. }
  20458. else {
  20459. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20460. }
  20461. this._refreshFrustumPlanes = false;
  20462. };
  20463. Camera.prototype.isInFrustum = function (target) {
  20464. this.updateFrustumPlanes();
  20465. return target.isInFrustum(this._frustumPlanes);
  20466. };
  20467. Camera.prototype.isCompletelyInFrustum = function (target) {
  20468. this.updateFrustumPlanes();
  20469. return target.isCompletelyInFrustum(this._frustumPlanes);
  20470. };
  20471. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20472. if (length === void 0) { length = 100; }
  20473. if (!transform) {
  20474. transform = this.getWorldMatrix();
  20475. }
  20476. if (!origin) {
  20477. origin = this.position;
  20478. }
  20479. var forward = new BABYLON.Vector3(0, 0, 1);
  20480. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20481. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20482. return new BABYLON.Ray(origin, direction, length);
  20483. };
  20484. /**
  20485. * Releases resources associated with this node.
  20486. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20487. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20488. */
  20489. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20490. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20491. // Observables
  20492. this.onViewMatrixChangedObservable.clear();
  20493. this.onProjectionMatrixChangedObservable.clear();
  20494. this.onAfterCheckInputsObservable.clear();
  20495. this.onRestoreStateObservable.clear();
  20496. // Inputs
  20497. if (this.inputs) {
  20498. this.inputs.clear();
  20499. }
  20500. // Animations
  20501. this.getScene().stopAnimation(this);
  20502. // Remove from scene
  20503. this.getScene().removeCamera(this);
  20504. while (this._rigCameras.length > 0) {
  20505. var camera = this._rigCameras.pop();
  20506. if (camera) {
  20507. camera.dispose();
  20508. }
  20509. }
  20510. // Postprocesses
  20511. if (this._rigPostProcess) {
  20512. this._rigPostProcess.dispose(this);
  20513. this._rigPostProcess = null;
  20514. this._postProcesses = [];
  20515. }
  20516. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20517. this._rigPostProcess = null;
  20518. this._postProcesses = [];
  20519. }
  20520. else {
  20521. var i = this._postProcesses.length;
  20522. while (--i >= 0) {
  20523. var postProcess = this._postProcesses[i];
  20524. if (postProcess) {
  20525. postProcess.dispose(this);
  20526. }
  20527. }
  20528. }
  20529. // Render targets
  20530. var i = this.customRenderTargets.length;
  20531. while (--i >= 0) {
  20532. this.customRenderTargets[i].dispose();
  20533. }
  20534. this.customRenderTargets = [];
  20535. // Active Meshes
  20536. this._activeMeshes.dispose();
  20537. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20538. };
  20539. Object.defineProperty(Camera.prototype, "leftCamera", {
  20540. // ---- Camera rigs section ----
  20541. get: function () {
  20542. if (this._rigCameras.length < 1) {
  20543. return null;
  20544. }
  20545. return this._rigCameras[0];
  20546. },
  20547. enumerable: true,
  20548. configurable: true
  20549. });
  20550. Object.defineProperty(Camera.prototype, "rightCamera", {
  20551. get: function () {
  20552. if (this._rigCameras.length < 2) {
  20553. return null;
  20554. }
  20555. return this._rigCameras[1];
  20556. },
  20557. enumerable: true,
  20558. configurable: true
  20559. });
  20560. Camera.prototype.getLeftTarget = function () {
  20561. if (this._rigCameras.length < 1) {
  20562. return null;
  20563. }
  20564. return this._rigCameras[0].getTarget();
  20565. };
  20566. Camera.prototype.getRightTarget = function () {
  20567. if (this._rigCameras.length < 2) {
  20568. return null;
  20569. }
  20570. return this._rigCameras[1].getTarget();
  20571. };
  20572. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20573. if (this.cameraRigMode === mode) {
  20574. return;
  20575. }
  20576. while (this._rigCameras.length > 0) {
  20577. var camera = this._rigCameras.pop();
  20578. if (camera) {
  20579. camera.dispose();
  20580. }
  20581. }
  20582. this.cameraRigMode = mode;
  20583. this._cameraRigParams = {};
  20584. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20585. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20586. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20587. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20588. // create the rig cameras, unless none
  20589. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20590. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20591. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20592. if (leftCamera && rightCamera) {
  20593. this._rigCameras.push(leftCamera);
  20594. this._rigCameras.push(rightCamera);
  20595. }
  20596. }
  20597. switch (this.cameraRigMode) {
  20598. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20599. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20600. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20601. break;
  20602. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20603. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20604. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20605. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20606. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20607. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20608. break;
  20609. case Camera.RIG_MODE_VR:
  20610. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20611. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20612. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20613. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20614. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20615. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20616. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20617. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20618. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20619. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20620. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20621. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20622. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20623. if (metrics.compensateDistortion) {
  20624. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20625. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20626. }
  20627. break;
  20628. case Camera.RIG_MODE_WEBVR:
  20629. if (rigParams.vrDisplay) {
  20630. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20631. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20632. //Left eye
  20633. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20634. this._rigCameras[0].setCameraRigParameter("left", true);
  20635. //leaving this for future reference
  20636. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20637. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20638. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20639. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20640. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20641. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20642. this._rigCameras[0].parent = this;
  20643. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20644. //Right eye
  20645. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20646. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20647. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20648. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20649. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20650. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20651. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20652. this._rigCameras[1].parent = this;
  20653. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20654. if (Camera.UseAlternateWebVRRendering) {
  20655. this._rigCameras[1]._skipRendering = true;
  20656. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20657. }
  20658. }
  20659. break;
  20660. }
  20661. this._cascadePostProcessesToRigCams();
  20662. this.update();
  20663. };
  20664. Camera.prototype._getVRProjectionMatrix = function () {
  20665. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20666. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20667. return this._projectionMatrix;
  20668. };
  20669. Camera.prototype._updateCameraRotationMatrix = function () {
  20670. //Here for WebVR
  20671. };
  20672. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20673. //Here for WebVR
  20674. };
  20675. /**
  20676. * This function MUST be overwritten by the different WebVR cameras available.
  20677. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20678. */
  20679. Camera.prototype._getWebVRProjectionMatrix = function () {
  20680. return BABYLON.Matrix.Identity();
  20681. };
  20682. /**
  20683. * This function MUST be overwritten by the different WebVR cameras available.
  20684. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20685. */
  20686. Camera.prototype._getWebVRViewMatrix = function () {
  20687. return BABYLON.Matrix.Identity();
  20688. };
  20689. Camera.prototype.setCameraRigParameter = function (name, value) {
  20690. if (!this._cameraRigParams) {
  20691. this._cameraRigParams = {};
  20692. }
  20693. this._cameraRigParams[name] = value;
  20694. //provisionnally:
  20695. if (name === "interaxialDistance") {
  20696. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20697. }
  20698. };
  20699. /**
  20700. * needs to be overridden by children so sub has required properties to be copied
  20701. */
  20702. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20703. return null;
  20704. };
  20705. /**
  20706. * May need to be overridden by children
  20707. */
  20708. Camera.prototype._updateRigCameras = function () {
  20709. for (var i = 0; i < this._rigCameras.length; i++) {
  20710. this._rigCameras[i].minZ = this.minZ;
  20711. this._rigCameras[i].maxZ = this.maxZ;
  20712. this._rigCameras[i].fov = this.fov;
  20713. }
  20714. // only update viewport when ANAGLYPH
  20715. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20716. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20717. }
  20718. };
  20719. Camera.prototype._setupInputs = function () {
  20720. };
  20721. Camera.prototype.serialize = function () {
  20722. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20723. // Type
  20724. serializationObject.type = this.getClassName();
  20725. // Parent
  20726. if (this.parent) {
  20727. serializationObject.parentId = this.parent.id;
  20728. }
  20729. if (this.inputs) {
  20730. this.inputs.serialize(serializationObject);
  20731. }
  20732. // Animations
  20733. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20734. serializationObject.ranges = this.serializeAnimationRanges();
  20735. return serializationObject;
  20736. };
  20737. Camera.prototype.clone = function (name) {
  20738. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20739. };
  20740. Camera.prototype.getDirection = function (localAxis) {
  20741. var result = BABYLON.Vector3.Zero();
  20742. this.getDirectionToRef(localAxis, result);
  20743. return result;
  20744. };
  20745. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20746. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20747. };
  20748. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20749. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20750. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20751. switch (type) {
  20752. case "ArcRotateCamera":
  20753. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20754. case "DeviceOrientationCamera":
  20755. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20756. case "FollowCamera":
  20757. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20758. case "ArcFollowCamera":
  20759. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20760. case "GamepadCamera":
  20761. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20762. case "TouchCamera":
  20763. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20764. case "VirtualJoysticksCamera":
  20765. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20766. case "WebVRFreeCamera":
  20767. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20768. case "WebVRGamepadCamera":
  20769. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20770. case "VRDeviceOrientationFreeCamera":
  20771. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20772. case "VRDeviceOrientationGamepadCamera":
  20773. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20774. case "AnaglyphArcRotateCamera":
  20775. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20776. case "AnaglyphFreeCamera":
  20777. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20778. case "AnaglyphGamepadCamera":
  20779. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20780. case "AnaglyphUniversalCamera":
  20781. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20782. case "StereoscopicArcRotateCamera":
  20783. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20784. case "StereoscopicFreeCamera":
  20785. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20786. case "StereoscopicGamepadCamera":
  20787. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20788. case "StereoscopicUniversalCamera":
  20789. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20790. case "FreeCamera":// Forcing Universal here
  20791. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20792. default:// Universal Camera is the default value
  20793. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20794. }
  20795. };
  20796. Camera.prototype.computeWorldMatrix = function () {
  20797. return this.getWorldMatrix();
  20798. };
  20799. Camera.Parse = function (parsedCamera, scene) {
  20800. var type = parsedCamera.type;
  20801. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20802. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20803. // Parent
  20804. if (parsedCamera.parentId) {
  20805. camera._waitingParentId = parsedCamera.parentId;
  20806. }
  20807. //If camera has an input manager, let it parse inputs settings
  20808. if (camera.inputs) {
  20809. camera.inputs.parse(parsedCamera);
  20810. camera._setupInputs();
  20811. }
  20812. if (camera.setPosition) {
  20813. camera.position.copyFromFloats(0, 0, 0);
  20814. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20815. }
  20816. // Target
  20817. if (parsedCamera.target) {
  20818. if (camera.setTarget) {
  20819. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20820. }
  20821. }
  20822. // Apply 3d rig, when found
  20823. if (parsedCamera.cameraRigMode) {
  20824. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20825. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20826. }
  20827. // Animations
  20828. if (parsedCamera.animations) {
  20829. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20830. var parsedAnimation = parsedCamera.animations[animationIndex];
  20831. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20832. }
  20833. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20834. }
  20835. if (parsedCamera.autoAnimate) {
  20836. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20837. }
  20838. return camera;
  20839. };
  20840. // Statics
  20841. Camera._PERSPECTIVE_CAMERA = 0;
  20842. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20843. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20844. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20845. Camera._RIG_MODE_NONE = 0;
  20846. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20847. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20848. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20849. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20850. Camera._RIG_MODE_VR = 20;
  20851. Camera._RIG_MODE_WEBVR = 21;
  20852. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20853. Camera.UseAlternateWebVRRendering = false;
  20854. __decorate([
  20855. BABYLON.serializeAsVector3()
  20856. ], Camera.prototype, "position", void 0);
  20857. __decorate([
  20858. BABYLON.serializeAsVector3()
  20859. ], Camera.prototype, "upVector", void 0);
  20860. __decorate([
  20861. BABYLON.serialize()
  20862. ], Camera.prototype, "orthoLeft", void 0);
  20863. __decorate([
  20864. BABYLON.serialize()
  20865. ], Camera.prototype, "orthoRight", void 0);
  20866. __decorate([
  20867. BABYLON.serialize()
  20868. ], Camera.prototype, "orthoBottom", void 0);
  20869. __decorate([
  20870. BABYLON.serialize()
  20871. ], Camera.prototype, "orthoTop", void 0);
  20872. __decorate([
  20873. BABYLON.serialize()
  20874. ], Camera.prototype, "fov", void 0);
  20875. __decorate([
  20876. BABYLON.serialize()
  20877. ], Camera.prototype, "minZ", void 0);
  20878. __decorate([
  20879. BABYLON.serialize()
  20880. ], Camera.prototype, "maxZ", void 0);
  20881. __decorate([
  20882. BABYLON.serialize()
  20883. ], Camera.prototype, "inertia", void 0);
  20884. __decorate([
  20885. BABYLON.serialize()
  20886. ], Camera.prototype, "mode", void 0);
  20887. __decorate([
  20888. BABYLON.serialize()
  20889. ], Camera.prototype, "layerMask", void 0);
  20890. __decorate([
  20891. BABYLON.serialize()
  20892. ], Camera.prototype, "fovMode", void 0);
  20893. __decorate([
  20894. BABYLON.serialize()
  20895. ], Camera.prototype, "cameraRigMode", void 0);
  20896. __decorate([
  20897. BABYLON.serialize()
  20898. ], Camera.prototype, "interaxialDistance", void 0);
  20899. __decorate([
  20900. BABYLON.serialize()
  20901. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20902. return Camera;
  20903. }(BABYLON.Node));
  20904. BABYLON.Camera = Camera;
  20905. })(BABYLON || (BABYLON = {}));
  20906. //# sourceMappingURL=babylon.camera.js.map
  20907. "use strict";
  20908. var BABYLON;
  20909. (function (BABYLON) {
  20910. var RenderingManager = /** @class */ (function () {
  20911. function RenderingManager(scene) {
  20912. this._renderingGroups = new Array();
  20913. this._autoClearDepthStencil = {};
  20914. this._customOpaqueSortCompareFn = {};
  20915. this._customAlphaTestSortCompareFn = {};
  20916. this._customTransparentSortCompareFn = {};
  20917. this._renderinGroupInfo = null;
  20918. this._scene = scene;
  20919. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20920. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20921. }
  20922. }
  20923. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20924. if (depth === void 0) { depth = true; }
  20925. if (stencil === void 0) { stencil = true; }
  20926. if (this._depthStencilBufferAlreadyCleaned) {
  20927. return;
  20928. }
  20929. this._scene.getEngine().clear(null, false, depth, stencil);
  20930. this._depthStencilBufferAlreadyCleaned = true;
  20931. };
  20932. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20933. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20934. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20935. var info = null;
  20936. if (observable) {
  20937. if (!this._renderinGroupInfo) {
  20938. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20939. }
  20940. info = this._renderinGroupInfo;
  20941. info.scene = this._scene;
  20942. info.camera = this._scene.activeCamera;
  20943. }
  20944. // Dispatch sprites
  20945. if (renderSprites) {
  20946. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20947. var manager = this._scene.spriteManagers[index];
  20948. this.dispatchSprites(manager);
  20949. }
  20950. }
  20951. // Render
  20952. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20953. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20954. var renderingGroup = this._renderingGroups[index];
  20955. if (!renderingGroup && !observable)
  20956. continue;
  20957. var renderingGroupMask = 0;
  20958. // Fire PRECLEAR stage
  20959. if (observable && info) {
  20960. renderingGroupMask = Math.pow(2, index);
  20961. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20962. info.renderingGroupId = index;
  20963. observable.notifyObservers(info, renderingGroupMask);
  20964. }
  20965. // Clear depth/stencil if needed
  20966. if (RenderingManager.AUTOCLEAR) {
  20967. var autoClear = this._autoClearDepthStencil[index];
  20968. if (autoClear && autoClear.autoClear) {
  20969. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20970. }
  20971. }
  20972. if (observable && info) {
  20973. // Fire PREOPAQUE stage
  20974. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20975. observable.notifyObservers(info, renderingGroupMask);
  20976. // Fire PRETRANSPARENT stage
  20977. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20978. observable.notifyObservers(info, renderingGroupMask);
  20979. }
  20980. if (renderingGroup)
  20981. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20982. // Fire POSTTRANSPARENT stage
  20983. if (observable && info) {
  20984. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20985. observable.notifyObservers(info, renderingGroupMask);
  20986. }
  20987. }
  20988. };
  20989. RenderingManager.prototype.reset = function () {
  20990. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20991. var renderingGroup = this._renderingGroups[index];
  20992. if (renderingGroup) {
  20993. renderingGroup.prepare();
  20994. }
  20995. }
  20996. };
  20997. RenderingManager.prototype.dispose = function () {
  20998. this.freeRenderingGroups();
  20999. this._renderingGroups.length = 0;
  21000. };
  21001. /**
  21002. * Clear the info related to rendering groups preventing retention points during dispose.
  21003. */
  21004. RenderingManager.prototype.freeRenderingGroups = function () {
  21005. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21006. var renderingGroup = this._renderingGroups[index];
  21007. if (renderingGroup) {
  21008. renderingGroup.dispose();
  21009. }
  21010. }
  21011. };
  21012. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21013. if (this._renderingGroups[renderingGroupId] === undefined) {
  21014. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21015. }
  21016. };
  21017. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21018. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21019. this._prepareRenderingGroup(renderingGroupId);
  21020. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21021. };
  21022. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21023. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21024. this._prepareRenderingGroup(renderingGroupId);
  21025. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21026. };
  21027. /**
  21028. * @param subMesh The submesh to dispatch
  21029. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21030. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21031. */
  21032. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21033. if (mesh === undefined) {
  21034. mesh = subMesh.getMesh();
  21035. }
  21036. var renderingGroupId = mesh.renderingGroupId || 0;
  21037. this._prepareRenderingGroup(renderingGroupId);
  21038. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21039. };
  21040. /**
  21041. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21042. * This allowed control for front to back rendering or reversly depending of the special needs.
  21043. *
  21044. * @param renderingGroupId The rendering group id corresponding to its index
  21045. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21046. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21047. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21048. */
  21049. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21050. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21051. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21052. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21053. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21054. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21055. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21056. if (this._renderingGroups[renderingGroupId]) {
  21057. var group = this._renderingGroups[renderingGroupId];
  21058. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21059. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21060. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21061. }
  21062. };
  21063. /**
  21064. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21065. *
  21066. * @param renderingGroupId The rendering group id corresponding to its index
  21067. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21068. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21069. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21070. */
  21071. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21072. if (depth === void 0) { depth = true; }
  21073. if (stencil === void 0) { stencil = true; }
  21074. this._autoClearDepthStencil[renderingGroupId] = {
  21075. autoClear: autoClearDepthStencil,
  21076. depth: depth,
  21077. stencil: stencil
  21078. };
  21079. };
  21080. /**
  21081. * The max id used for rendering groups (not included)
  21082. */
  21083. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21084. /**
  21085. * The min id used for rendering groups (included)
  21086. */
  21087. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21088. /**
  21089. * Used to globally prevent autoclearing scenes.
  21090. */
  21091. RenderingManager.AUTOCLEAR = true;
  21092. return RenderingManager;
  21093. }());
  21094. BABYLON.RenderingManager = RenderingManager;
  21095. })(BABYLON || (BABYLON = {}));
  21096. //# sourceMappingURL=babylon.renderingManager.js.map
  21097. "use strict";
  21098. var BABYLON;
  21099. (function (BABYLON) {
  21100. var RenderingGroup = /** @class */ (function () {
  21101. /**
  21102. * Creates a new rendering group.
  21103. * @param index The rendering group index
  21104. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21105. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21106. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21107. */
  21108. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21109. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21110. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21111. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21112. this.index = index;
  21113. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21114. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21115. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21116. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21117. this._particleSystems = new BABYLON.SmartArray(256);
  21118. this._spriteManagers = new BABYLON.SmartArray(256);
  21119. this._edgesRenderers = new BABYLON.SmartArray(16);
  21120. this._scene = scene;
  21121. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21122. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21123. this.transparentSortCompareFn = transparentSortCompareFn;
  21124. }
  21125. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21126. /**
  21127. * Set the opaque sort comparison function.
  21128. * If null the sub meshes will be render in the order they were created
  21129. */
  21130. set: function (value) {
  21131. this._opaqueSortCompareFn = value;
  21132. if (value) {
  21133. this._renderOpaque = this.renderOpaqueSorted;
  21134. }
  21135. else {
  21136. this._renderOpaque = RenderingGroup.renderUnsorted;
  21137. }
  21138. },
  21139. enumerable: true,
  21140. configurable: true
  21141. });
  21142. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21143. /**
  21144. * Set the alpha test sort comparison function.
  21145. * If null the sub meshes will be render in the order they were created
  21146. */
  21147. set: function (value) {
  21148. this._alphaTestSortCompareFn = value;
  21149. if (value) {
  21150. this._renderAlphaTest = this.renderAlphaTestSorted;
  21151. }
  21152. else {
  21153. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21154. }
  21155. },
  21156. enumerable: true,
  21157. configurable: true
  21158. });
  21159. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21160. /**
  21161. * Set the transparent sort comparison function.
  21162. * If null the sub meshes will be render in the order they were created
  21163. */
  21164. set: function (value) {
  21165. if (value) {
  21166. this._transparentSortCompareFn = value;
  21167. }
  21168. else {
  21169. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21170. }
  21171. this._renderTransparent = this.renderTransparentSorted;
  21172. },
  21173. enumerable: true,
  21174. configurable: true
  21175. });
  21176. /**
  21177. * Render all the sub meshes contained in the group.
  21178. * @param customRenderFunction Used to override the default render behaviour of the group.
  21179. * @returns true if rendered some submeshes.
  21180. */
  21181. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21182. if (customRenderFunction) {
  21183. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21184. return;
  21185. }
  21186. var engine = this._scene.getEngine();
  21187. // Depth only
  21188. if (this._depthOnlySubMeshes.length !== 0) {
  21189. engine.setColorWrite(false);
  21190. this._renderAlphaTest(this._depthOnlySubMeshes);
  21191. engine.setColorWrite(true);
  21192. }
  21193. // Opaque
  21194. if (this._opaqueSubMeshes.length !== 0) {
  21195. this._renderOpaque(this._opaqueSubMeshes);
  21196. }
  21197. // Alpha test
  21198. if (this._alphaTestSubMeshes.length !== 0) {
  21199. this._renderAlphaTest(this._alphaTestSubMeshes);
  21200. }
  21201. var stencilState = engine.getStencilBuffer();
  21202. engine.setStencilBuffer(false);
  21203. // Sprites
  21204. if (renderSprites) {
  21205. this._renderSprites();
  21206. }
  21207. // Particles
  21208. if (renderParticles) {
  21209. this._renderParticles(activeMeshes);
  21210. }
  21211. if (this.onBeforeTransparentRendering) {
  21212. this.onBeforeTransparentRendering();
  21213. }
  21214. // Transparent
  21215. if (this._transparentSubMeshes.length !== 0) {
  21216. this._renderTransparent(this._transparentSubMeshes);
  21217. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21218. }
  21219. // Set back stencil to false in case it changes before the edge renderer.
  21220. engine.setStencilBuffer(false);
  21221. // Edges
  21222. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21223. this._edgesRenderers.data[edgesRendererIndex].render();
  21224. }
  21225. // Restore Stencil state.
  21226. engine.setStencilBuffer(stencilState);
  21227. };
  21228. /**
  21229. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21230. * @param subMeshes The submeshes to render
  21231. */
  21232. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21233. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21234. };
  21235. /**
  21236. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21237. * @param subMeshes The submeshes to render
  21238. */
  21239. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21240. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21241. };
  21242. /**
  21243. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21244. * @param subMeshes The submeshes to render
  21245. */
  21246. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21247. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21248. };
  21249. /**
  21250. * Renders the submeshes in a specified order.
  21251. * @param subMeshes The submeshes to sort before render
  21252. * @param sortCompareFn The comparison function use to sort
  21253. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21254. * @param transparent Specifies to activate blending if true
  21255. */
  21256. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21257. var subIndex = 0;
  21258. var subMesh;
  21259. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21260. for (; subIndex < subMeshes.length; subIndex++) {
  21261. subMesh = subMeshes.data[subIndex];
  21262. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21263. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21264. }
  21265. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21266. if (sortCompareFn) {
  21267. sortedArray.sort(sortCompareFn);
  21268. }
  21269. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21270. subMesh = sortedArray[subIndex];
  21271. if (transparent) {
  21272. var material = subMesh.getMaterial();
  21273. if (material && material.needDepthPrePass) {
  21274. var engine = material.getScene().getEngine();
  21275. engine.setColorWrite(false);
  21276. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21277. subMesh.render(false);
  21278. engine.setColorWrite(true);
  21279. }
  21280. }
  21281. subMesh.render(transparent);
  21282. }
  21283. };
  21284. /**
  21285. * Renders the submeshes in the order they were dispatched (no sort applied).
  21286. * @param subMeshes The submeshes to render
  21287. */
  21288. RenderingGroup.renderUnsorted = function (subMeshes) {
  21289. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21290. var submesh = subMeshes.data[subIndex];
  21291. submesh.render(false);
  21292. }
  21293. };
  21294. /**
  21295. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21296. * are rendered back to front if in the same alpha index.
  21297. *
  21298. * @param a The first submesh
  21299. * @param b The second submesh
  21300. * @returns The result of the comparison
  21301. */
  21302. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21303. // Alpha index first
  21304. if (a._alphaIndex > b._alphaIndex) {
  21305. return 1;
  21306. }
  21307. if (a._alphaIndex < b._alphaIndex) {
  21308. return -1;
  21309. }
  21310. // Then distance to camera
  21311. return RenderingGroup.backToFrontSortCompare(a, b);
  21312. };
  21313. /**
  21314. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21315. * are rendered back to front.
  21316. *
  21317. * @param a The first submesh
  21318. * @param b The second submesh
  21319. * @returns The result of the comparison
  21320. */
  21321. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21322. // Then distance to camera
  21323. if (a._distanceToCamera < b._distanceToCamera) {
  21324. return 1;
  21325. }
  21326. if (a._distanceToCamera > b._distanceToCamera) {
  21327. return -1;
  21328. }
  21329. return 0;
  21330. };
  21331. /**
  21332. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21333. * are rendered front to back (prevent overdraw).
  21334. *
  21335. * @param a The first submesh
  21336. * @param b The second submesh
  21337. * @returns The result of the comparison
  21338. */
  21339. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21340. // Then distance to camera
  21341. if (a._distanceToCamera < b._distanceToCamera) {
  21342. return -1;
  21343. }
  21344. if (a._distanceToCamera > b._distanceToCamera) {
  21345. return 1;
  21346. }
  21347. return 0;
  21348. };
  21349. /**
  21350. * Resets the different lists of submeshes to prepare a new frame.
  21351. */
  21352. RenderingGroup.prototype.prepare = function () {
  21353. this._opaqueSubMeshes.reset();
  21354. this._transparentSubMeshes.reset();
  21355. this._alphaTestSubMeshes.reset();
  21356. this._depthOnlySubMeshes.reset();
  21357. this._particleSystems.reset();
  21358. this._spriteManagers.reset();
  21359. this._edgesRenderers.reset();
  21360. };
  21361. RenderingGroup.prototype.dispose = function () {
  21362. this._opaqueSubMeshes.dispose();
  21363. this._transparentSubMeshes.dispose();
  21364. this._alphaTestSubMeshes.dispose();
  21365. this._depthOnlySubMeshes.dispose();
  21366. this._particleSystems.dispose();
  21367. this._spriteManagers.dispose();
  21368. this._edgesRenderers.dispose();
  21369. };
  21370. /**
  21371. * Inserts the submesh in its correct queue depending on its material.
  21372. * @param subMesh The submesh to dispatch
  21373. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21374. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21375. */
  21376. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21377. // Get mesh and materials if not provided
  21378. if (mesh === undefined) {
  21379. mesh = subMesh.getMesh();
  21380. }
  21381. if (material === undefined) {
  21382. material = subMesh.getMaterial();
  21383. }
  21384. if (material === null || material === undefined) {
  21385. return;
  21386. }
  21387. if (material.needAlphaBlendingForMesh(mesh)) {
  21388. this._transparentSubMeshes.push(subMesh);
  21389. }
  21390. else if (material.needAlphaTesting()) {
  21391. if (material.needDepthPrePass) {
  21392. this._depthOnlySubMeshes.push(subMesh);
  21393. }
  21394. this._alphaTestSubMeshes.push(subMesh);
  21395. }
  21396. else {
  21397. if (material.needDepthPrePass) {
  21398. this._depthOnlySubMeshes.push(subMesh);
  21399. }
  21400. this._opaqueSubMeshes.push(subMesh); // Opaque
  21401. }
  21402. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21403. this._edgesRenderers.push(mesh._edgesRenderer);
  21404. }
  21405. };
  21406. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21407. this._spriteManagers.push(spriteManager);
  21408. };
  21409. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21410. this._particleSystems.push(particleSystem);
  21411. };
  21412. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21413. if (this._particleSystems.length === 0) {
  21414. return;
  21415. }
  21416. // Particles
  21417. var activeCamera = this._scene.activeCamera;
  21418. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21419. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21420. var particleSystem = this._particleSystems.data[particleIndex];
  21421. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21422. continue;
  21423. }
  21424. var emitter = particleSystem.emitter;
  21425. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21426. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21427. }
  21428. }
  21429. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21430. };
  21431. RenderingGroup.prototype._renderSprites = function () {
  21432. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21433. return;
  21434. }
  21435. // Sprites
  21436. var activeCamera = this._scene.activeCamera;
  21437. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21438. for (var id = 0; id < this._spriteManagers.length; id++) {
  21439. var spriteManager = this._spriteManagers.data[id];
  21440. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21441. spriteManager.render();
  21442. }
  21443. }
  21444. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21445. };
  21446. return RenderingGroup;
  21447. }());
  21448. BABYLON.RenderingGroup = RenderingGroup;
  21449. })(BABYLON || (BABYLON = {}));
  21450. //# sourceMappingURL=babylon.renderingGroup.js.map
  21451. "use strict";
  21452. var BABYLON;
  21453. (function (BABYLON) {
  21454. var ClickInfo = /** @class */ (function () {
  21455. function ClickInfo() {
  21456. this._singleClick = false;
  21457. this._doubleClick = false;
  21458. this._hasSwiped = false;
  21459. this._ignore = false;
  21460. }
  21461. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21462. get: function () {
  21463. return this._singleClick;
  21464. },
  21465. set: function (b) {
  21466. this._singleClick = b;
  21467. },
  21468. enumerable: true,
  21469. configurable: true
  21470. });
  21471. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21472. get: function () {
  21473. return this._doubleClick;
  21474. },
  21475. set: function (b) {
  21476. this._doubleClick = b;
  21477. },
  21478. enumerable: true,
  21479. configurable: true
  21480. });
  21481. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21482. get: function () {
  21483. return this._hasSwiped;
  21484. },
  21485. set: function (b) {
  21486. this._hasSwiped = b;
  21487. },
  21488. enumerable: true,
  21489. configurable: true
  21490. });
  21491. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21492. get: function () {
  21493. return this._ignore;
  21494. },
  21495. set: function (b) {
  21496. this._ignore = b;
  21497. },
  21498. enumerable: true,
  21499. configurable: true
  21500. });
  21501. return ClickInfo;
  21502. }());
  21503. /**
  21504. * This class is used by the onRenderingGroupObservable
  21505. */
  21506. var RenderingGroupInfo = /** @class */ (function () {
  21507. function RenderingGroupInfo() {
  21508. }
  21509. /**
  21510. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21511. * This stage will be fired no matter what
  21512. */
  21513. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21514. /**
  21515. * Called before opaque object are rendered.
  21516. * This stage will be fired only if there's 3D Opaque content to render
  21517. */
  21518. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21519. /**
  21520. * Called after the opaque objects are rendered and before the transparent ones
  21521. * This stage will be fired only if there's 3D transparent content to render
  21522. */
  21523. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21524. /**
  21525. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21526. * This stage will be fired no matter what
  21527. */
  21528. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21529. return RenderingGroupInfo;
  21530. }());
  21531. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21532. /**
  21533. * Represents a scene to be rendered by the engine.
  21534. * @see http://doc.babylonjs.com/page.php?p=21911
  21535. */
  21536. var Scene = /** @class */ (function () {
  21537. /**
  21538. * @constructor
  21539. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21540. */
  21541. function Scene(engine) {
  21542. // Members
  21543. this.autoClear = true;
  21544. this.autoClearDepthAndStencil = true;
  21545. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21546. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21547. this._forceWireframe = false;
  21548. this._forcePointsCloud = false;
  21549. this.forceShowBoundingBoxes = false;
  21550. this.animationsEnabled = true;
  21551. this.useConstantAnimationDeltaTime = false;
  21552. this.constantlyUpdateMeshUnderPointer = false;
  21553. this.hoverCursor = "pointer";
  21554. this.defaultCursor = "";
  21555. /**
  21556. * This is used to call preventDefault() on pointer down
  21557. * in order to block unwanted artifacts like system double clicks
  21558. */
  21559. this.preventDefaultOnPointerDown = true;
  21560. // Metadata
  21561. this.metadata = null;
  21562. /**
  21563. * An event triggered when the scene is disposed.
  21564. * @type {BABYLON.Observable}
  21565. */
  21566. this.onDisposeObservable = new BABYLON.Observable();
  21567. this._onDisposeObserver = null;
  21568. /**
  21569. * An event triggered before rendering the scene (right after animations and physics)
  21570. * @type {BABYLON.Observable}
  21571. */
  21572. this.onBeforeRenderObservable = new BABYLON.Observable();
  21573. this._onBeforeRenderObserver = null;
  21574. /**
  21575. * An event triggered after rendering the scene
  21576. * @type {BABYLON.Observable}
  21577. */
  21578. this.onAfterRenderObservable = new BABYLON.Observable();
  21579. this._onAfterRenderObserver = null;
  21580. /**
  21581. * An event triggered before animating the scene
  21582. * @type {BABYLON.Observable}
  21583. */
  21584. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21585. /**
  21586. * An event triggered after animations processing
  21587. * @type {BABYLON.Observable}
  21588. */
  21589. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21590. /**
  21591. * An event triggered before draw calls are ready to be sent
  21592. * @type {BABYLON.Observable}
  21593. */
  21594. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21595. /**
  21596. * An event triggered after draw calls have been sent
  21597. * @type {BABYLON.Observable}
  21598. */
  21599. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21600. /**
  21601. * An event triggered when physic simulation is about to be run
  21602. * @type {BABYLON.Observable}
  21603. */
  21604. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21605. /**
  21606. * An event triggered when physic simulation has been done
  21607. * @type {BABYLON.Observable}
  21608. */
  21609. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21610. /**
  21611. * An event triggered when the scene is ready
  21612. * @type {BABYLON.Observable}
  21613. */
  21614. this.onReadyObservable = new BABYLON.Observable();
  21615. /**
  21616. * An event triggered before rendering a camera
  21617. * @type {BABYLON.Observable}
  21618. */
  21619. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21620. this._onBeforeCameraRenderObserver = null;
  21621. /**
  21622. * An event triggered after rendering a camera
  21623. * @type {BABYLON.Observable}
  21624. */
  21625. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21626. this._onAfterCameraRenderObserver = null;
  21627. /**
  21628. * An event triggered when active meshes evaluation is about to start
  21629. * @type {BABYLON.Observable}
  21630. */
  21631. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21632. /**
  21633. * An event triggered when active meshes evaluation is done
  21634. * @type {BABYLON.Observable}
  21635. */
  21636. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21637. /**
  21638. * An event triggered when particles rendering is about to start
  21639. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21640. * @type {BABYLON.Observable}
  21641. */
  21642. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21643. /**
  21644. * An event triggered when particles rendering is done
  21645. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21646. * @type {BABYLON.Observable}
  21647. */
  21648. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21649. /**
  21650. * An event triggered when sprites rendering is about to start
  21651. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21652. * @type {BABYLON.Observable}
  21653. */
  21654. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21655. /**
  21656. * An event triggered when sprites rendering is done
  21657. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21658. * @type {BABYLON.Observable}
  21659. */
  21660. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21661. /**
  21662. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21663. * @type {BABYLON.Observable}
  21664. */
  21665. this.onDataLoadedObservable = new BABYLON.Observable();
  21666. /**
  21667. * An event triggered when a camera is created
  21668. * @type {BABYLON.Observable}
  21669. */
  21670. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21671. /**
  21672. * An event triggered when a camera is removed
  21673. * @type {BABYLON.Observable}
  21674. */
  21675. this.onCameraRemovedObservable = new BABYLON.Observable();
  21676. /**
  21677. * An event triggered when a light is created
  21678. * @type {BABYLON.Observable}
  21679. */
  21680. this.onNewLightAddedObservable = new BABYLON.Observable();
  21681. /**
  21682. * An event triggered when a light is removed
  21683. * @type {BABYLON.Observable}
  21684. */
  21685. this.onLightRemovedObservable = new BABYLON.Observable();
  21686. /**
  21687. * An event triggered when a geometry is created
  21688. * @type {BABYLON.Observable}
  21689. */
  21690. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21691. /**
  21692. * An event triggered when a geometry is removed
  21693. * @type {BABYLON.Observable}
  21694. */
  21695. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21696. /**
  21697. * An event triggered when a transform node is created
  21698. * @type {BABYLON.Observable}
  21699. */
  21700. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21701. /**
  21702. * An event triggered when a transform node is removed
  21703. * @type {BABYLON.Observable}
  21704. */
  21705. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21706. /**
  21707. * An event triggered when a mesh is created
  21708. * @type {BABYLON.Observable}
  21709. */
  21710. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21711. /**
  21712. * An event triggered when a mesh is removed
  21713. * @type {BABYLON.Observable}
  21714. */
  21715. this.onMeshRemovedObservable = new BABYLON.Observable();
  21716. /**
  21717. * An event triggered when render targets are about to be rendered
  21718. * Can happen multiple times per frame.
  21719. * @type {BABYLON.Observable}
  21720. */
  21721. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21722. /**
  21723. * An event triggered when render targets were rendered.
  21724. * Can happen multiple times per frame.
  21725. * @type {BABYLON.Observable}
  21726. */
  21727. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21728. /**
  21729. * An event triggered before calculating deterministic simulation step
  21730. * @type {BABYLON.Observable}
  21731. */
  21732. this.onBeforeStepObservable = new BABYLON.Observable();
  21733. /**
  21734. * An event triggered after calculating deterministic simulation step
  21735. * @type {BABYLON.Observable}
  21736. */
  21737. this.onAfterStepObservable = new BABYLON.Observable();
  21738. /**
  21739. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21740. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21741. * 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)
  21742. */
  21743. this.onRenderingGroupObservable = new BABYLON.Observable();
  21744. // Animations
  21745. this.animations = [];
  21746. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21747. /**
  21748. * 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).
  21749. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21750. */
  21751. this.onPrePointerObservable = new BABYLON.Observable();
  21752. /**
  21753. * Observable event triggered each time an input event is received from the rendering canvas
  21754. */
  21755. this.onPointerObservable = new BABYLON.Observable();
  21756. this._meshPickProceed = false;
  21757. this._currentPickResult = null;
  21758. this._previousPickResult = null;
  21759. this._totalPointersPressed = 0;
  21760. this._doubleClickOccured = false;
  21761. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21762. this.cameraToUseForPointers = null;
  21763. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21764. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21765. this._startingPointerTime = 0;
  21766. this._previousStartingPointerTime = 0;
  21767. // Deterministic lockstep
  21768. this._timeAccumulator = 0;
  21769. this._currentStepId = 0;
  21770. this._currentInternalStep = 0;
  21771. // Keyboard
  21772. /**
  21773. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21774. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21775. */
  21776. this.onPreKeyboardObservable = new BABYLON.Observable();
  21777. /**
  21778. * Observable event triggered each time an keyboard event is received from the hosting window
  21779. */
  21780. this.onKeyboardObservable = new BABYLON.Observable();
  21781. // Coordinate system
  21782. /**
  21783. * use right-handed coordinate system on this scene.
  21784. * @type {boolean}
  21785. */
  21786. this._useRightHandedSystem = false;
  21787. // Fog
  21788. this._fogEnabled = true;
  21789. this._fogMode = Scene.FOGMODE_NONE;
  21790. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21791. this.fogDensity = 0.1;
  21792. this.fogStart = 0;
  21793. this.fogEnd = 1000.0;
  21794. // Lights
  21795. /**
  21796. * is shadow enabled on this scene.
  21797. * @type {boolean}
  21798. */
  21799. this._shadowsEnabled = true;
  21800. /**
  21801. * is light enabled on this scene.
  21802. * @type {boolean}
  21803. */
  21804. this._lightsEnabled = true;
  21805. /**
  21806. * All of the lights added to this scene.
  21807. * @see BABYLON.Light
  21808. * @type {BABYLON.Light[]}
  21809. */
  21810. this.lights = new Array();
  21811. // Cameras
  21812. /** All of the cameras added to this scene. */
  21813. this.cameras = new Array();
  21814. /** All of the active cameras added to this scene. */
  21815. this.activeCameras = new Array();
  21816. // Meshes
  21817. /**
  21818. * All of the tranform nodes added to this scene.
  21819. * @see BABYLON.TransformNode
  21820. * @type {BABYLON.TransformNode[]}
  21821. */
  21822. this.transformNodes = new Array();
  21823. /**
  21824. * All of the (abstract) meshes added to this scene.
  21825. * @see BABYLON.AbstractMesh
  21826. * @type {BABYLON.AbstractMesh[]}
  21827. */
  21828. this.meshes = new Array();
  21829. /**
  21830. * All of the animation groups added to this scene.
  21831. * @see BABYLON.AnimationGroup
  21832. * @type {BABYLON.AnimationGroup[]}
  21833. */
  21834. this.animationGroups = new Array();
  21835. // Geometries
  21836. this._geometries = new Array();
  21837. this.materials = new Array();
  21838. this.multiMaterials = new Array();
  21839. // Textures
  21840. this._texturesEnabled = true;
  21841. this.textures = new Array();
  21842. // Particles
  21843. this.particlesEnabled = true;
  21844. this.particleSystems = new Array();
  21845. // Sprites
  21846. this.spritesEnabled = true;
  21847. this.spriteManagers = new Array();
  21848. /**
  21849. * The list of layers (background and foreground) of the scene.
  21850. */
  21851. this.layers = new Array();
  21852. /**
  21853. * The list of effect layers (highlights/glow) contained in the scene.
  21854. */
  21855. this.effectLayers = new Array();
  21856. // Skeletons
  21857. this._skeletonsEnabled = true;
  21858. this.skeletons = new Array();
  21859. // Morph targets
  21860. this.morphTargetManagers = new Array();
  21861. // Lens flares
  21862. this.lensFlaresEnabled = true;
  21863. this.lensFlareSystems = new Array();
  21864. // Collisions
  21865. this.collisionsEnabled = true;
  21866. /** Defines the gravity applied to this scene */
  21867. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21868. // Postprocesses
  21869. this.postProcesses = new Array();
  21870. this.postProcessesEnabled = true;
  21871. // Customs render targets
  21872. this.renderTargetsEnabled = true;
  21873. this.dumpNextRenderTargets = false;
  21874. this.customRenderTargets = new Array();
  21875. // Imported meshes
  21876. this.importedMeshesFiles = new Array();
  21877. // Probes
  21878. this.probesEnabled = true;
  21879. this.reflectionProbes = new Array();
  21880. this._actionManagers = new Array();
  21881. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21882. // Procedural textures
  21883. this.proceduralTexturesEnabled = true;
  21884. this._proceduralTextures = new Array();
  21885. this.soundTracks = new Array();
  21886. this._audioEnabled = true;
  21887. this._headphone = false;
  21888. // Performance counters
  21889. this._totalVertices = new BABYLON.PerfCounter();
  21890. this._activeIndices = new BABYLON.PerfCounter();
  21891. this._activeParticles = new BABYLON.PerfCounter();
  21892. this._activeBones = new BABYLON.PerfCounter();
  21893. this._animationTime = 0;
  21894. this.animationTimeScale = 1;
  21895. this._renderId = 0;
  21896. this._executeWhenReadyTimeoutId = -1;
  21897. this._intermediateRendering = false;
  21898. this._viewUpdateFlag = -1;
  21899. this._projectionUpdateFlag = -1;
  21900. this._alternateViewUpdateFlag = -1;
  21901. this._alternateProjectionUpdateFlag = -1;
  21902. this._toBeDisposed = new BABYLON.SmartArray(256);
  21903. this._activeRequests = new Array();
  21904. this._pendingData = new Array();
  21905. this._isDisposed = false;
  21906. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21907. this._activeMeshes = new BABYLON.SmartArray(256);
  21908. this._processedMaterials = new BABYLON.SmartArray(256);
  21909. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21910. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21911. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21912. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21913. this._activeAnimatables = new Array();
  21914. this._transformMatrix = BABYLON.Matrix.Zero();
  21915. this._useAlternateCameraConfiguration = false;
  21916. this._alternateRendering = false;
  21917. this.requireLightSorting = false;
  21918. this._depthRenderer = {};
  21919. this._activeMeshesFrozen = false;
  21920. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21921. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21922. this._engine.scenes.push(this);
  21923. this._uid = null;
  21924. this._renderingManager = new BABYLON.RenderingManager(this);
  21925. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21926. if (BABYLON.OutlineRenderer) {
  21927. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21928. }
  21929. if (BABYLON.Tools.IsWindowObjectExist()) {
  21930. this.attachControl();
  21931. }
  21932. //simplification queue
  21933. if (BABYLON.SimplificationQueue) {
  21934. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21935. }
  21936. //collision coordinator initialization. For now legacy per default.
  21937. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21938. // Uniform Buffer
  21939. this._createUbo();
  21940. // Default Image processing definition.
  21941. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21942. }
  21943. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21944. /** The fog is deactivated */
  21945. get: function () {
  21946. return Scene._FOGMODE_NONE;
  21947. },
  21948. enumerable: true,
  21949. configurable: true
  21950. });
  21951. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21952. /** The fog density is following an exponential function */
  21953. get: function () {
  21954. return Scene._FOGMODE_EXP;
  21955. },
  21956. enumerable: true,
  21957. configurable: true
  21958. });
  21959. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21960. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21961. get: function () {
  21962. return Scene._FOGMODE_EXP2;
  21963. },
  21964. enumerable: true,
  21965. configurable: true
  21966. });
  21967. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21968. /** The fog density is following a linear function. */
  21969. get: function () {
  21970. return Scene._FOGMODE_LINEAR;
  21971. },
  21972. enumerable: true,
  21973. configurable: true
  21974. });
  21975. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21976. /**
  21977. * Texture used in all pbr material as the reflection texture.
  21978. * As in the majority of the scene they are the same (exception for multi room and so on),
  21979. * this is easier to reference from here than from all the materials.
  21980. */
  21981. get: function () {
  21982. return this._environmentTexture;
  21983. },
  21984. /**
  21985. * Texture used in all pbr material as the reflection texture.
  21986. * As in the majority of the scene they are the same (exception for multi room and so on),
  21987. * this is easier to set here than in all the materials.
  21988. */
  21989. set: function (value) {
  21990. if (this._environmentTexture === value) {
  21991. return;
  21992. }
  21993. this._environmentTexture = value;
  21994. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21995. },
  21996. enumerable: true,
  21997. configurable: true
  21998. });
  21999. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  22000. /**
  22001. * Default image processing configuration used either in the rendering
  22002. * Forward main pass or through the imageProcessingPostProcess if present.
  22003. * As in the majority of the scene they are the same (exception for multi camera),
  22004. * this is easier to reference from here than from all the materials and post process.
  22005. *
  22006. * No setter as we it is a shared configuration, you can set the values instead.
  22007. */
  22008. get: function () {
  22009. return this._imageProcessingConfiguration;
  22010. },
  22011. enumerable: true,
  22012. configurable: true
  22013. });
  22014. Object.defineProperty(Scene.prototype, "forceWireframe", {
  22015. get: function () {
  22016. return this._forceWireframe;
  22017. },
  22018. set: function (value) {
  22019. if (this._forceWireframe === value) {
  22020. return;
  22021. }
  22022. this._forceWireframe = value;
  22023. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22024. },
  22025. enumerable: true,
  22026. configurable: true
  22027. });
  22028. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22029. get: function () {
  22030. return this._forcePointsCloud;
  22031. },
  22032. set: function (value) {
  22033. if (this._forcePointsCloud === value) {
  22034. return;
  22035. }
  22036. this._forcePointsCloud = value;
  22037. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22038. },
  22039. enumerable: true,
  22040. configurable: true
  22041. });
  22042. Object.defineProperty(Scene.prototype, "onDispose", {
  22043. /** A function to be executed when this scene is disposed. */
  22044. set: function (callback) {
  22045. if (this._onDisposeObserver) {
  22046. this.onDisposeObservable.remove(this._onDisposeObserver);
  22047. }
  22048. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22049. },
  22050. enumerable: true,
  22051. configurable: true
  22052. });
  22053. Object.defineProperty(Scene.prototype, "beforeRender", {
  22054. /** A function to be executed before rendering this scene */
  22055. set: function (callback) {
  22056. if (this._onBeforeRenderObserver) {
  22057. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22058. }
  22059. if (callback) {
  22060. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22061. }
  22062. },
  22063. enumerable: true,
  22064. configurable: true
  22065. });
  22066. Object.defineProperty(Scene.prototype, "afterRender", {
  22067. /** A function to be executed after rendering this scene */
  22068. set: function (callback) {
  22069. if (this._onAfterRenderObserver) {
  22070. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22071. }
  22072. if (callback) {
  22073. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22074. }
  22075. },
  22076. enumerable: true,
  22077. configurable: true
  22078. });
  22079. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22080. set: function (callback) {
  22081. if (this._onBeforeCameraRenderObserver) {
  22082. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22083. }
  22084. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22085. },
  22086. enumerable: true,
  22087. configurable: true
  22088. });
  22089. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22090. set: function (callback) {
  22091. if (this._onAfterCameraRenderObserver) {
  22092. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22093. }
  22094. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22095. },
  22096. enumerable: true,
  22097. configurable: true
  22098. });
  22099. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22100. get: function () {
  22101. if (!this._gamepadManager) {
  22102. this._gamepadManager = new BABYLON.GamepadManager(this);
  22103. }
  22104. return this._gamepadManager;
  22105. },
  22106. enumerable: true,
  22107. configurable: true
  22108. });
  22109. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22110. get: function () {
  22111. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22112. },
  22113. enumerable: true,
  22114. configurable: true
  22115. });
  22116. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22117. get: function () {
  22118. return this._useRightHandedSystem;
  22119. },
  22120. set: function (value) {
  22121. if (this._useRightHandedSystem === value) {
  22122. return;
  22123. }
  22124. this._useRightHandedSystem = value;
  22125. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22126. },
  22127. enumerable: true,
  22128. configurable: true
  22129. });
  22130. Scene.prototype.setStepId = function (newStepId) {
  22131. this._currentStepId = newStepId;
  22132. };
  22133. ;
  22134. Scene.prototype.getStepId = function () {
  22135. return this._currentStepId;
  22136. };
  22137. ;
  22138. Scene.prototype.getInternalStep = function () {
  22139. return this._currentInternalStep;
  22140. };
  22141. ;
  22142. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22143. get: function () {
  22144. return this._fogEnabled;
  22145. },
  22146. /**
  22147. * is fog enabled on this scene.
  22148. */
  22149. set: function (value) {
  22150. if (this._fogEnabled === value) {
  22151. return;
  22152. }
  22153. this._fogEnabled = value;
  22154. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22155. },
  22156. enumerable: true,
  22157. configurable: true
  22158. });
  22159. Object.defineProperty(Scene.prototype, "fogMode", {
  22160. get: function () {
  22161. return this._fogMode;
  22162. },
  22163. set: function (value) {
  22164. if (this._fogMode === value) {
  22165. return;
  22166. }
  22167. this._fogMode = value;
  22168. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22169. },
  22170. enumerable: true,
  22171. configurable: true
  22172. });
  22173. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22174. get: function () {
  22175. return this._shadowsEnabled;
  22176. },
  22177. set: function (value) {
  22178. if (this._shadowsEnabled === value) {
  22179. return;
  22180. }
  22181. this._shadowsEnabled = value;
  22182. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22183. },
  22184. enumerable: true,
  22185. configurable: true
  22186. });
  22187. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22188. get: function () {
  22189. return this._lightsEnabled;
  22190. },
  22191. set: function (value) {
  22192. if (this._lightsEnabled === value) {
  22193. return;
  22194. }
  22195. this._lightsEnabled = value;
  22196. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22197. },
  22198. enumerable: true,
  22199. configurable: true
  22200. });
  22201. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22202. /** The default material used on meshes when no material is affected */
  22203. get: function () {
  22204. if (!this._defaultMaterial) {
  22205. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22206. }
  22207. return this._defaultMaterial;
  22208. },
  22209. /** The default material used on meshes when no material is affected */
  22210. set: function (value) {
  22211. this._defaultMaterial = value;
  22212. },
  22213. enumerable: true,
  22214. configurable: true
  22215. });
  22216. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22217. get: function () {
  22218. return this._texturesEnabled;
  22219. },
  22220. set: function (value) {
  22221. if (this._texturesEnabled === value) {
  22222. return;
  22223. }
  22224. this._texturesEnabled = value;
  22225. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22226. },
  22227. enumerable: true,
  22228. configurable: true
  22229. });
  22230. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22231. get: function () {
  22232. return this._skeletonsEnabled;
  22233. },
  22234. set: function (value) {
  22235. if (this._skeletonsEnabled === value) {
  22236. return;
  22237. }
  22238. this._skeletonsEnabled = value;
  22239. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22240. },
  22241. enumerable: true,
  22242. configurable: true
  22243. });
  22244. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22245. get: function () {
  22246. if (!this._postProcessRenderPipelineManager) {
  22247. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22248. }
  22249. return this._postProcessRenderPipelineManager;
  22250. },
  22251. enumerable: true,
  22252. configurable: true
  22253. });
  22254. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22255. get: function () {
  22256. if (!this._mainSoundTrack) {
  22257. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22258. }
  22259. return this._mainSoundTrack;
  22260. },
  22261. enumerable: true,
  22262. configurable: true
  22263. });
  22264. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22265. get: function () {
  22266. return this._alternateRendering;
  22267. },
  22268. enumerable: true,
  22269. configurable: true
  22270. });
  22271. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22272. get: function () {
  22273. return this._frustumPlanes;
  22274. },
  22275. enumerable: true,
  22276. configurable: true
  22277. });
  22278. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22279. /**
  22280. * Gets the current geometry buffer associated to the scene.
  22281. */
  22282. get: function () {
  22283. return this._geometryBufferRenderer;
  22284. },
  22285. /**
  22286. * Sets the current geometry buffer for the scene.
  22287. */
  22288. set: function (geometryBufferRenderer) {
  22289. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22290. this._geometryBufferRenderer = geometryBufferRenderer;
  22291. }
  22292. },
  22293. enumerable: true,
  22294. configurable: true
  22295. });
  22296. Object.defineProperty(Scene.prototype, "debugLayer", {
  22297. // Properties
  22298. get: function () {
  22299. if (!this._debugLayer) {
  22300. this._debugLayer = new BABYLON.DebugLayer(this);
  22301. }
  22302. return this._debugLayer;
  22303. },
  22304. enumerable: true,
  22305. configurable: true
  22306. });
  22307. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22308. get: function () {
  22309. return this._workerCollisions;
  22310. },
  22311. set: function (enabled) {
  22312. if (!BABYLON.CollisionCoordinatorLegacy) {
  22313. return;
  22314. }
  22315. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22316. this._workerCollisions = enabled;
  22317. if (this.collisionCoordinator) {
  22318. this.collisionCoordinator.destroy();
  22319. }
  22320. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22321. this.collisionCoordinator.init(this);
  22322. },
  22323. enumerable: true,
  22324. configurable: true
  22325. });
  22326. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22327. get: function () {
  22328. return this._selectionOctree;
  22329. },
  22330. enumerable: true,
  22331. configurable: true
  22332. });
  22333. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22334. /**
  22335. * The mesh that is currently under the pointer.
  22336. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22337. */
  22338. get: function () {
  22339. return this._pointerOverMesh;
  22340. },
  22341. enumerable: true,
  22342. configurable: true
  22343. });
  22344. Object.defineProperty(Scene.prototype, "pointerX", {
  22345. /**
  22346. * Current on-screen X position of the pointer
  22347. * @return {number} X position of the pointer
  22348. */
  22349. get: function () {
  22350. return this._pointerX;
  22351. },
  22352. enumerable: true,
  22353. configurable: true
  22354. });
  22355. Object.defineProperty(Scene.prototype, "pointerY", {
  22356. /**
  22357. * Current on-screen Y position of the pointer
  22358. * @return {number} Y position of the pointer
  22359. */
  22360. get: function () {
  22361. return this._pointerY;
  22362. },
  22363. enumerable: true,
  22364. configurable: true
  22365. });
  22366. Scene.prototype.getCachedMaterial = function () {
  22367. return this._cachedMaterial;
  22368. };
  22369. Scene.prototype.getCachedEffect = function () {
  22370. return this._cachedEffect;
  22371. };
  22372. Scene.prototype.getCachedVisibility = function () {
  22373. return this._cachedVisibility;
  22374. };
  22375. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22376. if (visibility === void 0) { visibility = 1; }
  22377. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22378. };
  22379. Scene.prototype.getBoundingBoxRenderer = function () {
  22380. if (!this._boundingBoxRenderer) {
  22381. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22382. }
  22383. return this._boundingBoxRenderer;
  22384. };
  22385. Scene.prototype.getOutlineRenderer = function () {
  22386. return this._outlineRenderer;
  22387. };
  22388. Scene.prototype.getEngine = function () {
  22389. return this._engine;
  22390. };
  22391. Scene.prototype.getTotalVertices = function () {
  22392. return this._totalVertices.current;
  22393. };
  22394. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22395. get: function () {
  22396. return this._totalVertices;
  22397. },
  22398. enumerable: true,
  22399. configurable: true
  22400. });
  22401. Scene.prototype.getActiveIndices = function () {
  22402. return this._activeIndices.current;
  22403. };
  22404. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22405. get: function () {
  22406. return this._activeIndices;
  22407. },
  22408. enumerable: true,
  22409. configurable: true
  22410. });
  22411. Scene.prototype.getActiveParticles = function () {
  22412. return this._activeParticles.current;
  22413. };
  22414. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22415. get: function () {
  22416. return this._activeParticles;
  22417. },
  22418. enumerable: true,
  22419. configurable: true
  22420. });
  22421. Scene.prototype.getActiveBones = function () {
  22422. return this._activeBones.current;
  22423. };
  22424. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22425. get: function () {
  22426. return this._activeBones;
  22427. },
  22428. enumerable: true,
  22429. configurable: true
  22430. });
  22431. // Stats
  22432. Scene.prototype.getInterFramePerfCounter = function () {
  22433. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22434. return 0;
  22435. };
  22436. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22437. get: function () {
  22438. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22439. return null;
  22440. },
  22441. enumerable: true,
  22442. configurable: true
  22443. });
  22444. Scene.prototype.getLastFrameDuration = function () {
  22445. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22446. return 0;
  22447. };
  22448. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22449. get: function () {
  22450. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22451. return null;
  22452. },
  22453. enumerable: true,
  22454. configurable: true
  22455. });
  22456. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22457. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22458. return 0;
  22459. };
  22460. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22461. get: function () {
  22462. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22463. return null;
  22464. },
  22465. enumerable: true,
  22466. configurable: true
  22467. });
  22468. Scene.prototype.getActiveMeshes = function () {
  22469. return this._activeMeshes;
  22470. };
  22471. Scene.prototype.getRenderTargetsDuration = function () {
  22472. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22473. return 0;
  22474. };
  22475. Scene.prototype.getRenderDuration = function () {
  22476. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22477. return 0;
  22478. };
  22479. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22480. get: function () {
  22481. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22482. return null;
  22483. },
  22484. enumerable: true,
  22485. configurable: true
  22486. });
  22487. Scene.prototype.getParticlesDuration = function () {
  22488. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22489. return 0;
  22490. };
  22491. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22492. get: function () {
  22493. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22494. return null;
  22495. },
  22496. enumerable: true,
  22497. configurable: true
  22498. });
  22499. Scene.prototype.getSpritesDuration = function () {
  22500. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22501. return 0;
  22502. };
  22503. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22504. get: function () {
  22505. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22506. return null;
  22507. },
  22508. enumerable: true,
  22509. configurable: true
  22510. });
  22511. Scene.prototype.getAnimationRatio = function () {
  22512. return this._animationRatio;
  22513. };
  22514. Scene.prototype.getRenderId = function () {
  22515. return this._renderId;
  22516. };
  22517. Scene.prototype.incrementRenderId = function () {
  22518. this._renderId++;
  22519. };
  22520. Scene.prototype._updatePointerPosition = function (evt) {
  22521. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22522. if (!canvasRect) {
  22523. return;
  22524. }
  22525. this._pointerX = evt.clientX - canvasRect.left;
  22526. this._pointerY = evt.clientY - canvasRect.top;
  22527. this._unTranslatedPointerX = this._pointerX;
  22528. this._unTranslatedPointerY = this._pointerY;
  22529. };
  22530. Scene.prototype._createUbo = function () {
  22531. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22532. this._sceneUbo.addUniform("viewProjection", 16);
  22533. this._sceneUbo.addUniform("view", 16);
  22534. };
  22535. Scene.prototype._createAlternateUbo = function () {
  22536. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22537. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22538. this._alternateSceneUbo.addUniform("view", 16);
  22539. };
  22540. // Pointers handling
  22541. /**
  22542. * Use this method to simulate a pointer move on a mesh
  22543. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22544. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22545. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22546. */
  22547. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22548. var evt = new PointerEvent("pointermove", pointerEventInit);
  22549. return this._processPointerMove(pickResult, evt);
  22550. };
  22551. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22552. var canvas = this._engine.getRenderingCanvas();
  22553. if (!canvas) {
  22554. return this;
  22555. }
  22556. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22557. this.setPointerOverSprite(null);
  22558. this.setPointerOverMesh(pickResult.pickedMesh);
  22559. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22560. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22561. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22562. }
  22563. else {
  22564. canvas.style.cursor = this.hoverCursor;
  22565. }
  22566. }
  22567. else {
  22568. canvas.style.cursor = this.defaultCursor;
  22569. }
  22570. }
  22571. else {
  22572. this.setPointerOverMesh(null);
  22573. // Sprites
  22574. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22575. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22576. this.setPointerOverSprite(pickResult.pickedSprite);
  22577. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22578. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22579. }
  22580. else {
  22581. canvas.style.cursor = this.hoverCursor;
  22582. }
  22583. }
  22584. else {
  22585. this.setPointerOverSprite(null);
  22586. // Restore pointer
  22587. canvas.style.cursor = this.defaultCursor;
  22588. }
  22589. }
  22590. if (pickResult) {
  22591. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22592. if (this.onPointerMove) {
  22593. this.onPointerMove(evt, pickResult, type);
  22594. }
  22595. if (this.onPointerObservable.hasObservers()) {
  22596. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22597. this.onPointerObservable.notifyObservers(pi, type);
  22598. }
  22599. }
  22600. return this;
  22601. };
  22602. /**
  22603. * Use this method to simulate a pointer down on a mesh
  22604. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22605. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22606. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22607. */
  22608. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22609. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22610. return this._processPointerDown(pickResult, evt);
  22611. };
  22612. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22613. var _this = this;
  22614. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22615. this._pickedDownMesh = pickResult.pickedMesh;
  22616. var actionManager = pickResult.pickedMesh.actionManager;
  22617. if (actionManager) {
  22618. if (actionManager.hasPickTriggers) {
  22619. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22620. switch (evt.button) {
  22621. case 0:
  22622. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22623. break;
  22624. case 1:
  22625. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22626. break;
  22627. case 2:
  22628. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22629. break;
  22630. }
  22631. }
  22632. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22633. window.setTimeout(function () {
  22634. 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);
  22635. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22636. if (_this._totalPointersPressed !== 0 &&
  22637. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22638. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22639. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22640. _this._startingPointerTime = 0;
  22641. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22642. }
  22643. }
  22644. }, Scene.LongPressDelay);
  22645. }
  22646. }
  22647. }
  22648. if (pickResult) {
  22649. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22650. if (this.onPointerDown) {
  22651. this.onPointerDown(evt, pickResult, type);
  22652. }
  22653. if (this.onPointerObservable.hasObservers()) {
  22654. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22655. this.onPointerObservable.notifyObservers(pi, type);
  22656. }
  22657. }
  22658. return this;
  22659. };
  22660. /**
  22661. * Use this method to simulate a pointer up on a mesh
  22662. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22663. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22664. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22665. */
  22666. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22667. var evt = new PointerEvent("pointerup", pointerEventInit);
  22668. var clickInfo = new ClickInfo();
  22669. clickInfo.singleClick = true;
  22670. clickInfo.ignore = true;
  22671. return this._processPointerUp(pickResult, evt, clickInfo);
  22672. };
  22673. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22674. if (pickResult && pickResult && pickResult.pickedMesh) {
  22675. this._pickedUpMesh = pickResult.pickedMesh;
  22676. if (this._pickedDownMesh === this._pickedUpMesh) {
  22677. if (this.onPointerPick) {
  22678. this.onPointerPick(evt, pickResult);
  22679. }
  22680. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22681. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22682. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22683. this.onPointerObservable.notifyObservers(pi, type_1);
  22684. }
  22685. }
  22686. if (pickResult.pickedMesh.actionManager) {
  22687. if (clickInfo.ignore) {
  22688. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22689. }
  22690. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22691. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22692. }
  22693. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22694. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22695. }
  22696. }
  22697. }
  22698. if (this._pickedDownMesh &&
  22699. this._pickedDownMesh.actionManager &&
  22700. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22701. this._pickedDownMesh !== this._pickedUpMesh) {
  22702. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22703. }
  22704. var type = BABYLON.PointerEventTypes.POINTERUP;
  22705. if (this.onPointerObservable.hasObservers()) {
  22706. if (!clickInfo.ignore) {
  22707. if (!clickInfo.hasSwiped) {
  22708. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22709. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22710. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22711. this.onPointerObservable.notifyObservers(pi, type_2);
  22712. }
  22713. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22714. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22715. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22716. this.onPointerObservable.notifyObservers(pi, type_3);
  22717. }
  22718. }
  22719. }
  22720. else {
  22721. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22722. this.onPointerObservable.notifyObservers(pi, type);
  22723. }
  22724. }
  22725. if (this.onPointerUp) {
  22726. this.onPointerUp(evt, pickResult, type);
  22727. }
  22728. return this;
  22729. };
  22730. /**
  22731. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22732. * @param attachUp defines if you want to attach events to pointerup
  22733. * @param attachDown defines if you want to attach events to pointerdown
  22734. * @param attachMove defines if you want to attach events to pointermove
  22735. */
  22736. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22737. var _this = this;
  22738. if (attachUp === void 0) { attachUp = true; }
  22739. if (attachDown === void 0) { attachDown = true; }
  22740. if (attachMove === void 0) { attachMove = true; }
  22741. this._initActionManager = function (act, clickInfo) {
  22742. if (!_this._meshPickProceed) {
  22743. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22744. _this._currentPickResult = pickResult;
  22745. if (pickResult) {
  22746. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22747. }
  22748. _this._meshPickProceed = true;
  22749. }
  22750. return act;
  22751. };
  22752. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22753. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22754. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22755. btn !== _this._previousButtonPressed) {
  22756. _this._doubleClickOccured = false;
  22757. clickInfo.singleClick = true;
  22758. clickInfo.ignore = false;
  22759. cb(clickInfo, _this._currentPickResult);
  22760. }
  22761. };
  22762. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22763. var clickInfo = new ClickInfo();
  22764. _this._currentPickResult = null;
  22765. var act = null;
  22766. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22767. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22768. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22769. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22770. act = _this._initActionManager(act, clickInfo);
  22771. if (act)
  22772. checkPicking = act.hasPickTriggers;
  22773. }
  22774. if (checkPicking) {
  22775. var btn = evt.button;
  22776. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22777. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22778. if (!clickInfo.hasSwiped) {
  22779. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22780. if (!checkSingleClickImmediately) {
  22781. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22782. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22783. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22784. act = _this._initActionManager(act, clickInfo);
  22785. if (act)
  22786. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22787. }
  22788. }
  22789. if (checkSingleClickImmediately) {
  22790. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22791. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22792. btn !== _this._previousButtonPressed) {
  22793. clickInfo.singleClick = true;
  22794. cb(clickInfo, _this._currentPickResult);
  22795. }
  22796. }
  22797. else {
  22798. // wait that no double click has been raised during the double click delay
  22799. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22800. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22801. }
  22802. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22803. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22804. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22805. act = _this._initActionManager(act, clickInfo);
  22806. if (act)
  22807. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22808. }
  22809. if (checkDoubleClick) {
  22810. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22811. if (btn === _this._previousButtonPressed &&
  22812. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22813. !_this._doubleClickOccured) {
  22814. // pointer has not moved for 2 clicks, it's a double click
  22815. if (!clickInfo.hasSwiped &&
  22816. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22817. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22818. _this._previousStartingPointerTime = 0;
  22819. _this._doubleClickOccured = true;
  22820. clickInfo.doubleClick = true;
  22821. clickInfo.ignore = false;
  22822. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22823. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22824. }
  22825. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22826. cb(clickInfo, _this._currentPickResult);
  22827. }
  22828. else {
  22829. _this._doubleClickOccured = false;
  22830. _this._previousStartingPointerTime = _this._startingPointerTime;
  22831. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22832. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22833. _this._previousButtonPressed = btn;
  22834. if (Scene.ExclusiveDoubleClickMode) {
  22835. if (_this._previousDelayedSimpleClickTimeout) {
  22836. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22837. }
  22838. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22839. cb(clickInfo, _this._previousPickResult);
  22840. }
  22841. else {
  22842. cb(clickInfo, _this._currentPickResult);
  22843. }
  22844. }
  22845. }
  22846. else {
  22847. _this._doubleClickOccured = false;
  22848. _this._previousStartingPointerTime = _this._startingPointerTime;
  22849. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22850. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22851. _this._previousButtonPressed = btn;
  22852. }
  22853. }
  22854. }
  22855. }
  22856. clickInfo.ignore = true;
  22857. cb(clickInfo, _this._currentPickResult);
  22858. };
  22859. this._spritePredicate = function (sprite) {
  22860. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22861. };
  22862. this._onPointerMove = function (evt) {
  22863. _this._updatePointerPosition(evt);
  22864. // PreObservable support
  22865. if (_this.onPrePointerObservable.hasObservers()) {
  22866. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22867. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22868. _this.onPrePointerObservable.notifyObservers(pi, type);
  22869. if (pi.skipOnPointerObservable) {
  22870. return;
  22871. }
  22872. }
  22873. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22874. return;
  22875. }
  22876. if (!_this.pointerMovePredicate) {
  22877. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22878. }
  22879. // Meshes
  22880. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22881. _this._processPointerMove(pickResult, evt);
  22882. };
  22883. this._onPointerDown = function (evt) {
  22884. _this._totalPointersPressed++;
  22885. _this._pickedDownMesh = null;
  22886. _this._meshPickProceed = false;
  22887. _this._updatePointerPosition(evt);
  22888. if (_this.preventDefaultOnPointerDown && canvas) {
  22889. evt.preventDefault();
  22890. canvas.focus();
  22891. }
  22892. // PreObservable support
  22893. if (_this.onPrePointerObservable.hasObservers()) {
  22894. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22895. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22896. _this.onPrePointerObservable.notifyObservers(pi, type);
  22897. if (pi.skipOnPointerObservable) {
  22898. return;
  22899. }
  22900. }
  22901. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22902. return;
  22903. }
  22904. _this._startingPointerPosition.x = _this._pointerX;
  22905. _this._startingPointerPosition.y = _this._pointerY;
  22906. _this._startingPointerTime = new Date().getTime();
  22907. if (!_this.pointerDownPredicate) {
  22908. _this.pointerDownPredicate = function (mesh) {
  22909. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22910. };
  22911. }
  22912. // Meshes
  22913. _this._pickedDownMesh = null;
  22914. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22915. _this._processPointerDown(pickResult, evt);
  22916. // Sprites
  22917. _this._pickedDownSprite = null;
  22918. if (_this.spriteManagers.length > 0) {
  22919. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22920. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22921. if (pickResult.pickedSprite.actionManager) {
  22922. _this._pickedDownSprite = pickResult.pickedSprite;
  22923. switch (evt.button) {
  22924. case 0:
  22925. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22926. break;
  22927. case 1:
  22928. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22929. break;
  22930. case 2:
  22931. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22932. break;
  22933. }
  22934. if (pickResult.pickedSprite.actionManager) {
  22935. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22936. }
  22937. }
  22938. }
  22939. }
  22940. };
  22941. this._onPointerUp = function (evt) {
  22942. if (_this._totalPointersPressed === 0) {
  22943. return; // So we need to test it the pointer down was pressed before.
  22944. }
  22945. _this._totalPointersPressed--;
  22946. _this._pickedUpMesh = null;
  22947. _this._meshPickProceed = false;
  22948. _this._updatePointerPosition(evt);
  22949. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22950. // PreObservable support
  22951. if (_this.onPrePointerObservable.hasObservers()) {
  22952. if (!clickInfo.ignore) {
  22953. if (!clickInfo.hasSwiped) {
  22954. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22955. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22956. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22957. _this.onPrePointerObservable.notifyObservers(pi, type);
  22958. if (pi.skipOnPointerObservable) {
  22959. return;
  22960. }
  22961. }
  22962. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22963. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22964. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22965. _this.onPrePointerObservable.notifyObservers(pi, type);
  22966. if (pi.skipOnPointerObservable) {
  22967. return;
  22968. }
  22969. }
  22970. }
  22971. }
  22972. else {
  22973. var type = BABYLON.PointerEventTypes.POINTERUP;
  22974. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22975. _this.onPrePointerObservable.notifyObservers(pi, type);
  22976. if (pi.skipOnPointerObservable) {
  22977. return;
  22978. }
  22979. }
  22980. }
  22981. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22982. return;
  22983. }
  22984. if (!_this.pointerUpPredicate) {
  22985. _this.pointerUpPredicate = function (mesh) {
  22986. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22987. };
  22988. }
  22989. // Meshes
  22990. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22991. _this._initActionManager(null, clickInfo);
  22992. }
  22993. if (!pickResult) {
  22994. pickResult = _this._currentPickResult;
  22995. }
  22996. _this._processPointerUp(pickResult, evt, clickInfo);
  22997. // Sprites
  22998. if (_this.spriteManagers.length > 0) {
  22999. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23000. if (spritePickResult) {
  23001. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  23002. if (spritePickResult.pickedSprite.actionManager) {
  23003. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23004. if (spritePickResult.pickedSprite.actionManager) {
  23005. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  23006. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23007. }
  23008. }
  23009. }
  23010. }
  23011. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  23012. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  23013. }
  23014. }
  23015. }
  23016. _this._previousPickResult = _this._currentPickResult;
  23017. });
  23018. };
  23019. this._onKeyDown = function (evt) {
  23020. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  23021. if (_this.onPreKeyboardObservable.hasObservers()) {
  23022. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23023. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23024. if (pi.skipOnPointerObservable) {
  23025. return;
  23026. }
  23027. }
  23028. if (_this.onKeyboardObservable.hasObservers()) {
  23029. var pi = new BABYLON.KeyboardInfo(type, evt);
  23030. _this.onKeyboardObservable.notifyObservers(pi, type);
  23031. }
  23032. if (_this.actionManager) {
  23033. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23034. }
  23035. };
  23036. this._onKeyUp = function (evt) {
  23037. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23038. if (_this.onPreKeyboardObservable.hasObservers()) {
  23039. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23040. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23041. if (pi.skipOnPointerObservable) {
  23042. return;
  23043. }
  23044. }
  23045. if (_this.onKeyboardObservable.hasObservers()) {
  23046. var pi = new BABYLON.KeyboardInfo(type, evt);
  23047. _this.onKeyboardObservable.notifyObservers(pi, type);
  23048. }
  23049. if (_this.actionManager) {
  23050. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23051. }
  23052. };
  23053. var engine = this.getEngine();
  23054. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23055. if (!canvas) {
  23056. return;
  23057. }
  23058. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23059. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23060. });
  23061. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23062. if (!canvas) {
  23063. return;
  23064. }
  23065. canvas.removeEventListener("keydown", _this._onKeyDown);
  23066. canvas.removeEventListener("keyup", _this._onKeyUp);
  23067. });
  23068. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23069. var canvas = this._engine.getRenderingCanvas();
  23070. if (!canvas) {
  23071. return;
  23072. }
  23073. if (attachMove) {
  23074. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23075. // Wheel
  23076. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23077. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23078. }
  23079. if (attachDown) {
  23080. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23081. }
  23082. if (attachUp) {
  23083. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23084. }
  23085. canvas.tabIndex = 1;
  23086. };
  23087. Scene.prototype.detachControl = function () {
  23088. var engine = this.getEngine();
  23089. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23090. var canvas = engine.getRenderingCanvas();
  23091. if (!canvas) {
  23092. return;
  23093. }
  23094. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23095. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23096. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23097. if (this._onCanvasBlurObserver) {
  23098. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23099. }
  23100. if (this._onCanvasFocusObserver) {
  23101. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23102. }
  23103. // Wheel
  23104. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23105. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23106. // Keyboard
  23107. canvas.removeEventListener("keydown", this._onKeyDown);
  23108. canvas.removeEventListener("keyup", this._onKeyUp);
  23109. // Observables
  23110. this.onKeyboardObservable.clear();
  23111. this.onPreKeyboardObservable.clear();
  23112. this.onPointerObservable.clear();
  23113. this.onPrePointerObservable.clear();
  23114. };
  23115. /**
  23116. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23117. * Delay loaded resources are not taking in account
  23118. * @return true if all required resources are ready
  23119. */
  23120. Scene.prototype.isReady = function () {
  23121. if (this._isDisposed) {
  23122. return false;
  23123. }
  23124. if (this._pendingData.length > 0) {
  23125. return false;
  23126. }
  23127. var index;
  23128. var engine = this.getEngine();
  23129. // Geometries
  23130. for (index = 0; index < this._geometries.length; index++) {
  23131. var geometry = this._geometries[index];
  23132. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23133. return false;
  23134. }
  23135. }
  23136. // Meshes
  23137. for (index = 0; index < this.meshes.length; index++) {
  23138. var mesh = this.meshes[index];
  23139. if (!mesh.isEnabled()) {
  23140. continue;
  23141. }
  23142. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23143. continue;
  23144. }
  23145. if (!mesh.isReady(true)) {
  23146. return false;
  23147. }
  23148. // Effect layers
  23149. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23150. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23151. var layer = _a[_i];
  23152. if (!layer.hasMesh(mesh)) {
  23153. continue;
  23154. }
  23155. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23156. var subMesh = _c[_b];
  23157. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23158. return false;
  23159. }
  23160. }
  23161. }
  23162. }
  23163. // Particles
  23164. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  23165. var particleSystem = _e[_d];
  23166. if (!particleSystem.isReady()) {
  23167. return false;
  23168. }
  23169. }
  23170. return true;
  23171. };
  23172. Scene.prototype.resetCachedMaterial = function () {
  23173. this._cachedMaterial = null;
  23174. this._cachedEffect = null;
  23175. this._cachedVisibility = null;
  23176. };
  23177. Scene.prototype.registerBeforeRender = function (func) {
  23178. this.onBeforeRenderObservable.add(func);
  23179. };
  23180. Scene.prototype.unregisterBeforeRender = function (func) {
  23181. this.onBeforeRenderObservable.removeCallback(func);
  23182. };
  23183. Scene.prototype.registerAfterRender = function (func) {
  23184. this.onAfterRenderObservable.add(func);
  23185. };
  23186. Scene.prototype.unregisterAfterRender = function (func) {
  23187. this.onAfterRenderObservable.removeCallback(func);
  23188. };
  23189. Scene.prototype._executeOnceBeforeRender = function (func) {
  23190. var _this = this;
  23191. var execFunc = function () {
  23192. func();
  23193. setTimeout(function () {
  23194. _this.unregisterBeforeRender(execFunc);
  23195. });
  23196. };
  23197. this.registerBeforeRender(execFunc);
  23198. };
  23199. /**
  23200. * The provided function will run before render once and will be disposed afterwards.
  23201. * A timeout delay can be provided so that the function will be executed in N ms.
  23202. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23203. * @param func The function to be executed.
  23204. * @param timeout optional delay in ms
  23205. */
  23206. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23207. var _this = this;
  23208. if (timeout !== undefined) {
  23209. setTimeout(function () {
  23210. _this._executeOnceBeforeRender(func);
  23211. }, timeout);
  23212. }
  23213. else {
  23214. this._executeOnceBeforeRender(func);
  23215. }
  23216. };
  23217. Scene.prototype._addPendingData = function (data) {
  23218. this._pendingData.push(data);
  23219. };
  23220. Scene.prototype._removePendingData = function (data) {
  23221. var wasLoading = this.isLoading;
  23222. var index = this._pendingData.indexOf(data);
  23223. if (index !== -1) {
  23224. this._pendingData.splice(index, 1);
  23225. }
  23226. if (wasLoading && !this.isLoading) {
  23227. this.onDataLoadedObservable.notifyObservers(this);
  23228. }
  23229. };
  23230. Scene.prototype.getWaitingItemsCount = function () {
  23231. return this._pendingData.length;
  23232. };
  23233. Object.defineProperty(Scene.prototype, "isLoading", {
  23234. get: function () {
  23235. return this._pendingData.length > 0;
  23236. },
  23237. enumerable: true,
  23238. configurable: true
  23239. });
  23240. /**
  23241. * Registers a function to be executed when the scene is ready.
  23242. * @param {Function} func - the function to be executed.
  23243. */
  23244. Scene.prototype.executeWhenReady = function (func) {
  23245. var _this = this;
  23246. this.onReadyObservable.add(func);
  23247. if (this._executeWhenReadyTimeoutId !== -1) {
  23248. return;
  23249. }
  23250. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23251. _this._checkIsReady();
  23252. }, 150);
  23253. };
  23254. /**
  23255. * Returns a promise that resolves when the scene is ready.
  23256. * @returns A promise that resolves when the scene is ready.
  23257. */
  23258. Scene.prototype.whenReadyAsync = function () {
  23259. var _this = this;
  23260. return new Promise(function (resolve) {
  23261. _this.executeWhenReady(function () {
  23262. resolve();
  23263. });
  23264. });
  23265. };
  23266. Scene.prototype._checkIsReady = function () {
  23267. var _this = this;
  23268. if (this.isReady()) {
  23269. this.onReadyObservable.notifyObservers(this);
  23270. this.onReadyObservable.clear();
  23271. this._executeWhenReadyTimeoutId = -1;
  23272. return;
  23273. }
  23274. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23275. _this._checkIsReady();
  23276. }, 150);
  23277. };
  23278. // Animations
  23279. /**
  23280. * Will start the animation sequence of a given target
  23281. * @param target defines the target
  23282. * @param from defines from which frame should animation start
  23283. * @param to defines until which frame should animation run.
  23284. * @param weight defines the weight to apply to the animation (1.0 by default)
  23285. * @param loop defines if the animation loops
  23286. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23287. * @param onAnimationEnd defines the function to be executed when the animation ends
  23288. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23289. * @returns the animatable object created for this animation
  23290. * @see BABYLON.Animatable
  23291. */
  23292. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23293. if (weight === void 0) { weight = 1.0; }
  23294. if (speedRatio === void 0) { speedRatio = 1.0; }
  23295. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23296. returnedAnimatable.weight = weight;
  23297. return returnedAnimatable;
  23298. };
  23299. /**
  23300. * Will start the animation sequence of a given target
  23301. * @param target defines the target
  23302. * @param from defines from which frame should animation start
  23303. * @param to defines until which frame should animation run.
  23304. * @param loop defines if the animation loops
  23305. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23306. * @param onAnimationEnd defines the function to be executed when the animation ends
  23307. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23308. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23309. * @returns the animatable object created for this animation
  23310. * @see BABYLON.Animatable
  23311. */
  23312. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23313. if (speedRatio === void 0) { speedRatio = 1.0; }
  23314. if (stopCurrent === void 0) { stopCurrent = true; }
  23315. if (from > to && speedRatio > 0) {
  23316. speedRatio *= -1;
  23317. }
  23318. if (stopCurrent) {
  23319. this.stopAnimation(target);
  23320. }
  23321. if (!animatable) {
  23322. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23323. }
  23324. // Local animations
  23325. if (target.animations) {
  23326. animatable.appendAnimations(target, target.animations);
  23327. }
  23328. // Children animations
  23329. if (target.getAnimatables) {
  23330. var animatables = target.getAnimatables();
  23331. for (var index = 0; index < animatables.length; index++) {
  23332. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23333. }
  23334. }
  23335. animatable.reset();
  23336. return animatable;
  23337. };
  23338. /**
  23339. * Begin a new animation on a given node
  23340. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23341. * @param {BABYLON.Animation[]} defines the list of animations to start
  23342. * @param {number} from defines the initial value
  23343. * @param {number} to defines the final value
  23344. * @param {boolean} loop defines if you want animation to loop (off by default)
  23345. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23346. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23347. * @returns the list of created animatables
  23348. */
  23349. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23350. if (speedRatio === undefined) {
  23351. speedRatio = 1.0;
  23352. }
  23353. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23354. return animatable;
  23355. };
  23356. /**
  23357. * Begin a new animation on a given node and its hierarchy
  23358. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23359. * @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.
  23360. * @param {BABYLON.Animation[]} defines the list of animations to start
  23361. * @param {number} from defines the initial value
  23362. * @param {number} to defines the final value
  23363. * @param {boolean} loop defines if you want animation to loop (off by default)
  23364. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23365. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23366. * @returns the list of animatables created for all nodes
  23367. */
  23368. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23369. var children = target.getDescendants(directDescendantsOnly);
  23370. var result = [];
  23371. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23372. var child = children_1[_i];
  23373. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23374. }
  23375. return result;
  23376. };
  23377. Scene.prototype.getAnimatableByTarget = function (target) {
  23378. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23379. if (this._activeAnimatables[index].target === target) {
  23380. return this._activeAnimatables[index];
  23381. }
  23382. }
  23383. return null;
  23384. };
  23385. /**
  23386. * Gets all animatables associated with a given target
  23387. * @param target defines the target to look animatables for
  23388. * @returns an array of Animatables
  23389. */
  23390. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  23391. var result = [];
  23392. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23393. if (this._activeAnimatables[index].target === target) {
  23394. result.push(this._activeAnimatables[index]);
  23395. }
  23396. }
  23397. return result;
  23398. };
  23399. Object.defineProperty(Scene.prototype, "animatables", {
  23400. get: function () {
  23401. return this._activeAnimatables;
  23402. },
  23403. enumerable: true,
  23404. configurable: true
  23405. });
  23406. /**
  23407. * Will stop the animation of the given target
  23408. * @param target - the target
  23409. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  23410. * @see beginAnimation
  23411. */
  23412. Scene.prototype.stopAnimation = function (target, animationName) {
  23413. var animatables = this.getAllAnimatablesByTarget(target);
  23414. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  23415. var animatable = animatables_1[_i];
  23416. animatable.stop(animationName);
  23417. }
  23418. };
  23419. /**
  23420. * Stops and removes all animations that have been applied to the scene
  23421. */
  23422. Scene.prototype.stopAllAnimations = function () {
  23423. if (this._activeAnimatables) {
  23424. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23425. this._activeAnimatables[i].stop();
  23426. }
  23427. this._activeAnimatables = [];
  23428. }
  23429. };
  23430. Scene.prototype._animate = function () {
  23431. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23432. return;
  23433. }
  23434. // Getting time
  23435. var now = BABYLON.Tools.Now;
  23436. if (!this._animationTimeLast) {
  23437. if (this._pendingData.length > 0) {
  23438. return;
  23439. }
  23440. this._animationTimeLast = now;
  23441. }
  23442. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23443. this._animationTime += deltaTime;
  23444. this._animationTimeLast = now;
  23445. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23446. this._activeAnimatables[index]._animate(this._animationTime);
  23447. }
  23448. // Late animation bindings
  23449. this._processLateAnimationBindings();
  23450. };
  23451. /** @ignore */
  23452. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23453. var target = runtimeAnimation.target;
  23454. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23455. if (!target._lateAnimationHolders) {
  23456. target._lateAnimationHolders = {};
  23457. }
  23458. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23459. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23460. totalWeight: 0,
  23461. animations: []
  23462. };
  23463. }
  23464. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23465. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23466. };
  23467. Scene.prototype._processLateAnimationBindings = function () {
  23468. if (!this._registeredForLateAnimationBindings.length) {
  23469. return;
  23470. }
  23471. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23472. var target = this._registeredForLateAnimationBindings.data[index];
  23473. for (var path in target._lateAnimationHolders) {
  23474. var holder = target._lateAnimationHolders[path];
  23475. // Sanity check
  23476. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23477. continue;
  23478. }
  23479. var normalizer = 1.0;
  23480. var finalValue = void 0;
  23481. if (holder.totalWeight < 1.0) {
  23482. // We need to mix the original value in
  23483. var originalValue = holder.animations[0].originalValue;
  23484. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23485. }
  23486. else {
  23487. // We need to normalize the weights
  23488. normalizer = holder.totalWeight;
  23489. }
  23490. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23491. var runtimeAnimation = holder.animations[animIndex];
  23492. if (finalValue) {
  23493. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23494. }
  23495. else {
  23496. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23497. }
  23498. }
  23499. runtimeAnimation.target[path] = finalValue;
  23500. }
  23501. target._lateAnimationHolders = {};
  23502. }
  23503. this._registeredForLateAnimationBindings.reset();
  23504. };
  23505. // Matrix
  23506. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23507. this._useAlternateCameraConfiguration = active;
  23508. };
  23509. Scene.prototype.getViewMatrix = function () {
  23510. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23511. };
  23512. Scene.prototype.getProjectionMatrix = function () {
  23513. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23514. };
  23515. Scene.prototype.getTransformMatrix = function () {
  23516. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23517. };
  23518. Scene.prototype.setTransformMatrix = function (view, projection) {
  23519. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23520. return;
  23521. }
  23522. this._viewUpdateFlag = view.updateFlag;
  23523. this._projectionUpdateFlag = projection.updateFlag;
  23524. this._viewMatrix = view;
  23525. this._projectionMatrix = projection;
  23526. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23527. // Update frustum
  23528. if (!this._frustumPlanes) {
  23529. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23530. }
  23531. else {
  23532. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23533. }
  23534. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23535. var otherCamera = this.activeCamera._alternateCamera;
  23536. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23537. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23538. }
  23539. if (this._sceneUbo.useUbo) {
  23540. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23541. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23542. this._sceneUbo.update();
  23543. }
  23544. };
  23545. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23546. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23547. return;
  23548. }
  23549. this._alternateViewUpdateFlag = view.updateFlag;
  23550. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23551. this._alternateViewMatrix = view;
  23552. this._alternateProjectionMatrix = projection;
  23553. if (!this._alternateTransformMatrix) {
  23554. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23555. }
  23556. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23557. if (!this._alternateSceneUbo) {
  23558. this._createAlternateUbo();
  23559. }
  23560. if (this._alternateSceneUbo.useUbo) {
  23561. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23562. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23563. this._alternateSceneUbo.update();
  23564. }
  23565. };
  23566. Scene.prototype.getSceneUniformBuffer = function () {
  23567. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23568. };
  23569. // Methods
  23570. Scene.prototype.getUniqueId = function () {
  23571. var result = Scene._uniqueIdCounter;
  23572. Scene._uniqueIdCounter++;
  23573. return result;
  23574. };
  23575. Scene.prototype.addMesh = function (newMesh) {
  23576. this.meshes.push(newMesh);
  23577. //notify the collision coordinator
  23578. if (this.collisionCoordinator) {
  23579. this.collisionCoordinator.onMeshAdded(newMesh);
  23580. }
  23581. newMesh._resyncLightSources();
  23582. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23583. };
  23584. Scene.prototype.removeMesh = function (toRemove) {
  23585. var index = this.meshes.indexOf(toRemove);
  23586. if (index !== -1) {
  23587. // Remove from the scene if mesh found
  23588. this.meshes.splice(index, 1);
  23589. }
  23590. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23591. return index;
  23592. };
  23593. Scene.prototype.addTransformNode = function (newTransformNode) {
  23594. this.transformNodes.push(newTransformNode);
  23595. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23596. };
  23597. Scene.prototype.removeTransformNode = function (toRemove) {
  23598. var index = this.transformNodes.indexOf(toRemove);
  23599. if (index !== -1) {
  23600. // Remove from the scene if found
  23601. this.transformNodes.splice(index, 1);
  23602. }
  23603. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23604. return index;
  23605. };
  23606. Scene.prototype.removeSkeleton = function (toRemove) {
  23607. var index = this.skeletons.indexOf(toRemove);
  23608. if (index !== -1) {
  23609. // Remove from the scene if found
  23610. this.skeletons.splice(index, 1);
  23611. }
  23612. return index;
  23613. };
  23614. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23615. var index = this.morphTargetManagers.indexOf(toRemove);
  23616. if (index !== -1) {
  23617. // Remove from the scene if found
  23618. this.morphTargetManagers.splice(index, 1);
  23619. }
  23620. return index;
  23621. };
  23622. Scene.prototype.removeLight = function (toRemove) {
  23623. var index = this.lights.indexOf(toRemove);
  23624. if (index !== -1) {
  23625. // Remove from meshes
  23626. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23627. var mesh = _a[_i];
  23628. mesh._removeLightSource(toRemove);
  23629. }
  23630. // Remove from the scene if mesh found
  23631. this.lights.splice(index, 1);
  23632. this.sortLightsByPriority();
  23633. }
  23634. this.onLightRemovedObservable.notifyObservers(toRemove);
  23635. return index;
  23636. };
  23637. Scene.prototype.removeCamera = function (toRemove) {
  23638. var index = this.cameras.indexOf(toRemove);
  23639. if (index !== -1) {
  23640. // Remove from the scene if mesh found
  23641. this.cameras.splice(index, 1);
  23642. }
  23643. // Remove from activeCameras
  23644. var index2 = this.activeCameras.indexOf(toRemove);
  23645. if (index2 !== -1) {
  23646. // Remove from the scene if mesh found
  23647. this.activeCameras.splice(index2, 1);
  23648. }
  23649. // Reset the activeCamera
  23650. if (this.activeCamera === toRemove) {
  23651. if (this.cameras.length > 0) {
  23652. this.activeCamera = this.cameras[0];
  23653. }
  23654. else {
  23655. this.activeCamera = null;
  23656. }
  23657. }
  23658. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23659. return index;
  23660. };
  23661. Scene.prototype.removeParticleSystem = function (toRemove) {
  23662. var index = this.particleSystems.indexOf(toRemove);
  23663. if (index !== -1) {
  23664. this.particleSystems.splice(index, 1);
  23665. }
  23666. return index;
  23667. };
  23668. ;
  23669. Scene.prototype.removeAnimation = function (toRemove) {
  23670. var index = this.animations.indexOf(toRemove);
  23671. if (index !== -1) {
  23672. this.animations.splice(index, 1);
  23673. }
  23674. return index;
  23675. };
  23676. ;
  23677. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23678. var index = this.multiMaterials.indexOf(toRemove);
  23679. if (index !== -1) {
  23680. this.multiMaterials.splice(index, 1);
  23681. }
  23682. return index;
  23683. };
  23684. ;
  23685. Scene.prototype.removeMaterial = function (toRemove) {
  23686. var index = this.materials.indexOf(toRemove);
  23687. if (index !== -1) {
  23688. this.materials.splice(index, 1);
  23689. }
  23690. return index;
  23691. };
  23692. ;
  23693. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23694. var index = this.lensFlareSystems.indexOf(toRemove);
  23695. if (index !== -1) {
  23696. this.lensFlareSystems.splice(index, 1);
  23697. }
  23698. return index;
  23699. };
  23700. ;
  23701. Scene.prototype.removeActionManager = function (toRemove) {
  23702. var index = this._actionManagers.indexOf(toRemove);
  23703. if (index !== -1) {
  23704. this._actionManagers.splice(index, 1);
  23705. }
  23706. return index;
  23707. };
  23708. ;
  23709. Scene.prototype.addLight = function (newLight) {
  23710. this.lights.push(newLight);
  23711. this.sortLightsByPriority();
  23712. // Add light to all meshes (To support if the light is removed and then readded)
  23713. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23714. var mesh = _a[_i];
  23715. if (mesh._lightSources.indexOf(newLight) === -1) {
  23716. mesh._lightSources.push(newLight);
  23717. mesh._resyncLightSources();
  23718. }
  23719. }
  23720. this.onNewLightAddedObservable.notifyObservers(newLight);
  23721. };
  23722. Scene.prototype.sortLightsByPriority = function () {
  23723. if (this.requireLightSorting) {
  23724. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23725. }
  23726. };
  23727. Scene.prototype.addCamera = function (newCamera) {
  23728. this.cameras.push(newCamera);
  23729. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23730. };
  23731. Scene.prototype.addSkeleton = function (newSkeleton) {
  23732. this.skeletons.push(newSkeleton);
  23733. };
  23734. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23735. this.particleSystems.push(newParticleSystem);
  23736. };
  23737. Scene.prototype.addAnimation = function (newAnimation) {
  23738. this.animations.push(newAnimation);
  23739. };
  23740. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23741. this.multiMaterials.push(newMultiMaterial);
  23742. };
  23743. Scene.prototype.addMaterial = function (newMaterial) {
  23744. this.materials.push(newMaterial);
  23745. };
  23746. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23747. this.morphTargetManagers.push(newMorphTargetManager);
  23748. };
  23749. Scene.prototype.addGeometry = function (newGeometrie) {
  23750. this._geometries.push(newGeometrie);
  23751. };
  23752. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23753. this.lensFlareSystems.push(newLensFlareSystem);
  23754. };
  23755. Scene.prototype.addActionManager = function (newActionManager) {
  23756. this._actionManagers.push(newActionManager);
  23757. };
  23758. /**
  23759. * Switch active camera
  23760. * @param {Camera} newCamera - new active camera
  23761. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23762. */
  23763. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23764. if (attachControl === void 0) { attachControl = true; }
  23765. var canvas = this._engine.getRenderingCanvas();
  23766. if (!canvas) {
  23767. return;
  23768. }
  23769. if (this.activeCamera) {
  23770. this.activeCamera.detachControl(canvas);
  23771. }
  23772. this.activeCamera = newCamera;
  23773. if (attachControl) {
  23774. newCamera.attachControl(canvas);
  23775. }
  23776. };
  23777. /**
  23778. * sets the active camera of the scene using its ID
  23779. * @param {string} id - the camera's ID
  23780. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23781. * @see activeCamera
  23782. */
  23783. Scene.prototype.setActiveCameraByID = function (id) {
  23784. var camera = this.getCameraByID(id);
  23785. if (camera) {
  23786. this.activeCamera = camera;
  23787. return camera;
  23788. }
  23789. return null;
  23790. };
  23791. /**
  23792. * sets the active camera of the scene using its name
  23793. * @param {string} name - the camera's name
  23794. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23795. * @see activeCamera
  23796. */
  23797. Scene.prototype.setActiveCameraByName = function (name) {
  23798. var camera = this.getCameraByName(name);
  23799. if (camera) {
  23800. this.activeCamera = camera;
  23801. return camera;
  23802. }
  23803. return null;
  23804. };
  23805. /**
  23806. * get an animation group using its name
  23807. * @param {string} the material's name
  23808. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23809. */
  23810. Scene.prototype.getAnimationGroupByName = function (name) {
  23811. for (var index = 0; index < this.animationGroups.length; index++) {
  23812. if (this.animationGroups[index].name === name) {
  23813. return this.animationGroups[index];
  23814. }
  23815. }
  23816. return null;
  23817. };
  23818. /**
  23819. * get a material using its id
  23820. * @param {string} the material's ID
  23821. * @return {BABYLON.Material|null} the material or null if none found.
  23822. */
  23823. Scene.prototype.getMaterialByID = function (id) {
  23824. for (var index = 0; index < this.materials.length; index++) {
  23825. if (this.materials[index].id === id) {
  23826. return this.materials[index];
  23827. }
  23828. }
  23829. return null;
  23830. };
  23831. /**
  23832. * get a material using its name
  23833. * @param {string} the material's name
  23834. * @return {BABYLON.Material|null} the material or null if none found.
  23835. */
  23836. Scene.prototype.getMaterialByName = function (name) {
  23837. for (var index = 0; index < this.materials.length; index++) {
  23838. if (this.materials[index].name === name) {
  23839. return this.materials[index];
  23840. }
  23841. }
  23842. return null;
  23843. };
  23844. Scene.prototype.getLensFlareSystemByName = function (name) {
  23845. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23846. if (this.lensFlareSystems[index].name === name) {
  23847. return this.lensFlareSystems[index];
  23848. }
  23849. }
  23850. return null;
  23851. };
  23852. Scene.prototype.getLensFlareSystemByID = function (id) {
  23853. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23854. if (this.lensFlareSystems[index].id === id) {
  23855. return this.lensFlareSystems[index];
  23856. }
  23857. }
  23858. return null;
  23859. };
  23860. Scene.prototype.getCameraByID = function (id) {
  23861. for (var index = 0; index < this.cameras.length; index++) {
  23862. if (this.cameras[index].id === id) {
  23863. return this.cameras[index];
  23864. }
  23865. }
  23866. return null;
  23867. };
  23868. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23869. for (var index = 0; index < this.cameras.length; index++) {
  23870. if (this.cameras[index].uniqueId === uniqueId) {
  23871. return this.cameras[index];
  23872. }
  23873. }
  23874. return null;
  23875. };
  23876. /**
  23877. * get a camera using its name
  23878. * @param {string} the camera's name
  23879. * @return {BABYLON.Camera|null} the camera or null if none found.
  23880. */
  23881. Scene.prototype.getCameraByName = function (name) {
  23882. for (var index = 0; index < this.cameras.length; index++) {
  23883. if (this.cameras[index].name === name) {
  23884. return this.cameras[index];
  23885. }
  23886. }
  23887. return null;
  23888. };
  23889. /**
  23890. * get a bone using its id
  23891. * @param {string} the bone's id
  23892. * @return {BABYLON.Bone|null} the bone or null if not found
  23893. */
  23894. Scene.prototype.getBoneByID = function (id) {
  23895. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23896. var skeleton = this.skeletons[skeletonIndex];
  23897. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23898. if (skeleton.bones[boneIndex].id === id) {
  23899. return skeleton.bones[boneIndex];
  23900. }
  23901. }
  23902. }
  23903. return null;
  23904. };
  23905. /**
  23906. * get a bone using its id
  23907. * @param {string} the bone's name
  23908. * @return {BABYLON.Bone|null} the bone or null if not found
  23909. */
  23910. Scene.prototype.getBoneByName = function (name) {
  23911. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23912. var skeleton = this.skeletons[skeletonIndex];
  23913. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23914. if (skeleton.bones[boneIndex].name === name) {
  23915. return skeleton.bones[boneIndex];
  23916. }
  23917. }
  23918. }
  23919. return null;
  23920. };
  23921. /**
  23922. * get a light node using its name
  23923. * @param {string} the light's name
  23924. * @return {BABYLON.Light|null} the light or null if none found.
  23925. */
  23926. Scene.prototype.getLightByName = function (name) {
  23927. for (var index = 0; index < this.lights.length; index++) {
  23928. if (this.lights[index].name === name) {
  23929. return this.lights[index];
  23930. }
  23931. }
  23932. return null;
  23933. };
  23934. /**
  23935. * get a light node using its ID
  23936. * @param {string} the light's id
  23937. * @return {BABYLON.Light|null} the light or null if none found.
  23938. */
  23939. Scene.prototype.getLightByID = function (id) {
  23940. for (var index = 0; index < this.lights.length; index++) {
  23941. if (this.lights[index].id === id) {
  23942. return this.lights[index];
  23943. }
  23944. }
  23945. return null;
  23946. };
  23947. /**
  23948. * get a light node using its scene-generated unique ID
  23949. * @param {number} the light's unique id
  23950. * @return {BABYLON.Light|null} the light or null if none found.
  23951. */
  23952. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23953. for (var index = 0; index < this.lights.length; index++) {
  23954. if (this.lights[index].uniqueId === uniqueId) {
  23955. return this.lights[index];
  23956. }
  23957. }
  23958. return null;
  23959. };
  23960. /**
  23961. * get a particle system by id
  23962. * @param id {number} the particle system id
  23963. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23964. */
  23965. Scene.prototype.getParticleSystemByID = function (id) {
  23966. for (var index = 0; index < this.particleSystems.length; index++) {
  23967. if (this.particleSystems[index].id === id) {
  23968. return this.particleSystems[index];
  23969. }
  23970. }
  23971. return null;
  23972. };
  23973. /**
  23974. * get a geometry using its ID
  23975. * @param {string} the geometry's id
  23976. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23977. */
  23978. Scene.prototype.getGeometryByID = function (id) {
  23979. for (var index = 0; index < this._geometries.length; index++) {
  23980. if (this._geometries[index].id === id) {
  23981. return this._geometries[index];
  23982. }
  23983. }
  23984. return null;
  23985. };
  23986. /**
  23987. * add a new geometry to this scene.
  23988. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23989. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23990. * @return {boolean} was the geometry added or not
  23991. */
  23992. Scene.prototype.pushGeometry = function (geometry, force) {
  23993. if (!force && this.getGeometryByID(geometry.id)) {
  23994. return false;
  23995. }
  23996. this._geometries.push(geometry);
  23997. //notify the collision coordinator
  23998. if (this.collisionCoordinator) {
  23999. this.collisionCoordinator.onGeometryAdded(geometry);
  24000. }
  24001. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  24002. return true;
  24003. };
  24004. /**
  24005. * Removes an existing geometry
  24006. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  24007. * @return {boolean} was the geometry removed or not
  24008. */
  24009. Scene.prototype.removeGeometry = function (geometry) {
  24010. var index = this._geometries.indexOf(geometry);
  24011. if (index > -1) {
  24012. this._geometries.splice(index, 1);
  24013. //notify the collision coordinator
  24014. if (this.collisionCoordinator) {
  24015. this.collisionCoordinator.onGeometryDeleted(geometry);
  24016. }
  24017. this.onGeometryRemovedObservable.notifyObservers(geometry);
  24018. return true;
  24019. }
  24020. return false;
  24021. };
  24022. Scene.prototype.getGeometries = function () {
  24023. return this._geometries;
  24024. };
  24025. /**
  24026. * Get the first added mesh found of a given ID
  24027. * @param {string} id - the id to search for
  24028. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24029. */
  24030. Scene.prototype.getMeshByID = function (id) {
  24031. for (var index = 0; index < this.meshes.length; index++) {
  24032. if (this.meshes[index].id === id) {
  24033. return this.meshes[index];
  24034. }
  24035. }
  24036. return null;
  24037. };
  24038. Scene.prototype.getMeshesByID = function (id) {
  24039. return this.meshes.filter(function (m) {
  24040. return m.id === id;
  24041. });
  24042. };
  24043. /**
  24044. * Get the first added transform node found of a given ID
  24045. * @param {string} id - the id to search for
  24046. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  24047. */
  24048. Scene.prototype.getTransformNodeByID = function (id) {
  24049. for (var index = 0; index < this.transformNodes.length; index++) {
  24050. if (this.transformNodes[index].id === id) {
  24051. return this.transformNodes[index];
  24052. }
  24053. }
  24054. return null;
  24055. };
  24056. Scene.prototype.getTransformNodesByID = function (id) {
  24057. return this.transformNodes.filter(function (m) {
  24058. return m.id === id;
  24059. });
  24060. };
  24061. /**
  24062. * Get a mesh with its auto-generated unique id
  24063. * @param {number} uniqueId - the unique id to search for
  24064. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24065. */
  24066. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24067. for (var index = 0; index < this.meshes.length; index++) {
  24068. if (this.meshes[index].uniqueId === uniqueId) {
  24069. return this.meshes[index];
  24070. }
  24071. }
  24072. return null;
  24073. };
  24074. /**
  24075. * Get a the last added mesh found of a given ID
  24076. * @param {string} id - the id to search for
  24077. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24078. */
  24079. Scene.prototype.getLastMeshByID = function (id) {
  24080. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24081. if (this.meshes[index].id === id) {
  24082. return this.meshes[index];
  24083. }
  24084. }
  24085. return null;
  24086. };
  24087. /**
  24088. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24089. * @param {string} id - the id to search for
  24090. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24091. */
  24092. Scene.prototype.getLastEntryByID = function (id) {
  24093. var index;
  24094. for (index = this.meshes.length - 1; index >= 0; index--) {
  24095. if (this.meshes[index].id === id) {
  24096. return this.meshes[index];
  24097. }
  24098. }
  24099. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24100. if (this.transformNodes[index].id === id) {
  24101. return this.transformNodes[index];
  24102. }
  24103. }
  24104. for (index = this.cameras.length - 1; index >= 0; index--) {
  24105. if (this.cameras[index].id === id) {
  24106. return this.cameras[index];
  24107. }
  24108. }
  24109. for (index = this.lights.length - 1; index >= 0; index--) {
  24110. if (this.lights[index].id === id) {
  24111. return this.lights[index];
  24112. }
  24113. }
  24114. return null;
  24115. };
  24116. Scene.prototype.getNodeByID = function (id) {
  24117. var mesh = this.getMeshByID(id);
  24118. if (mesh) {
  24119. return mesh;
  24120. }
  24121. var light = this.getLightByID(id);
  24122. if (light) {
  24123. return light;
  24124. }
  24125. var camera = this.getCameraByID(id);
  24126. if (camera) {
  24127. return camera;
  24128. }
  24129. var bone = this.getBoneByID(id);
  24130. return bone;
  24131. };
  24132. Scene.prototype.getNodeByName = function (name) {
  24133. var mesh = this.getMeshByName(name);
  24134. if (mesh) {
  24135. return mesh;
  24136. }
  24137. var light = this.getLightByName(name);
  24138. if (light) {
  24139. return light;
  24140. }
  24141. var camera = this.getCameraByName(name);
  24142. if (camera) {
  24143. return camera;
  24144. }
  24145. var bone = this.getBoneByName(name);
  24146. return bone;
  24147. };
  24148. Scene.prototype.getMeshByName = function (name) {
  24149. for (var index = 0; index < this.meshes.length; index++) {
  24150. if (this.meshes[index].name === name) {
  24151. return this.meshes[index];
  24152. }
  24153. }
  24154. return null;
  24155. };
  24156. Scene.prototype.getTransformNodeByName = function (name) {
  24157. for (var index = 0; index < this.transformNodes.length; index++) {
  24158. if (this.transformNodes[index].name === name) {
  24159. return this.transformNodes[index];
  24160. }
  24161. }
  24162. return null;
  24163. };
  24164. Scene.prototype.getSoundByName = function (name) {
  24165. var index;
  24166. if (BABYLON.AudioEngine) {
  24167. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24168. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24169. return this.mainSoundTrack.soundCollection[index];
  24170. }
  24171. }
  24172. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24173. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24174. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24175. return this.soundTracks[sdIndex].soundCollection[index];
  24176. }
  24177. }
  24178. }
  24179. }
  24180. return null;
  24181. };
  24182. Scene.prototype.getLastSkeletonByID = function (id) {
  24183. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24184. if (this.skeletons[index].id === id) {
  24185. return this.skeletons[index];
  24186. }
  24187. }
  24188. return null;
  24189. };
  24190. Scene.prototype.getSkeletonById = function (id) {
  24191. for (var index = 0; index < this.skeletons.length; index++) {
  24192. if (this.skeletons[index].id === id) {
  24193. return this.skeletons[index];
  24194. }
  24195. }
  24196. return null;
  24197. };
  24198. Scene.prototype.getSkeletonByName = function (name) {
  24199. for (var index = 0; index < this.skeletons.length; index++) {
  24200. if (this.skeletons[index].name === name) {
  24201. return this.skeletons[index];
  24202. }
  24203. }
  24204. return null;
  24205. };
  24206. Scene.prototype.getMorphTargetManagerById = function (id) {
  24207. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24208. if (this.morphTargetManagers[index].uniqueId === id) {
  24209. return this.morphTargetManagers[index];
  24210. }
  24211. }
  24212. return null;
  24213. };
  24214. Scene.prototype.isActiveMesh = function (mesh) {
  24215. return (this._activeMeshes.indexOf(mesh) !== -1);
  24216. };
  24217. /**
  24218. * Return a the first highlight layer of the scene with a given name.
  24219. * @param name The name of the highlight layer to look for.
  24220. * @return The highlight layer if found otherwise null.
  24221. */
  24222. Scene.prototype.getHighlightLayerByName = function (name) {
  24223. for (var index = 0; index < this.effectLayers.length; index++) {
  24224. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24225. return this.effectLayers[index];
  24226. }
  24227. }
  24228. return null;
  24229. };
  24230. /**
  24231. * Return a the first highlight layer of the scene with a given name.
  24232. * @param name The name of the highlight layer to look for.
  24233. * @return The highlight layer if found otherwise null.
  24234. */
  24235. Scene.prototype.getGlowLayerByName = function (name) {
  24236. for (var index = 0; index < this.effectLayers.length; index++) {
  24237. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24238. return this.effectLayers[index];
  24239. }
  24240. }
  24241. return null;
  24242. };
  24243. Object.defineProperty(Scene.prototype, "uid", {
  24244. /**
  24245. * Return a unique id as a string which can serve as an identifier for the scene
  24246. */
  24247. get: function () {
  24248. if (!this._uid) {
  24249. this._uid = BABYLON.Tools.RandomId();
  24250. }
  24251. return this._uid;
  24252. },
  24253. enumerable: true,
  24254. configurable: true
  24255. });
  24256. /**
  24257. * Add an externaly attached data from its key.
  24258. * This method call will fail and return false, if such key already exists.
  24259. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24260. * @param key the unique key that identifies the data
  24261. * @param data the data object to associate to the key for this Engine instance
  24262. * @return true if no such key were already present and the data was added successfully, false otherwise
  24263. */
  24264. Scene.prototype.addExternalData = function (key, data) {
  24265. if (!this._externalData) {
  24266. this._externalData = new BABYLON.StringDictionary();
  24267. }
  24268. return this._externalData.add(key, data);
  24269. };
  24270. /**
  24271. * Get an externaly attached data from its key
  24272. * @param key the unique key that identifies the data
  24273. * @return the associated data, if present (can be null), or undefined if not present
  24274. */
  24275. Scene.prototype.getExternalData = function (key) {
  24276. if (!this._externalData) {
  24277. return null;
  24278. }
  24279. return this._externalData.get(key);
  24280. };
  24281. /**
  24282. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24283. * @param key the unique key that identifies the data
  24284. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24285. * @return the associated data, can be null if the factory returned null.
  24286. */
  24287. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24288. if (!this._externalData) {
  24289. this._externalData = new BABYLON.StringDictionary();
  24290. }
  24291. return this._externalData.getOrAddWithFactory(key, factory);
  24292. };
  24293. /**
  24294. * Remove an externaly attached data from the Engine instance
  24295. * @param key the unique key that identifies the data
  24296. * @return true if the data was successfully removed, false if it doesn't exist
  24297. */
  24298. Scene.prototype.removeExternalData = function (key) {
  24299. return this._externalData.remove(key);
  24300. };
  24301. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24302. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24303. if (mesh.showSubMeshesBoundingBox) {
  24304. var boundingInfo = subMesh.getBoundingInfo();
  24305. if (boundingInfo !== null && boundingInfo !== undefined) {
  24306. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24307. }
  24308. }
  24309. var material = subMesh.getMaterial();
  24310. if (material !== null && material !== undefined) {
  24311. // Render targets
  24312. if (material.getRenderTargetTextures !== undefined) {
  24313. if (this._processedMaterials.indexOf(material) === -1) {
  24314. this._processedMaterials.push(material);
  24315. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24316. }
  24317. }
  24318. // Dispatch
  24319. this._activeIndices.addCount(subMesh.indexCount, false);
  24320. this._renderingManager.dispatch(subMesh, mesh, material);
  24321. }
  24322. }
  24323. };
  24324. /**
  24325. * Clear the processed materials smart array preventing retention point in material dispose.
  24326. */
  24327. Scene.prototype.freeProcessedMaterials = function () {
  24328. this._processedMaterials.dispose();
  24329. };
  24330. /**
  24331. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24332. */
  24333. Scene.prototype.freeActiveMeshes = function () {
  24334. this._activeMeshes.dispose();
  24335. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24336. this.activeCamera._activeMeshes.dispose();
  24337. }
  24338. if (this.activeCameras) {
  24339. for (var i = 0; i < this.activeCameras.length; i++) {
  24340. var activeCamera = this.activeCameras[i];
  24341. if (activeCamera && activeCamera._activeMeshes) {
  24342. activeCamera._activeMeshes.dispose();
  24343. }
  24344. }
  24345. }
  24346. };
  24347. /**
  24348. * Clear the info related to rendering groups preventing retention points during dispose.
  24349. */
  24350. Scene.prototype.freeRenderingGroups = function () {
  24351. if (this._renderingManager) {
  24352. this._renderingManager.freeRenderingGroups();
  24353. }
  24354. if (this.textures) {
  24355. for (var i = 0; i < this.textures.length; i++) {
  24356. var texture = this.textures[i];
  24357. if (texture && texture.renderList) {
  24358. texture.freeRenderingGroups();
  24359. }
  24360. }
  24361. }
  24362. };
  24363. Scene.prototype._isInIntermediateRendering = function () {
  24364. return this._intermediateRendering;
  24365. };
  24366. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24367. this._activeMeshCandidateProvider = provider;
  24368. };
  24369. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24370. return this._activeMeshCandidateProvider;
  24371. };
  24372. /**
  24373. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24374. */
  24375. Scene.prototype.freezeActiveMeshes = function () {
  24376. if (!this.activeCamera) {
  24377. return this;
  24378. }
  24379. if (!this._frustumPlanes) {
  24380. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24381. }
  24382. this._evaluateActiveMeshes();
  24383. this._activeMeshesFrozen = true;
  24384. return this;
  24385. };
  24386. /**
  24387. * Use this function to restart evaluating active meshes on every frame
  24388. */
  24389. Scene.prototype.unfreezeActiveMeshes = function () {
  24390. this._activeMeshesFrozen = false;
  24391. return this;
  24392. };
  24393. Scene.prototype._evaluateActiveMeshes = function () {
  24394. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24395. return;
  24396. }
  24397. if (!this.activeCamera) {
  24398. return;
  24399. }
  24400. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24401. this.activeCamera._activeMeshes.reset();
  24402. this._activeMeshes.reset();
  24403. this._renderingManager.reset();
  24404. this._processedMaterials.reset();
  24405. this._activeParticleSystems.reset();
  24406. this._activeSkeletons.reset();
  24407. this._softwareSkinnedMeshes.reset();
  24408. if (this._boundingBoxRenderer) {
  24409. this._boundingBoxRenderer.reset();
  24410. }
  24411. // Meshes
  24412. var meshes;
  24413. var len;
  24414. var checkIsEnabled = true;
  24415. // Determine mesh candidates
  24416. if (this._activeMeshCandidateProvider !== undefined) {
  24417. // Use _activeMeshCandidateProvider
  24418. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24419. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24420. if (meshes !== undefined) {
  24421. len = meshes.length;
  24422. }
  24423. else {
  24424. len = 0;
  24425. }
  24426. }
  24427. else if (this._selectionOctree !== undefined) {
  24428. // Octree
  24429. var selection = this._selectionOctree.select(this._frustumPlanes);
  24430. meshes = selection.data;
  24431. len = selection.length;
  24432. }
  24433. else {
  24434. // Full scene traversal
  24435. len = this.meshes.length;
  24436. meshes = this.meshes;
  24437. }
  24438. // Check each mesh
  24439. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24440. mesh = meshes[meshIndex];
  24441. if (mesh.isBlocked) {
  24442. continue;
  24443. }
  24444. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24445. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24446. continue;
  24447. }
  24448. mesh.computeWorldMatrix();
  24449. // Intersections
  24450. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24451. this._meshesForIntersections.pushNoDuplicate(mesh);
  24452. }
  24453. // Switch to current LOD
  24454. meshLOD = mesh.getLOD(this.activeCamera);
  24455. if (meshLOD === undefined || meshLOD === null) {
  24456. continue;
  24457. }
  24458. mesh._preActivate();
  24459. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24460. this._activeMeshes.push(mesh);
  24461. this.activeCamera._activeMeshes.push(mesh);
  24462. mesh._activate(this._renderId);
  24463. if (meshLOD !== mesh) {
  24464. meshLOD._activate(this._renderId);
  24465. }
  24466. this._activeMesh(mesh, meshLOD);
  24467. }
  24468. }
  24469. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24470. // Particle systems
  24471. if (this.particlesEnabled) {
  24472. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24473. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24474. var particleSystem = this.particleSystems[particleIndex];
  24475. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24476. continue;
  24477. }
  24478. var emitter = particleSystem.emitter;
  24479. if (!emitter.position || emitter.isEnabled()) {
  24480. this._activeParticleSystems.push(particleSystem);
  24481. particleSystem.animate();
  24482. this._renderingManager.dispatchParticles(particleSystem);
  24483. }
  24484. }
  24485. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24486. }
  24487. };
  24488. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24489. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24490. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24491. mesh.skeleton.prepare();
  24492. }
  24493. if (!mesh.computeBonesUsingShaders) {
  24494. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24495. }
  24496. }
  24497. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24498. var boundingInfo = sourceMesh.getBoundingInfo();
  24499. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24500. }
  24501. if (mesh !== undefined && mesh !== null
  24502. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24503. // Submeshes Octrees
  24504. var len;
  24505. var subMeshes;
  24506. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24507. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24508. len = intersections.length;
  24509. subMeshes = intersections.data;
  24510. }
  24511. else {
  24512. subMeshes = mesh.subMeshes;
  24513. len = subMeshes.length;
  24514. }
  24515. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24516. subMesh = subMeshes[subIndex];
  24517. this._evaluateSubMesh(subMesh, mesh);
  24518. }
  24519. }
  24520. };
  24521. Scene.prototype.updateTransformMatrix = function (force) {
  24522. if (!this.activeCamera) {
  24523. return;
  24524. }
  24525. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24526. };
  24527. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24528. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24529. };
  24530. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24531. if (camera && camera._skipRendering) {
  24532. return;
  24533. }
  24534. var engine = this._engine;
  24535. this.activeCamera = camera;
  24536. if (!this.activeCamera)
  24537. throw new Error("Active camera not set");
  24538. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24539. // Viewport
  24540. engine.setViewport(this.activeCamera.viewport);
  24541. // Camera
  24542. this.resetCachedMaterial();
  24543. this._renderId++;
  24544. this.updateTransformMatrix();
  24545. if (camera._alternateCamera) {
  24546. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24547. this._alternateRendering = true;
  24548. }
  24549. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24550. // Meshes
  24551. this._evaluateActiveMeshes();
  24552. // Software skinning
  24553. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24554. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24555. mesh.applySkeleton(mesh.skeleton);
  24556. }
  24557. // Render targets
  24558. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24559. var needsRestoreFrameBuffer = false;
  24560. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24561. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24562. }
  24563. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24564. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24565. }
  24566. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24567. this._intermediateRendering = true;
  24568. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24569. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24570. var renderTarget = this._renderTargets.data[renderIndex];
  24571. if (renderTarget._shouldRender()) {
  24572. this._renderId++;
  24573. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24574. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24575. }
  24576. }
  24577. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24578. this._intermediateRendering = false;
  24579. this._renderId++;
  24580. needsRestoreFrameBuffer = true; // Restore back buffer
  24581. }
  24582. // Render EffecttLayer Texture
  24583. var stencilState = this._engine.getStencilBuffer();
  24584. var renderEffects = false;
  24585. var needStencil = false;
  24586. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24587. this._intermediateRendering = true;
  24588. for (var i = 0; i < this.effectLayers.length; i++) {
  24589. var effectLayer = this.effectLayers[i];
  24590. if (effectLayer.shouldRender() &&
  24591. (!effectLayer.camera ||
  24592. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24593. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24594. renderEffects = true;
  24595. needStencil = needStencil || effectLayer.needStencil();
  24596. var renderTarget = effectLayer._mainTexture;
  24597. if (renderTarget._shouldRender()) {
  24598. this._renderId++;
  24599. renderTarget.render(false, false);
  24600. needsRestoreFrameBuffer = true;
  24601. }
  24602. }
  24603. }
  24604. this._intermediateRendering = false;
  24605. this._renderId++;
  24606. }
  24607. if (needsRestoreFrameBuffer) {
  24608. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24609. }
  24610. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24611. // Prepare Frame
  24612. this.postProcessManager._prepareFrame();
  24613. // Backgrounds
  24614. var layerIndex;
  24615. var layer;
  24616. if (this.layers.length) {
  24617. engine.setDepthBuffer(false);
  24618. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24619. layer = this.layers[layerIndex];
  24620. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24621. layer.render();
  24622. }
  24623. }
  24624. engine.setDepthBuffer(true);
  24625. }
  24626. // Activate effect Layer stencil
  24627. if (needStencil) {
  24628. this._engine.setStencilBuffer(true);
  24629. }
  24630. // Render
  24631. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24632. this._renderingManager.render(null, null, true, true);
  24633. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24634. // Restore effect Layer stencil
  24635. if (needStencil) {
  24636. this._engine.setStencilBuffer(stencilState);
  24637. }
  24638. // Bounding boxes
  24639. if (this._boundingBoxRenderer) {
  24640. this._boundingBoxRenderer.render();
  24641. }
  24642. // Lens flares
  24643. if (this.lensFlaresEnabled) {
  24644. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24645. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24646. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24647. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24648. lensFlareSystem.render();
  24649. }
  24650. }
  24651. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24652. }
  24653. // Foregrounds
  24654. if (this.layers.length) {
  24655. engine.setDepthBuffer(false);
  24656. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24657. layer = this.layers[layerIndex];
  24658. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24659. layer.render();
  24660. }
  24661. }
  24662. engine.setDepthBuffer(true);
  24663. }
  24664. // Effect Layer
  24665. if (renderEffects) {
  24666. engine.setDepthBuffer(false);
  24667. for (var i = 0; i < this.effectLayers.length; i++) {
  24668. if (this.effectLayers[i].shouldRender()) {
  24669. this.effectLayers[i].render();
  24670. }
  24671. }
  24672. engine.setDepthBuffer(true);
  24673. }
  24674. // Finalize frame
  24675. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24676. // Reset some special arrays
  24677. this._renderTargets.reset();
  24678. this._alternateRendering = false;
  24679. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24680. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24681. };
  24682. Scene.prototype._processSubCameras = function (camera) {
  24683. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24684. this._renderForCamera(camera);
  24685. return;
  24686. }
  24687. // rig cameras
  24688. for (var index = 0; index < camera._rigCameras.length; index++) {
  24689. this._renderForCamera(camera._rigCameras[index], camera);
  24690. }
  24691. this.activeCamera = camera;
  24692. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24693. };
  24694. Scene.prototype._checkIntersections = function () {
  24695. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24696. var sourceMesh = this._meshesForIntersections.data[index];
  24697. if (!sourceMesh.actionManager) {
  24698. continue;
  24699. }
  24700. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24701. var action = sourceMesh.actionManager.actions[actionIndex];
  24702. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24703. var parameters = action.getTriggerParameter();
  24704. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24705. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24706. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24707. if (areIntersecting && currentIntersectionInProgress === -1) {
  24708. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24709. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24710. sourceMesh._intersectionsInProgress.push(otherMesh);
  24711. }
  24712. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24713. sourceMesh._intersectionsInProgress.push(otherMesh);
  24714. }
  24715. }
  24716. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24717. //They intersected, and now they don't.
  24718. //is this trigger an exit trigger? execute an event.
  24719. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24720. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24721. }
  24722. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24723. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24724. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24725. }
  24726. }
  24727. }
  24728. }
  24729. }
  24730. };
  24731. Scene.prototype.render = function () {
  24732. if (this.isDisposed) {
  24733. return;
  24734. }
  24735. this._activeParticles.fetchNewFrame();
  24736. this._totalVertices.fetchNewFrame();
  24737. this._activeIndices.fetchNewFrame();
  24738. this._activeBones.fetchNewFrame();
  24739. this._meshesForIntersections.reset();
  24740. this.resetCachedMaterial();
  24741. this.onBeforeAnimationsObservable.notifyObservers(this);
  24742. // Actions
  24743. if (this.actionManager) {
  24744. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24745. }
  24746. //Simplification Queue
  24747. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24748. this.simplificationQueue.executeNext();
  24749. }
  24750. if (this._engine.isDeterministicLockStep()) {
  24751. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24752. var defaultFPS = (60.0 / 1000.0);
  24753. var defaultFrameTime = 1000 / 60; // frame time in MS
  24754. if (this._physicsEngine) {
  24755. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24756. }
  24757. var stepsTaken = 0;
  24758. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24759. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24760. internalSteps = Math.min(internalSteps, maxSubSteps);
  24761. do {
  24762. this.onBeforeStepObservable.notifyObservers(this);
  24763. // Animations
  24764. this._animationRatio = defaultFrameTime * defaultFPS;
  24765. this._animate();
  24766. this.onAfterAnimationsObservable.notifyObservers(this);
  24767. // Physics
  24768. if (this._physicsEngine) {
  24769. this.onBeforePhysicsObservable.notifyObservers(this);
  24770. this._physicsEngine._step(defaultFrameTime / 1000);
  24771. this.onAfterPhysicsObservable.notifyObservers(this);
  24772. }
  24773. this.onAfterStepObservable.notifyObservers(this);
  24774. this._currentStepId++;
  24775. stepsTaken++;
  24776. deltaTime -= defaultFrameTime;
  24777. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24778. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24779. }
  24780. else {
  24781. // Animations
  24782. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24783. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24784. this._animate();
  24785. this.onAfterAnimationsObservable.notifyObservers(this);
  24786. // Physics
  24787. if (this._physicsEngine) {
  24788. this.onBeforePhysicsObservable.notifyObservers(this);
  24789. this._physicsEngine._step(deltaTime / 1000.0);
  24790. this.onAfterPhysicsObservable.notifyObservers(this);
  24791. }
  24792. }
  24793. // update gamepad manager
  24794. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24795. this._gamepadManager._checkGamepadsStatus();
  24796. }
  24797. // Update Cameras
  24798. if (this.activeCameras.length > 0) {
  24799. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24800. var camera = this.activeCameras[cameraIndex];
  24801. camera.update();
  24802. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24803. // rig cameras
  24804. for (var index = 0; index < camera._rigCameras.length; index++) {
  24805. camera._rigCameras[index].update();
  24806. }
  24807. }
  24808. }
  24809. }
  24810. else if (this.activeCamera) {
  24811. this.activeCamera.update();
  24812. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24813. // rig cameras
  24814. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24815. this.activeCamera._rigCameras[index].update();
  24816. }
  24817. }
  24818. }
  24819. // Before render
  24820. this.onBeforeRenderObservable.notifyObservers(this);
  24821. // Customs render targets
  24822. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24823. var engine = this.getEngine();
  24824. var currentActiveCamera = this.activeCamera;
  24825. if (this.renderTargetsEnabled) {
  24826. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24827. this._intermediateRendering = true;
  24828. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24829. var renderTarget = this.customRenderTargets[customIndex];
  24830. if (renderTarget._shouldRender()) {
  24831. this._renderId++;
  24832. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24833. if (!this.activeCamera)
  24834. throw new Error("Active camera not set");
  24835. // Viewport
  24836. engine.setViewport(this.activeCamera.viewport);
  24837. // Camera
  24838. this.updateTransformMatrix();
  24839. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24840. }
  24841. }
  24842. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24843. this._intermediateRendering = false;
  24844. this._renderId++;
  24845. }
  24846. // Restore back buffer
  24847. if (this.customRenderTargets.length > 0) {
  24848. engine.restoreDefaultFramebuffer();
  24849. }
  24850. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24851. this.activeCamera = currentActiveCamera;
  24852. // Procedural textures
  24853. if (this.proceduralTexturesEnabled) {
  24854. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24855. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24856. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24857. if (proceduralTexture._shouldRender()) {
  24858. proceduralTexture.render();
  24859. }
  24860. }
  24861. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24862. }
  24863. // Clear
  24864. if (this.autoClearDepthAndStencil || this.autoClear) {
  24865. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24866. }
  24867. // Shadows
  24868. if (this.shadowsEnabled) {
  24869. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24870. var light = this.lights[lightIndex];
  24871. var shadowGenerator = light.getShadowGenerator();
  24872. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24873. var shadowMap = (shadowGenerator.getShadowMap());
  24874. if (this.textures.indexOf(shadowMap) !== -1) {
  24875. this._renderTargets.push(shadowMap);
  24876. }
  24877. }
  24878. }
  24879. }
  24880. // Depth renderer
  24881. for (var key in this._depthRenderer) {
  24882. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24883. }
  24884. // Geometry renderer
  24885. if (this._geometryBufferRenderer) {
  24886. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24887. }
  24888. // RenderPipeline
  24889. if (this._postProcessRenderPipelineManager) {
  24890. this._postProcessRenderPipelineManager.update();
  24891. }
  24892. // Multi-cameras?
  24893. if (this.activeCameras.length > 0) {
  24894. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24895. if (cameraIndex > 0) {
  24896. this._engine.clear(null, false, true, true);
  24897. }
  24898. this._processSubCameras(this.activeCameras[cameraIndex]);
  24899. }
  24900. }
  24901. else {
  24902. if (!this.activeCamera) {
  24903. throw new Error("No camera defined");
  24904. }
  24905. this._processSubCameras(this.activeCamera);
  24906. }
  24907. // Intersection checks
  24908. this._checkIntersections();
  24909. // Update the audio listener attached to the camera
  24910. if (BABYLON.AudioEngine) {
  24911. this._updateAudioParameters();
  24912. }
  24913. // After render
  24914. if (this.afterRender) {
  24915. this.afterRender();
  24916. }
  24917. this.onAfterRenderObservable.notifyObservers(this);
  24918. // Cleaning
  24919. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24920. var data = this._toBeDisposed.data[index];
  24921. if (data) {
  24922. data.dispose();
  24923. }
  24924. this._toBeDisposed[index] = null;
  24925. }
  24926. this._toBeDisposed.reset();
  24927. if (this.dumpNextRenderTargets) {
  24928. this.dumpNextRenderTargets = false;
  24929. }
  24930. this._activeBones.addCount(0, true);
  24931. this._activeIndices.addCount(0, true);
  24932. this._activeParticles.addCount(0, true);
  24933. };
  24934. Scene.prototype._updateAudioParameters = function () {
  24935. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24936. return;
  24937. }
  24938. var listeningCamera;
  24939. var audioEngine = BABYLON.Engine.audioEngine;
  24940. if (this.activeCameras.length > 0) {
  24941. listeningCamera = this.activeCameras[0];
  24942. }
  24943. else {
  24944. listeningCamera = this.activeCamera;
  24945. }
  24946. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24947. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24948. // for VR cameras
  24949. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24950. listeningCamera = listeningCamera.rigCameras[0];
  24951. }
  24952. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24953. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24954. cameraDirection.normalize();
  24955. // To avoid some errors on GearVR
  24956. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24957. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24958. }
  24959. var i;
  24960. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24961. var sound = this.mainSoundTrack.soundCollection[i];
  24962. if (sound.useCustomAttenuation) {
  24963. sound.updateDistanceFromListener();
  24964. }
  24965. }
  24966. for (i = 0; i < this.soundTracks.length; i++) {
  24967. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24968. sound = this.soundTracks[i].soundCollection[j];
  24969. if (sound.useCustomAttenuation) {
  24970. sound.updateDistanceFromListener();
  24971. }
  24972. }
  24973. }
  24974. }
  24975. };
  24976. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24977. // Audio
  24978. get: function () {
  24979. return this._audioEnabled;
  24980. },
  24981. set: function (value) {
  24982. this._audioEnabled = value;
  24983. if (BABYLON.AudioEngine) {
  24984. if (this._audioEnabled) {
  24985. this._enableAudio();
  24986. }
  24987. else {
  24988. this._disableAudio();
  24989. }
  24990. }
  24991. },
  24992. enumerable: true,
  24993. configurable: true
  24994. });
  24995. Scene.prototype._disableAudio = function () {
  24996. var i;
  24997. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24998. this.mainSoundTrack.soundCollection[i].pause();
  24999. }
  25000. for (i = 0; i < this.soundTracks.length; i++) {
  25001. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25002. this.soundTracks[i].soundCollection[j].pause();
  25003. }
  25004. }
  25005. };
  25006. Scene.prototype._enableAudio = function () {
  25007. var i;
  25008. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25009. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  25010. this.mainSoundTrack.soundCollection[i].play();
  25011. }
  25012. }
  25013. for (i = 0; i < this.soundTracks.length; i++) {
  25014. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25015. if (this.soundTracks[i].soundCollection[j].isPaused) {
  25016. this.soundTracks[i].soundCollection[j].play();
  25017. }
  25018. }
  25019. }
  25020. };
  25021. Object.defineProperty(Scene.prototype, "headphone", {
  25022. get: function () {
  25023. return this._headphone;
  25024. },
  25025. set: function (value) {
  25026. this._headphone = value;
  25027. if (BABYLON.AudioEngine) {
  25028. if (this._headphone) {
  25029. this._switchAudioModeForHeadphones();
  25030. }
  25031. else {
  25032. this._switchAudioModeForNormalSpeakers();
  25033. }
  25034. }
  25035. },
  25036. enumerable: true,
  25037. configurable: true
  25038. });
  25039. Scene.prototype._switchAudioModeForHeadphones = function () {
  25040. this.mainSoundTrack.switchPanningModelToHRTF();
  25041. for (var i = 0; i < this.soundTracks.length; i++) {
  25042. this.soundTracks[i].switchPanningModelToHRTF();
  25043. }
  25044. };
  25045. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25046. this.mainSoundTrack.switchPanningModelToEqualPower();
  25047. for (var i = 0; i < this.soundTracks.length; i++) {
  25048. this.soundTracks[i].switchPanningModelToEqualPower();
  25049. }
  25050. };
  25051. /**
  25052. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25053. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25054. * @returns the created depth renderer
  25055. */
  25056. Scene.prototype.enableDepthRenderer = function (camera) {
  25057. camera = camera || this.activeCamera;
  25058. if (!camera) {
  25059. throw "No camera available to enable depth renderer";
  25060. }
  25061. if (!this._depthRenderer[camera.id]) {
  25062. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  25063. }
  25064. return this._depthRenderer[camera.id];
  25065. };
  25066. /**
  25067. * Disables a depth renderer for a given camera
  25068. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25069. */
  25070. Scene.prototype.disableDepthRenderer = function (camera) {
  25071. camera = camera || this.activeCamera;
  25072. if (!camera || !this._depthRenderer[camera.id]) {
  25073. return;
  25074. }
  25075. this._depthRenderer[camera.id].dispose();
  25076. delete this._depthRenderer[camera.id];
  25077. };
  25078. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25079. if (ratio === void 0) { ratio = 1; }
  25080. if (this._geometryBufferRenderer) {
  25081. return this._geometryBufferRenderer;
  25082. }
  25083. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25084. if (!this._geometryBufferRenderer.isSupported) {
  25085. this._geometryBufferRenderer = null;
  25086. }
  25087. return this._geometryBufferRenderer;
  25088. };
  25089. Scene.prototype.disableGeometryBufferRenderer = function () {
  25090. if (!this._geometryBufferRenderer) {
  25091. return;
  25092. }
  25093. this._geometryBufferRenderer.dispose();
  25094. this._geometryBufferRenderer = null;
  25095. };
  25096. Scene.prototype.freezeMaterials = function () {
  25097. for (var i = 0; i < this.materials.length; i++) {
  25098. this.materials[i].freeze();
  25099. }
  25100. };
  25101. Scene.prototype.unfreezeMaterials = function () {
  25102. for (var i = 0; i < this.materials.length; i++) {
  25103. this.materials[i].unfreeze();
  25104. }
  25105. };
  25106. Scene.prototype.dispose = function () {
  25107. this.beforeRender = null;
  25108. this.afterRender = null;
  25109. this.skeletons = [];
  25110. this.morphTargetManagers = [];
  25111. this.importedMeshesFiles = new Array();
  25112. this.stopAllAnimations();
  25113. this.resetCachedMaterial();
  25114. for (var key in this._depthRenderer) {
  25115. this._depthRenderer[key].dispose();
  25116. }
  25117. if (this._gamepadManager) {
  25118. this._gamepadManager.dispose();
  25119. this._gamepadManager = null;
  25120. }
  25121. // Smart arrays
  25122. if (this.activeCamera) {
  25123. this.activeCamera._activeMeshes.dispose();
  25124. this.activeCamera = null;
  25125. }
  25126. this._activeMeshes.dispose();
  25127. this._renderingManager.dispose();
  25128. this._processedMaterials.dispose();
  25129. this._activeParticleSystems.dispose();
  25130. this._activeSkeletons.dispose();
  25131. this._softwareSkinnedMeshes.dispose();
  25132. this._renderTargets.dispose();
  25133. this._registeredForLateAnimationBindings.dispose();
  25134. if (this._boundingBoxRenderer) {
  25135. this._boundingBoxRenderer.dispose();
  25136. }
  25137. this._meshesForIntersections.dispose();
  25138. this._toBeDisposed.dispose();
  25139. // Abort active requests
  25140. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25141. var request = _a[_i];
  25142. request.abort();
  25143. }
  25144. // Debug layer
  25145. if (this._debugLayer) {
  25146. this._debugLayer.hide();
  25147. }
  25148. // Events
  25149. this.onDisposeObservable.notifyObservers(this);
  25150. this.onDisposeObservable.clear();
  25151. this.onBeforeRenderObservable.clear();
  25152. this.onAfterRenderObservable.clear();
  25153. this.OnBeforeRenderTargetsRenderObservable.clear();
  25154. this.OnAfterRenderTargetsRenderObservable.clear();
  25155. this.onAfterStepObservable.clear();
  25156. this.onBeforeStepObservable.clear();
  25157. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25158. this.onAfterActiveMeshesEvaluationObservable.clear();
  25159. this.onBeforeParticlesRenderingObservable.clear();
  25160. this.onAfterParticlesRenderingObservable.clear();
  25161. this.onBeforeSpritesRenderingObservable.clear();
  25162. this.onAfterSpritesRenderingObservable.clear();
  25163. this.onBeforeDrawPhaseObservable.clear();
  25164. this.onAfterDrawPhaseObservable.clear();
  25165. this.onBeforePhysicsObservable.clear();
  25166. this.onAfterPhysicsObservable.clear();
  25167. this.onBeforeAnimationsObservable.clear();
  25168. this.onAfterAnimationsObservable.clear();
  25169. this.onDataLoadedObservable.clear();
  25170. this.detachControl();
  25171. // Release sounds & sounds tracks
  25172. if (BABYLON.AudioEngine) {
  25173. this.disposeSounds();
  25174. }
  25175. // VR Helper
  25176. if (this.VRHelper) {
  25177. this.VRHelper.dispose();
  25178. }
  25179. // Detach cameras
  25180. var canvas = this._engine.getRenderingCanvas();
  25181. if (canvas) {
  25182. var index;
  25183. for (index = 0; index < this.cameras.length; index++) {
  25184. this.cameras[index].detachControl(canvas);
  25185. }
  25186. }
  25187. // Release animation groups
  25188. while (this.animationGroups.length) {
  25189. this.animationGroups[0].dispose();
  25190. }
  25191. // Release lights
  25192. while (this.lights.length) {
  25193. this.lights[0].dispose();
  25194. }
  25195. // Release meshes
  25196. while (this.meshes.length) {
  25197. this.meshes[0].dispose(true);
  25198. }
  25199. while (this.transformNodes.length) {
  25200. this.removeTransformNode(this.transformNodes[0]);
  25201. }
  25202. // Release cameras
  25203. while (this.cameras.length) {
  25204. this.cameras[0].dispose();
  25205. }
  25206. // Release materials
  25207. if (this.defaultMaterial) {
  25208. this.defaultMaterial.dispose();
  25209. }
  25210. while (this.multiMaterials.length) {
  25211. this.multiMaterials[0].dispose();
  25212. }
  25213. while (this.materials.length) {
  25214. this.materials[0].dispose();
  25215. }
  25216. // Release particles
  25217. while (this.particleSystems.length) {
  25218. this.particleSystems[0].dispose();
  25219. }
  25220. // Release sprites
  25221. while (this.spriteManagers.length) {
  25222. this.spriteManagers[0].dispose();
  25223. }
  25224. // Release postProcesses
  25225. while (this.postProcesses.length) {
  25226. this.postProcesses[0].dispose();
  25227. }
  25228. // Release layers
  25229. while (this.layers.length) {
  25230. this.layers[0].dispose();
  25231. }
  25232. while (this.effectLayers.length) {
  25233. this.effectLayers[0].dispose();
  25234. }
  25235. // Release textures
  25236. while (this.textures.length) {
  25237. this.textures[0].dispose();
  25238. }
  25239. // Release UBO
  25240. this._sceneUbo.dispose();
  25241. if (this._alternateSceneUbo) {
  25242. this._alternateSceneUbo.dispose();
  25243. }
  25244. // Post-processes
  25245. this.postProcessManager.dispose();
  25246. if (this._postProcessRenderPipelineManager) {
  25247. this._postProcessRenderPipelineManager.dispose();
  25248. }
  25249. // Physics
  25250. if (this._physicsEngine) {
  25251. this.disablePhysicsEngine();
  25252. }
  25253. // Remove from engine
  25254. index = this._engine.scenes.indexOf(this);
  25255. if (index > -1) {
  25256. this._engine.scenes.splice(index, 1);
  25257. }
  25258. this._engine.wipeCaches(true);
  25259. this._isDisposed = true;
  25260. };
  25261. Object.defineProperty(Scene.prototype, "isDisposed", {
  25262. get: function () {
  25263. return this._isDisposed;
  25264. },
  25265. enumerable: true,
  25266. configurable: true
  25267. });
  25268. // Release sounds & sounds tracks
  25269. Scene.prototype.disposeSounds = function () {
  25270. if (!this._mainSoundTrack) {
  25271. return;
  25272. }
  25273. this.mainSoundTrack.dispose();
  25274. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25275. this.soundTracks[scIndex].dispose();
  25276. }
  25277. };
  25278. // Octrees
  25279. /**
  25280. * Get the world extend vectors with an optional filter
  25281. *
  25282. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25283. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25284. */
  25285. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25286. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25287. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25288. filterPredicate = filterPredicate || (function () { return true; });
  25289. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25290. mesh.computeWorldMatrix(true);
  25291. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25292. return;
  25293. }
  25294. var boundingInfo = mesh.getBoundingInfo();
  25295. var minBox = boundingInfo.boundingBox.minimumWorld;
  25296. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25297. BABYLON.Tools.CheckExtends(minBox, min, max);
  25298. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25299. });
  25300. return {
  25301. min: min,
  25302. max: max
  25303. };
  25304. };
  25305. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25306. if (maxCapacity === void 0) { maxCapacity = 64; }
  25307. if (maxDepth === void 0) { maxDepth = 2; }
  25308. if (!this._selectionOctree) {
  25309. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25310. }
  25311. var worldExtends = this.getWorldExtends();
  25312. // Update octree
  25313. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25314. return this._selectionOctree;
  25315. };
  25316. // Picking
  25317. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25318. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25319. var result = BABYLON.Ray.Zero();
  25320. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25321. return result;
  25322. };
  25323. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25324. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25325. var engine = this._engine;
  25326. if (!camera) {
  25327. if (!this.activeCamera)
  25328. throw new Error("Active camera not set");
  25329. camera = this.activeCamera;
  25330. }
  25331. var cameraViewport = camera.viewport;
  25332. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25333. // Moving coordinates to local viewport world
  25334. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25335. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25336. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25337. return this;
  25338. };
  25339. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25340. var result = BABYLON.Ray.Zero();
  25341. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25342. return result;
  25343. };
  25344. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25345. if (!BABYLON.PickingInfo) {
  25346. return this;
  25347. }
  25348. var engine = this._engine;
  25349. if (!camera) {
  25350. if (!this.activeCamera)
  25351. throw new Error("Active camera not set");
  25352. camera = this.activeCamera;
  25353. }
  25354. var cameraViewport = camera.viewport;
  25355. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25356. var identity = BABYLON.Matrix.Identity();
  25357. // Moving coordinates to local viewport world
  25358. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25359. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25360. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25361. return this;
  25362. };
  25363. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25364. if (!BABYLON.PickingInfo) {
  25365. return null;
  25366. }
  25367. var pickingInfo = null;
  25368. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25369. var mesh = this.meshes[meshIndex];
  25370. if (predicate) {
  25371. if (!predicate(mesh)) {
  25372. continue;
  25373. }
  25374. }
  25375. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25376. continue;
  25377. }
  25378. var world = mesh.getWorldMatrix();
  25379. var ray = rayFunction(world);
  25380. var result = mesh.intersects(ray, fastCheck);
  25381. if (!result || !result.hit)
  25382. continue;
  25383. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25384. continue;
  25385. pickingInfo = result;
  25386. if (fastCheck) {
  25387. break;
  25388. }
  25389. }
  25390. return pickingInfo || new BABYLON.PickingInfo();
  25391. };
  25392. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25393. if (!BABYLON.PickingInfo) {
  25394. return null;
  25395. }
  25396. var pickingInfos = new Array();
  25397. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25398. var mesh = this.meshes[meshIndex];
  25399. if (predicate) {
  25400. if (!predicate(mesh)) {
  25401. continue;
  25402. }
  25403. }
  25404. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25405. continue;
  25406. }
  25407. var world = mesh.getWorldMatrix();
  25408. var ray = rayFunction(world);
  25409. var result = mesh.intersects(ray, false);
  25410. if (!result || !result.hit)
  25411. continue;
  25412. pickingInfos.push(result);
  25413. }
  25414. return pickingInfos;
  25415. };
  25416. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25417. if (!BABYLON.PickingInfo) {
  25418. return null;
  25419. }
  25420. var pickingInfo = null;
  25421. if (!camera) {
  25422. if (!this.activeCamera) {
  25423. return null;
  25424. }
  25425. camera = this.activeCamera;
  25426. }
  25427. if (this.spriteManagers.length > 0) {
  25428. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25429. var spriteManager = this.spriteManagers[spriteIndex];
  25430. if (!spriteManager.isPickable) {
  25431. continue;
  25432. }
  25433. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25434. if (!result || !result.hit)
  25435. continue;
  25436. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25437. continue;
  25438. pickingInfo = result;
  25439. if (fastCheck) {
  25440. break;
  25441. }
  25442. }
  25443. }
  25444. return pickingInfo || new BABYLON.PickingInfo();
  25445. };
  25446. /** Launch a ray to try to pick a mesh in the scene
  25447. * @param x position on screen
  25448. * @param y position on screen
  25449. * @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
  25450. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25451. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25452. */
  25453. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25454. var _this = this;
  25455. if (!BABYLON.PickingInfo) {
  25456. return null;
  25457. }
  25458. return this._internalPick(function (world) {
  25459. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25460. return _this._tempPickingRay;
  25461. }, predicate, fastCheck);
  25462. };
  25463. /** Launch a ray to try to pick a sprite in the scene
  25464. * @param x position on screen
  25465. * @param y position on screen
  25466. * @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
  25467. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25468. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25469. */
  25470. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25471. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25472. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25473. };
  25474. /** Use the given ray to pick a mesh in the scene
  25475. * @param ray The ray to use to pick meshes
  25476. * @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
  25477. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25478. */
  25479. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25480. var _this = this;
  25481. return this._internalPick(function (world) {
  25482. if (!_this._pickWithRayInverseMatrix) {
  25483. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25484. }
  25485. world.invertToRef(_this._pickWithRayInverseMatrix);
  25486. if (!_this._cachedRayForTransform) {
  25487. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25488. }
  25489. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25490. return _this._cachedRayForTransform;
  25491. }, predicate, fastCheck);
  25492. };
  25493. /**
  25494. * Launch a ray to try to pick a mesh in the scene
  25495. * @param x X position on screen
  25496. * @param y Y position on screen
  25497. * @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
  25498. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25499. */
  25500. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25501. var _this = this;
  25502. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25503. };
  25504. /**
  25505. * Launch a ray to try to pick a mesh in the scene
  25506. * @param ray Ray to use
  25507. * @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
  25508. */
  25509. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25510. var _this = this;
  25511. return this._internalMultiPick(function (world) {
  25512. if (!_this._pickWithRayInverseMatrix) {
  25513. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25514. }
  25515. world.invertToRef(_this._pickWithRayInverseMatrix);
  25516. if (!_this._cachedRayForTransform) {
  25517. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25518. }
  25519. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25520. return _this._cachedRayForTransform;
  25521. }, predicate);
  25522. };
  25523. Scene.prototype.setPointerOverMesh = function (mesh) {
  25524. if (this._pointerOverMesh === mesh) {
  25525. return;
  25526. }
  25527. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25528. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25529. }
  25530. this._pointerOverMesh = mesh;
  25531. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25532. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25533. }
  25534. };
  25535. Scene.prototype.getPointerOverMesh = function () {
  25536. return this._pointerOverMesh;
  25537. };
  25538. Scene.prototype.setPointerOverSprite = function (sprite) {
  25539. if (this._pointerOverSprite === sprite) {
  25540. return;
  25541. }
  25542. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25543. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25544. }
  25545. this._pointerOverSprite = sprite;
  25546. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25547. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25548. }
  25549. };
  25550. Scene.prototype.getPointerOverSprite = function () {
  25551. return this._pointerOverSprite;
  25552. };
  25553. // Physics
  25554. Scene.prototype.getPhysicsEngine = function () {
  25555. return this._physicsEngine;
  25556. };
  25557. /**
  25558. * Enables physics to the current scene
  25559. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25560. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25561. * @return {boolean} was the physics engine initialized
  25562. */
  25563. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25564. if (gravity === void 0) { gravity = null; }
  25565. if (this._physicsEngine) {
  25566. return true;
  25567. }
  25568. try {
  25569. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25570. return true;
  25571. }
  25572. catch (e) {
  25573. BABYLON.Tools.Error(e.message);
  25574. return false;
  25575. }
  25576. };
  25577. Scene.prototype.disablePhysicsEngine = function () {
  25578. if (!this._physicsEngine) {
  25579. return;
  25580. }
  25581. this._physicsEngine.dispose();
  25582. this._physicsEngine = null;
  25583. };
  25584. Scene.prototype.isPhysicsEnabled = function () {
  25585. return this._physicsEngine !== undefined;
  25586. };
  25587. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25588. var mesh = compound.parts[0].mesh;
  25589. if (mesh.physicsImpostor) {
  25590. mesh.physicsImpostor.dispose();
  25591. mesh.physicsImpostor = null;
  25592. }
  25593. };
  25594. // Misc.
  25595. Scene.prototype._rebuildGeometries = function () {
  25596. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25597. var geometry = _a[_i];
  25598. geometry._rebuild();
  25599. }
  25600. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25601. var mesh = _c[_b];
  25602. mesh._rebuild();
  25603. }
  25604. if (this.postProcessManager) {
  25605. this.postProcessManager._rebuild();
  25606. }
  25607. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25608. var layer = _e[_d];
  25609. layer._rebuild();
  25610. }
  25611. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25612. var effectLayer = _g[_f];
  25613. effectLayer._rebuild();
  25614. }
  25615. if (this._boundingBoxRenderer) {
  25616. this._boundingBoxRenderer._rebuild();
  25617. }
  25618. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25619. var system = _j[_h];
  25620. system.rebuild();
  25621. }
  25622. if (this._postProcessRenderPipelineManager) {
  25623. this._postProcessRenderPipelineManager._rebuild();
  25624. }
  25625. };
  25626. Scene.prototype._rebuildTextures = function () {
  25627. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25628. var texture = _a[_i];
  25629. texture._rebuild();
  25630. }
  25631. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25632. };
  25633. /**
  25634. * Creates a default light for the scene.
  25635. * @param replace Whether to replace the existing lights in the scene.
  25636. */
  25637. Scene.prototype.createDefaultLight = function (replace) {
  25638. if (replace === void 0) { replace = false; }
  25639. // Dispose existing light in replace mode.
  25640. if (replace) {
  25641. if (this.lights) {
  25642. for (var i = 0; i < this.lights.length; i++) {
  25643. this.lights[i].dispose();
  25644. }
  25645. }
  25646. }
  25647. // Light
  25648. if (this.lights.length === 0) {
  25649. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25650. }
  25651. };
  25652. /**
  25653. * Creates a default camera for the scene.
  25654. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25655. * @param replace Whether to replace the existing active camera in the scene.
  25656. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25657. */
  25658. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25659. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25660. if (replace === void 0) { replace = false; }
  25661. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25662. // Dispose existing camera in replace mode.
  25663. if (replace) {
  25664. if (this.activeCamera) {
  25665. this.activeCamera.dispose();
  25666. this.activeCamera = null;
  25667. }
  25668. }
  25669. // Camera
  25670. if (!this.activeCamera) {
  25671. var worldExtends = this.getWorldExtends();
  25672. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25673. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25674. var camera;
  25675. var radius = worldSize.length() * 1.5;
  25676. // empty scene scenario!
  25677. if (!isFinite(radius)) {
  25678. radius = 1;
  25679. worldCenter.copyFromFloats(0, 0, 0);
  25680. }
  25681. if (createArcRotateCamera) {
  25682. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25683. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25684. arcRotateCamera.wheelPrecision = 100 / radius;
  25685. camera = arcRotateCamera;
  25686. }
  25687. else {
  25688. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25689. freeCamera.setTarget(worldCenter);
  25690. camera = freeCamera;
  25691. }
  25692. camera.minZ = radius * 0.01;
  25693. camera.maxZ = radius * 1000;
  25694. camera.speed = radius * 0.2;
  25695. this.activeCamera = camera;
  25696. var canvas = this.getEngine().getRenderingCanvas();
  25697. if (attachCameraControls && canvas) {
  25698. camera.attachControl(canvas);
  25699. }
  25700. }
  25701. };
  25702. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25703. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25704. if (replace === void 0) { replace = false; }
  25705. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25706. this.createDefaultLight(replace);
  25707. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25708. };
  25709. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25710. if (pbr === void 0) { pbr = false; }
  25711. if (scale === void 0) { scale = 1000; }
  25712. if (blur === void 0) { blur = 0; }
  25713. if (environmentTexture) {
  25714. this.environmentTexture = environmentTexture;
  25715. }
  25716. if (!this.environmentTexture) {
  25717. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25718. return null;
  25719. }
  25720. // Skybox
  25721. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25722. if (pbr) {
  25723. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25724. hdrSkyboxMaterial.backFaceCulling = false;
  25725. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25726. if (hdrSkyboxMaterial.reflectionTexture) {
  25727. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25728. }
  25729. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25730. hdrSkyboxMaterial.disableLighting = true;
  25731. hdrSkyboxMaterial.twoSidedLighting = true;
  25732. hdrSkybox.infiniteDistance = true;
  25733. hdrSkybox.material = hdrSkyboxMaterial;
  25734. }
  25735. else {
  25736. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25737. skyboxMaterial.backFaceCulling = false;
  25738. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25739. if (skyboxMaterial.reflectionTexture) {
  25740. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25741. }
  25742. skyboxMaterial.disableLighting = true;
  25743. hdrSkybox.infiniteDistance = true;
  25744. hdrSkybox.material = skyboxMaterial;
  25745. }
  25746. return hdrSkybox;
  25747. };
  25748. Scene.prototype.createDefaultEnvironment = function (options) {
  25749. if (BABYLON.EnvironmentHelper) {
  25750. return new BABYLON.EnvironmentHelper(options, this);
  25751. }
  25752. return null;
  25753. };
  25754. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25755. if (webVROptions === void 0) { webVROptions = {}; }
  25756. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25757. };
  25758. // Tags
  25759. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25760. if (tagsQuery === undefined) {
  25761. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25762. return list;
  25763. }
  25764. var listByTags = [];
  25765. forEach = forEach || (function (item) { return; });
  25766. for (var i in list) {
  25767. var item = list[i];
  25768. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25769. listByTags.push(item);
  25770. forEach(item);
  25771. }
  25772. }
  25773. return listByTags;
  25774. };
  25775. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25776. return this._getByTags(this.meshes, tagsQuery, forEach);
  25777. };
  25778. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25779. return this._getByTags(this.cameras, tagsQuery, forEach);
  25780. };
  25781. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25782. return this._getByTags(this.lights, tagsQuery, forEach);
  25783. };
  25784. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25785. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25786. };
  25787. /**
  25788. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25789. * This allowed control for front to back rendering or reversly depending of the special needs.
  25790. *
  25791. * @param renderingGroupId The rendering group id corresponding to its index
  25792. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25793. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25794. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25795. */
  25796. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25797. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25798. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25799. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25800. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25801. };
  25802. /**
  25803. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25804. *
  25805. * @param renderingGroupId The rendering group id corresponding to its index
  25806. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25807. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25808. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25809. */
  25810. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25811. if (depth === void 0) { depth = true; }
  25812. if (stencil === void 0) { stencil = true; }
  25813. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25814. };
  25815. /**
  25816. * Will flag all materials as dirty to trigger new shader compilation
  25817. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25818. */
  25819. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25820. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25821. var material = _a[_i];
  25822. if (predicate && !predicate(material)) {
  25823. continue;
  25824. }
  25825. material.markAsDirty(flag);
  25826. }
  25827. };
  25828. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25829. var _this = this;
  25830. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25831. this._activeRequests.push(request);
  25832. request.onCompleteObservable.add(function (request) {
  25833. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25834. });
  25835. return request;
  25836. };
  25837. /** @ignore */
  25838. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25839. var _this = this;
  25840. return new Promise(function (resolve, reject) {
  25841. _this._loadFile(url, function (data) {
  25842. resolve(data);
  25843. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25844. reject(exception);
  25845. });
  25846. });
  25847. };
  25848. // Statics
  25849. Scene._FOGMODE_NONE = 0;
  25850. Scene._FOGMODE_EXP = 1;
  25851. Scene._FOGMODE_EXP2 = 2;
  25852. Scene._FOGMODE_LINEAR = 3;
  25853. Scene._uniqueIdCounter = 0;
  25854. Scene.MinDeltaTime = 1.0;
  25855. Scene.MaxDeltaTime = 1000.0;
  25856. /** The distance in pixel that you have to move to prevent some events */
  25857. Scene.DragMovementThreshold = 10; // in pixels
  25858. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25859. Scene.LongPressDelay = 500; // in milliseconds
  25860. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25861. Scene.DoubleClickDelay = 300; // in milliseconds
  25862. /** If you need to check double click without raising a single click at first click, enable this flag */
  25863. Scene.ExclusiveDoubleClickMode = false;
  25864. return Scene;
  25865. }());
  25866. BABYLON.Scene = Scene;
  25867. })(BABYLON || (BABYLON = {}));
  25868. //# sourceMappingURL=babylon.scene.js.map
  25869. "use strict";
  25870. var BABYLON;
  25871. (function (BABYLON) {
  25872. /**
  25873. * Set of assets to keep when moving a scene into an asset container.
  25874. */
  25875. var KeepAssets = /** @class */ (function () {
  25876. function KeepAssets() {
  25877. /**
  25878. * Cameras to keep.
  25879. */
  25880. this.cameras = new Array();
  25881. /**
  25882. * Lights to keep.
  25883. */
  25884. this.lights = new Array();
  25885. /**
  25886. * Meshes to keep.
  25887. */
  25888. this.meshes = new Array();
  25889. /**
  25890. * Skeletons to keep.
  25891. */
  25892. this.skeletons = new Array();
  25893. /**
  25894. * ParticleSystems to keep.
  25895. */
  25896. this.particleSystems = new Array();
  25897. /**
  25898. * Animations to keep.
  25899. */
  25900. this.animations = new Array();
  25901. /**
  25902. * MultiMaterials to keep.
  25903. */
  25904. this.multiMaterials = new Array();
  25905. /**
  25906. * Materials to keep.
  25907. */
  25908. this.materials = new Array();
  25909. /**
  25910. * MorphTargetManagers to keep.
  25911. */
  25912. this.morphTargetManagers = new Array();
  25913. /**
  25914. * Geometries to keep.
  25915. */
  25916. this.geometries = new Array();
  25917. /**
  25918. * TransformNodes to keep.
  25919. */
  25920. this.transformNodes = new Array();
  25921. /**
  25922. * LensFlareSystems to keep.
  25923. */
  25924. this.lensFlareSystems = new Array();
  25925. /**
  25926. * ShadowGenerators to keep.
  25927. */
  25928. this.shadowGenerators = new Array();
  25929. /**
  25930. * ActionManagers to keep.
  25931. */
  25932. this.actionManagers = new Array();
  25933. /**
  25934. * Sounds to keep.
  25935. */
  25936. this.sounds = new Array();
  25937. }
  25938. return KeepAssets;
  25939. }());
  25940. BABYLON.KeepAssets = KeepAssets;
  25941. /**
  25942. * Container with a set of assets that can be added or removed from a scene.
  25943. */
  25944. var AssetContainer = /** @class */ (function () {
  25945. /**
  25946. * Instantiates an AssetContainer.
  25947. * @param scene The scene the AssetContainer belongs to.
  25948. */
  25949. function AssetContainer(scene) {
  25950. // Objects
  25951. /**
  25952. * Cameras populated in the container.
  25953. */
  25954. this.cameras = new Array();
  25955. /**
  25956. * Lights populated in the container.
  25957. */
  25958. this.lights = new Array();
  25959. /**
  25960. * Meshes populated in the container.
  25961. */
  25962. this.meshes = new Array();
  25963. /**
  25964. * Skeletons populated in the container.
  25965. */
  25966. this.skeletons = new Array();
  25967. /**
  25968. * ParticleSystems populated in the container.
  25969. */
  25970. this.particleSystems = new Array();
  25971. /**
  25972. * Animations populated in the container.
  25973. */
  25974. this.animations = new Array();
  25975. /**
  25976. * MultiMaterials populated in the container.
  25977. */
  25978. this.multiMaterials = new Array();
  25979. /**
  25980. * Materials populated in the container.
  25981. */
  25982. this.materials = new Array();
  25983. /**
  25984. * MorphTargetManagers populated in the container.
  25985. */
  25986. this.morphTargetManagers = new Array();
  25987. /**
  25988. * Geometries populated in the container.
  25989. */
  25990. this.geometries = new Array();
  25991. /**
  25992. * TransformNodes populated in the container.
  25993. */
  25994. this.transformNodes = new Array();
  25995. /**
  25996. * LensFlareSystems populated in the container.
  25997. */
  25998. this.lensFlareSystems = new Array();
  25999. /**
  26000. * ShadowGenerators populated in the container.
  26001. */
  26002. this.shadowGenerators = new Array();
  26003. /**
  26004. * ActionManagers populated in the container.
  26005. */
  26006. this.actionManagers = new Array();
  26007. /**
  26008. * Sounds populated in the container.
  26009. */
  26010. this.sounds = new Array();
  26011. this.scene = scene;
  26012. }
  26013. /**
  26014. * Adds all the assets from the container to the scene.
  26015. */
  26016. AssetContainer.prototype.addAllToScene = function () {
  26017. var _this = this;
  26018. this.cameras.forEach(function (o) {
  26019. _this.scene.addCamera(o);
  26020. });
  26021. this.lights.forEach(function (o) {
  26022. _this.scene.addLight(o);
  26023. });
  26024. this.meshes.forEach(function (o) {
  26025. _this.scene.addMesh(o);
  26026. });
  26027. this.skeletons.forEach(function (o) {
  26028. _this.scene.addSkeleton(o);
  26029. });
  26030. this.particleSystems.forEach(function (o) {
  26031. _this.scene.addParticleSystem(o);
  26032. });
  26033. this.animations.forEach(function (o) {
  26034. _this.scene.addAnimation(o);
  26035. });
  26036. this.multiMaterials.forEach(function (o) {
  26037. _this.scene.addMultiMaterial(o);
  26038. });
  26039. this.materials.forEach(function (o) {
  26040. _this.scene.addMaterial(o);
  26041. });
  26042. this.morphTargetManagers.forEach(function (o) {
  26043. _this.scene.addMorphTargetManager(o);
  26044. });
  26045. this.geometries.forEach(function (o) {
  26046. _this.scene.addGeometry(o);
  26047. });
  26048. this.transformNodes.forEach(function (o) {
  26049. _this.scene.addTransformNode(o);
  26050. });
  26051. this.lensFlareSystems.forEach(function (o) {
  26052. _this.scene.addLensFlareSystem(o);
  26053. });
  26054. this.actionManagers.forEach(function (o) {
  26055. _this.scene.addActionManager(o);
  26056. });
  26057. this.sounds.forEach(function (o) {
  26058. o.play();
  26059. o.autoplay = true;
  26060. _this.scene.mainSoundTrack.AddSound(o);
  26061. });
  26062. };
  26063. /**
  26064. * Removes all the assets in the container from the scene
  26065. */
  26066. AssetContainer.prototype.removeAllFromScene = function () {
  26067. var _this = this;
  26068. this.cameras.forEach(function (o) {
  26069. _this.scene.removeCamera(o);
  26070. });
  26071. this.lights.forEach(function (o) {
  26072. _this.scene.removeLight(o);
  26073. });
  26074. this.meshes.forEach(function (o) {
  26075. _this.scene.removeMesh(o);
  26076. });
  26077. this.skeletons.forEach(function (o) {
  26078. _this.scene.removeSkeleton(o);
  26079. });
  26080. this.particleSystems.forEach(function (o) {
  26081. _this.scene.removeParticleSystem(o);
  26082. });
  26083. this.animations.forEach(function (o) {
  26084. _this.scene.removeAnimation(o);
  26085. });
  26086. this.multiMaterials.forEach(function (o) {
  26087. _this.scene.removeMultiMaterial(o);
  26088. });
  26089. this.materials.forEach(function (o) {
  26090. _this.scene.removeMaterial(o);
  26091. });
  26092. this.morphTargetManagers.forEach(function (o) {
  26093. _this.scene.removeMorphTargetManager(o);
  26094. });
  26095. this.geometries.forEach(function (o) {
  26096. _this.scene.removeGeometry(o);
  26097. });
  26098. this.transformNodes.forEach(function (o) {
  26099. _this.scene.removeTransformNode(o);
  26100. });
  26101. this.lensFlareSystems.forEach(function (o) {
  26102. _this.scene.removeLensFlareSystem(o);
  26103. });
  26104. this.actionManagers.forEach(function (o) {
  26105. _this.scene.removeActionManager(o);
  26106. });
  26107. this.sounds.forEach(function (o) {
  26108. o.stop();
  26109. o.autoplay = false;
  26110. _this.scene.mainSoundTrack.RemoveSound(o);
  26111. });
  26112. };
  26113. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26114. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26115. var asset = sourceAssets_1[_i];
  26116. var move = true;
  26117. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26118. var keepAsset = keepAssets_1[_a];
  26119. if (asset === keepAsset) {
  26120. move = false;
  26121. break;
  26122. }
  26123. }
  26124. if (move) {
  26125. targetAssets.push(asset);
  26126. }
  26127. }
  26128. };
  26129. /**
  26130. * Removes all the assets contained in the scene and adds them to the container.
  26131. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26132. */
  26133. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26134. if (keepAssets === undefined) {
  26135. keepAssets = new KeepAssets();
  26136. }
  26137. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26138. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26139. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26140. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26141. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26142. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26143. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26144. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26145. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26146. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26147. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26148. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26149. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26150. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26151. this.removeAllFromScene();
  26152. };
  26153. return AssetContainer;
  26154. }());
  26155. BABYLON.AssetContainer = AssetContainer;
  26156. })(BABYLON || (BABYLON = {}));
  26157. //# sourceMappingURL=babylon.assetContainer.js.map
  26158. "use strict";
  26159. var BABYLON;
  26160. (function (BABYLON) {
  26161. var Buffer = /** @class */ (function () {
  26162. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26163. if (instanced === void 0) { instanced = false; }
  26164. if (engine instanceof BABYLON.Mesh) {
  26165. this._engine = engine.getScene().getEngine();
  26166. }
  26167. else {
  26168. this._engine = engine;
  26169. }
  26170. this._updatable = updatable;
  26171. this._instanced = instanced;
  26172. this._data = data;
  26173. this._strideSize = stride;
  26174. if (!postponeInternalCreation) {
  26175. this.create();
  26176. }
  26177. }
  26178. /**
  26179. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26180. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26181. * @param offset defines offset in the buffer (0 by default)
  26182. * @param size defines the size in floats of attributes (position is 3 for instance)
  26183. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26184. * @param instanced defines if the vertex buffer contains indexed data
  26185. * @returns the new vertex buffer
  26186. */
  26187. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26188. // a lot of these parameters are ignored as they are overriden by the buffer
  26189. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26190. };
  26191. // Properties
  26192. Buffer.prototype.isUpdatable = function () {
  26193. return this._updatable;
  26194. };
  26195. Buffer.prototype.getData = function () {
  26196. return this._data;
  26197. };
  26198. Buffer.prototype.getBuffer = function () {
  26199. return this._buffer;
  26200. };
  26201. Buffer.prototype.getStrideSize = function () {
  26202. return this._strideSize;
  26203. };
  26204. // public getIsInstanced(): boolean {
  26205. // return this._instanced;
  26206. // }
  26207. // public get instanceDivisor(): number {
  26208. // return this._instanceDivisor;
  26209. // }
  26210. // public set instanceDivisor(value: number) {
  26211. // this._instanceDivisor = value;
  26212. // if (value == 0) {
  26213. // this._instanced = false;
  26214. // } else {
  26215. // this._instanced = true;
  26216. // }
  26217. // }
  26218. // Methods
  26219. Buffer.prototype.create = function (data) {
  26220. if (data === void 0) { data = null; }
  26221. if (!data && this._buffer) {
  26222. return; // nothing to do
  26223. }
  26224. data = data || this._data;
  26225. if (!data) {
  26226. return;
  26227. }
  26228. if (!this._buffer) {
  26229. if (this._updatable) {
  26230. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26231. this._data = data;
  26232. }
  26233. else {
  26234. this._buffer = this._engine.createVertexBuffer(data);
  26235. }
  26236. }
  26237. else if (this._updatable) {
  26238. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26239. this._data = data;
  26240. }
  26241. };
  26242. Buffer.prototype._rebuild = function () {
  26243. this._buffer = null;
  26244. this.create(this._data);
  26245. };
  26246. Buffer.prototype.update = function (data) {
  26247. this.create(data);
  26248. };
  26249. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26250. if (!this._buffer) {
  26251. return;
  26252. }
  26253. if (this._updatable) {
  26254. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26255. this._data = null;
  26256. }
  26257. };
  26258. Buffer.prototype.dispose = function () {
  26259. if (!this._buffer) {
  26260. return;
  26261. }
  26262. if (this._engine._releaseBuffer(this._buffer)) {
  26263. this._buffer = null;
  26264. }
  26265. };
  26266. return Buffer;
  26267. }());
  26268. BABYLON.Buffer = Buffer;
  26269. })(BABYLON || (BABYLON = {}));
  26270. //# sourceMappingURL=babylon.buffer.js.map
  26271. "use strict";
  26272. var BABYLON;
  26273. (function (BABYLON) {
  26274. var VertexBuffer = /** @class */ (function () {
  26275. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26276. if (data instanceof BABYLON.Buffer) {
  26277. if (!stride) {
  26278. stride = data.getStrideSize();
  26279. }
  26280. this._buffer = data;
  26281. this._ownsBuffer = false;
  26282. }
  26283. else {
  26284. if (!stride) {
  26285. stride = VertexBuffer.DeduceStride(kind);
  26286. }
  26287. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26288. this._ownsBuffer = true;
  26289. }
  26290. this._stride = stride;
  26291. this._instanced = instanced !== undefined ? instanced : false;
  26292. this._instanceDivisor = instanced ? 1 : 0;
  26293. this._offset = offset ? offset : 0;
  26294. this._size = size ? size : stride;
  26295. this._kind = kind;
  26296. }
  26297. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26298. /**
  26299. * Gets or sets the instance divisor when in instanced mode
  26300. */
  26301. get: function () {
  26302. return this._instanceDivisor;
  26303. },
  26304. set: function (value) {
  26305. this._instanceDivisor = value;
  26306. if (value == 0) {
  26307. this._instanced = false;
  26308. }
  26309. else {
  26310. this._instanced = true;
  26311. }
  26312. },
  26313. enumerable: true,
  26314. configurable: true
  26315. });
  26316. VertexBuffer.prototype._rebuild = function () {
  26317. if (!this._buffer) {
  26318. return;
  26319. }
  26320. this._buffer._rebuild();
  26321. };
  26322. /**
  26323. * Returns the kind of the VertexBuffer (string).
  26324. */
  26325. VertexBuffer.prototype.getKind = function () {
  26326. return this._kind;
  26327. };
  26328. // Properties
  26329. /**
  26330. * Boolean : is the VertexBuffer updatable ?
  26331. */
  26332. VertexBuffer.prototype.isUpdatable = function () {
  26333. return this._buffer.isUpdatable();
  26334. };
  26335. /**
  26336. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26337. */
  26338. VertexBuffer.prototype.getData = function () {
  26339. return this._buffer.getData();
  26340. };
  26341. /**
  26342. * Returns the WebGLBuffer associated to the VertexBuffer.
  26343. */
  26344. VertexBuffer.prototype.getBuffer = function () {
  26345. return this._buffer.getBuffer();
  26346. };
  26347. /**
  26348. * Returns the stride of the VertexBuffer (integer).
  26349. */
  26350. VertexBuffer.prototype.getStrideSize = function () {
  26351. return this._stride;
  26352. };
  26353. /**
  26354. * Returns the offset (integer).
  26355. */
  26356. VertexBuffer.prototype.getOffset = function () {
  26357. return this._offset;
  26358. };
  26359. /**
  26360. * Returns the VertexBuffer total size (integer).
  26361. */
  26362. VertexBuffer.prototype.getSize = function () {
  26363. return this._size;
  26364. };
  26365. /**
  26366. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26367. */
  26368. VertexBuffer.prototype.getIsInstanced = function () {
  26369. return this._instanced;
  26370. };
  26371. /**
  26372. * Returns the instancing divisor, zero for non-instanced (integer).
  26373. */
  26374. VertexBuffer.prototype.getInstanceDivisor = function () {
  26375. return this._instanceDivisor;
  26376. };
  26377. // Methods
  26378. /**
  26379. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26380. * Returns the created WebGLBuffer.
  26381. */
  26382. VertexBuffer.prototype.create = function (data) {
  26383. return this._buffer.create(data);
  26384. };
  26385. /**
  26386. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26387. * This function will create a new buffer if the current one is not updatable
  26388. * Returns the updated WebGLBuffer.
  26389. */
  26390. VertexBuffer.prototype.update = function (data) {
  26391. return this._buffer.update(data);
  26392. };
  26393. /**
  26394. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26395. * Returns the directly updated WebGLBuffer.
  26396. */
  26397. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26398. return this._buffer.updateDirectly(data, offset);
  26399. };
  26400. /**
  26401. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26402. */
  26403. VertexBuffer.prototype.dispose = function () {
  26404. if (this._ownsBuffer) {
  26405. this._buffer.dispose();
  26406. }
  26407. };
  26408. Object.defineProperty(VertexBuffer, "PositionKind", {
  26409. get: function () {
  26410. return VertexBuffer._PositionKind;
  26411. },
  26412. enumerable: true,
  26413. configurable: true
  26414. });
  26415. Object.defineProperty(VertexBuffer, "NormalKind", {
  26416. get: function () {
  26417. return VertexBuffer._NormalKind;
  26418. },
  26419. enumerable: true,
  26420. configurable: true
  26421. });
  26422. Object.defineProperty(VertexBuffer, "TangentKind", {
  26423. get: function () {
  26424. return VertexBuffer._TangentKind;
  26425. },
  26426. enumerable: true,
  26427. configurable: true
  26428. });
  26429. Object.defineProperty(VertexBuffer, "UVKind", {
  26430. get: function () {
  26431. return VertexBuffer._UVKind;
  26432. },
  26433. enumerable: true,
  26434. configurable: true
  26435. });
  26436. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26437. get: function () {
  26438. return VertexBuffer._UV2Kind;
  26439. },
  26440. enumerable: true,
  26441. configurable: true
  26442. });
  26443. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26444. get: function () {
  26445. return VertexBuffer._UV3Kind;
  26446. },
  26447. enumerable: true,
  26448. configurable: true
  26449. });
  26450. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26451. get: function () {
  26452. return VertexBuffer._UV4Kind;
  26453. },
  26454. enumerable: true,
  26455. configurable: true
  26456. });
  26457. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26458. get: function () {
  26459. return VertexBuffer._UV5Kind;
  26460. },
  26461. enumerable: true,
  26462. configurable: true
  26463. });
  26464. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26465. get: function () {
  26466. return VertexBuffer._UV6Kind;
  26467. },
  26468. enumerable: true,
  26469. configurable: true
  26470. });
  26471. Object.defineProperty(VertexBuffer, "ColorKind", {
  26472. get: function () {
  26473. return VertexBuffer._ColorKind;
  26474. },
  26475. enumerable: true,
  26476. configurable: true
  26477. });
  26478. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26479. get: function () {
  26480. return VertexBuffer._MatricesIndicesKind;
  26481. },
  26482. enumerable: true,
  26483. configurable: true
  26484. });
  26485. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26486. get: function () {
  26487. return VertexBuffer._MatricesWeightsKind;
  26488. },
  26489. enumerable: true,
  26490. configurable: true
  26491. });
  26492. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26493. get: function () {
  26494. return VertexBuffer._MatricesIndicesExtraKind;
  26495. },
  26496. enumerable: true,
  26497. configurable: true
  26498. });
  26499. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26500. get: function () {
  26501. return VertexBuffer._MatricesWeightsExtraKind;
  26502. },
  26503. enumerable: true,
  26504. configurable: true
  26505. });
  26506. /**
  26507. * Deduces the stride given a kind.
  26508. * @param kind The kind string to deduce
  26509. * @returns The deduced stride
  26510. */
  26511. VertexBuffer.DeduceStride = function (kind) {
  26512. switch (kind) {
  26513. case VertexBuffer.UVKind:
  26514. case VertexBuffer.UV2Kind:
  26515. case VertexBuffer.UV3Kind:
  26516. case VertexBuffer.UV4Kind:
  26517. case VertexBuffer.UV5Kind:
  26518. case VertexBuffer.UV6Kind:
  26519. return 2;
  26520. case VertexBuffer.NormalKind:
  26521. case VertexBuffer.PositionKind:
  26522. return 3;
  26523. case VertexBuffer.ColorKind:
  26524. case VertexBuffer.MatricesIndicesKind:
  26525. case VertexBuffer.MatricesIndicesExtraKind:
  26526. case VertexBuffer.MatricesWeightsKind:
  26527. case VertexBuffer.MatricesWeightsExtraKind:
  26528. case VertexBuffer.TangentKind:
  26529. return 4;
  26530. default:
  26531. throw new Error("Invalid kind '" + kind + "'");
  26532. }
  26533. };
  26534. // Enums
  26535. VertexBuffer._PositionKind = "position";
  26536. VertexBuffer._NormalKind = "normal";
  26537. VertexBuffer._TangentKind = "tangent";
  26538. VertexBuffer._UVKind = "uv";
  26539. VertexBuffer._UV2Kind = "uv2";
  26540. VertexBuffer._UV3Kind = "uv3";
  26541. VertexBuffer._UV4Kind = "uv4";
  26542. VertexBuffer._UV5Kind = "uv5";
  26543. VertexBuffer._UV6Kind = "uv6";
  26544. VertexBuffer._ColorKind = "color";
  26545. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26546. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26547. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26548. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26549. return VertexBuffer;
  26550. }());
  26551. BABYLON.VertexBuffer = VertexBuffer;
  26552. })(BABYLON || (BABYLON = {}));
  26553. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26554. "use strict";
  26555. var BABYLON;
  26556. (function (BABYLON) {
  26557. /**
  26558. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26559. */
  26560. var DummyInternalTextureTracker = /** @class */ (function () {
  26561. function DummyInternalTextureTracker() {
  26562. /**
  26563. * Gets or set the previous tracker in the list
  26564. */
  26565. this.previous = null;
  26566. /**
  26567. * Gets or set the next tracker in the list
  26568. */
  26569. this.next = null;
  26570. }
  26571. return DummyInternalTextureTracker;
  26572. }());
  26573. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26574. })(BABYLON || (BABYLON = {}));
  26575. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26576. "use strict";
  26577. var BABYLON;
  26578. (function (BABYLON) {
  26579. /**
  26580. * Class used to store data associated with WebGL texture data for the engine
  26581. * This class should not be used directly
  26582. */
  26583. var InternalTexture = /** @class */ (function () {
  26584. /**
  26585. * Creates a new InternalTexture
  26586. * @param engine defines the engine to use
  26587. * @param dataSource defines the type of data that will be used
  26588. */
  26589. function InternalTexture(engine, dataSource) {
  26590. /**
  26591. * Observable called when the texture is loaded
  26592. */
  26593. this.onLoadedObservable = new BABYLON.Observable();
  26594. /**
  26595. * Gets or set the previous tracker in the list
  26596. */
  26597. this.previous = null;
  26598. /**
  26599. * Gets or set the next tracker in the list
  26600. */
  26601. this.next = null;
  26602. // Private
  26603. /** @ignore */
  26604. this._initialSlot = -1;
  26605. /** @ignore */
  26606. this._designatedSlot = -1;
  26607. /** @ignore */
  26608. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26609. /** @ignore */
  26610. this._comparisonFunction = 0;
  26611. /** @ignore */
  26612. this._references = 1;
  26613. this._engine = engine;
  26614. this._dataSource = dataSource;
  26615. this._webGLTexture = engine._createTexture();
  26616. }
  26617. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26618. /**
  26619. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26620. */
  26621. get: function () {
  26622. return this._dataSource;
  26623. },
  26624. enumerable: true,
  26625. configurable: true
  26626. });
  26627. /**
  26628. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26629. */
  26630. InternalTexture.prototype.incrementReferences = function () {
  26631. this._references++;
  26632. };
  26633. /**
  26634. * Change the size of the texture (not the size of the content)
  26635. * @param width defines the new width
  26636. * @param height defines the new height
  26637. * @param depth defines the new depth (1 by default)
  26638. */
  26639. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26640. if (depth === void 0) { depth = 1; }
  26641. this.width = width;
  26642. this.height = height;
  26643. this.depth = depth;
  26644. this.baseWidth = width;
  26645. this.baseHeight = height;
  26646. this.baseDepth = depth;
  26647. this._size = width * height * depth;
  26648. };
  26649. /** @ignore */
  26650. InternalTexture.prototype._rebuild = function () {
  26651. var _this = this;
  26652. var proxy;
  26653. this.isReady = false;
  26654. this._cachedCoordinatesMode = null;
  26655. this._cachedWrapU = null;
  26656. this._cachedWrapV = null;
  26657. this._cachedAnisotropicFilteringLevel = null;
  26658. switch (this._dataSource) {
  26659. case InternalTexture.DATASOURCE_TEMP:
  26660. return;
  26661. case InternalTexture.DATASOURCE_URL:
  26662. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26663. _this.isReady = true;
  26664. }, null, this._buffer, undefined, this.format);
  26665. proxy._swapAndDie(this);
  26666. return;
  26667. case InternalTexture.DATASOURCE_RAW:
  26668. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26669. proxy._swapAndDie(this);
  26670. this.isReady = true;
  26671. return;
  26672. case InternalTexture.DATASOURCE_RAW3D:
  26673. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26674. proxy._swapAndDie(this);
  26675. this.isReady = true;
  26676. return;
  26677. case InternalTexture.DATASOURCE_DYNAMIC:
  26678. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26679. proxy._swapAndDie(this);
  26680. // The engine will make sure to update content so no need to flag it as isReady = true
  26681. return;
  26682. case InternalTexture.DATASOURCE_RENDERTARGET:
  26683. var options = new BABYLON.RenderTargetCreationOptions();
  26684. options.generateDepthBuffer = this._generateDepthBuffer;
  26685. options.generateMipMaps = this.generateMipMaps;
  26686. options.generateStencilBuffer = this._generateStencilBuffer;
  26687. options.samplingMode = this.samplingMode;
  26688. options.type = this.type;
  26689. if (this.isCube) {
  26690. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26691. }
  26692. else {
  26693. var size = {
  26694. width: this.width,
  26695. height: this.height
  26696. };
  26697. proxy = this._engine.createRenderTargetTexture(size, options);
  26698. }
  26699. proxy._swapAndDie(this);
  26700. this.isReady = true;
  26701. return;
  26702. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26703. var depthTextureOptions = {
  26704. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26705. comparisonFunction: this._comparisonFunction,
  26706. generateStencil: this._generateStencilBuffer,
  26707. isCube: this.isCube
  26708. };
  26709. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26710. proxy._swapAndDie(this);
  26711. this.isReady = true;
  26712. return;
  26713. case InternalTexture.DATASOURCE_CUBE:
  26714. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26715. _this.isReady = true;
  26716. }, null, this.format, this._extension);
  26717. proxy._swapAndDie(this);
  26718. return;
  26719. case InternalTexture.DATASOURCE_CUBERAW:
  26720. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26721. proxy._swapAndDie(this);
  26722. this.isReady = true;
  26723. return;
  26724. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26725. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26726. if (proxy) {
  26727. proxy._swapAndDie(_this);
  26728. }
  26729. _this.isReady = true;
  26730. }, null, this.format, this._extension);
  26731. return;
  26732. }
  26733. };
  26734. InternalTexture.prototype._swapAndDie = function (target) {
  26735. target._webGLTexture = this._webGLTexture;
  26736. if (this._framebuffer) {
  26737. target._framebuffer = this._framebuffer;
  26738. }
  26739. if (this._depthStencilBuffer) {
  26740. target._depthStencilBuffer = this._depthStencilBuffer;
  26741. }
  26742. if (this._lodTextureHigh) {
  26743. if (target._lodTextureHigh) {
  26744. target._lodTextureHigh.dispose();
  26745. }
  26746. target._lodTextureHigh = this._lodTextureHigh;
  26747. }
  26748. if (this._lodTextureMid) {
  26749. if (target._lodTextureMid) {
  26750. target._lodTextureMid.dispose();
  26751. }
  26752. target._lodTextureMid = this._lodTextureMid;
  26753. }
  26754. if (this._lodTextureLow) {
  26755. if (target._lodTextureLow) {
  26756. target._lodTextureLow.dispose();
  26757. }
  26758. target._lodTextureLow = this._lodTextureLow;
  26759. }
  26760. var cache = this._engine.getLoadedTexturesCache();
  26761. var index = cache.indexOf(this);
  26762. if (index !== -1) {
  26763. cache.splice(index, 1);
  26764. }
  26765. };
  26766. /**
  26767. * Dispose the current allocated resources
  26768. */
  26769. InternalTexture.prototype.dispose = function () {
  26770. if (!this._webGLTexture) {
  26771. return;
  26772. }
  26773. this._references--;
  26774. if (this._references === 0) {
  26775. this._engine._releaseTexture(this);
  26776. this._webGLTexture = null;
  26777. this.previous = null;
  26778. this.next = null;
  26779. }
  26780. };
  26781. /**
  26782. * The source of the texture data is unknown
  26783. */
  26784. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26785. /**
  26786. * Texture data comes from an URL
  26787. */
  26788. InternalTexture.DATASOURCE_URL = 1;
  26789. /**
  26790. * Texture data is only used for temporary storage
  26791. */
  26792. InternalTexture.DATASOURCE_TEMP = 2;
  26793. /**
  26794. * Texture data comes from raw data (ArrayBuffer)
  26795. */
  26796. InternalTexture.DATASOURCE_RAW = 3;
  26797. /**
  26798. * Texture content is dynamic (video or dynamic texture)
  26799. */
  26800. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26801. /**
  26802. * Texture content is generated by rendering to it
  26803. */
  26804. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26805. /**
  26806. * Texture content is part of a multi render target process
  26807. */
  26808. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26809. /**
  26810. * Texture data comes from a cube data file
  26811. */
  26812. InternalTexture.DATASOURCE_CUBE = 7;
  26813. /**
  26814. * Texture data comes from a raw cube data
  26815. */
  26816. InternalTexture.DATASOURCE_CUBERAW = 8;
  26817. /**
  26818. * Texture data come from a prefiltered cube data file
  26819. */
  26820. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26821. /**
  26822. * Texture content is raw 3D data
  26823. */
  26824. InternalTexture.DATASOURCE_RAW3D = 10;
  26825. /**
  26826. * Texture content is a depth texture
  26827. */
  26828. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26829. return InternalTexture;
  26830. }());
  26831. BABYLON.InternalTexture = InternalTexture;
  26832. })(BABYLON || (BABYLON = {}));
  26833. //# sourceMappingURL=babylon.internalTexture.js.map
  26834. "use strict";
  26835. var BABYLON;
  26836. (function (BABYLON) {
  26837. var BaseTexture = /** @class */ (function () {
  26838. function BaseTexture(scene) {
  26839. this._hasAlpha = false;
  26840. this.getAlphaFromRGB = false;
  26841. this.level = 1;
  26842. this.coordinatesIndex = 0;
  26843. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26844. /**
  26845. * | Value | Type | Description |
  26846. * | ----- | ------------------ | ----------- |
  26847. * | 0 | CLAMP_ADDRESSMODE | |
  26848. * | 1 | WRAP_ADDRESSMODE | |
  26849. * | 2 | MIRROR_ADDRESSMODE | |
  26850. */
  26851. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26852. /**
  26853. * | Value | Type | Description |
  26854. * | ----- | ------------------ | ----------- |
  26855. * | 0 | CLAMP_ADDRESSMODE | |
  26856. * | 1 | WRAP_ADDRESSMODE | |
  26857. * | 2 | MIRROR_ADDRESSMODE | |
  26858. */
  26859. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26860. /**
  26861. * | Value | Type | Description |
  26862. * | ----- | ------------------ | ----------- |
  26863. * | 0 | CLAMP_ADDRESSMODE | |
  26864. * | 1 | WRAP_ADDRESSMODE | |
  26865. * | 2 | MIRROR_ADDRESSMODE | |
  26866. */
  26867. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26868. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26869. this.isCube = false;
  26870. this.is3D = false;
  26871. this.gammaSpace = true;
  26872. this.invertZ = false;
  26873. this.lodLevelInAlpha = false;
  26874. this.lodGenerationOffset = 0.0;
  26875. this.lodGenerationScale = 0.8;
  26876. this.isRenderTarget = false;
  26877. this.animations = new Array();
  26878. /**
  26879. * An event triggered when the texture is disposed.
  26880. * @type {BABYLON.Observable}
  26881. */
  26882. this.onDisposeObservable = new BABYLON.Observable();
  26883. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26884. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26885. if (this._scene) {
  26886. this._scene.textures.push(this);
  26887. }
  26888. this._uid = null;
  26889. }
  26890. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26891. get: function () {
  26892. return this._hasAlpha;
  26893. },
  26894. set: function (value) {
  26895. if (this._hasAlpha === value) {
  26896. return;
  26897. }
  26898. this._hasAlpha = value;
  26899. if (this._scene) {
  26900. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26901. }
  26902. },
  26903. enumerable: true,
  26904. configurable: true
  26905. });
  26906. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26907. get: function () {
  26908. return this._coordinatesMode;
  26909. },
  26910. /**
  26911. * How a texture is mapped.
  26912. *
  26913. * | Value | Type | Description |
  26914. * | ----- | ----------------------------------- | ----------- |
  26915. * | 0 | EXPLICIT_MODE | |
  26916. * | 1 | SPHERICAL_MODE | |
  26917. * | 2 | PLANAR_MODE | |
  26918. * | 3 | CUBIC_MODE | |
  26919. * | 4 | PROJECTION_MODE | |
  26920. * | 5 | SKYBOX_MODE | |
  26921. * | 6 | INVCUBIC_MODE | |
  26922. * | 7 | EQUIRECTANGULAR_MODE | |
  26923. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26924. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26925. */
  26926. set: function (value) {
  26927. if (this._coordinatesMode === value) {
  26928. return;
  26929. }
  26930. this._coordinatesMode = value;
  26931. if (this._scene) {
  26932. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26933. }
  26934. },
  26935. enumerable: true,
  26936. configurable: true
  26937. });
  26938. Object.defineProperty(BaseTexture.prototype, "uid", {
  26939. get: function () {
  26940. if (!this._uid) {
  26941. this._uid = BABYLON.Tools.RandomId();
  26942. }
  26943. return this._uid;
  26944. },
  26945. enumerable: true,
  26946. configurable: true
  26947. });
  26948. BaseTexture.prototype.toString = function () {
  26949. return this.name;
  26950. };
  26951. BaseTexture.prototype.getClassName = function () {
  26952. return "BaseTexture";
  26953. };
  26954. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26955. set: function (callback) {
  26956. if (this._onDisposeObserver) {
  26957. this.onDisposeObservable.remove(this._onDisposeObserver);
  26958. }
  26959. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26960. },
  26961. enumerable: true,
  26962. configurable: true
  26963. });
  26964. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26965. get: function () {
  26966. return true;
  26967. },
  26968. enumerable: true,
  26969. configurable: true
  26970. });
  26971. BaseTexture.prototype.getScene = function () {
  26972. return this._scene;
  26973. };
  26974. BaseTexture.prototype.getTextureMatrix = function () {
  26975. return BABYLON.Matrix.IdentityReadOnly;
  26976. };
  26977. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26978. return BABYLON.Matrix.IdentityReadOnly;
  26979. };
  26980. BaseTexture.prototype.getInternalTexture = function () {
  26981. return this._texture;
  26982. };
  26983. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26984. return !this.isBlocking || this.isReady();
  26985. };
  26986. BaseTexture.prototype.isReady = function () {
  26987. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26988. this.delayLoad();
  26989. return false;
  26990. }
  26991. if (this._texture) {
  26992. return this._texture.isReady;
  26993. }
  26994. return false;
  26995. };
  26996. BaseTexture.prototype.getSize = function () {
  26997. if (this._texture && this._texture.width) {
  26998. return new BABYLON.Size(this._texture.width, this._texture.height);
  26999. }
  27000. if (this._texture && this._texture._size) {
  27001. return new BABYLON.Size(this._texture._size, this._texture._size);
  27002. }
  27003. return BABYLON.Size.Zero();
  27004. };
  27005. BaseTexture.prototype.getBaseSize = function () {
  27006. if (!this.isReady() || !this._texture)
  27007. return BABYLON.Size.Zero();
  27008. if (this._texture._size) {
  27009. return new BABYLON.Size(this._texture._size, this._texture._size);
  27010. }
  27011. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  27012. };
  27013. BaseTexture.prototype.scale = function (ratio) {
  27014. };
  27015. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27016. get: function () {
  27017. return false;
  27018. },
  27019. enumerable: true,
  27020. configurable: true
  27021. });
  27022. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27023. if (!this._scene) {
  27024. return null;
  27025. }
  27026. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27027. for (var index = 0; index < texturesCache.length; index++) {
  27028. var texturesCacheEntry = texturesCache[index];
  27029. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27030. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27031. texturesCacheEntry.incrementReferences();
  27032. return texturesCacheEntry;
  27033. }
  27034. }
  27035. }
  27036. return null;
  27037. };
  27038. BaseTexture.prototype._rebuild = function () {
  27039. };
  27040. BaseTexture.prototype.delayLoad = function () {
  27041. };
  27042. BaseTexture.prototype.clone = function () {
  27043. return null;
  27044. };
  27045. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27046. get: function () {
  27047. if (!this._texture) {
  27048. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27049. }
  27050. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27051. },
  27052. enumerable: true,
  27053. configurable: true
  27054. });
  27055. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27056. get: function () {
  27057. if (!this._texture) {
  27058. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27059. }
  27060. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27061. },
  27062. enumerable: true,
  27063. configurable: true
  27064. });
  27065. BaseTexture.prototype.readPixels = function (faceIndex) {
  27066. if (faceIndex === void 0) { faceIndex = 0; }
  27067. if (!this._texture) {
  27068. return null;
  27069. }
  27070. var size = this.getSize();
  27071. var scene = this.getScene();
  27072. if (!scene) {
  27073. return null;
  27074. }
  27075. var engine = scene.getEngine();
  27076. if (this._texture.isCube) {
  27077. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27078. }
  27079. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27080. };
  27081. BaseTexture.prototype.releaseInternalTexture = function () {
  27082. if (this._texture) {
  27083. this._texture.dispose();
  27084. this._texture = null;
  27085. }
  27086. };
  27087. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27088. get: function () {
  27089. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27090. return null;
  27091. }
  27092. if (!this._texture._sphericalPolynomial) {
  27093. this._texture._sphericalPolynomial =
  27094. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27095. }
  27096. return this._texture._sphericalPolynomial;
  27097. },
  27098. set: function (value) {
  27099. if (this._texture) {
  27100. this._texture._sphericalPolynomial = value;
  27101. }
  27102. },
  27103. enumerable: true,
  27104. configurable: true
  27105. });
  27106. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27107. get: function () {
  27108. if (this._texture) {
  27109. return this._texture._lodTextureHigh;
  27110. }
  27111. return null;
  27112. },
  27113. enumerable: true,
  27114. configurable: true
  27115. });
  27116. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27117. get: function () {
  27118. if (this._texture) {
  27119. return this._texture._lodTextureMid;
  27120. }
  27121. return null;
  27122. },
  27123. enumerable: true,
  27124. configurable: true
  27125. });
  27126. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27127. get: function () {
  27128. if (this._texture) {
  27129. return this._texture._lodTextureLow;
  27130. }
  27131. return null;
  27132. },
  27133. enumerable: true,
  27134. configurable: true
  27135. });
  27136. BaseTexture.prototype.dispose = function () {
  27137. if (!this._scene) {
  27138. return;
  27139. }
  27140. // Animations
  27141. this._scene.stopAnimation(this);
  27142. // Remove from scene
  27143. this._scene._removePendingData(this);
  27144. var index = this._scene.textures.indexOf(this);
  27145. if (index >= 0) {
  27146. this._scene.textures.splice(index, 1);
  27147. }
  27148. if (this._texture === undefined) {
  27149. return;
  27150. }
  27151. // Release
  27152. this.releaseInternalTexture();
  27153. // Callback
  27154. this.onDisposeObservable.notifyObservers(this);
  27155. this.onDisposeObservable.clear();
  27156. };
  27157. BaseTexture.prototype.serialize = function () {
  27158. if (!this.name) {
  27159. return null;
  27160. }
  27161. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27162. // Animations
  27163. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27164. return serializationObject;
  27165. };
  27166. BaseTexture.WhenAllReady = function (textures, callback) {
  27167. var numRemaining = textures.length;
  27168. if (numRemaining === 0) {
  27169. callback();
  27170. return;
  27171. }
  27172. var _loop_1 = function () {
  27173. texture = textures[i];
  27174. if (texture.isReady()) {
  27175. if (--numRemaining === 0) {
  27176. callback();
  27177. }
  27178. }
  27179. else {
  27180. onLoadObservable = texture.onLoadObservable;
  27181. var onLoadCallback_1 = function () {
  27182. onLoadObservable.removeCallback(onLoadCallback_1);
  27183. if (--numRemaining === 0) {
  27184. callback();
  27185. }
  27186. };
  27187. onLoadObservable.add(onLoadCallback_1);
  27188. }
  27189. };
  27190. var texture, onLoadObservable;
  27191. for (var i = 0; i < textures.length; i++) {
  27192. _loop_1();
  27193. }
  27194. };
  27195. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27196. __decorate([
  27197. BABYLON.serialize()
  27198. ], BaseTexture.prototype, "name", void 0);
  27199. __decorate([
  27200. BABYLON.serialize("hasAlpha")
  27201. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27202. __decorate([
  27203. BABYLON.serialize()
  27204. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27205. __decorate([
  27206. BABYLON.serialize()
  27207. ], BaseTexture.prototype, "level", void 0);
  27208. __decorate([
  27209. BABYLON.serialize()
  27210. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27211. __decorate([
  27212. BABYLON.serialize("coordinatesMode")
  27213. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27214. __decorate([
  27215. BABYLON.serialize()
  27216. ], BaseTexture.prototype, "wrapU", void 0);
  27217. __decorate([
  27218. BABYLON.serialize()
  27219. ], BaseTexture.prototype, "wrapV", void 0);
  27220. __decorate([
  27221. BABYLON.serialize()
  27222. ], BaseTexture.prototype, "wrapR", void 0);
  27223. __decorate([
  27224. BABYLON.serialize()
  27225. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27226. __decorate([
  27227. BABYLON.serialize()
  27228. ], BaseTexture.prototype, "isCube", void 0);
  27229. __decorate([
  27230. BABYLON.serialize()
  27231. ], BaseTexture.prototype, "is3D", void 0);
  27232. __decorate([
  27233. BABYLON.serialize()
  27234. ], BaseTexture.prototype, "gammaSpace", void 0);
  27235. __decorate([
  27236. BABYLON.serialize()
  27237. ], BaseTexture.prototype, "invertZ", void 0);
  27238. __decorate([
  27239. BABYLON.serialize()
  27240. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27241. __decorate([
  27242. BABYLON.serialize()
  27243. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27244. __decorate([
  27245. BABYLON.serialize()
  27246. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27247. __decorate([
  27248. BABYLON.serialize()
  27249. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27250. return BaseTexture;
  27251. }());
  27252. BABYLON.BaseTexture = BaseTexture;
  27253. })(BABYLON || (BABYLON = {}));
  27254. //# sourceMappingURL=babylon.baseTexture.js.map
  27255. "use strict";
  27256. var BABYLON;
  27257. (function (BABYLON) {
  27258. var Texture = /** @class */ (function (_super) {
  27259. __extends(Texture, _super);
  27260. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27261. if (noMipmap === void 0) { noMipmap = false; }
  27262. if (invertY === void 0) { invertY = true; }
  27263. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27264. if (onLoad === void 0) { onLoad = null; }
  27265. if (onError === void 0) { onError = null; }
  27266. if (buffer === void 0) { buffer = null; }
  27267. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27268. var _this = _super.call(this, scene) || this;
  27269. _this.uOffset = 0;
  27270. _this.vOffset = 0;
  27271. _this.uScale = 1.0;
  27272. _this.vScale = 1.0;
  27273. _this.uAng = 0;
  27274. _this.vAng = 0;
  27275. _this.wAng = 0;
  27276. _this._isBlocking = true;
  27277. _this.name = url || "";
  27278. _this.url = url;
  27279. _this._noMipmap = noMipmap;
  27280. _this._invertY = invertY;
  27281. _this._samplingMode = samplingMode;
  27282. _this._buffer = buffer;
  27283. _this._deleteBuffer = deleteBuffer;
  27284. if (format) {
  27285. _this._format = format;
  27286. }
  27287. scene = _this.getScene();
  27288. if (!scene) {
  27289. return _this;
  27290. }
  27291. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27292. var load = function () {
  27293. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27294. _this.onLoadObservable.notifyObservers(_this);
  27295. }
  27296. if (onLoad) {
  27297. onLoad();
  27298. }
  27299. if (!_this.isBlocking && scene) {
  27300. scene.resetCachedMaterial();
  27301. }
  27302. };
  27303. if (!_this.url) {
  27304. _this._delayedOnLoad = load;
  27305. _this._delayedOnError = onError;
  27306. return _this;
  27307. }
  27308. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27309. if (!_this._texture) {
  27310. if (!scene.useDelayedTextureLoading) {
  27311. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27312. if (deleteBuffer) {
  27313. delete _this._buffer;
  27314. }
  27315. }
  27316. else {
  27317. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27318. _this._delayedOnLoad = load;
  27319. _this._delayedOnError = onError;
  27320. }
  27321. }
  27322. else {
  27323. if (_this._texture.isReady) {
  27324. BABYLON.Tools.SetImmediate(function () { return load(); });
  27325. }
  27326. else {
  27327. _this._texture.onLoadedObservable.add(load);
  27328. }
  27329. }
  27330. return _this;
  27331. }
  27332. Object.defineProperty(Texture.prototype, "noMipmap", {
  27333. get: function () {
  27334. return this._noMipmap;
  27335. },
  27336. enumerable: true,
  27337. configurable: true
  27338. });
  27339. Object.defineProperty(Texture.prototype, "isBlocking", {
  27340. get: function () {
  27341. return this._isBlocking;
  27342. },
  27343. set: function (value) {
  27344. this._isBlocking = value;
  27345. },
  27346. enumerable: true,
  27347. configurable: true
  27348. });
  27349. Object.defineProperty(Texture.prototype, "samplingMode", {
  27350. get: function () {
  27351. return this._samplingMode;
  27352. },
  27353. enumerable: true,
  27354. configurable: true
  27355. });
  27356. Texture.prototype.updateURL = function (url) {
  27357. this.url = url;
  27358. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27359. this.delayLoad();
  27360. };
  27361. Texture.prototype.delayLoad = function () {
  27362. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27363. return;
  27364. }
  27365. var scene = this.getScene();
  27366. if (!scene) {
  27367. return;
  27368. }
  27369. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27370. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27371. if (!this._texture) {
  27372. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27373. if (this._deleteBuffer) {
  27374. delete this._buffer;
  27375. }
  27376. }
  27377. else {
  27378. if (this._delayedOnLoad) {
  27379. if (this._texture.isReady) {
  27380. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27381. }
  27382. else {
  27383. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27384. }
  27385. }
  27386. }
  27387. this._delayedOnLoad = null;
  27388. this._delayedOnError = null;
  27389. };
  27390. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27391. if (!this._texture) {
  27392. return;
  27393. }
  27394. var scene = this.getScene();
  27395. if (!scene) {
  27396. return;
  27397. }
  27398. this._samplingMode = samplingMode;
  27399. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27400. };
  27401. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27402. x *= this.uScale;
  27403. y *= this.vScale;
  27404. x -= 0.5 * this.uScale;
  27405. y -= 0.5 * this.vScale;
  27406. z -= 0.5;
  27407. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27408. t.x += 0.5 * this.uScale + this.uOffset;
  27409. t.y += 0.5 * this.vScale + this.vOffset;
  27410. t.z += 0.5;
  27411. };
  27412. Texture.prototype.getTextureMatrix = function () {
  27413. var _this = this;
  27414. if (this.uOffset === this._cachedUOffset &&
  27415. this.vOffset === this._cachedVOffset &&
  27416. this.uScale === this._cachedUScale &&
  27417. this.vScale === this._cachedVScale &&
  27418. this.uAng === this._cachedUAng &&
  27419. this.vAng === this._cachedVAng &&
  27420. this.wAng === this._cachedWAng) {
  27421. return this._cachedTextureMatrix;
  27422. }
  27423. this._cachedUOffset = this.uOffset;
  27424. this._cachedVOffset = this.vOffset;
  27425. this._cachedUScale = this.uScale;
  27426. this._cachedVScale = this.vScale;
  27427. this._cachedUAng = this.uAng;
  27428. this._cachedVAng = this.vAng;
  27429. this._cachedWAng = this.wAng;
  27430. if (!this._cachedTextureMatrix) {
  27431. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27432. this._rowGenerationMatrix = new BABYLON.Matrix();
  27433. this._t0 = BABYLON.Vector3.Zero();
  27434. this._t1 = BABYLON.Vector3.Zero();
  27435. this._t2 = BABYLON.Vector3.Zero();
  27436. }
  27437. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27438. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27439. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27440. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27441. this._t1.subtractInPlace(this._t0);
  27442. this._t2.subtractInPlace(this._t0);
  27443. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27444. this._cachedTextureMatrix.m[0] = this._t1.x;
  27445. this._cachedTextureMatrix.m[1] = this._t1.y;
  27446. this._cachedTextureMatrix.m[2] = this._t1.z;
  27447. this._cachedTextureMatrix.m[4] = this._t2.x;
  27448. this._cachedTextureMatrix.m[5] = this._t2.y;
  27449. this._cachedTextureMatrix.m[6] = this._t2.z;
  27450. this._cachedTextureMatrix.m[8] = this._t0.x;
  27451. this._cachedTextureMatrix.m[9] = this._t0.y;
  27452. this._cachedTextureMatrix.m[10] = this._t0.z;
  27453. var scene = this.getScene();
  27454. if (!scene) {
  27455. return this._cachedTextureMatrix;
  27456. }
  27457. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27458. return mat.hasTexture(_this);
  27459. });
  27460. return this._cachedTextureMatrix;
  27461. };
  27462. Texture.prototype.getReflectionTextureMatrix = function () {
  27463. var _this = this;
  27464. var scene = this.getScene();
  27465. if (!scene) {
  27466. return this._cachedTextureMatrix;
  27467. }
  27468. if (this.uOffset === this._cachedUOffset &&
  27469. this.vOffset === this._cachedVOffset &&
  27470. this.uScale === this._cachedUScale &&
  27471. this.vScale === this._cachedVScale &&
  27472. this.coordinatesMode === this._cachedCoordinatesMode) {
  27473. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27474. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27475. return this._cachedTextureMatrix;
  27476. }
  27477. }
  27478. else {
  27479. return this._cachedTextureMatrix;
  27480. }
  27481. }
  27482. if (!this._cachedTextureMatrix) {
  27483. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27484. }
  27485. if (!this._projectionModeMatrix) {
  27486. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27487. }
  27488. this._cachedUOffset = this.uOffset;
  27489. this._cachedVOffset = this.vOffset;
  27490. this._cachedUScale = this.uScale;
  27491. this._cachedVScale = this.vScale;
  27492. this._cachedCoordinatesMode = this.coordinatesMode;
  27493. switch (this.coordinatesMode) {
  27494. case Texture.PLANAR_MODE:
  27495. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27496. this._cachedTextureMatrix[0] = this.uScale;
  27497. this._cachedTextureMatrix[5] = this.vScale;
  27498. this._cachedTextureMatrix[12] = this.uOffset;
  27499. this._cachedTextureMatrix[13] = this.vOffset;
  27500. break;
  27501. case Texture.PROJECTION_MODE:
  27502. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27503. this._projectionModeMatrix.m[0] = 0.5;
  27504. this._projectionModeMatrix.m[5] = -0.5;
  27505. this._projectionModeMatrix.m[10] = 0.0;
  27506. this._projectionModeMatrix.m[12] = 0.5;
  27507. this._projectionModeMatrix.m[13] = 0.5;
  27508. this._projectionModeMatrix.m[14] = 1.0;
  27509. this._projectionModeMatrix.m[15] = 1.0;
  27510. var projectionMatrix = scene.getProjectionMatrix();
  27511. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27512. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27513. break;
  27514. default:
  27515. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27516. break;
  27517. }
  27518. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27519. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27520. });
  27521. return this._cachedTextureMatrix;
  27522. };
  27523. Texture.prototype.clone = function () {
  27524. var _this = this;
  27525. return BABYLON.SerializationHelper.Clone(function () {
  27526. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27527. }, this);
  27528. };
  27529. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27530. get: function () {
  27531. if (!this._onLoadObservable) {
  27532. this._onLoadObservable = new BABYLON.Observable();
  27533. }
  27534. return this._onLoadObservable;
  27535. },
  27536. enumerable: true,
  27537. configurable: true
  27538. });
  27539. Texture.prototype.serialize = function () {
  27540. var serializationObject = _super.prototype.serialize.call(this);
  27541. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27542. serializationObject.base64String = this._buffer;
  27543. serializationObject.name = serializationObject.name.replace("data:", "");
  27544. }
  27545. return serializationObject;
  27546. };
  27547. Texture.prototype.getClassName = function () {
  27548. return "Texture";
  27549. };
  27550. Texture.prototype.dispose = function () {
  27551. _super.prototype.dispose.call(this);
  27552. if (this.onLoadObservable) {
  27553. this.onLoadObservable.clear();
  27554. this._onLoadObservable = null;
  27555. }
  27556. this._delayedOnLoad = null;
  27557. this._delayedOnError = null;
  27558. };
  27559. // Statics
  27560. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27561. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27562. if (onLoad === void 0) { onLoad = null; }
  27563. if (onError === void 0) { onError = null; }
  27564. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27565. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27566. };
  27567. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27568. if (parsedTexture.customType) {
  27569. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27570. // Update Sampling Mode
  27571. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27572. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27573. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27574. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27575. }
  27576. }
  27577. return parsedCustomTexture;
  27578. }
  27579. if (parsedTexture.isCube) {
  27580. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27581. }
  27582. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27583. return null;
  27584. }
  27585. var texture = BABYLON.SerializationHelper.Parse(function () {
  27586. var generateMipMaps = true;
  27587. if (parsedTexture.noMipmap) {
  27588. generateMipMaps = false;
  27589. }
  27590. if (parsedTexture.mirrorPlane) {
  27591. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27592. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27593. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27594. return mirrorTexture;
  27595. }
  27596. else if (parsedTexture.isRenderTarget) {
  27597. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27598. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27599. return renderTargetTexture;
  27600. }
  27601. else {
  27602. var texture;
  27603. if (parsedTexture.base64String) {
  27604. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27605. }
  27606. else {
  27607. var url = rootUrl + parsedTexture.name;
  27608. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27609. url = parsedTexture.url;
  27610. }
  27611. texture = new Texture(url, scene, !generateMipMaps);
  27612. }
  27613. return texture;
  27614. }
  27615. }, parsedTexture, scene);
  27616. // Update Sampling Mode
  27617. if (parsedTexture.samplingMode) {
  27618. var sampling = parsedTexture.samplingMode;
  27619. if (texture._samplingMode !== sampling) {
  27620. texture.updateSamplingMode(sampling);
  27621. }
  27622. }
  27623. // Animations
  27624. if (parsedTexture.animations) {
  27625. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27626. var parsedAnimation = parsedTexture.animations[animationIndex];
  27627. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27628. }
  27629. }
  27630. return texture;
  27631. };
  27632. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27633. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27634. if (noMipmap === void 0) { noMipmap = false; }
  27635. if (invertY === void 0) { invertY = true; }
  27636. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27637. if (onLoad === void 0) { onLoad = null; }
  27638. if (onError === void 0) { onError = null; }
  27639. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27640. if (name.substr(0, 5) !== "data:") {
  27641. name = "data:" + name;
  27642. }
  27643. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27644. };
  27645. // Constants
  27646. Texture.NEAREST_SAMPLINGMODE = 1;
  27647. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27648. Texture.BILINEAR_SAMPLINGMODE = 2;
  27649. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27650. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27651. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27652. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27653. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27654. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27655. Texture.NEAREST_LINEAR = 7;
  27656. Texture.NEAREST_NEAREST = 8;
  27657. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27658. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27659. Texture.LINEAR_LINEAR = 11;
  27660. Texture.LINEAR_NEAREST = 12;
  27661. Texture.EXPLICIT_MODE = 0;
  27662. Texture.SPHERICAL_MODE = 1;
  27663. Texture.PLANAR_MODE = 2;
  27664. Texture.CUBIC_MODE = 3;
  27665. Texture.PROJECTION_MODE = 4;
  27666. Texture.SKYBOX_MODE = 5;
  27667. Texture.INVCUBIC_MODE = 6;
  27668. Texture.EQUIRECTANGULAR_MODE = 7;
  27669. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27670. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27671. Texture.CLAMP_ADDRESSMODE = 0;
  27672. Texture.WRAP_ADDRESSMODE = 1;
  27673. Texture.MIRROR_ADDRESSMODE = 2;
  27674. /**
  27675. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  27676. */
  27677. Texture.UseSerializedUrlIfAny = false;
  27678. __decorate([
  27679. BABYLON.serialize()
  27680. ], Texture.prototype, "url", void 0);
  27681. __decorate([
  27682. BABYLON.serialize()
  27683. ], Texture.prototype, "uOffset", void 0);
  27684. __decorate([
  27685. BABYLON.serialize()
  27686. ], Texture.prototype, "vOffset", void 0);
  27687. __decorate([
  27688. BABYLON.serialize()
  27689. ], Texture.prototype, "uScale", void 0);
  27690. __decorate([
  27691. BABYLON.serialize()
  27692. ], Texture.prototype, "vScale", void 0);
  27693. __decorate([
  27694. BABYLON.serialize()
  27695. ], Texture.prototype, "uAng", void 0);
  27696. __decorate([
  27697. BABYLON.serialize()
  27698. ], Texture.prototype, "vAng", void 0);
  27699. __decorate([
  27700. BABYLON.serialize()
  27701. ], Texture.prototype, "wAng", void 0);
  27702. __decorate([
  27703. BABYLON.serialize()
  27704. ], Texture.prototype, "isBlocking", null);
  27705. return Texture;
  27706. }(BABYLON.BaseTexture));
  27707. BABYLON.Texture = Texture;
  27708. })(BABYLON || (BABYLON = {}));
  27709. //# sourceMappingURL=babylon.texture.js.map
  27710. "use strict";
  27711. var BABYLON;
  27712. (function (BABYLON) {
  27713. var _InstancesBatch = /** @class */ (function () {
  27714. function _InstancesBatch() {
  27715. this.mustReturn = false;
  27716. this.visibleInstances = new Array();
  27717. this.renderSelf = new Array();
  27718. }
  27719. return _InstancesBatch;
  27720. }());
  27721. BABYLON._InstancesBatch = _InstancesBatch;
  27722. var Mesh = /** @class */ (function (_super) {
  27723. __extends(Mesh, _super);
  27724. /**
  27725. * @constructor
  27726. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27727. * @param {Scene} scene The scene to add this mesh to.
  27728. * @param {Node} parent The parent of this mesh, if it has one
  27729. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27730. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27731. * When false, achieved by calling a clone(), also passing False.
  27732. * This will make creation of children, recursive.
  27733. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27734. */
  27735. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27736. if (scene === void 0) { scene = null; }
  27737. if (parent === void 0) { parent = null; }
  27738. if (source === void 0) { source = null; }
  27739. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27740. var _this = _super.call(this, name, scene) || this;
  27741. // Events
  27742. /**
  27743. * An event triggered before rendering the mesh
  27744. * @type {BABYLON.Observable}
  27745. */
  27746. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27747. /**
  27748. * An event triggered after rendering the mesh
  27749. * @type {BABYLON.Observable}
  27750. */
  27751. _this.onAfterRenderObservable = new BABYLON.Observable();
  27752. /**
  27753. * An event triggered before drawing the mesh
  27754. * @type {BABYLON.Observable}
  27755. */
  27756. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27757. // Members
  27758. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27759. _this.instances = new Array();
  27760. _this._LODLevels = new Array();
  27761. _this._visibleInstances = {};
  27762. _this._renderIdForInstances = new Array();
  27763. _this._batchCache = new _InstancesBatch();
  27764. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27765. // Use by builder only to know what orientation were the mesh build in.
  27766. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27767. _this.overrideMaterialSideOrientation = null;
  27768. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27769. // Will be used to save a source mesh reference, If any
  27770. _this._source = null;
  27771. scene = _this.getScene();
  27772. if (source) {
  27773. // Source mesh
  27774. _this._source = source;
  27775. // Geometry
  27776. if (source._geometry) {
  27777. source._geometry.applyToMesh(_this);
  27778. }
  27779. // Deep copy
  27780. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  27781. "source", "metadata", "hasLODLevels", "geometry", "isBlocked"], ["_poseMatrix", "_source"]);
  27782. // Metadata
  27783. if (source.metadata && source.metadata.clone) {
  27784. _this.metadata = source.metadata.clone();
  27785. }
  27786. else {
  27787. _this.metadata = source.metadata;
  27788. }
  27789. // Tags
  27790. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27791. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27792. }
  27793. // Parent
  27794. _this.parent = source.parent;
  27795. // Pivot
  27796. _this.setPivotMatrix(source.getPivotMatrix());
  27797. _this.id = name + "." + source.id;
  27798. // Material
  27799. _this.material = source.material;
  27800. var index;
  27801. if (!doNotCloneChildren) {
  27802. // Children
  27803. var directDescendants = source.getDescendants(true);
  27804. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27805. var child = directDescendants[index_1];
  27806. if (child.clone) {
  27807. child.clone(name + "." + child.name, _this);
  27808. }
  27809. }
  27810. }
  27811. // Physics clone
  27812. var physicsEngine = _this.getScene().getPhysicsEngine();
  27813. if (clonePhysicsImpostor && physicsEngine) {
  27814. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27815. if (impostor) {
  27816. _this.physicsImpostor = impostor.clone(_this);
  27817. }
  27818. }
  27819. // Particles
  27820. for (index = 0; index < scene.particleSystems.length; index++) {
  27821. var system = scene.particleSystems[index];
  27822. if (system.emitter === source) {
  27823. system.clone(system.name, _this);
  27824. }
  27825. }
  27826. _this.computeWorldMatrix(true);
  27827. }
  27828. // Parent
  27829. if (parent !== null) {
  27830. _this.parent = parent;
  27831. }
  27832. return _this;
  27833. }
  27834. Object.defineProperty(Mesh, "FRONTSIDE", {
  27835. /**
  27836. * Mesh side orientation : usually the external or front surface
  27837. */
  27838. get: function () {
  27839. return Mesh._FRONTSIDE;
  27840. },
  27841. enumerable: true,
  27842. configurable: true
  27843. });
  27844. Object.defineProperty(Mesh, "BACKSIDE", {
  27845. /**
  27846. * Mesh side orientation : usually the internal or back surface
  27847. */
  27848. get: function () {
  27849. return Mesh._BACKSIDE;
  27850. },
  27851. enumerable: true,
  27852. configurable: true
  27853. });
  27854. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27855. /**
  27856. * Mesh side orientation : both internal and external or front and back surfaces
  27857. */
  27858. get: function () {
  27859. return Mesh._DOUBLESIDE;
  27860. },
  27861. enumerable: true,
  27862. configurable: true
  27863. });
  27864. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27865. /**
  27866. * Mesh side orientation : by default, `FRONTSIDE`
  27867. */
  27868. get: function () {
  27869. return Mesh._DEFAULTSIDE;
  27870. },
  27871. enumerable: true,
  27872. configurable: true
  27873. });
  27874. Object.defineProperty(Mesh, "NO_CAP", {
  27875. /**
  27876. * Mesh cap setting : no cap
  27877. */
  27878. get: function () {
  27879. return Mesh._NO_CAP;
  27880. },
  27881. enumerable: true,
  27882. configurable: true
  27883. });
  27884. Object.defineProperty(Mesh, "CAP_START", {
  27885. /**
  27886. * Mesh cap setting : one cap at the beginning of the mesh
  27887. */
  27888. get: function () {
  27889. return Mesh._CAP_START;
  27890. },
  27891. enumerable: true,
  27892. configurable: true
  27893. });
  27894. Object.defineProperty(Mesh, "CAP_END", {
  27895. /**
  27896. * Mesh cap setting : one cap at the end of the mesh
  27897. */
  27898. get: function () {
  27899. return Mesh._CAP_END;
  27900. },
  27901. enumerable: true,
  27902. configurable: true
  27903. });
  27904. Object.defineProperty(Mesh, "CAP_ALL", {
  27905. /**
  27906. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27907. */
  27908. get: function () {
  27909. return Mesh._CAP_ALL;
  27910. },
  27911. enumerable: true,
  27912. configurable: true
  27913. });
  27914. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27915. set: function (callback) {
  27916. if (this._onBeforeDrawObserver) {
  27917. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27918. }
  27919. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27920. },
  27921. enumerable: true,
  27922. configurable: true
  27923. });
  27924. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27925. get: function () {
  27926. return this._morphTargetManager;
  27927. },
  27928. set: function (value) {
  27929. if (this._morphTargetManager === value) {
  27930. return;
  27931. }
  27932. this._morphTargetManager = value;
  27933. this._syncGeometryWithMorphTargetManager();
  27934. },
  27935. enumerable: true,
  27936. configurable: true
  27937. });
  27938. Object.defineProperty(Mesh.prototype, "source", {
  27939. get: function () {
  27940. return this._source;
  27941. },
  27942. enumerable: true,
  27943. configurable: true
  27944. });
  27945. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27946. get: function () {
  27947. return this._unIndexed;
  27948. },
  27949. set: function (value) {
  27950. if (this._unIndexed !== value) {
  27951. this._unIndexed = value;
  27952. this._markSubMeshesAsAttributesDirty();
  27953. }
  27954. },
  27955. enumerable: true,
  27956. configurable: true
  27957. });
  27958. // Methods
  27959. /**
  27960. * Returns the string "Mesh".
  27961. */
  27962. Mesh.prototype.getClassName = function () {
  27963. return "Mesh";
  27964. };
  27965. /**
  27966. * Returns a string.
  27967. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27968. */
  27969. Mesh.prototype.toString = function (fullDetails) {
  27970. var ret = _super.prototype.toString.call(this, fullDetails);
  27971. ret += ", n vertices: " + this.getTotalVertices();
  27972. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27973. if (this.animations) {
  27974. for (var i = 0; i < this.animations.length; i++) {
  27975. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27976. }
  27977. }
  27978. if (fullDetails) {
  27979. if (this._geometry) {
  27980. var ib = this.getIndices();
  27981. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27982. if (vb && ib) {
  27983. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27984. }
  27985. }
  27986. else {
  27987. ret += ", flat shading: UNKNOWN";
  27988. }
  27989. }
  27990. return ret;
  27991. };
  27992. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27993. /**
  27994. * True if the mesh has some Levels Of Details (LOD).
  27995. * Returns a boolean.
  27996. */
  27997. get: function () {
  27998. return this._LODLevels.length > 0;
  27999. },
  28000. enumerable: true,
  28001. configurable: true
  28002. });
  28003. /**
  28004. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  28005. * @returns an array of {BABYLON.MeshLODLevel}
  28006. */
  28007. Mesh.prototype.getLODLevels = function () {
  28008. return this._LODLevels;
  28009. };
  28010. Mesh.prototype._sortLODLevels = function () {
  28011. this._LODLevels.sort(function (a, b) {
  28012. if (a.distance < b.distance) {
  28013. return 1;
  28014. }
  28015. if (a.distance > b.distance) {
  28016. return -1;
  28017. }
  28018. return 0;
  28019. });
  28020. };
  28021. /**
  28022. * Add a mesh as LOD level triggered at the given distance.
  28023. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28024. * @param {number} distance The distance from the center of the object to show this level
  28025. * @param {Mesh} mesh The mesh to be added as LOD level
  28026. * @return {Mesh} This mesh (for chaining)
  28027. */
  28028. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28029. if (mesh && mesh._masterMesh) {
  28030. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28031. return this;
  28032. }
  28033. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28034. this._LODLevels.push(level);
  28035. if (mesh) {
  28036. mesh._masterMesh = this;
  28037. }
  28038. this._sortLODLevels();
  28039. return this;
  28040. };
  28041. /**
  28042. * Returns the LOD level mesh at the passed distance or null if not found.
  28043. * It is related to the method `addLODLevel(distance, mesh)`.
  28044. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28045. * Returns an object Mesh or `null`.
  28046. */
  28047. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28048. for (var index = 0; index < this._LODLevels.length; index++) {
  28049. var level = this._LODLevels[index];
  28050. if (level.distance === distance) {
  28051. return level.mesh;
  28052. }
  28053. }
  28054. return null;
  28055. };
  28056. /**
  28057. * Remove a mesh from the LOD array
  28058. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28059. * @param {Mesh} mesh The mesh to be removed.
  28060. * @return {Mesh} This mesh (for chaining)
  28061. */
  28062. Mesh.prototype.removeLODLevel = function (mesh) {
  28063. for (var index = 0; index < this._LODLevels.length; index++) {
  28064. if (this._LODLevels[index].mesh === mesh) {
  28065. this._LODLevels.splice(index, 1);
  28066. if (mesh) {
  28067. mesh._masterMesh = null;
  28068. }
  28069. }
  28070. }
  28071. this._sortLODLevels();
  28072. return this;
  28073. };
  28074. /**
  28075. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28076. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28077. */
  28078. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28079. if (!this._LODLevels || this._LODLevels.length === 0) {
  28080. return this;
  28081. }
  28082. var bSphere;
  28083. if (boundingSphere) {
  28084. bSphere = boundingSphere;
  28085. }
  28086. else {
  28087. var boundingInfo = this.getBoundingInfo();
  28088. bSphere = boundingInfo.boundingSphere;
  28089. }
  28090. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28091. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28092. if (this.onLODLevelSelection) {
  28093. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28094. }
  28095. return this;
  28096. }
  28097. for (var index = 0; index < this._LODLevels.length; index++) {
  28098. var level = this._LODLevels[index];
  28099. if (level.distance < distanceToCamera) {
  28100. if (level.mesh) {
  28101. level.mesh._preActivate();
  28102. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28103. }
  28104. if (this.onLODLevelSelection) {
  28105. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28106. }
  28107. return level.mesh;
  28108. }
  28109. }
  28110. if (this.onLODLevelSelection) {
  28111. this.onLODLevelSelection(distanceToCamera, this, this);
  28112. }
  28113. return this;
  28114. };
  28115. Object.defineProperty(Mesh.prototype, "geometry", {
  28116. /**
  28117. * Returns the mesh internal Geometry object.
  28118. */
  28119. get: function () {
  28120. return this._geometry;
  28121. },
  28122. enumerable: true,
  28123. configurable: true
  28124. });
  28125. /**
  28126. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28127. */
  28128. Mesh.prototype.getTotalVertices = function () {
  28129. if (this._geometry === null || this._geometry === undefined) {
  28130. return 0;
  28131. }
  28132. return this._geometry.getTotalVertices();
  28133. };
  28134. /**
  28135. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28136. * 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.
  28137. * You can force the copy with forceCopy === true
  28138. * Returns null if the mesh has no geometry or no vertex buffer.
  28139. * Possible `kind` values :
  28140. * - BABYLON.VertexBuffer.PositionKind
  28141. * - BABYLON.VertexBuffer.UVKind
  28142. * - BABYLON.VertexBuffer.UV2Kind
  28143. * - BABYLON.VertexBuffer.UV3Kind
  28144. * - BABYLON.VertexBuffer.UV4Kind
  28145. * - BABYLON.VertexBuffer.UV5Kind
  28146. * - BABYLON.VertexBuffer.UV6Kind
  28147. * - BABYLON.VertexBuffer.ColorKind
  28148. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28149. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28150. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28151. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28152. */
  28153. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28154. if (!this._geometry) {
  28155. return null;
  28156. }
  28157. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28158. };
  28159. /**
  28160. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28161. * Returns `null` if the mesh has no geometry.
  28162. * Possible `kind` values :
  28163. * - BABYLON.VertexBuffer.PositionKind
  28164. * - BABYLON.VertexBuffer.UVKind
  28165. * - BABYLON.VertexBuffer.UV2Kind
  28166. * - BABYLON.VertexBuffer.UV3Kind
  28167. * - BABYLON.VertexBuffer.UV4Kind
  28168. * - BABYLON.VertexBuffer.UV5Kind
  28169. * - BABYLON.VertexBuffer.UV6Kind
  28170. * - BABYLON.VertexBuffer.ColorKind
  28171. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28172. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28173. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28174. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28175. */
  28176. Mesh.prototype.getVertexBuffer = function (kind) {
  28177. if (!this._geometry) {
  28178. return null;
  28179. }
  28180. return this._geometry.getVertexBuffer(kind);
  28181. };
  28182. /**
  28183. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28184. * Possible `kind` values :
  28185. * - BABYLON.VertexBuffer.PositionKind
  28186. * - BABYLON.VertexBuffer.UVKind
  28187. * - BABYLON.VertexBuffer.UV2Kind
  28188. * - BABYLON.VertexBuffer.UV3Kind
  28189. * - BABYLON.VertexBuffer.UV4Kind
  28190. * - BABYLON.VertexBuffer.UV5Kind
  28191. * - BABYLON.VertexBuffer.UV6Kind
  28192. * - BABYLON.VertexBuffer.ColorKind
  28193. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28194. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28195. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28196. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28197. */
  28198. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28199. if (!this._geometry) {
  28200. if (this._delayInfo) {
  28201. return this._delayInfo.indexOf(kind) !== -1;
  28202. }
  28203. return false;
  28204. }
  28205. return this._geometry.isVerticesDataPresent(kind);
  28206. };
  28207. /**
  28208. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28209. * Possible `kind` values :
  28210. * - BABYLON.VertexBuffer.PositionKind
  28211. * - BABYLON.VertexBuffer.UVKind
  28212. * - BABYLON.VertexBuffer.UV2Kind
  28213. * - BABYLON.VertexBuffer.UV3Kind
  28214. * - BABYLON.VertexBuffer.UV4Kind
  28215. * - BABYLON.VertexBuffer.UV5Kind
  28216. * - BABYLON.VertexBuffer.UV6Kind
  28217. * - BABYLON.VertexBuffer.ColorKind
  28218. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28219. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28220. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28221. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28222. */
  28223. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28224. if (!this._geometry) {
  28225. if (this._delayInfo) {
  28226. return this._delayInfo.indexOf(kind) !== -1;
  28227. }
  28228. return false;
  28229. }
  28230. return this._geometry.isVertexBufferUpdatable(kind);
  28231. };
  28232. /**
  28233. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28234. * Possible `kind` values :
  28235. * - BABYLON.VertexBuffer.PositionKind
  28236. * - BABYLON.VertexBuffer.UVKind
  28237. * - BABYLON.VertexBuffer.UV2Kind
  28238. * - BABYLON.VertexBuffer.UV3Kind
  28239. * - BABYLON.VertexBuffer.UV4Kind
  28240. * - BABYLON.VertexBuffer.UV5Kind
  28241. * - BABYLON.VertexBuffer.UV6Kind
  28242. * - BABYLON.VertexBuffer.ColorKind
  28243. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28244. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28245. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28246. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28247. */
  28248. Mesh.prototype.getVerticesDataKinds = function () {
  28249. if (!this._geometry) {
  28250. var result = new Array();
  28251. if (this._delayInfo) {
  28252. this._delayInfo.forEach(function (kind, index, array) {
  28253. result.push(kind);
  28254. });
  28255. }
  28256. return result;
  28257. }
  28258. return this._geometry.getVerticesDataKinds();
  28259. };
  28260. /**
  28261. * Returns a positive integer : the total number of indices in this mesh geometry.
  28262. * Returns zero if the mesh has no geometry.
  28263. */
  28264. Mesh.prototype.getTotalIndices = function () {
  28265. if (!this._geometry) {
  28266. return 0;
  28267. }
  28268. return this._geometry.getTotalIndices();
  28269. };
  28270. /**
  28271. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28272. * 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.
  28273. * Returns an empty array if the mesh has no geometry.
  28274. */
  28275. Mesh.prototype.getIndices = function (copyWhenShared) {
  28276. if (!this._geometry) {
  28277. return [];
  28278. }
  28279. return this._geometry.getIndices(copyWhenShared);
  28280. };
  28281. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28282. get: function () {
  28283. return this._masterMesh !== null && this._masterMesh !== undefined;
  28284. },
  28285. enumerable: true,
  28286. configurable: true
  28287. });
  28288. /**
  28289. * Determine if the current mesh is ready to be rendered
  28290. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28291. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28292. * @returns true if all associated assets are ready (material, textures, shaders)
  28293. */
  28294. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28295. if (completeCheck === void 0) { completeCheck = false; }
  28296. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28297. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28298. return false;
  28299. }
  28300. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28301. return false;
  28302. }
  28303. if (!this.subMeshes || this.subMeshes.length === 0) {
  28304. return true;
  28305. }
  28306. if (!completeCheck) {
  28307. return true;
  28308. }
  28309. var engine = this.getEngine();
  28310. var scene = this.getScene();
  28311. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28312. this.computeWorldMatrix();
  28313. var mat = this.material || scene.defaultMaterial;
  28314. if (mat) {
  28315. if (mat.storeEffectOnSubMeshes) {
  28316. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28317. var subMesh = _a[_i];
  28318. var effectiveMaterial = subMesh.getMaterial();
  28319. if (effectiveMaterial) {
  28320. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28321. return false;
  28322. }
  28323. }
  28324. }
  28325. }
  28326. else {
  28327. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28328. return false;
  28329. }
  28330. }
  28331. }
  28332. // Shadows
  28333. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28334. var light = _c[_b];
  28335. var generator = light.getShadowGenerator();
  28336. if (generator) {
  28337. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28338. var subMesh = _e[_d];
  28339. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28340. return false;
  28341. }
  28342. }
  28343. }
  28344. }
  28345. // LOD
  28346. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28347. var lod = _g[_f];
  28348. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28349. return false;
  28350. }
  28351. }
  28352. return true;
  28353. };
  28354. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28355. /**
  28356. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28357. * This property is pertinent only for updatable parametric shapes.
  28358. */
  28359. get: function () {
  28360. return this._areNormalsFrozen;
  28361. },
  28362. enumerable: true,
  28363. configurable: true
  28364. });
  28365. /**
  28366. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28367. * It has no effect at all on other shapes.
  28368. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28369. * Returns the Mesh.
  28370. */
  28371. Mesh.prototype.freezeNormals = function () {
  28372. this._areNormalsFrozen = true;
  28373. return this;
  28374. };
  28375. /**
  28376. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28377. * It has no effect at all on other shapes.
  28378. * It reactivates the mesh normals computation if it was previously frozen.
  28379. * Returns the Mesh.
  28380. */
  28381. Mesh.prototype.unfreezeNormals = function () {
  28382. this._areNormalsFrozen = false;
  28383. return this;
  28384. };
  28385. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28386. /**
  28387. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28388. */
  28389. set: function (count) {
  28390. this._overridenInstanceCount = count;
  28391. },
  28392. enumerable: true,
  28393. configurable: true
  28394. });
  28395. // Methods
  28396. Mesh.prototype._preActivate = function () {
  28397. var sceneRenderId = this.getScene().getRenderId();
  28398. if (this._preActivateId === sceneRenderId) {
  28399. return this;
  28400. }
  28401. this._preActivateId = sceneRenderId;
  28402. this._visibleInstances = null;
  28403. return this;
  28404. };
  28405. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28406. if (this._visibleInstances) {
  28407. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28408. }
  28409. return this;
  28410. };
  28411. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28412. if (!this._visibleInstances) {
  28413. this._visibleInstances = {};
  28414. this._visibleInstances.defaultRenderId = renderId;
  28415. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28416. }
  28417. if (!this._visibleInstances[renderId]) {
  28418. this._visibleInstances[renderId] = new Array();
  28419. }
  28420. this._visibleInstances[renderId].push(instance);
  28421. return this;
  28422. };
  28423. /**
  28424. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28425. * This means the mesh underlying bounding box and sphere are recomputed.
  28426. * Returns the Mesh.
  28427. */
  28428. Mesh.prototype.refreshBoundingInfo = function () {
  28429. return this._refreshBoundingInfo(false);
  28430. };
  28431. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28432. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28433. return this;
  28434. }
  28435. var data = this._getPositionData(applySkeleton);
  28436. if (data) {
  28437. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28438. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28439. }
  28440. if (this.subMeshes) {
  28441. for (var index = 0; index < this.subMeshes.length; index++) {
  28442. this.subMeshes[index].refreshBoundingInfo();
  28443. }
  28444. }
  28445. this._updateBoundingInfo();
  28446. return this;
  28447. };
  28448. Mesh.prototype._getPositionData = function (applySkeleton) {
  28449. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28450. if (data && applySkeleton && this.skeleton) {
  28451. data = BABYLON.Tools.Slice(data);
  28452. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28453. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28454. if (matricesWeightsData && matricesIndicesData) {
  28455. var needExtras = this.numBoneInfluencers > 4;
  28456. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28457. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28458. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28459. var tempVector = BABYLON.Tmp.Vector3[0];
  28460. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28461. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28462. var matWeightIdx = 0;
  28463. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28464. finalMatrix.reset();
  28465. var inf;
  28466. var weight;
  28467. for (inf = 0; inf < 4; inf++) {
  28468. weight = matricesWeightsData[matWeightIdx + inf];
  28469. if (weight <= 0)
  28470. break;
  28471. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28472. finalMatrix.addToSelf(tempMatrix);
  28473. }
  28474. if (needExtras) {
  28475. for (inf = 0; inf < 4; inf++) {
  28476. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28477. if (weight <= 0)
  28478. break;
  28479. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28480. finalMatrix.addToSelf(tempMatrix);
  28481. }
  28482. }
  28483. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28484. tempVector.toArray(data, index);
  28485. }
  28486. }
  28487. }
  28488. return data;
  28489. };
  28490. Mesh.prototype._createGlobalSubMesh = function (force) {
  28491. var totalVertices = this.getTotalVertices();
  28492. if (!totalVertices || !this.getIndices()) {
  28493. return null;
  28494. }
  28495. // Check if we need to recreate the submeshes
  28496. if (this.subMeshes && this.subMeshes.length > 0) {
  28497. var ib = this.getIndices();
  28498. if (!ib) {
  28499. return null;
  28500. }
  28501. var totalIndices = ib.length;
  28502. var needToRecreate = false;
  28503. if (force) {
  28504. needToRecreate = true;
  28505. }
  28506. else {
  28507. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28508. var submesh = _a[_i];
  28509. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28510. needToRecreate = true;
  28511. break;
  28512. }
  28513. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28514. needToRecreate = true;
  28515. break;
  28516. }
  28517. }
  28518. }
  28519. if (!needToRecreate) {
  28520. return this.subMeshes[0];
  28521. }
  28522. }
  28523. this.releaseSubMeshes();
  28524. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28525. };
  28526. Mesh.prototype.subdivide = function (count) {
  28527. if (count < 1) {
  28528. return;
  28529. }
  28530. var totalIndices = this.getTotalIndices();
  28531. var subdivisionSize = (totalIndices / count) | 0;
  28532. var offset = 0;
  28533. // Ensure that subdivisionSize is a multiple of 3
  28534. while (subdivisionSize % 3 !== 0) {
  28535. subdivisionSize++;
  28536. }
  28537. this.releaseSubMeshes();
  28538. for (var index = 0; index < count; index++) {
  28539. if (offset >= totalIndices) {
  28540. break;
  28541. }
  28542. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28543. offset += subdivisionSize;
  28544. }
  28545. this.synchronizeInstances();
  28546. };
  28547. /**
  28548. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28549. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28550. * The `data` are either a numeric array either a Float32Array.
  28551. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28552. * 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).
  28553. * Note that a new underlying VertexBuffer object is created each call.
  28554. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28555. *
  28556. * Possible `kind` values :
  28557. * - BABYLON.VertexBuffer.PositionKind
  28558. * - BABYLON.VertexBuffer.UVKind
  28559. * - BABYLON.VertexBuffer.UV2Kind
  28560. * - BABYLON.VertexBuffer.UV3Kind
  28561. * - BABYLON.VertexBuffer.UV4Kind
  28562. * - BABYLON.VertexBuffer.UV5Kind
  28563. * - BABYLON.VertexBuffer.UV6Kind
  28564. * - BABYLON.VertexBuffer.ColorKind
  28565. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28566. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28567. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28568. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28569. *
  28570. * Returns the Mesh.
  28571. */
  28572. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28573. if (updatable === void 0) { updatable = false; }
  28574. if (!this._geometry) {
  28575. var vertexData = new BABYLON.VertexData();
  28576. vertexData.set(data, kind);
  28577. var scene = this.getScene();
  28578. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28579. }
  28580. else {
  28581. this._geometry.setVerticesData(kind, data, updatable, stride);
  28582. }
  28583. return this;
  28584. };
  28585. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28586. if (updatable === void 0) { updatable = true; }
  28587. var vb = this.getVertexBuffer(kind);
  28588. if (!vb || vb.isUpdatable() === updatable) {
  28589. return;
  28590. }
  28591. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28592. };
  28593. /**
  28594. * Sets the mesh VertexBuffer.
  28595. * Returns the Mesh.
  28596. */
  28597. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28598. if (!this._geometry) {
  28599. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28600. }
  28601. this._geometry.setVerticesBuffer(buffer);
  28602. return this;
  28603. };
  28604. /**
  28605. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28606. * If the mesh has no geometry, it is simply returned as it is.
  28607. * The `data` are either a numeric array either a Float32Array.
  28608. * No new underlying VertexBuffer object is created.
  28609. * 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.
  28610. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28611. *
  28612. * Possible `kind` values :
  28613. * - BABYLON.VertexBuffer.PositionKind
  28614. * - BABYLON.VertexBuffer.UVKind
  28615. * - BABYLON.VertexBuffer.UV2Kind
  28616. * - BABYLON.VertexBuffer.UV3Kind
  28617. * - BABYLON.VertexBuffer.UV4Kind
  28618. * - BABYLON.VertexBuffer.UV5Kind
  28619. * - BABYLON.VertexBuffer.UV6Kind
  28620. * - BABYLON.VertexBuffer.ColorKind
  28621. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28622. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28623. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28624. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28625. *
  28626. * Returns the Mesh.
  28627. */
  28628. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28629. if (!this._geometry) {
  28630. return this;
  28631. }
  28632. if (!makeItUnique) {
  28633. this._geometry.updateVerticesData(kind, data, updateExtends);
  28634. }
  28635. else {
  28636. this.makeGeometryUnique();
  28637. this.updateVerticesData(kind, data, updateExtends, false);
  28638. }
  28639. return this;
  28640. };
  28641. /**
  28642. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28643. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28644. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28645. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28646. * Returns the Mesh.
  28647. */
  28648. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28649. if (computeNormals === void 0) { computeNormals = true; }
  28650. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28651. if (!positions) {
  28652. return this;
  28653. }
  28654. positionFunction(positions);
  28655. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28656. if (computeNormals) {
  28657. var indices = this.getIndices();
  28658. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28659. if (!normals) {
  28660. return this;
  28661. }
  28662. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28663. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28664. }
  28665. return this;
  28666. };
  28667. /**
  28668. * Creates a un-shared specific occurence of the geometry for the mesh.
  28669. * Returns the Mesh.
  28670. */
  28671. Mesh.prototype.makeGeometryUnique = function () {
  28672. if (!this._geometry) {
  28673. return this;
  28674. }
  28675. var oldGeometry = this._geometry;
  28676. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28677. oldGeometry.releaseForMesh(this, true);
  28678. geometry.applyToMesh(this);
  28679. return this;
  28680. };
  28681. /**
  28682. * Sets the mesh indices.
  28683. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28684. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28685. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28686. * This method creates a new index buffer each call.
  28687. * Returns the Mesh.
  28688. */
  28689. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28690. if (totalVertices === void 0) { totalVertices = null; }
  28691. if (updatable === void 0) { updatable = false; }
  28692. if (!this._geometry) {
  28693. var vertexData = new BABYLON.VertexData();
  28694. vertexData.indices = indices;
  28695. var scene = this.getScene();
  28696. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28697. }
  28698. else {
  28699. this._geometry.setIndices(indices, totalVertices, updatable);
  28700. }
  28701. return this;
  28702. };
  28703. /**
  28704. * Update the current index buffer
  28705. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28706. * Returns the Mesh.
  28707. */
  28708. Mesh.prototype.updateIndices = function (indices, offset) {
  28709. if (!this._geometry) {
  28710. return this;
  28711. }
  28712. this._geometry.updateIndices(indices, offset);
  28713. return this;
  28714. };
  28715. /**
  28716. * Invert the geometry to move from a right handed system to a left handed one.
  28717. * Returns the Mesh.
  28718. */
  28719. Mesh.prototype.toLeftHanded = function () {
  28720. if (!this._geometry) {
  28721. return this;
  28722. }
  28723. this._geometry.toLeftHanded();
  28724. return this;
  28725. };
  28726. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28727. if (!this._geometry) {
  28728. return this;
  28729. }
  28730. var engine = this.getScene().getEngine();
  28731. // Wireframe
  28732. var indexToBind;
  28733. if (this._unIndexed) {
  28734. indexToBind = null;
  28735. }
  28736. else {
  28737. switch (fillMode) {
  28738. case BABYLON.Material.PointFillMode:
  28739. indexToBind = null;
  28740. break;
  28741. case BABYLON.Material.WireFrameFillMode:
  28742. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28743. break;
  28744. default:
  28745. case BABYLON.Material.TriangleFillMode:
  28746. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28747. break;
  28748. }
  28749. }
  28750. // VBOs
  28751. this._geometry._bind(effect, indexToBind);
  28752. return this;
  28753. };
  28754. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28755. if (alternate === void 0) { alternate = false; }
  28756. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28757. return this;
  28758. }
  28759. this.onBeforeDrawObservable.notifyObservers(this);
  28760. var scene = this.getScene();
  28761. var engine = scene.getEngine();
  28762. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28763. // or triangles as points
  28764. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28765. }
  28766. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28767. // Triangles as wireframe
  28768. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28769. }
  28770. else {
  28771. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28772. }
  28773. if (scene._isAlternateRenderingEnabled && !alternate) {
  28774. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28775. if (!effect || !scene.activeCamera) {
  28776. return this;
  28777. }
  28778. scene._switchToAlternateCameraConfiguration(true);
  28779. this._effectiveMaterial.bindView(effect);
  28780. this._effectiveMaterial.bindViewProjection(effect);
  28781. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28782. this._draw(subMesh, fillMode, instancesCount, true);
  28783. engine.setViewport(scene.activeCamera.viewport);
  28784. scene._switchToAlternateCameraConfiguration(false);
  28785. this._effectiveMaterial.bindView(effect);
  28786. this._effectiveMaterial.bindViewProjection(effect);
  28787. }
  28788. return this;
  28789. };
  28790. /**
  28791. * Registers for this mesh a javascript function called just before the rendering process.
  28792. * This function is passed the current mesh.
  28793. * Return the Mesh.
  28794. */
  28795. Mesh.prototype.registerBeforeRender = function (func) {
  28796. this.onBeforeRenderObservable.add(func);
  28797. return this;
  28798. };
  28799. /**
  28800. * Disposes a previously registered javascript function called before the rendering.
  28801. * This function is passed the current mesh.
  28802. * Returns the Mesh.
  28803. */
  28804. Mesh.prototype.unregisterBeforeRender = function (func) {
  28805. this.onBeforeRenderObservable.removeCallback(func);
  28806. return this;
  28807. };
  28808. /**
  28809. * Registers for this mesh a javascript function called just after the rendering is complete.
  28810. * This function is passed the current mesh.
  28811. * Returns the Mesh.
  28812. */
  28813. Mesh.prototype.registerAfterRender = function (func) {
  28814. this.onAfterRenderObservable.add(func);
  28815. return this;
  28816. };
  28817. /**
  28818. * Disposes a previously registered javascript function called after the rendering.
  28819. * This function is passed the current mesh.
  28820. * Return the Mesh.
  28821. */
  28822. Mesh.prototype.unregisterAfterRender = function (func) {
  28823. this.onAfterRenderObservable.removeCallback(func);
  28824. return this;
  28825. };
  28826. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28827. var scene = this.getScene();
  28828. this._batchCache.mustReturn = false;
  28829. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28830. this._batchCache.visibleInstances[subMeshId] = null;
  28831. if (this._visibleInstances) {
  28832. var currentRenderId = scene.getRenderId();
  28833. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28834. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28835. var selfRenderId = this._renderId;
  28836. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28837. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28838. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28839. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28840. }
  28841. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28842. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28843. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28844. this._batchCache.mustReturn = true;
  28845. return this._batchCache;
  28846. }
  28847. if (currentRenderId !== selfRenderId) {
  28848. this._batchCache.renderSelf[subMeshId] = false;
  28849. }
  28850. }
  28851. this._renderIdForInstances[subMeshId] = currentRenderId;
  28852. }
  28853. return this._batchCache;
  28854. };
  28855. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28856. var visibleInstances = batch.visibleInstances[subMesh._id];
  28857. if (!visibleInstances) {
  28858. return this;
  28859. }
  28860. var matricesCount = visibleInstances.length + 1;
  28861. var bufferSize = matricesCount * 16 * 4;
  28862. var currentInstancesBufferSize = this._instancesBufferSize;
  28863. var instancesBuffer = this._instancesBuffer;
  28864. while (this._instancesBufferSize < bufferSize) {
  28865. this._instancesBufferSize *= 2;
  28866. }
  28867. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28868. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28869. }
  28870. var offset = 0;
  28871. var instancesCount = 0;
  28872. var world = this.getWorldMatrix();
  28873. if (batch.renderSelf[subMesh._id]) {
  28874. world.copyToArray(this._instancesData, offset);
  28875. offset += 16;
  28876. instancesCount++;
  28877. }
  28878. if (visibleInstances) {
  28879. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28880. var instance = visibleInstances[instanceIndex];
  28881. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28882. offset += 16;
  28883. instancesCount++;
  28884. }
  28885. }
  28886. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28887. if (instancesBuffer) {
  28888. instancesBuffer.dispose();
  28889. }
  28890. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28891. this._instancesBuffer = instancesBuffer;
  28892. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28893. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28894. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28895. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28896. }
  28897. else {
  28898. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28899. }
  28900. this._bind(subMesh, effect, fillMode);
  28901. this._draw(subMesh, fillMode, instancesCount);
  28902. engine.unbindInstanceAttributes();
  28903. return this;
  28904. };
  28905. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28906. var scene = this.getScene();
  28907. var engine = scene.getEngine();
  28908. if (hardwareInstancedRendering) {
  28909. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28910. }
  28911. else {
  28912. if (batch.renderSelf[subMesh._id]) {
  28913. // Draw
  28914. if (onBeforeDraw) {
  28915. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28916. }
  28917. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28918. }
  28919. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28920. if (visibleInstancesForSubMesh) {
  28921. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28922. var instance = visibleInstancesForSubMesh[instanceIndex];
  28923. // World
  28924. var world = instance.getWorldMatrix();
  28925. if (onBeforeDraw) {
  28926. onBeforeDraw(true, world, effectiveMaterial);
  28927. }
  28928. // Draw
  28929. this._draw(subMesh, fillMode);
  28930. }
  28931. }
  28932. }
  28933. return this;
  28934. };
  28935. /**
  28936. * Triggers the draw call for the mesh.
  28937. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28938. * Returns the Mesh.
  28939. */
  28940. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28941. this.checkOcclusionQuery();
  28942. if (this._isOccluded) {
  28943. return this;
  28944. }
  28945. var scene = this.getScene();
  28946. // Managing instances
  28947. var batch = this._getInstancesRenderList(subMesh._id);
  28948. if (batch.mustReturn) {
  28949. return this;
  28950. }
  28951. // Checking geometry state
  28952. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28953. return this;
  28954. }
  28955. this.onBeforeRenderObservable.notifyObservers(this);
  28956. var engine = scene.getEngine();
  28957. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28958. // Material
  28959. var material = subMesh.getMaterial();
  28960. if (!material) {
  28961. return this;
  28962. }
  28963. this._effectiveMaterial = material;
  28964. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28965. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28966. return this;
  28967. }
  28968. }
  28969. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28970. return this;
  28971. }
  28972. // Alpha mode
  28973. if (enableAlphaMode) {
  28974. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28975. }
  28976. // Outline - step 1
  28977. var savedDepthWrite = engine.getDepthWrite();
  28978. if (this.renderOutline) {
  28979. engine.setDepthWrite(false);
  28980. scene.getOutlineRenderer().render(subMesh, batch);
  28981. engine.setDepthWrite(savedDepthWrite);
  28982. }
  28983. var effect;
  28984. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28985. effect = subMesh.effect;
  28986. }
  28987. else {
  28988. effect = this._effectiveMaterial.getEffect();
  28989. }
  28990. if (!effect) {
  28991. return this;
  28992. }
  28993. var sideOrientation = this.overrideMaterialSideOrientation;
  28994. if (sideOrientation == null) {
  28995. sideOrientation = this._effectiveMaterial.sideOrientation;
  28996. if (this._getWorldMatrixDeterminant() < 0) {
  28997. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28998. }
  28999. }
  29000. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  29001. if (this._effectiveMaterial.forceDepthWrite) {
  29002. engine.setDepthWrite(true);
  29003. }
  29004. // Bind
  29005. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  29006. if (!hardwareInstancedRendering) {
  29007. this._bind(subMesh, effect, fillMode);
  29008. }
  29009. var world = this.getWorldMatrix();
  29010. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29011. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  29012. }
  29013. else {
  29014. this._effectiveMaterial.bind(world, this);
  29015. }
  29016. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  29017. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  29018. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29019. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  29020. }
  29021. // Draw
  29022. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29023. // Unbind
  29024. this._effectiveMaterial.unbind();
  29025. // Outline - step 2
  29026. if (this.renderOutline && savedDepthWrite) {
  29027. engine.setDepthWrite(true);
  29028. engine.setColorWrite(false);
  29029. scene.getOutlineRenderer().render(subMesh, batch);
  29030. engine.setColorWrite(true);
  29031. }
  29032. // Overlay
  29033. if (this.renderOverlay) {
  29034. var currentMode = engine.getAlphaMode();
  29035. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29036. scene.getOutlineRenderer().render(subMesh, batch, true);
  29037. engine.setAlphaMode(currentMode);
  29038. }
  29039. this.onAfterRenderObservable.notifyObservers(this);
  29040. return this;
  29041. };
  29042. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29043. if (isInstance && effectiveMaterial) {
  29044. effectiveMaterial.bindOnlyWorldMatrix(world);
  29045. }
  29046. };
  29047. /**
  29048. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29049. */
  29050. Mesh.prototype.getEmittedParticleSystems = function () {
  29051. var results = new Array();
  29052. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29053. var particleSystem = this.getScene().particleSystems[index];
  29054. if (particleSystem.emitter === this) {
  29055. results.push(particleSystem);
  29056. }
  29057. }
  29058. return results;
  29059. };
  29060. /**
  29061. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29062. */
  29063. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29064. var results = new Array();
  29065. var descendants = this.getDescendants();
  29066. descendants.push(this);
  29067. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29068. var particleSystem = this.getScene().particleSystems[index];
  29069. var emitter = particleSystem.emitter;
  29070. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29071. results.push(particleSystem);
  29072. }
  29073. }
  29074. return results;
  29075. };
  29076. Mesh.prototype._checkDelayState = function () {
  29077. var scene = this.getScene();
  29078. if (this._geometry) {
  29079. this._geometry.load(scene);
  29080. }
  29081. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29082. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29083. this._queueLoad(scene);
  29084. }
  29085. return this;
  29086. };
  29087. Mesh.prototype._queueLoad = function (scene) {
  29088. var _this = this;
  29089. scene._addPendingData(this);
  29090. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29091. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29092. if (data instanceof ArrayBuffer) {
  29093. _this._delayLoadingFunction(data, _this);
  29094. }
  29095. else {
  29096. _this._delayLoadingFunction(JSON.parse(data), _this);
  29097. }
  29098. _this.instances.forEach(function (instance) {
  29099. instance._syncSubMeshes();
  29100. });
  29101. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29102. scene._removePendingData(_this);
  29103. }, function () { }, scene.database, getBinaryData);
  29104. return this;
  29105. };
  29106. /**
  29107. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29108. */
  29109. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29110. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29111. return false;
  29112. }
  29113. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29114. return false;
  29115. }
  29116. this._checkDelayState();
  29117. return true;
  29118. };
  29119. /**
  29120. * Sets the mesh material by the material or multiMaterial `id` property.
  29121. * The material `id` is a string identifying the material or the multiMaterial.
  29122. * This method returns the Mesh.
  29123. */
  29124. Mesh.prototype.setMaterialByID = function (id) {
  29125. var materials = this.getScene().materials;
  29126. var index;
  29127. for (index = materials.length - 1; index > -1; index--) {
  29128. if (materials[index].id === id) {
  29129. this.material = materials[index];
  29130. return this;
  29131. }
  29132. }
  29133. // Multi
  29134. var multiMaterials = this.getScene().multiMaterials;
  29135. for (index = multiMaterials.length - 1; index > -1; index--) {
  29136. if (multiMaterials[index].id === id) {
  29137. this.material = multiMaterials[index];
  29138. return this;
  29139. }
  29140. }
  29141. return this;
  29142. };
  29143. /**
  29144. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29145. */
  29146. Mesh.prototype.getAnimatables = function () {
  29147. var results = new Array();
  29148. if (this.material) {
  29149. results.push(this.material);
  29150. }
  29151. if (this.skeleton) {
  29152. results.push(this.skeleton);
  29153. }
  29154. return results;
  29155. };
  29156. /**
  29157. * Modifies the mesh geometry according to the passed transformation matrix.
  29158. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29159. * The mesh normals are modified accordingly the same transformation.
  29160. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29161. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29162. * Returns the Mesh.
  29163. */
  29164. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29165. // Position
  29166. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29167. return this;
  29168. }
  29169. var submeshes = this.subMeshes.splice(0);
  29170. this._resetPointsArrayCache();
  29171. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29172. var temp = new Array();
  29173. var index;
  29174. for (index = 0; index < data.length; index += 3) {
  29175. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29176. }
  29177. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29178. // Normals
  29179. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29180. return this;
  29181. }
  29182. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29183. temp = [];
  29184. for (index = 0; index < data.length; index += 3) {
  29185. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29186. }
  29187. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29188. // flip faces?
  29189. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29190. this.flipFaces();
  29191. }
  29192. // Restore submeshes
  29193. this.releaseSubMeshes();
  29194. this.subMeshes = submeshes;
  29195. return this;
  29196. };
  29197. /**
  29198. * Modifies the mesh geometry according to its own current World Matrix.
  29199. * The mesh World Matrix is then reset.
  29200. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29201. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29202. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29203. * Returns the Mesh.
  29204. */
  29205. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29206. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29207. this.scaling.copyFromFloats(1, 1, 1);
  29208. this.position.copyFromFloats(0, 0, 0);
  29209. this.rotation.copyFromFloats(0, 0, 0);
  29210. //only if quaternion is already set
  29211. if (this.rotationQuaternion) {
  29212. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29213. }
  29214. this._worldMatrix = BABYLON.Matrix.Identity();
  29215. return this;
  29216. };
  29217. Object.defineProperty(Mesh.prototype, "_positions", {
  29218. // Cache
  29219. get: function () {
  29220. if (this._geometry) {
  29221. return this._geometry._positions;
  29222. }
  29223. return null;
  29224. },
  29225. enumerable: true,
  29226. configurable: true
  29227. });
  29228. Mesh.prototype._resetPointsArrayCache = function () {
  29229. if (this._geometry) {
  29230. this._geometry._resetPointsArrayCache();
  29231. }
  29232. return this;
  29233. };
  29234. Mesh.prototype._generatePointsArray = function () {
  29235. if (this._geometry) {
  29236. return this._geometry._generatePointsArray();
  29237. }
  29238. return false;
  29239. };
  29240. /**
  29241. * Returns a new Mesh object generated from the current mesh properties.
  29242. * This method must not get confused with createInstance().
  29243. * The parameter `name` is a string, the name given to the new mesh.
  29244. * The optional parameter `newParent` can be any Node object (default `null`).
  29245. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29246. * 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.
  29247. */
  29248. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29249. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29250. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29251. };
  29252. /**
  29253. * Releases resources associated with this mesh.
  29254. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29255. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29256. */
  29257. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29258. var _this = this;
  29259. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29260. this.morphTargetManager = null;
  29261. if (this._geometry) {
  29262. this._geometry.releaseForMesh(this, true);
  29263. }
  29264. // Sources
  29265. var meshes = this.getScene().meshes;
  29266. meshes.forEach(function (abstractMesh) {
  29267. var mesh = abstractMesh;
  29268. if (mesh._source && mesh._source === _this) {
  29269. mesh._source = null;
  29270. }
  29271. });
  29272. this._source = null;
  29273. // Instances
  29274. if (this._instancesBuffer) {
  29275. this._instancesBuffer.dispose();
  29276. this._instancesBuffer = null;
  29277. }
  29278. while (this.instances.length) {
  29279. this.instances[0].dispose();
  29280. }
  29281. // Effect layers.
  29282. var effectLayers = this.getScene().effectLayers;
  29283. for (var i = 0; i < effectLayers.length; i++) {
  29284. var effectLayer = effectLayers[i];
  29285. if (effectLayer) {
  29286. effectLayer._disposeMesh(this);
  29287. }
  29288. }
  29289. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29290. };
  29291. /**
  29292. * Modifies the mesh geometry according to a displacement map.
  29293. * 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.
  29294. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29295. * This method returns nothing.
  29296. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29297. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29298. * 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.
  29299. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29300. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29301. *
  29302. * Returns the Mesh.
  29303. */
  29304. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29305. var _this = this;
  29306. var scene = this.getScene();
  29307. var onload = function (img) {
  29308. // Getting height map data
  29309. var canvas = document.createElement("canvas");
  29310. var context = canvas.getContext("2d");
  29311. var heightMapWidth = img.width;
  29312. var heightMapHeight = img.height;
  29313. canvas.width = heightMapWidth;
  29314. canvas.height = heightMapHeight;
  29315. context.drawImage(img, 0, 0);
  29316. // Create VertexData from map data
  29317. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29318. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29319. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29320. //execute success callback, if set
  29321. if (onSuccess) {
  29322. onSuccess(_this);
  29323. }
  29324. };
  29325. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29326. return this;
  29327. };
  29328. /**
  29329. * Modifies the mesh geometry according to a displacementMap buffer.
  29330. * 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.
  29331. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29332. * This method returns nothing.
  29333. * 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.
  29334. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29335. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29336. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29337. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29338. *
  29339. * Returns the Mesh.
  29340. */
  29341. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29342. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29343. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29344. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29345. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29346. return this;
  29347. }
  29348. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29349. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29350. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29351. var position = BABYLON.Vector3.Zero();
  29352. var normal = BABYLON.Vector3.Zero();
  29353. var uv = BABYLON.Vector2.Zero();
  29354. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29355. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29356. for (var index = 0; index < positions.length; index += 3) {
  29357. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29358. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29359. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29360. // Compute height
  29361. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29362. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29363. var pos = (u + v * heightMapWidth) * 4;
  29364. var r = buffer[pos] / 255.0;
  29365. var g = buffer[pos + 1] / 255.0;
  29366. var b = buffer[pos + 2] / 255.0;
  29367. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29368. normal.normalize();
  29369. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29370. position = position.add(normal);
  29371. position.toArray(positions, index);
  29372. }
  29373. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29374. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29375. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29376. return this;
  29377. };
  29378. /**
  29379. * Modify the mesh to get a flat shading rendering.
  29380. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29381. * This method returns the Mesh.
  29382. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29383. */
  29384. Mesh.prototype.convertToFlatShadedMesh = function () {
  29385. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29386. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29387. var kinds = this.getVerticesDataKinds();
  29388. var vbs = {};
  29389. var data = {};
  29390. var newdata = {};
  29391. var updatableNormals = false;
  29392. var kindIndex;
  29393. var kind;
  29394. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29395. kind = kinds[kindIndex];
  29396. var vertexBuffer = this.getVertexBuffer(kind);
  29397. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29398. updatableNormals = vertexBuffer.isUpdatable();
  29399. kinds.splice(kindIndex, 1);
  29400. kindIndex--;
  29401. continue;
  29402. }
  29403. vbs[kind] = vertexBuffer;
  29404. data[kind] = vbs[kind].getData();
  29405. newdata[kind] = [];
  29406. }
  29407. // Save previous submeshes
  29408. var previousSubmeshes = this.subMeshes.slice(0);
  29409. var indices = this.getIndices();
  29410. var totalIndices = this.getTotalIndices();
  29411. // Generating unique vertices per face
  29412. var index;
  29413. for (index = 0; index < totalIndices; index++) {
  29414. var vertexIndex = indices[index];
  29415. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29416. kind = kinds[kindIndex];
  29417. var stride = vbs[kind].getStrideSize();
  29418. for (var offset = 0; offset < stride; offset++) {
  29419. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29420. }
  29421. }
  29422. }
  29423. // Updating faces & normal
  29424. var normals = [];
  29425. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29426. for (index = 0; index < totalIndices; index += 3) {
  29427. indices[index] = index;
  29428. indices[index + 1] = index + 1;
  29429. indices[index + 2] = index + 2;
  29430. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29431. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29432. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29433. var p1p2 = p1.subtract(p2);
  29434. var p3p2 = p3.subtract(p2);
  29435. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29436. // Store same normals for every vertex
  29437. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29438. normals.push(normal.x);
  29439. normals.push(normal.y);
  29440. normals.push(normal.z);
  29441. }
  29442. }
  29443. this.setIndices(indices);
  29444. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29445. // Updating vertex buffers
  29446. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29447. kind = kinds[kindIndex];
  29448. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29449. }
  29450. // Updating submeshes
  29451. this.releaseSubMeshes();
  29452. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29453. var previousOne = previousSubmeshes[submeshIndex];
  29454. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29455. }
  29456. this.synchronizeInstances();
  29457. return this;
  29458. };
  29459. /**
  29460. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29461. * In other words, more vertices, no more indices and a single bigger VBO.
  29462. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29463. * Returns the Mesh.
  29464. */
  29465. Mesh.prototype.convertToUnIndexedMesh = function () {
  29466. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29467. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29468. var kinds = this.getVerticesDataKinds();
  29469. var vbs = {};
  29470. var data = {};
  29471. var newdata = {};
  29472. var kindIndex;
  29473. var kind;
  29474. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29475. kind = kinds[kindIndex];
  29476. var vertexBuffer = this.getVertexBuffer(kind);
  29477. vbs[kind] = vertexBuffer;
  29478. data[kind] = vbs[kind].getData();
  29479. newdata[kind] = [];
  29480. }
  29481. // Save previous submeshes
  29482. var previousSubmeshes = this.subMeshes.slice(0);
  29483. var indices = this.getIndices();
  29484. var totalIndices = this.getTotalIndices();
  29485. // Generating unique vertices per face
  29486. var index;
  29487. for (index = 0; index < totalIndices; index++) {
  29488. var vertexIndex = indices[index];
  29489. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29490. kind = kinds[kindIndex];
  29491. var stride = vbs[kind].getStrideSize();
  29492. for (var offset = 0; offset < stride; offset++) {
  29493. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29494. }
  29495. }
  29496. }
  29497. // Updating indices
  29498. for (index = 0; index < totalIndices; index += 3) {
  29499. indices[index] = index;
  29500. indices[index + 1] = index + 1;
  29501. indices[index + 2] = index + 2;
  29502. }
  29503. this.setIndices(indices);
  29504. // Updating vertex buffers
  29505. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29506. kind = kinds[kindIndex];
  29507. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29508. }
  29509. // Updating submeshes
  29510. this.releaseSubMeshes();
  29511. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29512. var previousOne = previousSubmeshes[submeshIndex];
  29513. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29514. }
  29515. this._unIndexed = true;
  29516. this.synchronizeInstances();
  29517. return this;
  29518. };
  29519. /**
  29520. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29521. * This method returns the Mesh.
  29522. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29523. */
  29524. Mesh.prototype.flipFaces = function (flipNormals) {
  29525. if (flipNormals === void 0) { flipNormals = false; }
  29526. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29527. var i;
  29528. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29529. for (i = 0; i < vertex_data.normals.length; i++) {
  29530. vertex_data.normals[i] *= -1;
  29531. }
  29532. }
  29533. if (vertex_data.indices) {
  29534. var temp;
  29535. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29536. // reassign indices
  29537. temp = vertex_data.indices[i + 1];
  29538. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29539. vertex_data.indices[i + 2] = temp;
  29540. }
  29541. }
  29542. vertex_data.applyToMesh(this);
  29543. return this;
  29544. };
  29545. // Instances
  29546. /**
  29547. * Creates a new InstancedMesh object from the mesh model.
  29548. * An instance shares the same properties and the same material than its model.
  29549. * Only these properties of each instance can then be set individually :
  29550. * - position
  29551. * - rotation
  29552. * - rotationQuaternion
  29553. * - setPivotMatrix
  29554. * - scaling
  29555. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29556. * Warning : this method is not supported for Line mesh and LineSystem
  29557. */
  29558. Mesh.prototype.createInstance = function (name) {
  29559. return new BABYLON.InstancedMesh(name, this);
  29560. };
  29561. /**
  29562. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29563. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29564. * This method returns the Mesh.
  29565. */
  29566. Mesh.prototype.synchronizeInstances = function () {
  29567. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29568. var instance = this.instances[instanceIndex];
  29569. instance._syncSubMeshes();
  29570. }
  29571. return this;
  29572. };
  29573. /**
  29574. * Simplify the mesh according to the given array of settings.
  29575. * Function will return immediately and will simplify async. It returns the Mesh.
  29576. * @param settings a collection of simplification settings.
  29577. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29578. * @param type the type of simplification to run.
  29579. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29580. */
  29581. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29582. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29583. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29584. this.getScene().simplificationQueue.addTask({
  29585. settings: settings,
  29586. parallelProcessing: parallelProcessing,
  29587. mesh: this,
  29588. simplificationType: simplificationType,
  29589. successCallback: successCallback
  29590. });
  29591. return this;
  29592. };
  29593. /**
  29594. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29595. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29596. * This should be used together with the simplification to avoid disappearing triangles.
  29597. * Returns the Mesh.
  29598. * @param successCallback an optional success callback to be called after the optimization finished.
  29599. */
  29600. Mesh.prototype.optimizeIndices = function (successCallback) {
  29601. var _this = this;
  29602. var indices = this.getIndices();
  29603. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29604. if (!positions || !indices) {
  29605. return this;
  29606. }
  29607. var vectorPositions = new Array();
  29608. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29609. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29610. }
  29611. var dupes = new Array();
  29612. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29613. var realPos = vectorPositions.length - 1 - iteration;
  29614. var testedPosition = vectorPositions[realPos];
  29615. for (var j = 0; j < realPos; ++j) {
  29616. var againstPosition = vectorPositions[j];
  29617. if (testedPosition.equals(againstPosition)) {
  29618. dupes[realPos] = j;
  29619. break;
  29620. }
  29621. }
  29622. }, function () {
  29623. for (var i = 0; i < indices.length; ++i) {
  29624. indices[i] = dupes[indices[i]] || indices[i];
  29625. }
  29626. //indices are now reordered
  29627. var originalSubMeshes = _this.subMeshes.slice(0);
  29628. _this.setIndices(indices);
  29629. _this.subMeshes = originalSubMeshes;
  29630. if (successCallback) {
  29631. successCallback(_this);
  29632. }
  29633. });
  29634. return this;
  29635. };
  29636. Mesh.prototype.serialize = function (serializationObject) {
  29637. serializationObject.name = this.name;
  29638. serializationObject.id = this.id;
  29639. serializationObject.type = this.getClassName();
  29640. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29641. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29642. }
  29643. serializationObject.position = this.position.asArray();
  29644. if (this.rotationQuaternion) {
  29645. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29646. }
  29647. else if (this.rotation) {
  29648. serializationObject.rotation = this.rotation.asArray();
  29649. }
  29650. serializationObject.scaling = this.scaling.asArray();
  29651. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29652. serializationObject.isEnabled = this.isEnabled(false);
  29653. serializationObject.isVisible = this.isVisible;
  29654. serializationObject.infiniteDistance = this.infiniteDistance;
  29655. serializationObject.pickable = this.isPickable;
  29656. serializationObject.receiveShadows = this.receiveShadows;
  29657. serializationObject.billboardMode = this.billboardMode;
  29658. serializationObject.visibility = this.visibility;
  29659. serializationObject.checkCollisions = this.checkCollisions;
  29660. serializationObject.isBlocker = this.isBlocker;
  29661. // Parent
  29662. if (this.parent) {
  29663. serializationObject.parentId = this.parent.id;
  29664. }
  29665. // Geometry
  29666. serializationObject.isUnIndexed = this.isUnIndexed;
  29667. var geometry = this._geometry;
  29668. if (geometry) {
  29669. var geometryId = geometry.id;
  29670. serializationObject.geometryId = geometryId;
  29671. // SubMeshes
  29672. serializationObject.subMeshes = [];
  29673. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29674. var subMesh = this.subMeshes[subIndex];
  29675. serializationObject.subMeshes.push({
  29676. materialIndex: subMesh.materialIndex,
  29677. verticesStart: subMesh.verticesStart,
  29678. verticesCount: subMesh.verticesCount,
  29679. indexStart: subMesh.indexStart,
  29680. indexCount: subMesh.indexCount
  29681. });
  29682. }
  29683. }
  29684. // Material
  29685. if (this.material) {
  29686. serializationObject.materialId = this.material.id;
  29687. }
  29688. else {
  29689. this.material = null;
  29690. }
  29691. // Morph targets
  29692. if (this.morphTargetManager) {
  29693. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29694. }
  29695. // Skeleton
  29696. if (this.skeleton) {
  29697. serializationObject.skeletonId = this.skeleton.id;
  29698. }
  29699. // Physics
  29700. //TODO implement correct serialization for physics impostors.
  29701. var impostor = this.getPhysicsImpostor();
  29702. if (impostor) {
  29703. serializationObject.physicsMass = impostor.getParam("mass");
  29704. serializationObject.physicsFriction = impostor.getParam("friction");
  29705. serializationObject.physicsRestitution = impostor.getParam("mass");
  29706. serializationObject.physicsImpostor = impostor.type;
  29707. }
  29708. // Metadata
  29709. if (this.metadata) {
  29710. serializationObject.metadata = this.metadata;
  29711. }
  29712. // Instances
  29713. serializationObject.instances = [];
  29714. for (var index = 0; index < this.instances.length; index++) {
  29715. var instance = this.instances[index];
  29716. var serializationInstance = {
  29717. name: instance.name,
  29718. id: instance.id,
  29719. position: instance.position.asArray(),
  29720. scaling: instance.scaling.asArray()
  29721. };
  29722. if (instance.rotationQuaternion) {
  29723. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29724. }
  29725. else if (instance.rotation) {
  29726. serializationInstance.rotation = instance.rotation.asArray();
  29727. }
  29728. serializationObject.instances.push(serializationInstance);
  29729. // Animations
  29730. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29731. serializationInstance.ranges = instance.serializeAnimationRanges();
  29732. }
  29733. //
  29734. // Animations
  29735. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29736. serializationObject.ranges = this.serializeAnimationRanges();
  29737. // Layer mask
  29738. serializationObject.layerMask = this.layerMask;
  29739. // Alpha
  29740. serializationObject.alphaIndex = this.alphaIndex;
  29741. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29742. // Overlay
  29743. serializationObject.overlayAlpha = this.overlayAlpha;
  29744. serializationObject.overlayColor = this.overlayColor.asArray();
  29745. serializationObject.renderOverlay = this.renderOverlay;
  29746. // Fog
  29747. serializationObject.applyFog = this.applyFog;
  29748. // Action Manager
  29749. if (this.actionManager) {
  29750. serializationObject.actions = this.actionManager.serialize(this.name);
  29751. }
  29752. };
  29753. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29754. if (!this.geometry) {
  29755. return;
  29756. }
  29757. this._markSubMeshesAsAttributesDirty();
  29758. var morphTargetManager = this._morphTargetManager;
  29759. if (morphTargetManager && morphTargetManager.vertexCount) {
  29760. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29761. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29762. this.morphTargetManager = null;
  29763. return;
  29764. }
  29765. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29766. var morphTarget = morphTargetManager.getActiveTarget(index);
  29767. var positions = morphTarget.getPositions();
  29768. if (!positions) {
  29769. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29770. return;
  29771. }
  29772. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29773. var normals = morphTarget.getNormals();
  29774. if (normals) {
  29775. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29776. }
  29777. var tangents = morphTarget.getTangents();
  29778. if (tangents) {
  29779. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29780. }
  29781. }
  29782. }
  29783. else {
  29784. var index = 0;
  29785. // Positions
  29786. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29787. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29788. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29789. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29790. }
  29791. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29792. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29793. }
  29794. index++;
  29795. }
  29796. }
  29797. };
  29798. // Statics
  29799. /**
  29800. * Returns a new Mesh object parsed from the source provided.
  29801. * The parameter `parsedMesh` is the source.
  29802. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29803. */
  29804. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29805. var mesh;
  29806. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29807. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29808. }
  29809. else {
  29810. mesh = new Mesh(parsedMesh.name, scene);
  29811. }
  29812. mesh.id = parsedMesh.id;
  29813. if (BABYLON.Tags) {
  29814. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29815. }
  29816. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29817. if (parsedMesh.metadata !== undefined) {
  29818. mesh.metadata = parsedMesh.metadata;
  29819. }
  29820. if (parsedMesh.rotationQuaternion) {
  29821. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29822. }
  29823. else if (parsedMesh.rotation) {
  29824. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29825. }
  29826. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29827. if (parsedMesh.localMatrix) {
  29828. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29829. }
  29830. else if (parsedMesh.pivotMatrix) {
  29831. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29832. }
  29833. mesh.setEnabled(parsedMesh.isEnabled);
  29834. mesh.isVisible = parsedMesh.isVisible;
  29835. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29836. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29837. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29838. if (parsedMesh.applyFog !== undefined) {
  29839. mesh.applyFog = parsedMesh.applyFog;
  29840. }
  29841. if (parsedMesh.pickable !== undefined) {
  29842. mesh.isPickable = parsedMesh.pickable;
  29843. }
  29844. if (parsedMesh.alphaIndex !== undefined) {
  29845. mesh.alphaIndex = parsedMesh.alphaIndex;
  29846. }
  29847. mesh.receiveShadows = parsedMesh.receiveShadows;
  29848. mesh.billboardMode = parsedMesh.billboardMode;
  29849. if (parsedMesh.visibility !== undefined) {
  29850. mesh.visibility = parsedMesh.visibility;
  29851. }
  29852. mesh.checkCollisions = parsedMesh.checkCollisions;
  29853. if (parsedMesh.isBlocker !== undefined) {
  29854. mesh.isBlocker = parsedMesh.isBlocker;
  29855. }
  29856. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29857. // freezeWorldMatrix
  29858. if (parsedMesh.freezeWorldMatrix) {
  29859. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29860. }
  29861. // Parent
  29862. if (parsedMesh.parentId) {
  29863. mesh._waitingParentId = parsedMesh.parentId;
  29864. }
  29865. // Actions
  29866. if (parsedMesh.actions !== undefined) {
  29867. mesh._waitingActions = parsedMesh.actions;
  29868. }
  29869. // Overlay
  29870. if (parsedMesh.overlayAlpha !== undefined) {
  29871. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29872. }
  29873. if (parsedMesh.overlayColor !== undefined) {
  29874. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29875. }
  29876. if (parsedMesh.renderOverlay !== undefined) {
  29877. mesh.renderOverlay = parsedMesh.renderOverlay;
  29878. }
  29879. // Geometry
  29880. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29881. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29882. if (parsedMesh.delayLoadingFile) {
  29883. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29884. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29885. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29886. if (parsedMesh._binaryInfo) {
  29887. mesh._binaryInfo = parsedMesh._binaryInfo;
  29888. }
  29889. mesh._delayInfo = [];
  29890. if (parsedMesh.hasUVs) {
  29891. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29892. }
  29893. if (parsedMesh.hasUVs2) {
  29894. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29895. }
  29896. if (parsedMesh.hasUVs3) {
  29897. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29898. }
  29899. if (parsedMesh.hasUVs4) {
  29900. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29901. }
  29902. if (parsedMesh.hasUVs5) {
  29903. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29904. }
  29905. if (parsedMesh.hasUVs6) {
  29906. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29907. }
  29908. if (parsedMesh.hasColors) {
  29909. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29910. }
  29911. if (parsedMesh.hasMatricesIndices) {
  29912. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29913. }
  29914. if (parsedMesh.hasMatricesWeights) {
  29915. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29916. }
  29917. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29918. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29919. mesh._checkDelayState();
  29920. }
  29921. }
  29922. else {
  29923. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29924. }
  29925. // Material
  29926. if (parsedMesh.materialId) {
  29927. mesh.setMaterialByID(parsedMesh.materialId);
  29928. }
  29929. else {
  29930. mesh.material = null;
  29931. }
  29932. // Morph targets
  29933. if (parsedMesh.morphTargetManagerId > -1) {
  29934. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29935. }
  29936. // Skeleton
  29937. if (parsedMesh.skeletonId > -1) {
  29938. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29939. if (parsedMesh.numBoneInfluencers) {
  29940. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29941. }
  29942. }
  29943. // Animations
  29944. if (parsedMesh.animations) {
  29945. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29946. var parsedAnimation = parsedMesh.animations[animationIndex];
  29947. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29948. }
  29949. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29950. }
  29951. if (parsedMesh.autoAnimate) {
  29952. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29953. }
  29954. // Layer Mask
  29955. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29956. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29957. }
  29958. else {
  29959. mesh.layerMask = 0x0FFFFFFF;
  29960. }
  29961. // Physics
  29962. if (parsedMesh.physicsImpostor) {
  29963. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29964. mass: parsedMesh.physicsMass,
  29965. friction: parsedMesh.physicsFriction,
  29966. restitution: parsedMesh.physicsRestitution
  29967. }, scene);
  29968. }
  29969. // Instances
  29970. if (parsedMesh.instances) {
  29971. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29972. var parsedInstance = parsedMesh.instances[index];
  29973. var instance = mesh.createInstance(parsedInstance.name);
  29974. if (parsedInstance.id) {
  29975. instance.id = parsedInstance.id;
  29976. }
  29977. if (BABYLON.Tags) {
  29978. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29979. }
  29980. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29981. if (parsedInstance.parentId) {
  29982. instance._waitingParentId = parsedInstance.parentId;
  29983. }
  29984. if (parsedInstance.rotationQuaternion) {
  29985. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29986. }
  29987. else if (parsedInstance.rotation) {
  29988. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29989. }
  29990. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29991. instance.checkCollisions = mesh.checkCollisions;
  29992. if (parsedMesh.animations) {
  29993. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29994. parsedAnimation = parsedMesh.animations[animationIndex];
  29995. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29996. }
  29997. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29998. }
  29999. }
  30000. }
  30001. return mesh;
  30002. };
  30003. /**
  30004. * Creates a ribbon mesh.
  30005. * Please consider using the same method from the MeshBuilder class instead.
  30006. * 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.
  30007. *
  30008. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  30009. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  30010. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  30011. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  30012. * 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.
  30013. * 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.
  30014. * 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
  30015. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30016. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30017. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30018. */
  30019. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  30020. if (closeArray === void 0) { closeArray = false; }
  30021. if (updatable === void 0) { updatable = false; }
  30022. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30023. pathArray: pathArray,
  30024. closeArray: closeArray,
  30025. closePath: closePath,
  30026. offset: offset,
  30027. updatable: updatable,
  30028. sideOrientation: sideOrientation,
  30029. instance: instance
  30030. }, scene);
  30031. };
  30032. /**
  30033. * Creates a plane polygonal mesh. By default, this is a disc.
  30034. * Please consider using the same method from the MeshBuilder class instead.
  30035. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30036. * 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.
  30037. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30038. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30039. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30040. */
  30041. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30042. if (scene === void 0) { scene = null; }
  30043. var options = {
  30044. radius: radius,
  30045. tessellation: tessellation,
  30046. sideOrientation: sideOrientation,
  30047. updatable: updatable
  30048. };
  30049. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30050. };
  30051. /**
  30052. * Creates a box mesh.
  30053. * Please consider using the same method from the MeshBuilder class instead.
  30054. * The parameter `size` sets the size (float) of each box side (default 1).
  30055. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30056. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30057. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30058. */
  30059. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30060. if (scene === void 0) { scene = null; }
  30061. var options = {
  30062. size: size,
  30063. sideOrientation: sideOrientation,
  30064. updatable: updatable
  30065. };
  30066. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30067. };
  30068. /**
  30069. * Creates a sphere mesh.
  30070. * Please consider using the same method from the MeshBuilder class instead.
  30071. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30072. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30073. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30074. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30075. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30076. */
  30077. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30078. var options = {
  30079. segments: segments,
  30080. diameterX: diameter,
  30081. diameterY: diameter,
  30082. diameterZ: diameter,
  30083. sideOrientation: sideOrientation,
  30084. updatable: updatable
  30085. };
  30086. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30087. };
  30088. /**
  30089. * Creates a cylinder or a cone mesh.
  30090. * Please consider using the same method from the MeshBuilder class instead.
  30091. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30092. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30093. * 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.
  30094. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30095. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30096. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30097. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30098. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30099. */
  30100. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30101. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30102. if (scene !== undefined) {
  30103. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30104. updatable = scene;
  30105. }
  30106. scene = subdivisions;
  30107. subdivisions = 1;
  30108. }
  30109. var options = {
  30110. height: height,
  30111. diameterTop: diameterTop,
  30112. diameterBottom: diameterBottom,
  30113. tessellation: tessellation,
  30114. subdivisions: subdivisions,
  30115. sideOrientation: sideOrientation,
  30116. updatable: updatable
  30117. };
  30118. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30119. };
  30120. // Torus (Code from SharpDX.org)
  30121. /**
  30122. * Creates a torus mesh.
  30123. * Please consider using the same method from the MeshBuilder class instead.
  30124. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30125. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30126. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30127. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30128. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30129. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30130. */
  30131. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30132. var options = {
  30133. diameter: diameter,
  30134. thickness: thickness,
  30135. tessellation: tessellation,
  30136. sideOrientation: sideOrientation,
  30137. updatable: updatable
  30138. };
  30139. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30140. };
  30141. /**
  30142. * Creates a torus knot mesh.
  30143. * Please consider using the same method from the MeshBuilder class instead.
  30144. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30145. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30146. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30147. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30148. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30149. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30150. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30151. */
  30152. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30153. var options = {
  30154. radius: radius,
  30155. tube: tube,
  30156. radialSegments: radialSegments,
  30157. tubularSegments: tubularSegments,
  30158. p: p,
  30159. q: q,
  30160. sideOrientation: sideOrientation,
  30161. updatable: updatable
  30162. };
  30163. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30164. };
  30165. /**
  30166. * Creates a line mesh.
  30167. * Please consider using the same method from the MeshBuilder class instead.
  30168. * 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.
  30169. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30170. * The parameter `points` is an array successive Vector3.
  30171. * 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
  30172. * When updating an instance, remember that only point positions can change, not the number of points.
  30173. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30174. */
  30175. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30176. if (scene === void 0) { scene = null; }
  30177. if (updatable === void 0) { updatable = false; }
  30178. if (instance === void 0) { instance = null; }
  30179. var options = {
  30180. points: points,
  30181. updatable: updatable,
  30182. instance: instance
  30183. };
  30184. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30185. };
  30186. /**
  30187. * Creates a dashed line mesh.
  30188. * Please consider using the same method from the MeshBuilder class instead.
  30189. * 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.
  30190. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30191. * The parameter `points` is an array successive Vector3.
  30192. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30193. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30194. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30195. * 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
  30196. * When updating an instance, remember that only point positions can change, not the number of points.
  30197. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30198. */
  30199. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30200. if (scene === void 0) { scene = null; }
  30201. var options = {
  30202. points: points,
  30203. dashSize: dashSize,
  30204. gapSize: gapSize,
  30205. dashNb: dashNb,
  30206. updatable: updatable,
  30207. instance: instance
  30208. };
  30209. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30210. };
  30211. /**
  30212. * Creates a polygon mesh.
  30213. * Please consider using the same method from the MeshBuilder class instead.
  30214. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30215. * 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.
  30216. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30217. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30218. * Remember you can only change the shape positions, not their number when updating a polygon.
  30219. */
  30220. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30221. var options = {
  30222. shape: shape,
  30223. holes: holes,
  30224. updatable: updatable,
  30225. sideOrientation: sideOrientation
  30226. };
  30227. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30228. };
  30229. /**
  30230. * Creates an extruded polygon mesh, with depth in the Y direction.
  30231. * Please consider using the same method from the MeshBuilder class instead.
  30232. */
  30233. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30234. var options = {
  30235. shape: shape,
  30236. holes: holes,
  30237. depth: depth,
  30238. updatable: updatable,
  30239. sideOrientation: sideOrientation
  30240. };
  30241. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30242. };
  30243. /**
  30244. * Creates an extruded shape mesh.
  30245. * 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.
  30246. * Please consider using the same method from the MeshBuilder class instead.
  30247. *
  30248. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30249. * 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
  30250. * extruded along the Z axis.
  30251. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30252. * 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.
  30253. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30254. * 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
  30255. * 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
  30256. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30257. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30258. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30259. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30260. */
  30261. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30262. if (scene === void 0) { scene = null; }
  30263. var options = {
  30264. shape: shape,
  30265. path: path,
  30266. scale: scale,
  30267. rotation: rotation,
  30268. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30269. sideOrientation: sideOrientation,
  30270. instance: instance,
  30271. updatable: updatable
  30272. };
  30273. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30274. };
  30275. /**
  30276. * Creates an custom extruded shape mesh.
  30277. * 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.
  30278. * Please consider using the same method from the MeshBuilder class instead.
  30279. *
  30280. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30281. * 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
  30282. * extruded along the Z axis.
  30283. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30284. * 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
  30285. * and the distance of this point from the begining of the path :
  30286. * ```javascript
  30287. * var rotationFunction = function(i, distance) {
  30288. * // do things
  30289. * return rotationValue; }
  30290. * ```
  30291. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30292. * 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
  30293. * and the distance of this point from the begining of the path :
  30294. * ```javascript
  30295. * var scaleFunction = function(i, distance) {
  30296. * // do things
  30297. * return scaleValue;}
  30298. * ```
  30299. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30300. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30301. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30302. * 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
  30303. * 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
  30304. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30305. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30306. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30308. */
  30309. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30310. var options = {
  30311. shape: shape,
  30312. path: path,
  30313. scaleFunction: scaleFunction,
  30314. rotationFunction: rotationFunction,
  30315. ribbonCloseArray: ribbonCloseArray,
  30316. ribbonClosePath: ribbonClosePath,
  30317. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30318. sideOrientation: sideOrientation,
  30319. instance: instance,
  30320. updatable: updatable
  30321. };
  30322. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30323. };
  30324. /**
  30325. * Creates lathe mesh.
  30326. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30327. * Please consider using the same method from the MeshBuilder class instead.
  30328. * 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
  30329. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30330. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30331. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30332. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30333. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30334. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30335. */
  30336. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30337. var options = {
  30338. shape: shape,
  30339. radius: radius,
  30340. tessellation: tessellation,
  30341. sideOrientation: sideOrientation,
  30342. updatable: updatable
  30343. };
  30344. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30345. };
  30346. /**
  30347. * Creates a plane mesh.
  30348. * Please consider using the same method from the MeshBuilder class instead.
  30349. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30350. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30351. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30352. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30353. */
  30354. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30355. var options = {
  30356. size: size,
  30357. width: size,
  30358. height: size,
  30359. sideOrientation: sideOrientation,
  30360. updatable: updatable
  30361. };
  30362. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30363. };
  30364. /**
  30365. * Creates a ground mesh.
  30366. * Please consider using the same method from the MeshBuilder class instead.
  30367. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30368. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30369. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30370. */
  30371. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30372. var options = {
  30373. width: width,
  30374. height: height,
  30375. subdivisions: subdivisions,
  30376. updatable: updatable
  30377. };
  30378. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30379. };
  30380. /**
  30381. * Creates a tiled ground mesh.
  30382. * Please consider using the same method from the MeshBuilder class instead.
  30383. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30384. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30385. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30386. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30387. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30388. * numbers of subdivisions on the ground width and height of each tile.
  30389. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30390. */
  30391. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30392. var options = {
  30393. xmin: xmin,
  30394. zmin: zmin,
  30395. xmax: xmax,
  30396. zmax: zmax,
  30397. subdivisions: subdivisions,
  30398. precision: precision,
  30399. updatable: updatable
  30400. };
  30401. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30402. };
  30403. /**
  30404. * Creates a ground mesh from a height map.
  30405. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30406. * Please consider using the same method from the MeshBuilder class instead.
  30407. * The parameter `url` sets the URL of the height map image resource.
  30408. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30409. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30410. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30411. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30412. * 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).
  30413. * This function is passed the newly built mesh :
  30414. * ```javascript
  30415. * function(mesh) { // do things
  30416. * return; }
  30417. * ```
  30418. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30419. */
  30420. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30421. var options = {
  30422. width: width,
  30423. height: height,
  30424. subdivisions: subdivisions,
  30425. minHeight: minHeight,
  30426. maxHeight: maxHeight,
  30427. updatable: updatable,
  30428. onReady: onReady
  30429. };
  30430. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30431. };
  30432. /**
  30433. * Creates a tube mesh.
  30434. * 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.
  30435. * Please consider using the same method from the MeshBuilder class instead.
  30436. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30437. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30438. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30439. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30440. * 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.
  30441. * It must return a radius value (positive float) :
  30442. * ```javascript
  30443. * var radiusFunction = function(i, distance) {
  30444. * // do things
  30445. * return radius; }
  30446. * ```
  30447. * 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
  30448. * 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
  30449. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30450. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30451. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30452. */
  30453. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30454. var options = {
  30455. path: path,
  30456. radius: radius,
  30457. tessellation: tessellation,
  30458. radiusFunction: radiusFunction,
  30459. arc: 1,
  30460. cap: cap,
  30461. updatable: updatable,
  30462. sideOrientation: sideOrientation,
  30463. instance: instance
  30464. };
  30465. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30466. };
  30467. /**
  30468. * Creates a polyhedron mesh.
  30469. * Please consider using the same method from the MeshBuilder class instead.
  30470. * 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
  30471. * to choose the wanted type.
  30472. * The parameter `size` (positive float, default 1) sets the polygon size.
  30473. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30474. * 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`.
  30475. * 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
  30476. * 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)`).
  30477. * 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
  30478. * 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.
  30479. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30480. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30481. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30482. */
  30483. Mesh.CreatePolyhedron = function (name, options, scene) {
  30484. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30485. };
  30486. /**
  30487. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30488. * Please consider using the same method from the MeshBuilder class instead.
  30489. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30490. * 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`).
  30491. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30492. * 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.
  30493. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30494. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30495. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30496. */
  30497. Mesh.CreateIcoSphere = function (name, options, scene) {
  30498. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30499. };
  30500. /**
  30501. * Creates a decal mesh.
  30502. * Please consider using the same method from the MeshBuilder class instead.
  30503. * 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.
  30504. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30505. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30506. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30507. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30508. */
  30509. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30510. var options = {
  30511. position: position,
  30512. normal: normal,
  30513. size: size,
  30514. angle: angle
  30515. };
  30516. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30517. };
  30518. // Skeletons
  30519. /**
  30520. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30521. */
  30522. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30523. if (!this._sourcePositions) {
  30524. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30525. if (!source) {
  30526. return this._sourcePositions;
  30527. }
  30528. this._sourcePositions = new Float32Array(source);
  30529. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30530. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30531. }
  30532. }
  30533. return this._sourcePositions;
  30534. };
  30535. /**
  30536. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30537. */
  30538. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30539. if (!this._sourceNormals) {
  30540. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30541. if (!source) {
  30542. return this._sourceNormals;
  30543. }
  30544. this._sourceNormals = new Float32Array(source);
  30545. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30546. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30547. }
  30548. }
  30549. return this._sourceNormals;
  30550. };
  30551. /**
  30552. * Updates the vertex buffer by applying transformation from the bones.
  30553. * Returns the Mesh.
  30554. *
  30555. * @param {skeleton} skeleton to apply
  30556. */
  30557. Mesh.prototype.applySkeleton = function (skeleton) {
  30558. if (!this.geometry) {
  30559. return this;
  30560. }
  30561. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30562. return this;
  30563. }
  30564. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30565. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30566. return this;
  30567. }
  30568. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30569. return this;
  30570. }
  30571. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30572. return this;
  30573. }
  30574. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30575. return this;
  30576. }
  30577. if (!this._sourcePositions) {
  30578. var submeshes = this.subMeshes.slice();
  30579. this.setPositionsForCPUSkinning();
  30580. this.subMeshes = submeshes;
  30581. }
  30582. if (!this._sourceNormals) {
  30583. this.setNormalsForCPUSkinning();
  30584. }
  30585. // positionsData checks for not being Float32Array will only pass at most once
  30586. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30587. if (!positionsData) {
  30588. return this;
  30589. }
  30590. if (!(positionsData instanceof Float32Array)) {
  30591. positionsData = new Float32Array(positionsData);
  30592. }
  30593. // normalsData checks for not being Float32Array will only pass at most once
  30594. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30595. if (!normalsData) {
  30596. return this;
  30597. }
  30598. if (!(normalsData instanceof Float32Array)) {
  30599. normalsData = new Float32Array(normalsData);
  30600. }
  30601. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30602. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30603. if (!matricesWeightsData || !matricesIndicesData) {
  30604. return this;
  30605. }
  30606. var needExtras = this.numBoneInfluencers > 4;
  30607. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30608. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30609. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30610. var tempVector3 = BABYLON.Vector3.Zero();
  30611. var finalMatrix = new BABYLON.Matrix();
  30612. var tempMatrix = new BABYLON.Matrix();
  30613. var matWeightIdx = 0;
  30614. var inf;
  30615. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30616. var weight;
  30617. for (inf = 0; inf < 4; inf++) {
  30618. weight = matricesWeightsData[matWeightIdx + inf];
  30619. if (weight > 0) {
  30620. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30621. finalMatrix.addToSelf(tempMatrix);
  30622. }
  30623. else
  30624. break;
  30625. }
  30626. if (needExtras) {
  30627. for (inf = 0; inf < 4; inf++) {
  30628. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30629. if (weight > 0) {
  30630. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30631. finalMatrix.addToSelf(tempMatrix);
  30632. }
  30633. else
  30634. break;
  30635. }
  30636. }
  30637. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30638. tempVector3.toArray(positionsData, index);
  30639. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30640. tempVector3.toArray(normalsData, index);
  30641. finalMatrix.reset();
  30642. }
  30643. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30644. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30645. return this;
  30646. };
  30647. // Tools
  30648. /**
  30649. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30650. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30651. */
  30652. Mesh.MinMax = function (meshes) {
  30653. var minVector = null;
  30654. var maxVector = null;
  30655. meshes.forEach(function (mesh, index, array) {
  30656. var boundingInfo = mesh.getBoundingInfo();
  30657. var boundingBox = boundingInfo.boundingBox;
  30658. if (!minVector || !maxVector) {
  30659. minVector = boundingBox.minimumWorld;
  30660. maxVector = boundingBox.maximumWorld;
  30661. }
  30662. else {
  30663. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30664. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30665. }
  30666. });
  30667. if (!minVector || !maxVector) {
  30668. return {
  30669. min: BABYLON.Vector3.Zero(),
  30670. max: BABYLON.Vector3.Zero()
  30671. };
  30672. }
  30673. return {
  30674. min: minVector,
  30675. max: maxVector
  30676. };
  30677. };
  30678. /**
  30679. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30680. */
  30681. Mesh.Center = function (meshesOrMinMaxVector) {
  30682. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30683. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30684. };
  30685. /**
  30686. * Merge the array of meshes into a single mesh for performance reasons.
  30687. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30688. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30689. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30690. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30691. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30692. */
  30693. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30694. if (disposeSource === void 0) { disposeSource = true; }
  30695. var index;
  30696. if (!allow32BitsIndices) {
  30697. var totalVertices = 0;
  30698. // Counting vertices
  30699. for (index = 0; index < meshes.length; index++) {
  30700. if (meshes[index]) {
  30701. totalVertices += meshes[index].getTotalVertices();
  30702. if (totalVertices > 65536) {
  30703. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30704. return null;
  30705. }
  30706. }
  30707. }
  30708. }
  30709. // Merge
  30710. var vertexData = null;
  30711. var otherVertexData;
  30712. var indiceArray = new Array();
  30713. var source = null;
  30714. for (index = 0; index < meshes.length; index++) {
  30715. if (meshes[index]) {
  30716. meshes[index].computeWorldMatrix(true);
  30717. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30718. otherVertexData.transform(meshes[index].getWorldMatrix());
  30719. if (vertexData) {
  30720. vertexData.merge(otherVertexData);
  30721. }
  30722. else {
  30723. vertexData = otherVertexData;
  30724. source = meshes[index];
  30725. }
  30726. if (subdivideWithSubMeshes) {
  30727. indiceArray.push(meshes[index].getTotalIndices());
  30728. }
  30729. }
  30730. }
  30731. source = source;
  30732. if (!meshSubclass) {
  30733. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30734. }
  30735. vertexData.applyToMesh(meshSubclass);
  30736. // Setting properties
  30737. meshSubclass.material = source.material;
  30738. meshSubclass.checkCollisions = source.checkCollisions;
  30739. // Cleaning
  30740. if (disposeSource) {
  30741. for (index = 0; index < meshes.length; index++) {
  30742. if (meshes[index]) {
  30743. meshes[index].dispose();
  30744. }
  30745. }
  30746. }
  30747. // Subdivide
  30748. if (subdivideWithSubMeshes) {
  30749. //-- Suppresions du submesh global
  30750. meshSubclass.releaseSubMeshes();
  30751. index = 0;
  30752. var offset = 0;
  30753. //-- aplique la subdivision en fonction du tableau d'indices
  30754. while (index < indiceArray.length) {
  30755. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30756. offset += indiceArray[index];
  30757. index++;
  30758. }
  30759. }
  30760. return meshSubclass;
  30761. };
  30762. // Consts
  30763. Mesh._FRONTSIDE = 0;
  30764. Mesh._BACKSIDE = 1;
  30765. Mesh._DOUBLESIDE = 2;
  30766. Mesh._DEFAULTSIDE = 0;
  30767. Mesh._NO_CAP = 0;
  30768. Mesh._CAP_START = 1;
  30769. Mesh._CAP_END = 2;
  30770. Mesh._CAP_ALL = 3;
  30771. return Mesh;
  30772. }(BABYLON.AbstractMesh));
  30773. BABYLON.Mesh = Mesh;
  30774. })(BABYLON || (BABYLON = {}));
  30775. //# sourceMappingURL=babylon.mesh.js.map
  30776. "use strict";
  30777. var BABYLON;
  30778. (function (BABYLON) {
  30779. var BaseSubMesh = /** @class */ (function () {
  30780. function BaseSubMesh() {
  30781. }
  30782. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30783. get: function () {
  30784. return this._materialEffect;
  30785. },
  30786. enumerable: true,
  30787. configurable: true
  30788. });
  30789. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30790. if (defines === void 0) { defines = null; }
  30791. if (this._materialEffect === effect) {
  30792. if (!effect) {
  30793. this._materialDefines = null;
  30794. }
  30795. return;
  30796. }
  30797. this._materialDefines = defines;
  30798. this._materialEffect = effect;
  30799. };
  30800. return BaseSubMesh;
  30801. }());
  30802. BABYLON.BaseSubMesh = BaseSubMesh;
  30803. var SubMesh = /** @class */ (function (_super) {
  30804. __extends(SubMesh, _super);
  30805. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30806. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30807. var _this = _super.call(this) || this;
  30808. _this.materialIndex = materialIndex;
  30809. _this.verticesStart = verticesStart;
  30810. _this.verticesCount = verticesCount;
  30811. _this.indexStart = indexStart;
  30812. _this.indexCount = indexCount;
  30813. _this._renderId = 0;
  30814. _this._mesh = mesh;
  30815. _this._renderingMesh = renderingMesh || mesh;
  30816. mesh.subMeshes.push(_this);
  30817. _this._trianglePlanes = [];
  30818. _this._id = mesh.subMeshes.length - 1;
  30819. if (createBoundingBox) {
  30820. _this.refreshBoundingInfo();
  30821. mesh.computeWorldMatrix(true);
  30822. }
  30823. return _this;
  30824. }
  30825. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30826. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30827. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30828. };
  30829. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30830. get: function () {
  30831. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30832. },
  30833. enumerable: true,
  30834. configurable: true
  30835. });
  30836. /**
  30837. * Returns the submesh BoudingInfo object.
  30838. */
  30839. SubMesh.prototype.getBoundingInfo = function () {
  30840. if (this.IsGlobal) {
  30841. return this._mesh.getBoundingInfo();
  30842. }
  30843. return this._boundingInfo;
  30844. };
  30845. /**
  30846. * Sets the submesh BoundingInfo.
  30847. * Return the SubMesh.
  30848. */
  30849. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30850. this._boundingInfo = boundingInfo;
  30851. return this;
  30852. };
  30853. /**
  30854. * Returns the mesh of the current submesh.
  30855. */
  30856. SubMesh.prototype.getMesh = function () {
  30857. return this._mesh;
  30858. };
  30859. /**
  30860. * Returns the rendering mesh of the submesh.
  30861. */
  30862. SubMesh.prototype.getRenderingMesh = function () {
  30863. return this._renderingMesh;
  30864. };
  30865. /**
  30866. * Returns the submesh material.
  30867. */
  30868. SubMesh.prototype.getMaterial = function () {
  30869. var rootMaterial = this._renderingMesh.material;
  30870. if (rootMaterial === null || rootMaterial === undefined) {
  30871. return this._mesh.getScene().defaultMaterial;
  30872. }
  30873. else if (rootMaterial.getSubMaterial) {
  30874. var multiMaterial = rootMaterial;
  30875. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30876. if (this._currentMaterial !== effectiveMaterial) {
  30877. this._currentMaterial = effectiveMaterial;
  30878. this._materialDefines = null;
  30879. }
  30880. return effectiveMaterial;
  30881. }
  30882. return rootMaterial;
  30883. };
  30884. // Methods
  30885. /**
  30886. * Sets a new updated BoundingInfo object to the submesh.
  30887. * Returns the SubMesh.
  30888. */
  30889. SubMesh.prototype.refreshBoundingInfo = function () {
  30890. this._lastColliderWorldVertices = null;
  30891. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30892. return this;
  30893. }
  30894. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30895. if (!data) {
  30896. this._boundingInfo = this._mesh.getBoundingInfo();
  30897. return this;
  30898. }
  30899. var indices = this._renderingMesh.getIndices();
  30900. var extend;
  30901. //is this the only submesh?
  30902. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30903. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30904. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30905. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30906. }
  30907. else {
  30908. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30909. }
  30910. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30911. return this;
  30912. };
  30913. SubMesh.prototype._checkCollision = function (collider) {
  30914. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30915. return boundingInfo._checkCollision(collider);
  30916. };
  30917. /**
  30918. * Updates the submesh BoundingInfo.
  30919. * Returns the Submesh.
  30920. */
  30921. SubMesh.prototype.updateBoundingInfo = function (world) {
  30922. var boundingInfo = this.getBoundingInfo();
  30923. if (!boundingInfo) {
  30924. this.refreshBoundingInfo();
  30925. boundingInfo = this.getBoundingInfo();
  30926. }
  30927. boundingInfo.update(world);
  30928. return this;
  30929. };
  30930. /**
  30931. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30932. * Boolean returned.
  30933. */
  30934. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30935. var boundingInfo = this.getBoundingInfo();
  30936. if (!boundingInfo) {
  30937. return false;
  30938. }
  30939. return boundingInfo.isInFrustum(frustumPlanes);
  30940. };
  30941. /**
  30942. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30943. * Boolean returned.
  30944. */
  30945. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30946. var boundingInfo = this.getBoundingInfo();
  30947. if (!boundingInfo) {
  30948. return false;
  30949. }
  30950. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30951. };
  30952. /**
  30953. * Renders the submesh.
  30954. * Returns it.
  30955. */
  30956. SubMesh.prototype.render = function (enableAlphaMode) {
  30957. this._renderingMesh.render(this, enableAlphaMode);
  30958. return this;
  30959. };
  30960. /**
  30961. * Returns a new Index Buffer.
  30962. * Type returned : WebGLBuffer.
  30963. */
  30964. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30965. if (!this._linesIndexBuffer) {
  30966. var linesIndices = [];
  30967. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30968. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30969. }
  30970. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30971. this.linesIndexCount = linesIndices.length;
  30972. }
  30973. return this._linesIndexBuffer;
  30974. };
  30975. /**
  30976. * True is the passed Ray intersects the submesh bounding box.
  30977. * Boolean returned.
  30978. */
  30979. SubMesh.prototype.canIntersects = function (ray) {
  30980. var boundingInfo = this.getBoundingInfo();
  30981. if (!boundingInfo) {
  30982. return false;
  30983. }
  30984. return ray.intersectsBox(boundingInfo.boundingBox);
  30985. };
  30986. /**
  30987. * Returns an object IntersectionInfo.
  30988. */
  30989. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30990. var intersectInfo = null;
  30991. var material = this.getMaterial();
  30992. if (!material) {
  30993. return null;
  30994. }
  30995. switch (material.fillMode) {
  30996. case BABYLON.Material.PointListDrawMode:
  30997. case BABYLON.Material.LineListDrawMode:
  30998. case BABYLON.Material.LineLoopDrawMode:
  30999. case BABYLON.Material.LineStripDrawMode:
  31000. case BABYLON.Material.TriangleFanDrawMode:
  31001. case BABYLON.Material.TriangleStripDrawMode:
  31002. return null;
  31003. }
  31004. // LineMesh first as it's also a Mesh...
  31005. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  31006. var lineMesh = this._mesh;
  31007. // Line test
  31008. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  31009. var p0 = positions[indices[index]];
  31010. var p1 = positions[indices[index + 1]];
  31011. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  31012. if (length < 0) {
  31013. continue;
  31014. }
  31015. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  31016. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  31017. if (fastCheck) {
  31018. break;
  31019. }
  31020. }
  31021. }
  31022. }
  31023. else {
  31024. // Triangles test
  31025. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31026. var p0 = positions[indices[index]];
  31027. var p1 = positions[indices[index + 1]];
  31028. var p2 = positions[indices[index + 2]];
  31029. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31030. if (currentIntersectInfo) {
  31031. if (currentIntersectInfo.distance < 0) {
  31032. continue;
  31033. }
  31034. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31035. intersectInfo = currentIntersectInfo;
  31036. intersectInfo.faceId = index / 3;
  31037. if (fastCheck) {
  31038. break;
  31039. }
  31040. }
  31041. }
  31042. }
  31043. }
  31044. return intersectInfo;
  31045. };
  31046. SubMesh.prototype._rebuild = function () {
  31047. if (this._linesIndexBuffer) {
  31048. this._linesIndexBuffer = null;
  31049. }
  31050. };
  31051. // Clone
  31052. /**
  31053. * Creates a new Submesh from the passed Mesh.
  31054. */
  31055. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31056. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31057. if (!this.IsGlobal) {
  31058. var boundingInfo = this.getBoundingInfo();
  31059. if (!boundingInfo) {
  31060. return result;
  31061. }
  31062. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31063. }
  31064. return result;
  31065. };
  31066. // Dispose
  31067. /**
  31068. * Disposes the Submesh.
  31069. * Returns nothing.
  31070. */
  31071. SubMesh.prototype.dispose = function () {
  31072. if (this._linesIndexBuffer) {
  31073. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31074. this._linesIndexBuffer = null;
  31075. }
  31076. // Remove from mesh
  31077. var index = this._mesh.subMeshes.indexOf(this);
  31078. this._mesh.subMeshes.splice(index, 1);
  31079. };
  31080. // Statics
  31081. /**
  31082. * Creates a new Submesh from the passed parameters :
  31083. * - materialIndex (integer) : the index of the main mesh material.
  31084. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31085. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31086. * - mesh (Mesh) : the main mesh to create the submesh from.
  31087. * - renderingMesh (optional Mesh) : rendering mesh.
  31088. */
  31089. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31090. var minVertexIndex = Number.MAX_VALUE;
  31091. var maxVertexIndex = -Number.MAX_VALUE;
  31092. renderingMesh = (renderingMesh || mesh);
  31093. var indices = renderingMesh.getIndices();
  31094. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31095. var vertexIndex = indices[index];
  31096. if (vertexIndex < minVertexIndex)
  31097. minVertexIndex = vertexIndex;
  31098. if (vertexIndex > maxVertexIndex)
  31099. maxVertexIndex = vertexIndex;
  31100. }
  31101. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31102. };
  31103. return SubMesh;
  31104. }(BaseSubMesh));
  31105. BABYLON.SubMesh = SubMesh;
  31106. })(BABYLON || (BABYLON = {}));
  31107. //# sourceMappingURL=babylon.subMesh.js.map
  31108. "use strict";
  31109. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31110. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31111. s = arguments[i];
  31112. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31113. t[p] = s[p];
  31114. }
  31115. return t;
  31116. };
  31117. var BABYLON;
  31118. (function (BABYLON) {
  31119. /**
  31120. * Manages the defines for the Material.
  31121. */
  31122. var MaterialDefines = /** @class */ (function () {
  31123. function MaterialDefines() {
  31124. this._isDirty = true;
  31125. this._areLightsDirty = true;
  31126. this._areAttributesDirty = true;
  31127. this._areTexturesDirty = true;
  31128. this._areFresnelDirty = true;
  31129. this._areMiscDirty = true;
  31130. this._areImageProcessingDirty = true;
  31131. this._normals = false;
  31132. this._uvs = false;
  31133. this._needNormals = false;
  31134. this._needUVs = false;
  31135. }
  31136. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31137. /**
  31138. * Specifies if the material needs to be re-calculated.
  31139. */
  31140. get: function () {
  31141. return this._isDirty;
  31142. },
  31143. enumerable: true,
  31144. configurable: true
  31145. });
  31146. /**
  31147. * Marks the material to indicate that it has been re-calculated.
  31148. */
  31149. MaterialDefines.prototype.markAsProcessed = function () {
  31150. this._isDirty = false;
  31151. this._areAttributesDirty = false;
  31152. this._areTexturesDirty = false;
  31153. this._areFresnelDirty = false;
  31154. this._areLightsDirty = false;
  31155. this._areMiscDirty = false;
  31156. this._areImageProcessingDirty = false;
  31157. };
  31158. /**
  31159. * Marks the material to indicate that it needs to be re-calculated.
  31160. */
  31161. MaterialDefines.prototype.markAsUnprocessed = function () {
  31162. this._isDirty = true;
  31163. };
  31164. /**
  31165. * Marks the material to indicate all of its defines need to be re-calculated.
  31166. */
  31167. MaterialDefines.prototype.markAllAsDirty = function () {
  31168. this._areTexturesDirty = true;
  31169. this._areAttributesDirty = true;
  31170. this._areLightsDirty = true;
  31171. this._areFresnelDirty = true;
  31172. this._areMiscDirty = true;
  31173. this._areImageProcessingDirty = true;
  31174. this._isDirty = true;
  31175. };
  31176. /**
  31177. * Marks the material to indicate that image processing needs to be re-calculated.
  31178. */
  31179. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31180. this._areImageProcessingDirty = true;
  31181. this._isDirty = true;
  31182. };
  31183. /**
  31184. * Marks the material to indicate the lights need to be re-calculated.
  31185. */
  31186. MaterialDefines.prototype.markAsLightDirty = function () {
  31187. this._areLightsDirty = true;
  31188. this._isDirty = true;
  31189. };
  31190. /**
  31191. * Marks the attribute state as changed.
  31192. */
  31193. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31194. this._areAttributesDirty = true;
  31195. this._isDirty = true;
  31196. };
  31197. /**
  31198. * Marks the texture state as changed.
  31199. */
  31200. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31201. this._areTexturesDirty = true;
  31202. this._isDirty = true;
  31203. };
  31204. /**
  31205. * Marks the fresnel state as changed.
  31206. */
  31207. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31208. this._areFresnelDirty = true;
  31209. this._isDirty = true;
  31210. };
  31211. /**
  31212. * Marks the misc state as changed.
  31213. */
  31214. MaterialDefines.prototype.markAsMiscDirty = function () {
  31215. this._areMiscDirty = true;
  31216. this._isDirty = true;
  31217. };
  31218. /**
  31219. * Rebuilds the material defines.
  31220. */
  31221. MaterialDefines.prototype.rebuild = function () {
  31222. if (this._keys) {
  31223. delete this._keys;
  31224. }
  31225. this._keys = [];
  31226. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31227. var key = _a[_i];
  31228. if (key[0] === "_") {
  31229. continue;
  31230. }
  31231. this._keys.push(key);
  31232. }
  31233. };
  31234. /**
  31235. * Specifies if two material defines are equal.
  31236. * @param other - A material define instance to compare to.
  31237. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31238. */
  31239. MaterialDefines.prototype.isEqual = function (other) {
  31240. if (this._keys.length !== other._keys.length) {
  31241. return false;
  31242. }
  31243. for (var index = 0; index < this._keys.length; index++) {
  31244. var prop = this._keys[index];
  31245. if (this[prop] !== other[prop]) {
  31246. return false;
  31247. }
  31248. }
  31249. return true;
  31250. };
  31251. /**
  31252. * Clones this instance's defines to another instance.
  31253. * @param other - material defines to clone values to.
  31254. */
  31255. MaterialDefines.prototype.cloneTo = function (other) {
  31256. if (this._keys.length !== other._keys.length) {
  31257. other._keys = this._keys.slice(0);
  31258. }
  31259. for (var index = 0; index < this._keys.length; index++) {
  31260. var prop = this._keys[index];
  31261. other[prop] = this[prop];
  31262. }
  31263. };
  31264. /**
  31265. * Resets the material define values.
  31266. */
  31267. MaterialDefines.prototype.reset = function () {
  31268. for (var index = 0; index < this._keys.length; index++) {
  31269. var prop = this._keys[index];
  31270. var type = typeof this[prop];
  31271. switch (type) {
  31272. case "number":
  31273. this[prop] = 0;
  31274. break;
  31275. case "string":
  31276. this[prop] = "";
  31277. break;
  31278. default:
  31279. this[prop] = false;
  31280. break;
  31281. }
  31282. }
  31283. };
  31284. /**
  31285. * Converts the material define values to a string.
  31286. * @returns - String of material define information.
  31287. */
  31288. MaterialDefines.prototype.toString = function () {
  31289. var result = "";
  31290. for (var index = 0; index < this._keys.length; index++) {
  31291. var prop = this._keys[index];
  31292. var value = this[prop];
  31293. var type = typeof value;
  31294. switch (type) {
  31295. case "number":
  31296. case "string":
  31297. result += "#define " + prop + " " + value + "\n";
  31298. break;
  31299. default:
  31300. if (value) {
  31301. result += "#define " + prop + "\n";
  31302. }
  31303. break;
  31304. }
  31305. }
  31306. return result;
  31307. };
  31308. return MaterialDefines;
  31309. }());
  31310. BABYLON.MaterialDefines = MaterialDefines;
  31311. /**
  31312. * This offers the main features of a material in BJS.
  31313. */
  31314. var Material = /** @class */ (function () {
  31315. /**
  31316. * Creates a material instance.
  31317. * @param name - The name of the material.
  31318. * @param scene - The BJS scene to reference.
  31319. * @param doNotAdd - Specifies if the material should be added to the scene.
  31320. */
  31321. function Material(name, scene, doNotAdd) {
  31322. /**
  31323. * Specifies if the ready state should be checked on each call.
  31324. */
  31325. this.checkReadyOnEveryCall = false;
  31326. /**
  31327. * Specifies if the ready state should be checked once.
  31328. */
  31329. this.checkReadyOnlyOnce = false;
  31330. /**
  31331. * The state of the material.
  31332. */
  31333. this.state = "";
  31334. /**
  31335. * The alpha value of the material.
  31336. */
  31337. this._alpha = 1.0;
  31338. /**
  31339. * Specifies if back face culling is enabled.
  31340. */
  31341. this._backFaceCulling = true;
  31342. /**
  31343. * Specifies if the material should be serialized.
  31344. */
  31345. this.doNotSerialize = false;
  31346. /**
  31347. * Specifies if the effect should be stored on sub meshes.
  31348. */
  31349. this.storeEffectOnSubMeshes = false;
  31350. /**
  31351. * An event triggered when the material is disposed.
  31352. * @type {BABYLON.Observable}
  31353. */
  31354. this.onDisposeObservable = new BABYLON.Observable();
  31355. /**
  31356. * An event triggered when the material is bound.
  31357. * @type {BABYLON.Observable}
  31358. */
  31359. this.onBindObservable = new BABYLON.Observable();
  31360. /**
  31361. * An event triggered when the material is unbound.
  31362. * @type {BABYLON.Observable}
  31363. */
  31364. this.onUnBindObservable = new BABYLON.Observable();
  31365. /**
  31366. * Stores the value of the alpha mode.
  31367. */
  31368. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31369. /**
  31370. * Stores the state of the need depth pre-pass value.
  31371. */
  31372. this._needDepthPrePass = false;
  31373. /**
  31374. * Specifies if depth writing should be disabled.
  31375. */
  31376. this.disableDepthWrite = false;
  31377. /**
  31378. * Specifies if depth writing should be forced.
  31379. */
  31380. this.forceDepthWrite = false;
  31381. /**
  31382. * Specifies if there should be a separate pass for culling.
  31383. */
  31384. this.separateCullingPass = false;
  31385. /**
  31386. * Stores the state specifing if fog should be enabled.
  31387. */
  31388. this._fogEnabled = true;
  31389. /**
  31390. * Stores the size of points.
  31391. */
  31392. this.pointSize = 1.0;
  31393. /**
  31394. * Stores the z offset value.
  31395. */
  31396. this.zOffset = 0;
  31397. /**
  31398. * Specifies if the material was previously ready.
  31399. */
  31400. this._wasPreviouslyReady = false;
  31401. /**
  31402. * Stores the fill mode state.
  31403. */
  31404. this._fillMode = Material.TriangleFillMode;
  31405. this.name = name;
  31406. this.id = name || BABYLON.Tools.RandomId();
  31407. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31408. if (this._scene.useRightHandedSystem) {
  31409. this.sideOrientation = Material.ClockWiseSideOrientation;
  31410. }
  31411. else {
  31412. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31413. }
  31414. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31415. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31416. if (!doNotAdd) {
  31417. this._scene.materials.push(this);
  31418. }
  31419. }
  31420. Object.defineProperty(Material, "TriangleFillMode", {
  31421. /**
  31422. * Returns the triangle fill mode.
  31423. */
  31424. get: function () {
  31425. return Material._TriangleFillMode;
  31426. },
  31427. enumerable: true,
  31428. configurable: true
  31429. });
  31430. Object.defineProperty(Material, "WireFrameFillMode", {
  31431. /**
  31432. * Returns the wireframe mode.
  31433. */
  31434. get: function () {
  31435. return Material._WireFrameFillMode;
  31436. },
  31437. enumerable: true,
  31438. configurable: true
  31439. });
  31440. Object.defineProperty(Material, "PointFillMode", {
  31441. /**
  31442. * Returns the point fill mode.
  31443. */
  31444. get: function () {
  31445. return Material._PointFillMode;
  31446. },
  31447. enumerable: true,
  31448. configurable: true
  31449. });
  31450. Object.defineProperty(Material, "PointListDrawMode", {
  31451. /**
  31452. * Returns the point list draw mode.
  31453. */
  31454. get: function () {
  31455. return Material._PointListDrawMode;
  31456. },
  31457. enumerable: true,
  31458. configurable: true
  31459. });
  31460. Object.defineProperty(Material, "LineListDrawMode", {
  31461. /**
  31462. * Returns the line list draw mode.
  31463. */
  31464. get: function () {
  31465. return Material._LineListDrawMode;
  31466. },
  31467. enumerable: true,
  31468. configurable: true
  31469. });
  31470. Object.defineProperty(Material, "LineLoopDrawMode", {
  31471. /**
  31472. * Returns the line loop draw mode.
  31473. */
  31474. get: function () {
  31475. return Material._LineLoopDrawMode;
  31476. },
  31477. enumerable: true,
  31478. configurable: true
  31479. });
  31480. Object.defineProperty(Material, "LineStripDrawMode", {
  31481. /**
  31482. * Returns the line strip draw mode.
  31483. */
  31484. get: function () {
  31485. return Material._LineStripDrawMode;
  31486. },
  31487. enumerable: true,
  31488. configurable: true
  31489. });
  31490. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31491. /**
  31492. * Returns the triangle strip draw mode.
  31493. */
  31494. get: function () {
  31495. return Material._TriangleStripDrawMode;
  31496. },
  31497. enumerable: true,
  31498. configurable: true
  31499. });
  31500. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31501. /**
  31502. * Returns the triangle fan draw mode.
  31503. */
  31504. get: function () {
  31505. return Material._TriangleFanDrawMode;
  31506. },
  31507. enumerable: true,
  31508. configurable: true
  31509. });
  31510. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31511. /**
  31512. * Returns the clock-wise side orientation.
  31513. */
  31514. get: function () {
  31515. return Material._ClockWiseSideOrientation;
  31516. },
  31517. enumerable: true,
  31518. configurable: true
  31519. });
  31520. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31521. /**
  31522. * Returns the counter clock-wise side orientation.
  31523. */
  31524. get: function () {
  31525. return Material._CounterClockWiseSideOrientation;
  31526. },
  31527. enumerable: true,
  31528. configurable: true
  31529. });
  31530. Object.defineProperty(Material, "TextureDirtyFlag", {
  31531. /**
  31532. * Returns the dirty texture flag value.
  31533. */
  31534. get: function () {
  31535. return Material._TextureDirtyFlag;
  31536. },
  31537. enumerable: true,
  31538. configurable: true
  31539. });
  31540. Object.defineProperty(Material, "LightDirtyFlag", {
  31541. /**
  31542. * Returns the dirty light flag value.
  31543. */
  31544. get: function () {
  31545. return Material._LightDirtyFlag;
  31546. },
  31547. enumerable: true,
  31548. configurable: true
  31549. });
  31550. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31551. /**
  31552. * Returns the dirty fresnel flag value.
  31553. */
  31554. get: function () {
  31555. return Material._FresnelDirtyFlag;
  31556. },
  31557. enumerable: true,
  31558. configurable: true
  31559. });
  31560. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31561. /**
  31562. * Returns the dirty attributes flag value.
  31563. */
  31564. get: function () {
  31565. return Material._AttributesDirtyFlag;
  31566. },
  31567. enumerable: true,
  31568. configurable: true
  31569. });
  31570. Object.defineProperty(Material, "MiscDirtyFlag", {
  31571. /**
  31572. * Returns the dirty misc flag value.
  31573. */
  31574. get: function () {
  31575. return Material._MiscDirtyFlag;
  31576. },
  31577. enumerable: true,
  31578. configurable: true
  31579. });
  31580. Object.defineProperty(Material.prototype, "alpha", {
  31581. /**
  31582. * Gets the alpha value of the material.
  31583. */
  31584. get: function () {
  31585. return this._alpha;
  31586. },
  31587. /**
  31588. * Sets the alpha value of the material.
  31589. */
  31590. set: function (value) {
  31591. if (this._alpha === value) {
  31592. return;
  31593. }
  31594. this._alpha = value;
  31595. this.markAsDirty(Material.MiscDirtyFlag);
  31596. },
  31597. enumerable: true,
  31598. configurable: true
  31599. });
  31600. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31601. /**
  31602. * Gets the back-face culling state.
  31603. */
  31604. get: function () {
  31605. return this._backFaceCulling;
  31606. },
  31607. /**
  31608. * Sets the back-face culling state.
  31609. */
  31610. set: function (value) {
  31611. if (this._backFaceCulling === value) {
  31612. return;
  31613. }
  31614. this._backFaceCulling = value;
  31615. this.markAsDirty(Material.TextureDirtyFlag);
  31616. },
  31617. enumerable: true,
  31618. configurable: true
  31619. });
  31620. Object.defineProperty(Material.prototype, "onDispose", {
  31621. /**
  31622. * Called during a dispose event.
  31623. */
  31624. set: function (callback) {
  31625. if (this._onDisposeObserver) {
  31626. this.onDisposeObservable.remove(this._onDisposeObserver);
  31627. }
  31628. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31629. },
  31630. enumerable: true,
  31631. configurable: true
  31632. });
  31633. Object.defineProperty(Material.prototype, "onBind", {
  31634. /**
  31635. * Called during a bind event.
  31636. */
  31637. set: function (callback) {
  31638. if (this._onBindObserver) {
  31639. this.onBindObservable.remove(this._onBindObserver);
  31640. }
  31641. this._onBindObserver = this.onBindObservable.add(callback);
  31642. },
  31643. enumerable: true,
  31644. configurable: true
  31645. });
  31646. Object.defineProperty(Material.prototype, "alphaMode", {
  31647. /**
  31648. * Gets the value of the alpha mode.
  31649. */
  31650. get: function () {
  31651. return this._alphaMode;
  31652. },
  31653. /**
  31654. * Sets the value of the alpha mode.
  31655. */
  31656. set: function (value) {
  31657. if (this._alphaMode === value) {
  31658. return;
  31659. }
  31660. this._alphaMode = value;
  31661. this.markAsDirty(Material.TextureDirtyFlag);
  31662. },
  31663. enumerable: true,
  31664. configurable: true
  31665. });
  31666. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31667. /**
  31668. * Gets the depth pre-pass value.
  31669. */
  31670. get: function () {
  31671. return this._needDepthPrePass;
  31672. },
  31673. /**
  31674. * Sets the need depth pre-pass value.
  31675. */
  31676. set: function (value) {
  31677. if (this._needDepthPrePass === value) {
  31678. return;
  31679. }
  31680. this._needDepthPrePass = value;
  31681. if (this._needDepthPrePass) {
  31682. this.checkReadyOnEveryCall = true;
  31683. }
  31684. },
  31685. enumerable: true,
  31686. configurable: true
  31687. });
  31688. Object.defineProperty(Material.prototype, "fogEnabled", {
  31689. /**
  31690. * Gets the value of the fog enabled state.
  31691. */
  31692. get: function () {
  31693. return this._fogEnabled;
  31694. },
  31695. /**
  31696. * Sets the state for enabling fog.
  31697. */
  31698. set: function (value) {
  31699. if (this._fogEnabled === value) {
  31700. return;
  31701. }
  31702. this._fogEnabled = value;
  31703. this.markAsDirty(Material.MiscDirtyFlag);
  31704. },
  31705. enumerable: true,
  31706. configurable: true
  31707. });
  31708. Object.defineProperty(Material.prototype, "wireframe", {
  31709. /**
  31710. * Gets a value specifying if wireframe mode is enabled.
  31711. */
  31712. get: function () {
  31713. switch (this._fillMode) {
  31714. case Material.WireFrameFillMode:
  31715. case Material.LineListDrawMode:
  31716. case Material.LineLoopDrawMode:
  31717. case Material.LineStripDrawMode:
  31718. return true;
  31719. }
  31720. return this._scene.forceWireframe;
  31721. },
  31722. /**
  31723. * Sets the state of wireframe mode.
  31724. */
  31725. set: function (value) {
  31726. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31727. },
  31728. enumerable: true,
  31729. configurable: true
  31730. });
  31731. Object.defineProperty(Material.prototype, "pointsCloud", {
  31732. /**
  31733. * Gets the value specifying if point clouds are enabled.
  31734. */
  31735. get: function () {
  31736. switch (this._fillMode) {
  31737. case Material.PointFillMode:
  31738. case Material.PointListDrawMode:
  31739. return true;
  31740. }
  31741. return this._scene.forcePointsCloud;
  31742. },
  31743. /**
  31744. * Sets the state of point cloud mode.
  31745. */
  31746. set: function (value) {
  31747. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31748. },
  31749. enumerable: true,
  31750. configurable: true
  31751. });
  31752. Object.defineProperty(Material.prototype, "fillMode", {
  31753. /**
  31754. * Gets the material fill mode.
  31755. */
  31756. get: function () {
  31757. return this._fillMode;
  31758. },
  31759. /**
  31760. * Sets the material fill mode.
  31761. */
  31762. set: function (value) {
  31763. if (this._fillMode === value) {
  31764. return;
  31765. }
  31766. this._fillMode = value;
  31767. this.markAsDirty(Material.MiscDirtyFlag);
  31768. },
  31769. enumerable: true,
  31770. configurable: true
  31771. });
  31772. /**
  31773. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31774. * subclasses should override adding information pertainent to themselves.
  31775. * @returns - String with material information.
  31776. */
  31777. Material.prototype.toString = function (fullDetails) {
  31778. var ret = "Name: " + this.name;
  31779. if (fullDetails) {
  31780. }
  31781. return ret;
  31782. };
  31783. /**
  31784. * Gets the class name of the material.
  31785. * @returns - String with the class name of the material.
  31786. */
  31787. Material.prototype.getClassName = function () {
  31788. return "Material";
  31789. };
  31790. Object.defineProperty(Material.prototype, "isFrozen", {
  31791. /**
  31792. * Specifies if updates for the material been locked.
  31793. */
  31794. get: function () {
  31795. return this.checkReadyOnlyOnce;
  31796. },
  31797. enumerable: true,
  31798. configurable: true
  31799. });
  31800. /**
  31801. * Locks updates for the material.
  31802. */
  31803. Material.prototype.freeze = function () {
  31804. this.checkReadyOnlyOnce = true;
  31805. };
  31806. /**
  31807. * Unlocks updates for the material.
  31808. */
  31809. Material.prototype.unfreeze = function () {
  31810. this.checkReadyOnlyOnce = false;
  31811. };
  31812. /**
  31813. * Specifies if the material is ready to be used.
  31814. * @param mesh - BJS mesh.
  31815. * @param useInstances - Specifies if instances should be used.
  31816. * @returns - Boolean indicating if the material is ready to be used.
  31817. */
  31818. Material.prototype.isReady = function (mesh, useInstances) {
  31819. return true;
  31820. };
  31821. /**
  31822. * Specifies that the submesh is ready to be used.
  31823. * @param mesh - BJS mesh.
  31824. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31825. * @param useInstances - Specifies that instances should be used.
  31826. * @returns - boolean indicating that the submesh is ready or not.
  31827. */
  31828. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31829. return false;
  31830. };
  31831. /**
  31832. * Returns the material effect.
  31833. * @returns - Nullable material effect.
  31834. */
  31835. Material.prototype.getEffect = function () {
  31836. return this._effect;
  31837. };
  31838. /**
  31839. * Returns the BJS scene.
  31840. * @returns - BJS Scene.
  31841. */
  31842. Material.prototype.getScene = function () {
  31843. return this._scene;
  31844. };
  31845. /**
  31846. * Specifies if the material will require alpha blending
  31847. * @returns - Boolean specifying if alpha blending is needed.
  31848. */
  31849. Material.prototype.needAlphaBlending = function () {
  31850. return (this.alpha < 1.0);
  31851. };
  31852. /**
  31853. * Specifies if the mesh will require alpha blending.
  31854. * @param mesh - BJS mesh.
  31855. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31856. */
  31857. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31858. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31859. };
  31860. /**
  31861. * Specifies if this material should be rendered in alpha test mode.
  31862. * @returns - Boolean specifying if an alpha test is needed.
  31863. */
  31864. Material.prototype.needAlphaTesting = function () {
  31865. return false;
  31866. };
  31867. /**
  31868. * Gets the texture used for the alpha test.
  31869. * @returns - Nullable alpha test texture.
  31870. */
  31871. Material.prototype.getAlphaTestTexture = function () {
  31872. return null;
  31873. };
  31874. /**
  31875. * Marks the material to indicate that it needs to be re-calculated.
  31876. */
  31877. Material.prototype.markDirty = function () {
  31878. this._wasPreviouslyReady = false;
  31879. };
  31880. Material.prototype._preBind = function (effect, overrideOrientation) {
  31881. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31882. var engine = this._scene.getEngine();
  31883. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31884. var reverse = orientation === Material.ClockWiseSideOrientation;
  31885. engine.enableEffect(effect ? effect : this._effect);
  31886. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31887. return reverse;
  31888. };
  31889. /**
  31890. * Binds the material to the mesh.
  31891. * @param world - World transformation matrix.
  31892. * @param mesh - Mesh to bind the material to.
  31893. */
  31894. Material.prototype.bind = function (world, mesh) {
  31895. };
  31896. /**
  31897. * Binds the submesh to the material.
  31898. * @param world - World transformation matrix.
  31899. * @param mesh - Mesh containing the submesh.
  31900. * @param subMesh - Submesh to bind the material to.
  31901. */
  31902. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31903. };
  31904. /**
  31905. * Binds the world matrix to the material.
  31906. * @param world - World transformation matrix.
  31907. */
  31908. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31909. };
  31910. /**
  31911. * Binds the scene's uniform buffer to the effect.
  31912. * @param effect - Effect to bind to the scene uniform buffer.
  31913. * @param sceneUbo - Scene uniform buffer.
  31914. */
  31915. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31916. sceneUbo.bindToEffect(effect, "Scene");
  31917. };
  31918. /**
  31919. * Binds the view matrix to the effect.
  31920. * @param effect - Effect to bind the view matrix to.
  31921. */
  31922. Material.prototype.bindView = function (effect) {
  31923. if (!this._useUBO) {
  31924. effect.setMatrix("view", this.getScene().getViewMatrix());
  31925. }
  31926. else {
  31927. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31928. }
  31929. };
  31930. /**
  31931. * Binds the view projection matrix to the effect.
  31932. * @param effect - Effect to bind the view projection matrix to.
  31933. */
  31934. Material.prototype.bindViewProjection = function (effect) {
  31935. if (!this._useUBO) {
  31936. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31937. }
  31938. else {
  31939. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31940. }
  31941. };
  31942. /**
  31943. * Specifies if material alpha testing should be turned on for the mesh.
  31944. * @param mesh - BJS mesh.
  31945. */
  31946. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31947. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31948. };
  31949. /**
  31950. * Processes to execute after binding the material to a mesh.
  31951. * @param mesh - BJS mesh.
  31952. */
  31953. Material.prototype._afterBind = function (mesh) {
  31954. this._scene._cachedMaterial = this;
  31955. if (mesh) {
  31956. this._scene._cachedVisibility = mesh.visibility;
  31957. }
  31958. else {
  31959. this._scene._cachedVisibility = 1;
  31960. }
  31961. if (mesh) {
  31962. this.onBindObservable.notifyObservers(mesh);
  31963. }
  31964. if (this.disableDepthWrite) {
  31965. var engine = this._scene.getEngine();
  31966. this._cachedDepthWriteState = engine.getDepthWrite();
  31967. engine.setDepthWrite(false);
  31968. }
  31969. };
  31970. /**
  31971. * Unbinds the material from the mesh.
  31972. */
  31973. Material.prototype.unbind = function () {
  31974. this.onUnBindObservable.notifyObservers(this);
  31975. if (this.disableDepthWrite) {
  31976. var engine = this._scene.getEngine();
  31977. engine.setDepthWrite(this._cachedDepthWriteState);
  31978. }
  31979. };
  31980. /**
  31981. * Gets the active textures from the material.
  31982. * @returns - Array of textures.
  31983. */
  31984. Material.prototype.getActiveTextures = function () {
  31985. return [];
  31986. };
  31987. /**
  31988. * Specifies if the material uses a texture.
  31989. * @param texture - Texture to check against the material.
  31990. * @returns - Boolean specifying if the material uses the texture.
  31991. */
  31992. Material.prototype.hasTexture = function (texture) {
  31993. return false;
  31994. };
  31995. /**
  31996. * Makes a duplicate of the material, and gives it a new name.
  31997. * @param name - Name to call the duplicated material.
  31998. * @returns - Nullable cloned material
  31999. */
  32000. Material.prototype.clone = function (name) {
  32001. return null;
  32002. };
  32003. /**
  32004. * Gets the meshes bound to the material.
  32005. * @returns - Array of meshes bound to the material.
  32006. */
  32007. Material.prototype.getBindedMeshes = function () {
  32008. var result = new Array();
  32009. for (var index = 0; index < this._scene.meshes.length; index++) {
  32010. var mesh = this._scene.meshes[index];
  32011. if (mesh.material === this) {
  32012. result.push(mesh);
  32013. }
  32014. }
  32015. return result;
  32016. };
  32017. /**
  32018. * Force shader compilation
  32019. * @param mesh - BJS mesh.
  32020. * @param onCompiled - function to execute once the material is compiled.
  32021. * @param options - options to pass to this function.
  32022. */
  32023. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  32024. var _this = this;
  32025. var localOptions = __assign({ clipPlane: false }, options);
  32026. var subMesh = new BABYLON.BaseSubMesh();
  32027. var scene = this.getScene();
  32028. var checkReady = function () {
  32029. if (!_this._scene || !_this._scene.getEngine()) {
  32030. return;
  32031. }
  32032. if (subMesh._materialDefines) {
  32033. subMesh._materialDefines._renderId = -1;
  32034. }
  32035. var clipPlaneState = scene.clipPlane;
  32036. if (localOptions.clipPlane) {
  32037. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  32038. }
  32039. if (_this.storeEffectOnSubMeshes) {
  32040. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  32041. if (onCompiled) {
  32042. onCompiled(_this);
  32043. }
  32044. }
  32045. else {
  32046. setTimeout(checkReady, 16);
  32047. }
  32048. }
  32049. else {
  32050. if (_this.isReady(mesh)) {
  32051. if (onCompiled) {
  32052. onCompiled(_this);
  32053. }
  32054. }
  32055. else {
  32056. setTimeout(checkReady, 16);
  32057. }
  32058. }
  32059. if (localOptions.clipPlane) {
  32060. scene.clipPlane = clipPlaneState;
  32061. }
  32062. };
  32063. checkReady();
  32064. };
  32065. /**
  32066. * Force shader compilation.
  32067. * @param mesh The mesh that will use this material
  32068. * @param options Additional options for compiling the shaders
  32069. * @returns A promise that resolves when the compilation completes
  32070. */
  32071. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32072. var _this = this;
  32073. return new Promise(function (resolve) {
  32074. _this.forceCompilation(mesh, function () {
  32075. resolve();
  32076. }, options);
  32077. });
  32078. };
  32079. /**
  32080. * Marks a define in the material to indicate that it needs to be re-computed.
  32081. * @param flag - Material define flag.
  32082. */
  32083. Material.prototype.markAsDirty = function (flag) {
  32084. if (flag & Material.TextureDirtyFlag) {
  32085. this._markAllSubMeshesAsTexturesDirty();
  32086. }
  32087. if (flag & Material.LightDirtyFlag) {
  32088. this._markAllSubMeshesAsLightsDirty();
  32089. }
  32090. if (flag & Material.FresnelDirtyFlag) {
  32091. this._markAllSubMeshesAsFresnelDirty();
  32092. }
  32093. if (flag & Material.AttributesDirtyFlag) {
  32094. this._markAllSubMeshesAsAttributesDirty();
  32095. }
  32096. if (flag & Material.MiscDirtyFlag) {
  32097. this._markAllSubMeshesAsMiscDirty();
  32098. }
  32099. this.getScene().resetCachedMaterial();
  32100. };
  32101. /**
  32102. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32103. * @param func - function which checks material defines against the submeshes.
  32104. */
  32105. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32106. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32107. var mesh = _a[_i];
  32108. if (!mesh.subMeshes) {
  32109. continue;
  32110. }
  32111. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32112. var subMesh = _c[_b];
  32113. if (subMesh.getMaterial() !== this) {
  32114. continue;
  32115. }
  32116. if (!subMesh._materialDefines) {
  32117. continue;
  32118. }
  32119. func(subMesh._materialDefines);
  32120. }
  32121. }
  32122. };
  32123. /**
  32124. * Indicates that image processing needs to be re-calculated for all submeshes.
  32125. */
  32126. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32127. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32128. };
  32129. /**
  32130. * Indicates that textures need to be re-calculated for all submeshes.
  32131. */
  32132. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32133. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32134. };
  32135. /**
  32136. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32137. */
  32138. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32139. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32140. };
  32141. /**
  32142. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32143. */
  32144. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32145. this._markAllSubMeshesAsDirty(function (defines) {
  32146. defines.markAsFresnelDirty();
  32147. defines.markAsMiscDirty();
  32148. });
  32149. };
  32150. /**
  32151. * Indicates that lights need to be re-calculated for all submeshes.
  32152. */
  32153. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32154. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32155. };
  32156. /**
  32157. * Indicates that attributes need to be re-calculated for all submeshes.
  32158. */
  32159. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32160. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32161. };
  32162. /**
  32163. * Indicates that misc needs to be re-calculated for all submeshes.
  32164. */
  32165. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32166. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32167. };
  32168. /**
  32169. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32170. */
  32171. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32172. this._markAllSubMeshesAsDirty(function (defines) {
  32173. defines.markAsTexturesDirty();
  32174. defines.markAsMiscDirty();
  32175. });
  32176. };
  32177. /**
  32178. * Disposes the material.
  32179. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32180. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32181. */
  32182. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32183. // Animations
  32184. this.getScene().stopAnimation(this);
  32185. this.getScene().freeProcessedMaterials();
  32186. // Remove from scene
  32187. var index = this._scene.materials.indexOf(this);
  32188. if (index >= 0) {
  32189. this._scene.materials.splice(index, 1);
  32190. }
  32191. // Remove from meshes
  32192. for (index = 0; index < this._scene.meshes.length; index++) {
  32193. var mesh = this._scene.meshes[index];
  32194. if (mesh.material === this) {
  32195. mesh.material = null;
  32196. if (mesh.geometry) {
  32197. var geometry = (mesh.geometry);
  32198. if (this.storeEffectOnSubMeshes) {
  32199. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32200. var subMesh = _a[_i];
  32201. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32202. if (forceDisposeEffect && subMesh._materialEffect) {
  32203. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32204. }
  32205. }
  32206. }
  32207. else {
  32208. geometry._releaseVertexArrayObject(this._effect);
  32209. }
  32210. }
  32211. }
  32212. }
  32213. this._uniformBuffer.dispose();
  32214. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32215. if (forceDisposeEffect && this._effect) {
  32216. if (!this.storeEffectOnSubMeshes) {
  32217. this._scene.getEngine()._releaseEffect(this._effect);
  32218. }
  32219. this._effect = null;
  32220. }
  32221. // Callback
  32222. this.onDisposeObservable.notifyObservers(this);
  32223. this.onDisposeObservable.clear();
  32224. this.onBindObservable.clear();
  32225. this.onUnBindObservable.clear();
  32226. };
  32227. /**
  32228. * Serializes this material.
  32229. * @returns - serialized material object.
  32230. */
  32231. Material.prototype.serialize = function () {
  32232. return BABYLON.SerializationHelper.Serialize(this);
  32233. };
  32234. /**
  32235. * Creates a MultiMaterial from parse MultiMaterial data.
  32236. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32237. * @param scene - BJS scene.
  32238. * @returns - MultiMaterial.
  32239. */
  32240. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32241. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32242. multiMaterial.id = parsedMultiMaterial.id;
  32243. if (BABYLON.Tags) {
  32244. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32245. }
  32246. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32247. var subMatId = parsedMultiMaterial.materials[matIndex];
  32248. if (subMatId) {
  32249. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32250. }
  32251. else {
  32252. multiMaterial.subMaterials.push(null);
  32253. }
  32254. }
  32255. return multiMaterial;
  32256. };
  32257. /**
  32258. * Creates a material from parsed material data.
  32259. * @param parsedMaterial - Parsed material data.
  32260. * @param scene - BJS scene.
  32261. * @param rootUrl - Root URL containing the material information.
  32262. * @returns - Parsed material.
  32263. */
  32264. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32265. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32266. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32267. }
  32268. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32269. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32270. if (!BABYLON.LegacyPBRMaterial) {
  32271. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32272. return;
  32273. }
  32274. }
  32275. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32276. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32277. ;
  32278. };
  32279. // Triangle views
  32280. Material._TriangleFillMode = 0;
  32281. Material._WireFrameFillMode = 1;
  32282. Material._PointFillMode = 2;
  32283. // Draw modes
  32284. Material._PointListDrawMode = 3;
  32285. Material._LineListDrawMode = 4;
  32286. Material._LineLoopDrawMode = 5;
  32287. Material._LineStripDrawMode = 6;
  32288. Material._TriangleStripDrawMode = 7;
  32289. Material._TriangleFanDrawMode = 8;
  32290. /**
  32291. * Stores the clock-wise side orientation.
  32292. */
  32293. Material._ClockWiseSideOrientation = 0;
  32294. /**
  32295. * Stores the counter clock-wise side orientation.
  32296. */
  32297. Material._CounterClockWiseSideOrientation = 1;
  32298. /**
  32299. * The dirty texture flag value.
  32300. */
  32301. Material._TextureDirtyFlag = 1;
  32302. /**
  32303. * The dirty light flag value.
  32304. */
  32305. Material._LightDirtyFlag = 2;
  32306. /**
  32307. * The dirty fresnel flag value.
  32308. */
  32309. Material._FresnelDirtyFlag = 4;
  32310. /**
  32311. * The dirty attribute flag value.
  32312. */
  32313. Material._AttributesDirtyFlag = 8;
  32314. /**
  32315. * The dirty misc flag value.
  32316. */
  32317. Material._MiscDirtyFlag = 16;
  32318. __decorate([
  32319. BABYLON.serialize()
  32320. ], Material.prototype, "id", void 0);
  32321. __decorate([
  32322. BABYLON.serialize()
  32323. ], Material.prototype, "name", void 0);
  32324. __decorate([
  32325. BABYLON.serialize()
  32326. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32327. __decorate([
  32328. BABYLON.serialize()
  32329. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32330. __decorate([
  32331. BABYLON.serialize()
  32332. ], Material.prototype, "state", void 0);
  32333. __decorate([
  32334. BABYLON.serialize("alpha")
  32335. ], Material.prototype, "_alpha", void 0);
  32336. __decorate([
  32337. BABYLON.serialize("backFaceCulling")
  32338. ], Material.prototype, "_backFaceCulling", void 0);
  32339. __decorate([
  32340. BABYLON.serialize()
  32341. ], Material.prototype, "sideOrientation", void 0);
  32342. __decorate([
  32343. BABYLON.serialize("alphaMode")
  32344. ], Material.prototype, "_alphaMode", void 0);
  32345. __decorate([
  32346. BABYLON.serialize()
  32347. ], Material.prototype, "_needDepthPrePass", void 0);
  32348. __decorate([
  32349. BABYLON.serialize()
  32350. ], Material.prototype, "disableDepthWrite", void 0);
  32351. __decorate([
  32352. BABYLON.serialize()
  32353. ], Material.prototype, "forceDepthWrite", void 0);
  32354. __decorate([
  32355. BABYLON.serialize()
  32356. ], Material.prototype, "separateCullingPass", void 0);
  32357. __decorate([
  32358. BABYLON.serialize("fogEnabled")
  32359. ], Material.prototype, "_fogEnabled", void 0);
  32360. __decorate([
  32361. BABYLON.serialize()
  32362. ], Material.prototype, "pointSize", void 0);
  32363. __decorate([
  32364. BABYLON.serialize()
  32365. ], Material.prototype, "zOffset", void 0);
  32366. __decorate([
  32367. BABYLON.serialize()
  32368. ], Material.prototype, "wireframe", null);
  32369. __decorate([
  32370. BABYLON.serialize()
  32371. ], Material.prototype, "pointsCloud", null);
  32372. __decorate([
  32373. BABYLON.serialize()
  32374. ], Material.prototype, "fillMode", null);
  32375. return Material;
  32376. }());
  32377. BABYLON.Material = Material;
  32378. })(BABYLON || (BABYLON = {}));
  32379. //# sourceMappingURL=babylon.material.js.map
  32380. "use strict";
  32381. var BABYLON;
  32382. (function (BABYLON) {
  32383. var UniformBuffer = /** @class */ (function () {
  32384. /**
  32385. * Uniform buffer objects.
  32386. *
  32387. * Handles blocks of uniform on the GPU.
  32388. *
  32389. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32390. *
  32391. * For more information, please refer to :
  32392. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32393. */
  32394. function UniformBuffer(engine, data, dynamic) {
  32395. this._engine = engine;
  32396. this._noUBO = !engine.supportsUniformBuffers;
  32397. this._dynamic = dynamic;
  32398. this._data = data || [];
  32399. this._uniformLocations = {};
  32400. this._uniformSizes = {};
  32401. this._uniformLocationPointer = 0;
  32402. this._needSync = false;
  32403. if (this._noUBO) {
  32404. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32405. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32406. this.updateFloat = this._updateFloatForEffect;
  32407. this.updateFloat2 = this._updateFloat2ForEffect;
  32408. this.updateFloat3 = this._updateFloat3ForEffect;
  32409. this.updateFloat4 = this._updateFloat4ForEffect;
  32410. this.updateMatrix = this._updateMatrixForEffect;
  32411. this.updateVector3 = this._updateVector3ForEffect;
  32412. this.updateVector4 = this._updateVector4ForEffect;
  32413. this.updateColor3 = this._updateColor3ForEffect;
  32414. this.updateColor4 = this._updateColor4ForEffect;
  32415. }
  32416. else {
  32417. this._engine._uniformBuffers.push(this);
  32418. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32419. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32420. this.updateFloat = this._updateFloatForUniform;
  32421. this.updateFloat2 = this._updateFloat2ForUniform;
  32422. this.updateFloat3 = this._updateFloat3ForUniform;
  32423. this.updateFloat4 = this._updateFloat4ForUniform;
  32424. this.updateMatrix = this._updateMatrixForUniform;
  32425. this.updateVector3 = this._updateVector3ForUniform;
  32426. this.updateVector4 = this._updateVector4ForUniform;
  32427. this.updateColor3 = this._updateColor3ForUniform;
  32428. this.updateColor4 = this._updateColor4ForUniform;
  32429. }
  32430. }
  32431. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32432. // Properties
  32433. /**
  32434. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32435. * or just falling back on setUniformXXX calls.
  32436. */
  32437. get: function () {
  32438. return !this._noUBO;
  32439. },
  32440. enumerable: true,
  32441. configurable: true
  32442. });
  32443. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32444. /**
  32445. * Indicates if the WebGL underlying uniform buffer is in sync
  32446. * with the javascript cache data.
  32447. */
  32448. get: function () {
  32449. return !this._needSync;
  32450. },
  32451. enumerable: true,
  32452. configurable: true
  32453. });
  32454. /**
  32455. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32456. * Also, a dynamic UniformBuffer will disable cache verification and always
  32457. * update the underlying WebGL uniform buffer to the GPU.
  32458. */
  32459. UniformBuffer.prototype.isDynamic = function () {
  32460. return this._dynamic !== undefined;
  32461. };
  32462. /**
  32463. * The data cache on JS side.
  32464. */
  32465. UniformBuffer.prototype.getData = function () {
  32466. return this._bufferData;
  32467. };
  32468. /**
  32469. * The underlying WebGL Uniform buffer.
  32470. */
  32471. UniformBuffer.prototype.getBuffer = function () {
  32472. return this._buffer;
  32473. };
  32474. /**
  32475. * std140 layout specifies how to align data within an UBO structure.
  32476. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32477. * for specs.
  32478. */
  32479. UniformBuffer.prototype._fillAlignment = function (size) {
  32480. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32481. // and 4x4 matrices
  32482. // TODO : change if other types are used
  32483. var alignment;
  32484. if (size <= 2) {
  32485. alignment = size;
  32486. }
  32487. else {
  32488. alignment = 4;
  32489. }
  32490. if ((this._uniformLocationPointer % alignment) !== 0) {
  32491. var oldPointer = this._uniformLocationPointer;
  32492. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32493. var diff = this._uniformLocationPointer - oldPointer;
  32494. for (var i = 0; i < diff; i++) {
  32495. this._data.push(0);
  32496. }
  32497. }
  32498. };
  32499. /**
  32500. * Adds an uniform in the buffer.
  32501. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32502. * for the layout to be correct !
  32503. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32504. * @param {number|number[]} size Data size, or data directly.
  32505. */
  32506. UniformBuffer.prototype.addUniform = function (name, size) {
  32507. if (this._noUBO) {
  32508. return;
  32509. }
  32510. if (this._uniformLocations[name] !== undefined) {
  32511. // Already existing uniform
  32512. return;
  32513. }
  32514. // This function must be called in the order of the shader layout !
  32515. // size can be the size of the uniform, or data directly
  32516. var data;
  32517. if (size instanceof Array) {
  32518. data = size;
  32519. size = data.length;
  32520. }
  32521. else {
  32522. size = size;
  32523. data = [];
  32524. // Fill with zeros
  32525. for (var i = 0; i < size; i++) {
  32526. data.push(0);
  32527. }
  32528. }
  32529. this._fillAlignment(size);
  32530. this._uniformSizes[name] = size;
  32531. this._uniformLocations[name] = this._uniformLocationPointer;
  32532. this._uniformLocationPointer += size;
  32533. for (var i = 0; i < size; i++) {
  32534. this._data.push(data[i]);
  32535. }
  32536. this._needSync = true;
  32537. };
  32538. /**
  32539. * Wrapper for addUniform.
  32540. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32541. * @param {Matrix} mat A 4x4 matrix.
  32542. */
  32543. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32544. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32545. };
  32546. /**
  32547. * Wrapper for addUniform.
  32548. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32549. * @param {number} x
  32550. * @param {number} y
  32551. */
  32552. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32553. var temp = [x, y];
  32554. this.addUniform(name, temp);
  32555. };
  32556. /**
  32557. * Wrapper for addUniform.
  32558. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32559. * @param {number} x
  32560. * @param {number} y
  32561. * @param {number} z
  32562. */
  32563. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32564. var temp = [x, y, z];
  32565. this.addUniform(name, temp);
  32566. };
  32567. /**
  32568. * Wrapper for addUniform.
  32569. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32570. * @param {Color3} color
  32571. */
  32572. UniformBuffer.prototype.addColor3 = function (name, color) {
  32573. var temp = new Array();
  32574. color.toArray(temp);
  32575. this.addUniform(name, temp);
  32576. };
  32577. /**
  32578. * Wrapper for addUniform.
  32579. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32580. * @param {Color3} color
  32581. * @param {number} alpha
  32582. */
  32583. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32584. var temp = new Array();
  32585. color.toArray(temp);
  32586. temp.push(alpha);
  32587. this.addUniform(name, temp);
  32588. };
  32589. /**
  32590. * Wrapper for addUniform.
  32591. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32592. * @param {Vector3} vector
  32593. */
  32594. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32595. var temp = new Array();
  32596. vector.toArray(temp);
  32597. this.addUniform(name, temp);
  32598. };
  32599. /**
  32600. * Wrapper for addUniform.
  32601. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32602. */
  32603. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32604. this.addUniform(name, 12);
  32605. };
  32606. /**
  32607. * Wrapper for addUniform.
  32608. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32609. */
  32610. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32611. this.addUniform(name, 8);
  32612. };
  32613. /**
  32614. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32615. */
  32616. UniformBuffer.prototype.create = function () {
  32617. if (this._noUBO) {
  32618. return;
  32619. }
  32620. if (this._buffer) {
  32621. return; // nothing to do
  32622. }
  32623. // See spec, alignment must be filled as a vec4
  32624. this._fillAlignment(4);
  32625. this._bufferData = new Float32Array(this._data);
  32626. this._rebuild();
  32627. this._needSync = true;
  32628. };
  32629. UniformBuffer.prototype._rebuild = function () {
  32630. if (this._noUBO) {
  32631. return;
  32632. }
  32633. if (this._dynamic) {
  32634. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32635. }
  32636. else {
  32637. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32638. }
  32639. };
  32640. /**
  32641. * Updates the WebGL Uniform Buffer on the GPU.
  32642. * If the `dynamic` flag is set to true, no cache comparison is done.
  32643. * Otherwise, the buffer will be updated only if the cache differs.
  32644. */
  32645. UniformBuffer.prototype.update = function () {
  32646. if (!this._buffer) {
  32647. this.create();
  32648. return;
  32649. }
  32650. if (!this._dynamic && !this._needSync) {
  32651. return;
  32652. }
  32653. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32654. this._needSync = false;
  32655. };
  32656. /**
  32657. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32658. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32659. * @param {number[]|Float32Array} data Flattened data
  32660. * @param {number} size Size of the data.
  32661. */
  32662. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32663. var location = this._uniformLocations[uniformName];
  32664. if (location === undefined) {
  32665. if (this._buffer) {
  32666. // Cannot add an uniform if the buffer is already created
  32667. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32668. return;
  32669. }
  32670. this.addUniform(uniformName, size);
  32671. location = this._uniformLocations[uniformName];
  32672. }
  32673. if (!this._buffer) {
  32674. this.create();
  32675. }
  32676. if (!this._dynamic) {
  32677. // Cache for static uniform buffers
  32678. var changed = false;
  32679. for (var i = 0; i < size; i++) {
  32680. if (this._bufferData[location + i] !== data[i]) {
  32681. changed = true;
  32682. this._bufferData[location + i] = data[i];
  32683. }
  32684. }
  32685. this._needSync = this._needSync || changed;
  32686. }
  32687. else {
  32688. // No cache for dynamic
  32689. for (var i = 0; i < size; i++) {
  32690. this._bufferData[location + i] = data[i];
  32691. }
  32692. }
  32693. };
  32694. // Update methods
  32695. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32696. // To match std140, matrix must be realigned
  32697. for (var i = 0; i < 3; i++) {
  32698. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32699. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32700. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32701. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32702. }
  32703. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32704. };
  32705. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32706. this._currentEffect.setMatrix3x3(name, matrix);
  32707. };
  32708. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32709. this._currentEffect.setMatrix2x2(name, matrix);
  32710. };
  32711. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32712. // To match std140, matrix must be realigned
  32713. for (var i = 0; i < 2; i++) {
  32714. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32715. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32716. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32717. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32718. }
  32719. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32720. };
  32721. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32722. this._currentEffect.setFloat(name, x);
  32723. };
  32724. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32725. UniformBuffer._tempBuffer[0] = x;
  32726. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32727. };
  32728. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32729. if (suffix === void 0) { suffix = ""; }
  32730. this._currentEffect.setFloat2(name + suffix, x, y);
  32731. };
  32732. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32733. if (suffix === void 0) { suffix = ""; }
  32734. UniformBuffer._tempBuffer[0] = x;
  32735. UniformBuffer._tempBuffer[1] = y;
  32736. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32737. };
  32738. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32739. if (suffix === void 0) { suffix = ""; }
  32740. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32741. };
  32742. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32743. if (suffix === void 0) { suffix = ""; }
  32744. UniformBuffer._tempBuffer[0] = x;
  32745. UniformBuffer._tempBuffer[1] = y;
  32746. UniformBuffer._tempBuffer[2] = z;
  32747. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32748. };
  32749. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32750. if (suffix === void 0) { suffix = ""; }
  32751. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32752. };
  32753. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32754. if (suffix === void 0) { suffix = ""; }
  32755. UniformBuffer._tempBuffer[0] = x;
  32756. UniformBuffer._tempBuffer[1] = y;
  32757. UniformBuffer._tempBuffer[2] = z;
  32758. UniformBuffer._tempBuffer[3] = w;
  32759. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32760. };
  32761. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32762. this._currentEffect.setMatrix(name, mat);
  32763. };
  32764. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32765. this.updateUniform(name, mat.toArray(), 16);
  32766. };
  32767. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32768. this._currentEffect.setVector3(name, vector);
  32769. };
  32770. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32771. vector.toArray(UniformBuffer._tempBuffer);
  32772. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32773. };
  32774. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32775. this._currentEffect.setVector4(name, vector);
  32776. };
  32777. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32778. vector.toArray(UniformBuffer._tempBuffer);
  32779. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32780. };
  32781. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32782. if (suffix === void 0) { suffix = ""; }
  32783. this._currentEffect.setColor3(name + suffix, color);
  32784. };
  32785. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32786. if (suffix === void 0) { suffix = ""; }
  32787. color.toArray(UniformBuffer._tempBuffer);
  32788. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32789. };
  32790. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32791. if (suffix === void 0) { suffix = ""; }
  32792. this._currentEffect.setColor4(name + suffix, color, alpha);
  32793. };
  32794. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32795. if (suffix === void 0) { suffix = ""; }
  32796. color.toArray(UniformBuffer._tempBuffer);
  32797. UniformBuffer._tempBuffer[3] = alpha;
  32798. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32799. };
  32800. /**
  32801. * Sets a sampler uniform on the effect.
  32802. * @param {string} name Name of the sampler.
  32803. * @param {Texture} texture
  32804. */
  32805. UniformBuffer.prototype.setTexture = function (name, texture) {
  32806. this._currentEffect.setTexture(name, texture);
  32807. };
  32808. /**
  32809. * Directly updates the value of the uniform in the cache AND on the GPU.
  32810. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32811. * @param {number[]|Float32Array} data Flattened data
  32812. */
  32813. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32814. this.updateUniform(uniformName, data, data.length);
  32815. this.update();
  32816. };
  32817. /**
  32818. * Binds this uniform buffer to an effect.
  32819. * @param {Effect} effect
  32820. * @param {string} name Name of the uniform block in the shader.
  32821. */
  32822. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32823. this._currentEffect = effect;
  32824. if (this._noUBO || !this._buffer) {
  32825. return;
  32826. }
  32827. effect.bindUniformBuffer(this._buffer, name);
  32828. };
  32829. /**
  32830. * Disposes the uniform buffer.
  32831. */
  32832. UniformBuffer.prototype.dispose = function () {
  32833. if (this._noUBO) {
  32834. return;
  32835. }
  32836. var index = this._engine._uniformBuffers.indexOf(this);
  32837. if (index !== -1) {
  32838. this._engine._uniformBuffers.splice(index, 1);
  32839. }
  32840. if (!this._buffer) {
  32841. return;
  32842. }
  32843. if (this._engine._releaseBuffer(this._buffer)) {
  32844. this._buffer = null;
  32845. }
  32846. };
  32847. // Pool for avoiding memory leaks
  32848. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32849. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32850. return UniformBuffer;
  32851. }());
  32852. BABYLON.UniformBuffer = UniformBuffer;
  32853. })(BABYLON || (BABYLON = {}));
  32854. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32855. "use strict";
  32856. var BABYLON;
  32857. (function (BABYLON) {
  32858. var VertexData = /** @class */ (function () {
  32859. function VertexData() {
  32860. }
  32861. VertexData.prototype.set = function (data, kind) {
  32862. switch (kind) {
  32863. case BABYLON.VertexBuffer.PositionKind:
  32864. this.positions = data;
  32865. break;
  32866. case BABYLON.VertexBuffer.NormalKind:
  32867. this.normals = data;
  32868. break;
  32869. case BABYLON.VertexBuffer.TangentKind:
  32870. this.tangents = data;
  32871. break;
  32872. case BABYLON.VertexBuffer.UVKind:
  32873. this.uvs = data;
  32874. break;
  32875. case BABYLON.VertexBuffer.UV2Kind:
  32876. this.uvs2 = data;
  32877. break;
  32878. case BABYLON.VertexBuffer.UV3Kind:
  32879. this.uvs3 = data;
  32880. break;
  32881. case BABYLON.VertexBuffer.UV4Kind:
  32882. this.uvs4 = data;
  32883. break;
  32884. case BABYLON.VertexBuffer.UV5Kind:
  32885. this.uvs5 = data;
  32886. break;
  32887. case BABYLON.VertexBuffer.UV6Kind:
  32888. this.uvs6 = data;
  32889. break;
  32890. case BABYLON.VertexBuffer.ColorKind:
  32891. this.colors = data;
  32892. break;
  32893. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32894. this.matricesIndices = data;
  32895. break;
  32896. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32897. this.matricesWeights = data;
  32898. break;
  32899. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32900. this.matricesIndicesExtra = data;
  32901. break;
  32902. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32903. this.matricesWeightsExtra = data;
  32904. break;
  32905. }
  32906. };
  32907. /**
  32908. * Associates the vertexData to the passed Mesh.
  32909. * Sets it as updatable or not (default `false`).
  32910. * Returns the VertexData.
  32911. */
  32912. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32913. this._applyTo(mesh, updatable);
  32914. return this;
  32915. };
  32916. /**
  32917. * Associates the vertexData to the passed Geometry.
  32918. * Sets it as updatable or not (default `false`).
  32919. * Returns the VertexData.
  32920. */
  32921. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32922. this._applyTo(geometry, updatable);
  32923. return this;
  32924. };
  32925. /**
  32926. * Updates the associated mesh.
  32927. * Returns the VertexData.
  32928. */
  32929. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32930. this._update(mesh);
  32931. return this;
  32932. };
  32933. /**
  32934. * Updates the associated geometry.
  32935. * Returns the VertexData.
  32936. */
  32937. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32938. this._update(geometry);
  32939. return this;
  32940. };
  32941. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32942. if (updatable === void 0) { updatable = false; }
  32943. if (this.positions) {
  32944. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32945. }
  32946. if (this.normals) {
  32947. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32948. }
  32949. if (this.tangents) {
  32950. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32951. }
  32952. if (this.uvs) {
  32953. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32954. }
  32955. if (this.uvs2) {
  32956. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32957. }
  32958. if (this.uvs3) {
  32959. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32960. }
  32961. if (this.uvs4) {
  32962. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32963. }
  32964. if (this.uvs5) {
  32965. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32966. }
  32967. if (this.uvs6) {
  32968. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32969. }
  32970. if (this.colors) {
  32971. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32972. }
  32973. if (this.matricesIndices) {
  32974. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32975. }
  32976. if (this.matricesWeights) {
  32977. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32978. }
  32979. if (this.matricesIndicesExtra) {
  32980. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32981. }
  32982. if (this.matricesWeightsExtra) {
  32983. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32984. }
  32985. if (this.indices) {
  32986. meshOrGeometry.setIndices(this.indices, null, updatable);
  32987. }
  32988. return this;
  32989. };
  32990. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32991. if (this.positions) {
  32992. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32993. }
  32994. if (this.normals) {
  32995. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32996. }
  32997. if (this.tangents) {
  32998. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32999. }
  33000. if (this.uvs) {
  33001. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33002. }
  33003. if (this.uvs2) {
  33004. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33005. }
  33006. if (this.uvs3) {
  33007. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33008. }
  33009. if (this.uvs4) {
  33010. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33011. }
  33012. if (this.uvs5) {
  33013. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33014. }
  33015. if (this.uvs6) {
  33016. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33017. }
  33018. if (this.colors) {
  33019. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33020. }
  33021. if (this.matricesIndices) {
  33022. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33023. }
  33024. if (this.matricesWeights) {
  33025. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33026. }
  33027. if (this.matricesIndicesExtra) {
  33028. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33029. }
  33030. if (this.matricesWeightsExtra) {
  33031. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33032. }
  33033. if (this.indices) {
  33034. meshOrGeometry.setIndices(this.indices, null);
  33035. }
  33036. return this;
  33037. };
  33038. /**
  33039. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  33040. * Returns the VertexData.
  33041. */
  33042. VertexData.prototype.transform = function (matrix) {
  33043. var transformed = BABYLON.Vector3.Zero();
  33044. var index;
  33045. if (this.positions) {
  33046. var position = BABYLON.Vector3.Zero();
  33047. for (index = 0; index < this.positions.length; index += 3) {
  33048. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33049. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33050. this.positions[index] = transformed.x;
  33051. this.positions[index + 1] = transformed.y;
  33052. this.positions[index + 2] = transformed.z;
  33053. }
  33054. }
  33055. if (this.normals) {
  33056. var normal = BABYLON.Vector3.Zero();
  33057. for (index = 0; index < this.normals.length; index += 3) {
  33058. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33059. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33060. this.normals[index] = transformed.x;
  33061. this.normals[index + 1] = transformed.y;
  33062. this.normals[index + 2] = transformed.z;
  33063. }
  33064. }
  33065. if (this.tangents) {
  33066. var tangent = BABYLON.Vector4.Zero();
  33067. var tangentTransformed = BABYLON.Vector4.Zero();
  33068. for (index = 0; index < this.tangents.length; index += 4) {
  33069. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33070. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33071. this.tangents[index] = tangentTransformed.x;
  33072. this.tangents[index + 1] = tangentTransformed.y;
  33073. this.tangents[index + 2] = tangentTransformed.z;
  33074. this.tangents[index + 3] = tangentTransformed.w;
  33075. }
  33076. }
  33077. return this;
  33078. };
  33079. /**
  33080. * Merges the passed VertexData into the current one.
  33081. * Returns the modified VertexData.
  33082. */
  33083. VertexData.prototype.merge = function (other) {
  33084. this._validate();
  33085. other._validate();
  33086. if (!this.normals !== !other.normals ||
  33087. !this.tangents !== !other.tangents ||
  33088. !this.uvs !== !other.uvs ||
  33089. !this.uvs2 !== !other.uvs2 ||
  33090. !this.uvs3 !== !other.uvs3 ||
  33091. !this.uvs4 !== !other.uvs4 ||
  33092. !this.uvs5 !== !other.uvs5 ||
  33093. !this.uvs6 !== !other.uvs6 ||
  33094. !this.colors !== !other.colors ||
  33095. !this.matricesIndices !== !other.matricesIndices ||
  33096. !this.matricesWeights !== !other.matricesWeights ||
  33097. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33098. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33099. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33100. }
  33101. if (other.indices) {
  33102. if (!this.indices) {
  33103. this.indices = [];
  33104. }
  33105. var offset = this.positions ? this.positions.length / 3 : 0;
  33106. for (var index = 0; index < other.indices.length; index++) {
  33107. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33108. this.indices.push(other.indices[index] + offset);
  33109. }
  33110. }
  33111. this.positions = this._mergeElement(this.positions, other.positions);
  33112. this.normals = this._mergeElement(this.normals, other.normals);
  33113. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33114. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33115. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33116. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33117. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33118. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33119. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33120. this.colors = this._mergeElement(this.colors, other.colors);
  33121. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33122. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33123. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33124. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33125. return this;
  33126. };
  33127. VertexData.prototype._mergeElement = function (source, other) {
  33128. if (!source) {
  33129. return other;
  33130. }
  33131. if (!other) {
  33132. return source;
  33133. }
  33134. var len = other.length + source.length;
  33135. var isSrcTypedArray = source instanceof Float32Array;
  33136. var isOthTypedArray = other instanceof Float32Array;
  33137. // use non-loop method when the source is Float32Array
  33138. if (isSrcTypedArray) {
  33139. var ret32 = new Float32Array(len);
  33140. ret32.set(source);
  33141. ret32.set(other, source.length);
  33142. return ret32;
  33143. // source is number[], when other is also use concat
  33144. }
  33145. else if (!isOthTypedArray) {
  33146. return source.concat(other);
  33147. // source is a number[], but other is a Float32Array, loop required
  33148. }
  33149. else {
  33150. var ret = source.slice(0); // copy source to a separate array
  33151. for (var i = 0, len = other.length; i < len; i++) {
  33152. ret.push(other[i]);
  33153. }
  33154. return ret;
  33155. }
  33156. };
  33157. VertexData.prototype._validate = function () {
  33158. if (!this.positions) {
  33159. throw new Error("Positions are required");
  33160. }
  33161. var getElementCount = function (kind, values) {
  33162. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33163. if ((values.length % stride) !== 0) {
  33164. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33165. }
  33166. return values.length / stride;
  33167. };
  33168. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33169. var validateElementCount = function (kind, values) {
  33170. var elementCount = getElementCount(kind, values);
  33171. if (elementCount !== positionsElementCount) {
  33172. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33173. }
  33174. };
  33175. if (this.normals)
  33176. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33177. if (this.tangents)
  33178. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33179. if (this.uvs)
  33180. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33181. if (this.uvs2)
  33182. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33183. if (this.uvs3)
  33184. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33185. if (this.uvs4)
  33186. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33187. if (this.uvs5)
  33188. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33189. if (this.uvs6)
  33190. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33191. if (this.colors)
  33192. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33193. if (this.matricesIndices)
  33194. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33195. if (this.matricesWeights)
  33196. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33197. if (this.matricesIndicesExtra)
  33198. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33199. if (this.matricesWeightsExtra)
  33200. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33201. };
  33202. /**
  33203. * Serializes the VertexData.
  33204. * Returns a serialized object.
  33205. */
  33206. VertexData.prototype.serialize = function () {
  33207. var serializationObject = this.serialize();
  33208. if (this.positions) {
  33209. serializationObject.positions = this.positions;
  33210. }
  33211. if (this.normals) {
  33212. serializationObject.normals = this.normals;
  33213. }
  33214. if (this.tangents) {
  33215. serializationObject.tangents = this.tangents;
  33216. }
  33217. if (this.uvs) {
  33218. serializationObject.uvs = this.uvs;
  33219. }
  33220. if (this.uvs2) {
  33221. serializationObject.uvs2 = this.uvs2;
  33222. }
  33223. if (this.uvs3) {
  33224. serializationObject.uvs3 = this.uvs3;
  33225. }
  33226. if (this.uvs4) {
  33227. serializationObject.uvs4 = this.uvs4;
  33228. }
  33229. if (this.uvs5) {
  33230. serializationObject.uvs5 = this.uvs5;
  33231. }
  33232. if (this.uvs6) {
  33233. serializationObject.uvs6 = this.uvs6;
  33234. }
  33235. if (this.colors) {
  33236. serializationObject.colors = this.colors;
  33237. }
  33238. if (this.matricesIndices) {
  33239. serializationObject.matricesIndices = this.matricesIndices;
  33240. serializationObject.matricesIndices._isExpanded = true;
  33241. }
  33242. if (this.matricesWeights) {
  33243. serializationObject.matricesWeights = this.matricesWeights;
  33244. }
  33245. if (this.matricesIndicesExtra) {
  33246. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33247. serializationObject.matricesIndicesExtra._isExpanded = true;
  33248. }
  33249. if (this.matricesWeightsExtra) {
  33250. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33251. }
  33252. serializationObject.indices = this.indices;
  33253. return serializationObject;
  33254. };
  33255. // Statics
  33256. /**
  33257. * Returns the object VertexData associated to the passed mesh.
  33258. */
  33259. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33260. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33261. };
  33262. /**
  33263. * Returns the object VertexData associated to the passed geometry.
  33264. */
  33265. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33266. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33267. };
  33268. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33269. var result = new VertexData();
  33270. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33271. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33272. }
  33273. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33274. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33275. }
  33276. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33277. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33278. }
  33279. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33280. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33281. }
  33282. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33283. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33284. }
  33285. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33286. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33287. }
  33288. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33289. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33290. }
  33291. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33292. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33293. }
  33294. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33295. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33296. }
  33297. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33298. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33299. }
  33300. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33301. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33302. }
  33303. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33304. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33305. }
  33306. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33307. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33308. }
  33309. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33310. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33311. }
  33312. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33313. return result;
  33314. };
  33315. /**
  33316. * Creates the vertexData of the Ribbon.
  33317. */
  33318. VertexData.CreateRibbon = function (options) {
  33319. var pathArray = options.pathArray;
  33320. var closeArray = options.closeArray || false;
  33321. var closePath = options.closePath || false;
  33322. var invertUV = options.invertUV || false;
  33323. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33324. var offset = options.offset || defaultOffset;
  33325. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33326. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33327. var customUV = options.uvs;
  33328. var customColors = options.colors;
  33329. var positions = [];
  33330. var indices = [];
  33331. var normals = [];
  33332. var uvs = [];
  33333. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33334. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33335. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33336. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33337. var minlg; // minimal length among all paths from pathArray
  33338. var lg = []; // array of path lengths : nb of vertex per path
  33339. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33340. var p; // path iterator
  33341. var i; // point iterator
  33342. var j; // point iterator
  33343. // if single path in pathArray
  33344. if (pathArray.length < 2) {
  33345. var ar1 = [];
  33346. var ar2 = [];
  33347. for (i = 0; i < pathArray[0].length - offset; i++) {
  33348. ar1.push(pathArray[0][i]);
  33349. ar2.push(pathArray[0][i + offset]);
  33350. }
  33351. pathArray = [ar1, ar2];
  33352. }
  33353. // positions and horizontal distances (u)
  33354. var idc = 0;
  33355. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33356. var path;
  33357. var l;
  33358. minlg = pathArray[0].length;
  33359. var vectlg;
  33360. var dist;
  33361. for (p = 0; p < pathArray.length; p++) {
  33362. uTotalDistance[p] = 0;
  33363. us[p] = [0];
  33364. path = pathArray[p];
  33365. l = path.length;
  33366. minlg = (minlg < l) ? minlg : l;
  33367. j = 0;
  33368. while (j < l) {
  33369. positions.push(path[j].x, path[j].y, path[j].z);
  33370. if (j > 0) {
  33371. vectlg = path[j].subtract(path[j - 1]).length();
  33372. dist = vectlg + uTotalDistance[p];
  33373. us[p].push(dist);
  33374. uTotalDistance[p] = dist;
  33375. }
  33376. j++;
  33377. }
  33378. if (closePath) {
  33379. j--;
  33380. positions.push(path[0].x, path[0].y, path[0].z);
  33381. vectlg = path[j].subtract(path[0]).length();
  33382. dist = vectlg + uTotalDistance[p];
  33383. us[p].push(dist);
  33384. uTotalDistance[p] = dist;
  33385. }
  33386. lg[p] = l + closePathCorr;
  33387. idx[p] = idc;
  33388. idc += (l + closePathCorr);
  33389. }
  33390. // vertical distances (v)
  33391. var path1;
  33392. var path2;
  33393. var vertex1 = null;
  33394. var vertex2 = null;
  33395. for (i = 0; i < minlg + closePathCorr; i++) {
  33396. vTotalDistance[i] = 0;
  33397. vs[i] = [0];
  33398. for (p = 0; p < pathArray.length - 1; p++) {
  33399. path1 = pathArray[p];
  33400. path2 = pathArray[p + 1];
  33401. if (i === minlg) {
  33402. vertex1 = path1[0];
  33403. vertex2 = path2[0];
  33404. }
  33405. else {
  33406. vertex1 = path1[i];
  33407. vertex2 = path2[i];
  33408. }
  33409. vectlg = vertex2.subtract(vertex1).length();
  33410. dist = vectlg + vTotalDistance[i];
  33411. vs[i].push(dist);
  33412. vTotalDistance[i] = dist;
  33413. }
  33414. if (closeArray && vertex2 && vertex1) {
  33415. path1 = pathArray[p];
  33416. path2 = pathArray[0];
  33417. if (i === minlg) {
  33418. vertex2 = path2[0];
  33419. }
  33420. vectlg = vertex2.subtract(vertex1).length();
  33421. dist = vectlg + vTotalDistance[i];
  33422. vTotalDistance[i] = dist;
  33423. }
  33424. }
  33425. // uvs
  33426. var u;
  33427. var v;
  33428. if (customUV) {
  33429. for (p = 0; p < customUV.length; p++) {
  33430. uvs.push(customUV[p].x, customUV[p].y);
  33431. }
  33432. }
  33433. else {
  33434. for (p = 0; p < pathArray.length; p++) {
  33435. for (i = 0; i < minlg + closePathCorr; i++) {
  33436. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33437. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33438. if (invertUV) {
  33439. uvs.push(v, u);
  33440. }
  33441. else {
  33442. uvs.push(u, v);
  33443. }
  33444. }
  33445. }
  33446. }
  33447. // indices
  33448. p = 0; // path index
  33449. var pi = 0; // positions array index
  33450. var l1 = lg[p] - 1; // path1 length
  33451. var l2 = lg[p + 1] - 1; // path2 length
  33452. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33453. var shft = idx[1] - idx[0]; // shift
  33454. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33455. while (pi <= min && p < path1nb) {
  33456. // 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
  33457. indices.push(pi, pi + shft, pi + 1);
  33458. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33459. pi += 1;
  33460. if (pi === min) {
  33461. p++;
  33462. if (p === lg.length - 1) {
  33463. shft = idx[0] - idx[p];
  33464. l1 = lg[p] - 1;
  33465. l2 = lg[0] - 1;
  33466. }
  33467. else {
  33468. shft = idx[p + 1] - idx[p];
  33469. l1 = lg[p] - 1;
  33470. l2 = lg[p + 1] - 1;
  33471. }
  33472. pi = idx[p];
  33473. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33474. }
  33475. }
  33476. // normals
  33477. VertexData.ComputeNormals(positions, indices, normals);
  33478. if (closePath) {
  33479. var indexFirst = 0;
  33480. var indexLast = 0;
  33481. for (p = 0; p < pathArray.length; p++) {
  33482. indexFirst = idx[p] * 3;
  33483. if (p + 1 < pathArray.length) {
  33484. indexLast = (idx[p + 1] - 1) * 3;
  33485. }
  33486. else {
  33487. indexLast = normals.length - 3;
  33488. }
  33489. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33490. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33491. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33492. normals[indexLast] = normals[indexFirst];
  33493. normals[indexLast + 1] = normals[indexFirst + 1];
  33494. normals[indexLast + 2] = normals[indexFirst + 2];
  33495. }
  33496. }
  33497. // sides
  33498. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33499. // Colors
  33500. var colors = null;
  33501. if (customColors) {
  33502. colors = new Float32Array(customColors.length * 4);
  33503. for (var c = 0; c < customColors.length; c++) {
  33504. colors[c * 4] = customColors[c].r;
  33505. colors[c * 4 + 1] = customColors[c].g;
  33506. colors[c * 4 + 2] = customColors[c].b;
  33507. colors[c * 4 + 3] = customColors[c].a;
  33508. }
  33509. }
  33510. // Result
  33511. var vertexData = new VertexData();
  33512. var positions32 = new Float32Array(positions);
  33513. var normals32 = new Float32Array(normals);
  33514. var uvs32 = new Float32Array(uvs);
  33515. vertexData.indices = indices;
  33516. vertexData.positions = positions32;
  33517. vertexData.normals = normals32;
  33518. vertexData.uvs = uvs32;
  33519. if (colors) {
  33520. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33521. }
  33522. if (closePath) {
  33523. vertexData._idx = idx;
  33524. }
  33525. return vertexData;
  33526. };
  33527. /**
  33528. * Creates the VertexData of the Box.
  33529. */
  33530. VertexData.CreateBox = function (options) {
  33531. var normalsSource = [
  33532. new BABYLON.Vector3(0, 0, 1),
  33533. new BABYLON.Vector3(0, 0, -1),
  33534. new BABYLON.Vector3(1, 0, 0),
  33535. new BABYLON.Vector3(-1, 0, 0),
  33536. new BABYLON.Vector3(0, 1, 0),
  33537. new BABYLON.Vector3(0, -1, 0)
  33538. ];
  33539. var indices = [];
  33540. var positions = [];
  33541. var normals = [];
  33542. var uvs = [];
  33543. var width = options.width || options.size || 1;
  33544. var height = options.height || options.size || 1;
  33545. var depth = options.depth || options.size || 1;
  33546. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33547. var faceUV = options.faceUV || new Array(6);
  33548. var faceColors = options.faceColors;
  33549. var colors = [];
  33550. // default face colors and UV if undefined
  33551. for (var f = 0; f < 6; f++) {
  33552. if (faceUV[f] === undefined) {
  33553. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33554. }
  33555. if (faceColors && faceColors[f] === undefined) {
  33556. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33557. }
  33558. }
  33559. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33560. // Create each face in turn.
  33561. for (var index = 0; index < normalsSource.length; index++) {
  33562. var normal = normalsSource[index];
  33563. // Get two vectors perpendicular to the face normal and to each other.
  33564. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33565. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33566. // Six indices (two triangles) per face.
  33567. var verticesLength = positions.length / 3;
  33568. indices.push(verticesLength);
  33569. indices.push(verticesLength + 1);
  33570. indices.push(verticesLength + 2);
  33571. indices.push(verticesLength);
  33572. indices.push(verticesLength + 2);
  33573. indices.push(verticesLength + 3);
  33574. // Four vertices per face.
  33575. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33576. positions.push(vertex.x, vertex.y, vertex.z);
  33577. normals.push(normal.x, normal.y, normal.z);
  33578. uvs.push(faceUV[index].z, faceUV[index].w);
  33579. if (faceColors) {
  33580. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33581. }
  33582. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33583. positions.push(vertex.x, vertex.y, vertex.z);
  33584. normals.push(normal.x, normal.y, normal.z);
  33585. uvs.push(faceUV[index].x, faceUV[index].w);
  33586. if (faceColors) {
  33587. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33588. }
  33589. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33590. positions.push(vertex.x, vertex.y, vertex.z);
  33591. normals.push(normal.x, normal.y, normal.z);
  33592. uvs.push(faceUV[index].x, faceUV[index].y);
  33593. if (faceColors) {
  33594. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33595. }
  33596. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33597. positions.push(vertex.x, vertex.y, vertex.z);
  33598. normals.push(normal.x, normal.y, normal.z);
  33599. uvs.push(faceUV[index].z, faceUV[index].y);
  33600. if (faceColors) {
  33601. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33602. }
  33603. }
  33604. // sides
  33605. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33606. // Result
  33607. var vertexData = new VertexData();
  33608. vertexData.indices = indices;
  33609. vertexData.positions = positions;
  33610. vertexData.normals = normals;
  33611. vertexData.uvs = uvs;
  33612. if (faceColors) {
  33613. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33614. vertexData.colors = totalColors;
  33615. }
  33616. return vertexData;
  33617. };
  33618. /**
  33619. * Creates the VertexData of the Sphere.
  33620. */
  33621. VertexData.CreateSphere = function (options) {
  33622. var segments = options.segments || 32;
  33623. var diameterX = options.diameterX || options.diameter || 1;
  33624. var diameterY = options.diameterY || options.diameter || 1;
  33625. var diameterZ = options.diameterZ || options.diameter || 1;
  33626. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33627. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33628. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33629. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33630. var totalZRotationSteps = 2 + segments;
  33631. var totalYRotationSteps = 2 * totalZRotationSteps;
  33632. var indices = [];
  33633. var positions = [];
  33634. var normals = [];
  33635. var uvs = [];
  33636. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33637. var normalizedZ = zRotationStep / totalZRotationSteps;
  33638. var angleZ = normalizedZ * Math.PI * slice;
  33639. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33640. var normalizedY = yRotationStep / totalYRotationSteps;
  33641. var angleY = normalizedY * Math.PI * 2 * arc;
  33642. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33643. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33644. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33645. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33646. var vertex = complete.multiply(radius);
  33647. var normal = complete.divide(radius).normalize();
  33648. positions.push(vertex.x, vertex.y, vertex.z);
  33649. normals.push(normal.x, normal.y, normal.z);
  33650. uvs.push(normalizedY, normalizedZ);
  33651. }
  33652. if (zRotationStep > 0) {
  33653. var verticesCount = positions.length / 3;
  33654. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33655. indices.push((firstIndex));
  33656. indices.push((firstIndex + 1));
  33657. indices.push(firstIndex + totalYRotationSteps + 1);
  33658. indices.push((firstIndex + totalYRotationSteps + 1));
  33659. indices.push((firstIndex + 1));
  33660. indices.push((firstIndex + totalYRotationSteps + 2));
  33661. }
  33662. }
  33663. }
  33664. // Sides
  33665. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33666. // Result
  33667. var vertexData = new VertexData();
  33668. vertexData.indices = indices;
  33669. vertexData.positions = positions;
  33670. vertexData.normals = normals;
  33671. vertexData.uvs = uvs;
  33672. return vertexData;
  33673. };
  33674. /**
  33675. * Creates the VertexData of the Cylinder or Cone.
  33676. */
  33677. VertexData.CreateCylinder = function (options) {
  33678. var height = options.height || 2;
  33679. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33680. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33681. var tessellation = options.tessellation || 24;
  33682. var subdivisions = options.subdivisions || 1;
  33683. var hasRings = options.hasRings ? true : false;
  33684. var enclose = options.enclose ? true : false;
  33685. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33686. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33687. var faceUV = options.faceUV || new Array(3);
  33688. var faceColors = options.faceColors;
  33689. // default face colors and UV if undefined
  33690. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33691. var ringNb = (hasRings) ? subdivisions : 1;
  33692. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33693. var f;
  33694. for (f = 0; f < surfaceNb; f++) {
  33695. if (faceColors && faceColors[f] === undefined) {
  33696. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33697. }
  33698. }
  33699. for (f = 0; f < surfaceNb; f++) {
  33700. if (faceUV && faceUV[f] === undefined) {
  33701. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33702. }
  33703. }
  33704. var indices = new Array();
  33705. var positions = new Array();
  33706. var normals = new Array();
  33707. var uvs = new Array();
  33708. var colors = new Array();
  33709. var angle_step = Math.PI * 2 * arc / tessellation;
  33710. var angle;
  33711. var h;
  33712. var radius;
  33713. var tan = (diameterBottom - diameterTop) / 2 / height;
  33714. var ringVertex = BABYLON.Vector3.Zero();
  33715. var ringNormal = BABYLON.Vector3.Zero();
  33716. var ringFirstVertex = BABYLON.Vector3.Zero();
  33717. var ringFirstNormal = BABYLON.Vector3.Zero();
  33718. var quadNormal = BABYLON.Vector3.Zero();
  33719. var Y = BABYLON.Axis.Y;
  33720. // positions, normals, uvs
  33721. var i;
  33722. var j;
  33723. var r;
  33724. var ringIdx = 1;
  33725. var s = 1; // surface index
  33726. var cs = 0;
  33727. var v = 0;
  33728. for (i = 0; i <= subdivisions; i++) {
  33729. h = i / subdivisions;
  33730. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33731. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33732. for (r = 0; r < ringIdx; r++) {
  33733. if (hasRings) {
  33734. s += r;
  33735. }
  33736. if (enclose) {
  33737. s += 2 * r;
  33738. }
  33739. for (j = 0; j <= tessellation; j++) {
  33740. angle = j * angle_step;
  33741. // position
  33742. ringVertex.x = Math.cos(-angle) * radius;
  33743. ringVertex.y = -height / 2 + h * height;
  33744. ringVertex.z = Math.sin(-angle) * radius;
  33745. // normal
  33746. if (diameterTop === 0 && i === subdivisions) {
  33747. // if no top cap, reuse former normals
  33748. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33749. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33750. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33751. }
  33752. else {
  33753. ringNormal.x = ringVertex.x;
  33754. ringNormal.z = ringVertex.z;
  33755. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33756. ringNormal.normalize();
  33757. }
  33758. // keep first ring vertex values for enclose
  33759. if (j === 0) {
  33760. ringFirstVertex.copyFrom(ringVertex);
  33761. ringFirstNormal.copyFrom(ringNormal);
  33762. }
  33763. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33764. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33765. if (hasRings) {
  33766. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33767. }
  33768. else {
  33769. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33770. }
  33771. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33772. if (faceColors) {
  33773. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33774. }
  33775. }
  33776. // if enclose, add four vertices and their dedicated normals
  33777. if (arc !== 1 && enclose) {
  33778. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33779. positions.push(0, ringVertex.y, 0);
  33780. positions.push(0, ringVertex.y, 0);
  33781. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33782. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33783. quadNormal.normalize();
  33784. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33785. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33786. quadNormal.normalize();
  33787. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33788. if (hasRings) {
  33789. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33790. }
  33791. else {
  33792. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33793. }
  33794. uvs.push(faceUV[s + 1].x, v);
  33795. uvs.push(faceUV[s + 1].z, v);
  33796. if (hasRings) {
  33797. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33798. }
  33799. else {
  33800. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33801. }
  33802. uvs.push(faceUV[s + 2].x, v);
  33803. uvs.push(faceUV[s + 2].z, v);
  33804. if (faceColors) {
  33805. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33806. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33807. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33808. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33809. }
  33810. }
  33811. if (cs !== s) {
  33812. cs = s;
  33813. }
  33814. }
  33815. }
  33816. // indices
  33817. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33818. var s;
  33819. i = 0;
  33820. for (s = 0; s < subdivisions; s++) {
  33821. var i0 = 0;
  33822. var i1 = 0;
  33823. var i2 = 0;
  33824. var i3 = 0;
  33825. for (j = 0; j < tessellation; j++) {
  33826. i0 = i * (e + 1) + j;
  33827. i1 = (i + 1) * (e + 1) + j;
  33828. i2 = i * (e + 1) + (j + 1);
  33829. i3 = (i + 1) * (e + 1) + (j + 1);
  33830. indices.push(i0, i1, i2);
  33831. indices.push(i3, i2, i1);
  33832. }
  33833. if (arc !== 1 && enclose) {
  33834. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33835. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33836. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33837. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33838. }
  33839. i = (hasRings) ? (i + 2) : (i + 1);
  33840. }
  33841. // Caps
  33842. var createCylinderCap = function (isTop) {
  33843. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33844. if (radius === 0) {
  33845. return;
  33846. }
  33847. // Cap positions, normals & uvs
  33848. var angle;
  33849. var circleVector;
  33850. var i;
  33851. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33852. var c = null;
  33853. if (faceColors) {
  33854. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33855. }
  33856. // cap center
  33857. var vbase = positions.length / 3;
  33858. var offset = isTop ? height / 2 : -height / 2;
  33859. var center = new BABYLON.Vector3(0, offset, 0);
  33860. positions.push(center.x, center.y, center.z);
  33861. normals.push(0, isTop ? 1 : -1, 0);
  33862. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33863. if (c) {
  33864. colors.push(c.r, c.g, c.b, c.a);
  33865. }
  33866. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33867. for (i = 0; i <= tessellation; i++) {
  33868. angle = Math.PI * 2 * i * arc / tessellation;
  33869. var cos = Math.cos(-angle);
  33870. var sin = Math.sin(-angle);
  33871. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33872. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33873. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33874. normals.push(0, isTop ? 1 : -1, 0);
  33875. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33876. if (c) {
  33877. colors.push(c.r, c.g, c.b, c.a);
  33878. }
  33879. }
  33880. // Cap indices
  33881. for (i = 0; i < tessellation; i++) {
  33882. if (!isTop) {
  33883. indices.push(vbase);
  33884. indices.push(vbase + (i + 1));
  33885. indices.push(vbase + (i + 2));
  33886. }
  33887. else {
  33888. indices.push(vbase);
  33889. indices.push(vbase + (i + 2));
  33890. indices.push(vbase + (i + 1));
  33891. }
  33892. }
  33893. };
  33894. // add caps to geometry
  33895. createCylinderCap(false);
  33896. createCylinderCap(true);
  33897. // Sides
  33898. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33899. var vertexData = new VertexData();
  33900. vertexData.indices = indices;
  33901. vertexData.positions = positions;
  33902. vertexData.normals = normals;
  33903. vertexData.uvs = uvs;
  33904. if (faceColors) {
  33905. vertexData.colors = colors;
  33906. }
  33907. return vertexData;
  33908. };
  33909. /**
  33910. * Creates the VertexData of the Torus.
  33911. */
  33912. VertexData.CreateTorus = function (options) {
  33913. var indices = [];
  33914. var positions = [];
  33915. var normals = [];
  33916. var uvs = [];
  33917. var diameter = options.diameter || 1;
  33918. var thickness = options.thickness || 0.5;
  33919. var tessellation = options.tessellation || 16;
  33920. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33921. var stride = tessellation + 1;
  33922. for (var i = 0; i <= tessellation; i++) {
  33923. var u = i / tessellation;
  33924. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33925. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33926. for (var j = 0; j <= tessellation; j++) {
  33927. var v = 1 - j / tessellation;
  33928. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33929. var dx = Math.cos(innerAngle);
  33930. var dy = Math.sin(innerAngle);
  33931. // Create a vertex.
  33932. var normal = new BABYLON.Vector3(dx, dy, 0);
  33933. var position = normal.scale(thickness / 2);
  33934. var textureCoordinate = new BABYLON.Vector2(u, v);
  33935. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33936. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33937. positions.push(position.x, position.y, position.z);
  33938. normals.push(normal.x, normal.y, normal.z);
  33939. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33940. // And create indices for two triangles.
  33941. var nextI = (i + 1) % stride;
  33942. var nextJ = (j + 1) % stride;
  33943. indices.push(i * stride + j);
  33944. indices.push(i * stride + nextJ);
  33945. indices.push(nextI * stride + j);
  33946. indices.push(i * stride + nextJ);
  33947. indices.push(nextI * stride + nextJ);
  33948. indices.push(nextI * stride + j);
  33949. }
  33950. }
  33951. // Sides
  33952. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33953. // Result
  33954. var vertexData = new VertexData();
  33955. vertexData.indices = indices;
  33956. vertexData.positions = positions;
  33957. vertexData.normals = normals;
  33958. vertexData.uvs = uvs;
  33959. return vertexData;
  33960. };
  33961. /**
  33962. * Creates the VertexData of the LineSystem.
  33963. */
  33964. VertexData.CreateLineSystem = function (options) {
  33965. var indices = [];
  33966. var positions = [];
  33967. var lines = options.lines;
  33968. var colors = options.colors;
  33969. var vertexColors = [];
  33970. var idx = 0;
  33971. for (var l = 0; l < lines.length; l++) {
  33972. var points = lines[l];
  33973. for (var index = 0; index < points.length; index++) {
  33974. positions.push(points[index].x, points[index].y, points[index].z);
  33975. if (colors) {
  33976. var color = colors[l];
  33977. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33978. }
  33979. if (index > 0) {
  33980. indices.push(idx - 1);
  33981. indices.push(idx);
  33982. }
  33983. idx++;
  33984. }
  33985. }
  33986. var vertexData = new VertexData();
  33987. vertexData.indices = indices;
  33988. vertexData.positions = positions;
  33989. if (colors) {
  33990. vertexData.colors = vertexColors;
  33991. }
  33992. return vertexData;
  33993. };
  33994. /**
  33995. * Create the VertexData of the DashedLines.
  33996. */
  33997. VertexData.CreateDashedLines = function (options) {
  33998. var dashSize = options.dashSize || 3;
  33999. var gapSize = options.gapSize || 1;
  34000. var dashNb = options.dashNb || 200;
  34001. var points = options.points;
  34002. var positions = new Array();
  34003. var indices = new Array();
  34004. var curvect = BABYLON.Vector3.Zero();
  34005. var lg = 0;
  34006. var nb = 0;
  34007. var shft = 0;
  34008. var dashshft = 0;
  34009. var curshft = 0;
  34010. var idx = 0;
  34011. var i = 0;
  34012. for (i = 0; i < points.length - 1; i++) {
  34013. points[i + 1].subtractToRef(points[i], curvect);
  34014. lg += curvect.length();
  34015. }
  34016. shft = lg / dashNb;
  34017. dashshft = dashSize * shft / (dashSize + gapSize);
  34018. for (i = 0; i < points.length - 1; i++) {
  34019. points[i + 1].subtractToRef(points[i], curvect);
  34020. nb = Math.floor(curvect.length() / shft);
  34021. curvect.normalize();
  34022. for (var j = 0; j < nb; j++) {
  34023. curshft = shft * j;
  34024. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34025. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34026. indices.push(idx, idx + 1);
  34027. idx += 2;
  34028. }
  34029. }
  34030. // Result
  34031. var vertexData = new VertexData();
  34032. vertexData.positions = positions;
  34033. vertexData.indices = indices;
  34034. return vertexData;
  34035. };
  34036. /**
  34037. * Creates the VertexData of the Ground.
  34038. */
  34039. VertexData.CreateGround = function (options) {
  34040. var indices = [];
  34041. var positions = [];
  34042. var normals = [];
  34043. var uvs = [];
  34044. var row, col;
  34045. var width = options.width || 1;
  34046. var height = options.height || 1;
  34047. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34048. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34049. for (row = 0; row <= subdivisionsY; row++) {
  34050. for (col = 0; col <= subdivisionsX; col++) {
  34051. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34052. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34053. positions.push(position.x, position.y, position.z);
  34054. normals.push(normal.x, normal.y, normal.z);
  34055. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34056. }
  34057. }
  34058. for (row = 0; row < subdivisionsY; row++) {
  34059. for (col = 0; col < subdivisionsX; col++) {
  34060. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34061. indices.push(col + 1 + row * (subdivisionsX + 1));
  34062. indices.push(col + row * (subdivisionsX + 1));
  34063. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34064. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34065. indices.push(col + row * (subdivisionsX + 1));
  34066. }
  34067. }
  34068. // Result
  34069. var vertexData = new VertexData();
  34070. vertexData.indices = indices;
  34071. vertexData.positions = positions;
  34072. vertexData.normals = normals;
  34073. vertexData.uvs = uvs;
  34074. return vertexData;
  34075. };
  34076. /**
  34077. * Creates the VertexData of the TiledGround.
  34078. */
  34079. VertexData.CreateTiledGround = function (options) {
  34080. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34081. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34082. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34083. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34084. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34085. var precision = options.precision || { w: 1, h: 1 };
  34086. var indices = new Array();
  34087. var positions = new Array();
  34088. var normals = new Array();
  34089. var uvs = new Array();
  34090. var row, col, tileRow, tileCol;
  34091. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34092. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34093. precision.w = (precision.w < 1) ? 1 : precision.w;
  34094. precision.h = (precision.h < 1) ? 1 : precision.h;
  34095. var tileSize = {
  34096. 'w': (xmax - xmin) / subdivisions.w,
  34097. 'h': (zmax - zmin) / subdivisions.h
  34098. };
  34099. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34100. // Indices
  34101. var base = positions.length / 3;
  34102. var rowLength = precision.w + 1;
  34103. for (row = 0; row < precision.h; row++) {
  34104. for (col = 0; col < precision.w; col++) {
  34105. var square = [
  34106. base + col + row * rowLength,
  34107. base + (col + 1) + row * rowLength,
  34108. base + (col + 1) + (row + 1) * rowLength,
  34109. base + col + (row + 1) * rowLength
  34110. ];
  34111. indices.push(square[1]);
  34112. indices.push(square[2]);
  34113. indices.push(square[3]);
  34114. indices.push(square[0]);
  34115. indices.push(square[1]);
  34116. indices.push(square[3]);
  34117. }
  34118. }
  34119. // Position, normals and uvs
  34120. var position = BABYLON.Vector3.Zero();
  34121. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34122. for (row = 0; row <= precision.h; row++) {
  34123. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34124. for (col = 0; col <= precision.w; col++) {
  34125. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34126. position.y = 0;
  34127. positions.push(position.x, position.y, position.z);
  34128. normals.push(normal.x, normal.y, normal.z);
  34129. uvs.push(col / precision.w, row / precision.h);
  34130. }
  34131. }
  34132. }
  34133. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34134. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34135. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34136. }
  34137. }
  34138. // Result
  34139. var vertexData = new VertexData();
  34140. vertexData.indices = indices;
  34141. vertexData.positions = positions;
  34142. vertexData.normals = normals;
  34143. vertexData.uvs = uvs;
  34144. return vertexData;
  34145. };
  34146. /**
  34147. * Creates the VertexData of the Ground designed from a heightmap.
  34148. */
  34149. VertexData.CreateGroundFromHeightMap = function (options) {
  34150. var indices = [];
  34151. var positions = [];
  34152. var normals = [];
  34153. var uvs = [];
  34154. var row, col;
  34155. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34156. // Vertices
  34157. for (row = 0; row <= options.subdivisions; row++) {
  34158. for (col = 0; col <= options.subdivisions; col++) {
  34159. 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));
  34160. // Compute height
  34161. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34162. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34163. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34164. var r = options.buffer[pos] / 255.0;
  34165. var g = options.buffer[pos + 1] / 255.0;
  34166. var b = options.buffer[pos + 2] / 255.0;
  34167. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34168. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34169. // Add vertex
  34170. positions.push(position.x, position.y, position.z);
  34171. normals.push(0, 0, 0);
  34172. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34173. }
  34174. }
  34175. // Indices
  34176. for (row = 0; row < options.subdivisions; row++) {
  34177. for (col = 0; col < options.subdivisions; col++) {
  34178. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34179. indices.push(col + 1 + row * (options.subdivisions + 1));
  34180. indices.push(col + row * (options.subdivisions + 1));
  34181. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34182. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34183. indices.push(col + row * (options.subdivisions + 1));
  34184. }
  34185. }
  34186. // Normals
  34187. VertexData.ComputeNormals(positions, indices, normals);
  34188. // Result
  34189. var vertexData = new VertexData();
  34190. vertexData.indices = indices;
  34191. vertexData.positions = positions;
  34192. vertexData.normals = normals;
  34193. vertexData.uvs = uvs;
  34194. return vertexData;
  34195. };
  34196. /**
  34197. * Creates the VertexData of the Plane.
  34198. */
  34199. VertexData.CreatePlane = function (options) {
  34200. var indices = [];
  34201. var positions = [];
  34202. var normals = [];
  34203. var uvs = [];
  34204. var width = options.width || options.size || 1;
  34205. var height = options.height || options.size || 1;
  34206. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34207. // Vertices
  34208. var halfWidth = width / 2.0;
  34209. var halfHeight = height / 2.0;
  34210. positions.push(-halfWidth, -halfHeight, 0);
  34211. normals.push(0, 0, -1.0);
  34212. uvs.push(0.0, 0.0);
  34213. positions.push(halfWidth, -halfHeight, 0);
  34214. normals.push(0, 0, -1.0);
  34215. uvs.push(1.0, 0.0);
  34216. positions.push(halfWidth, halfHeight, 0);
  34217. normals.push(0, 0, -1.0);
  34218. uvs.push(1.0, 1.0);
  34219. positions.push(-halfWidth, halfHeight, 0);
  34220. normals.push(0, 0, -1.0);
  34221. uvs.push(0.0, 1.0);
  34222. // Indices
  34223. indices.push(0);
  34224. indices.push(1);
  34225. indices.push(2);
  34226. indices.push(0);
  34227. indices.push(2);
  34228. indices.push(3);
  34229. // Sides
  34230. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34231. // Result
  34232. var vertexData = new VertexData();
  34233. vertexData.indices = indices;
  34234. vertexData.positions = positions;
  34235. vertexData.normals = normals;
  34236. vertexData.uvs = uvs;
  34237. return vertexData;
  34238. };
  34239. /**
  34240. * Creates the VertexData of the Disc or regular Polygon.
  34241. */
  34242. VertexData.CreateDisc = function (options) {
  34243. var positions = new Array();
  34244. var indices = new Array();
  34245. var normals = new Array();
  34246. var uvs = new Array();
  34247. var radius = options.radius || 0.5;
  34248. var tessellation = options.tessellation || 64;
  34249. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34250. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34251. // positions and uvs
  34252. positions.push(0, 0, 0); // disc center first
  34253. uvs.push(0.5, 0.5);
  34254. var theta = Math.PI * 2 * arc;
  34255. var step = theta / tessellation;
  34256. for (var a = 0; a < theta; a += step) {
  34257. var x = Math.cos(a);
  34258. var y = Math.sin(a);
  34259. var u = (x + 1) / 2;
  34260. var v = (1 - y) / 2;
  34261. positions.push(radius * x, radius * y, 0);
  34262. uvs.push(u, v);
  34263. }
  34264. if (arc === 1) {
  34265. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34266. uvs.push(uvs[2], uvs[3]);
  34267. }
  34268. //indices
  34269. var vertexNb = positions.length / 3;
  34270. for (var i = 1; i < vertexNb - 1; i++) {
  34271. indices.push(i + 1, 0, i);
  34272. }
  34273. // result
  34274. VertexData.ComputeNormals(positions, indices, normals);
  34275. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34276. var vertexData = new VertexData();
  34277. vertexData.indices = indices;
  34278. vertexData.positions = positions;
  34279. vertexData.normals = normals;
  34280. vertexData.uvs = uvs;
  34281. return vertexData;
  34282. };
  34283. /**
  34284. * Re-creates the VertexData of the Polygon for sideOrientation.
  34285. */
  34286. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34287. var faceUV = fUV || new Array(3);
  34288. var faceColors = fColors;
  34289. var colors = [];
  34290. // default face colors and UV if undefined
  34291. for (var f = 0; f < 3; f++) {
  34292. if (faceUV[f] === undefined) {
  34293. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34294. }
  34295. if (faceColors && faceColors[f] === undefined) {
  34296. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34297. }
  34298. }
  34299. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34300. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34301. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34302. var indices = polygon.getIndices();
  34303. // set face colours and textures
  34304. var idx = 0;
  34305. var face = 0;
  34306. for (var index = 0; index < normals.length; index += 3) {
  34307. //Edge Face no. 1
  34308. if (Math.abs(normals[index + 1]) < 0.001) {
  34309. face = 1;
  34310. }
  34311. //Top Face no. 0
  34312. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34313. face = 0;
  34314. }
  34315. //Bottom Face no. 2
  34316. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34317. face = 2;
  34318. }
  34319. idx = index / 3;
  34320. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34321. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34322. if (faceColors) {
  34323. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34324. }
  34325. }
  34326. // sides
  34327. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34328. // Result
  34329. var vertexData = new VertexData();
  34330. vertexData.indices = indices;
  34331. vertexData.positions = positions;
  34332. vertexData.normals = normals;
  34333. vertexData.uvs = uvs;
  34334. if (faceColors) {
  34335. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34336. vertexData.colors = totalColors;
  34337. }
  34338. return vertexData;
  34339. };
  34340. /**
  34341. * Creates the VertexData of the IcoSphere.
  34342. */
  34343. VertexData.CreateIcoSphere = function (options) {
  34344. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34345. var radius = options.radius || 1;
  34346. var flat = (options.flat === undefined) ? true : options.flat;
  34347. var subdivisions = options.subdivisions || 4;
  34348. var radiusX = options.radiusX || radius;
  34349. var radiusY = options.radiusY || radius;
  34350. var radiusZ = options.radiusZ || radius;
  34351. var t = (1 + Math.sqrt(5)) / 2;
  34352. // 12 vertex x,y,z
  34353. var ico_vertices = [
  34354. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34355. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34356. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34357. ];
  34358. // index of 3 vertex makes a face of icopshere
  34359. var ico_indices = [
  34360. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34361. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34362. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34363. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34364. ];
  34365. // vertex for uv have aliased position, not for UV
  34366. var vertices_unalias_id = [
  34367. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34368. // vertex alias
  34369. 0,
  34370. 2,
  34371. 3,
  34372. 3,
  34373. 3,
  34374. 4,
  34375. 7,
  34376. 8,
  34377. 9,
  34378. 9,
  34379. 10,
  34380. 11 // 23: B + 12
  34381. ];
  34382. // uv as integer step (not pixels !)
  34383. var ico_vertexuv = [
  34384. 5, 1, 3, 1, 6, 4, 0, 0,
  34385. 5, 3, 4, 2, 2, 2, 4, 0,
  34386. 2, 0, 1, 1, 6, 0, 6, 2,
  34387. // vertex alias (for same vertex on different faces)
  34388. 0, 4,
  34389. 3, 3,
  34390. 4, 4,
  34391. 3, 1,
  34392. 4, 2,
  34393. 4, 4,
  34394. 0, 2,
  34395. 1, 1,
  34396. 2, 2,
  34397. 3, 3,
  34398. 1, 3,
  34399. 2, 4 // 23: B + 12
  34400. ];
  34401. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34402. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34403. // First island of uv mapping
  34404. // v = 4h 3+ 2
  34405. // v = 3h 9+ 4
  34406. // v = 2h 9+ 5 B
  34407. // v = 1h 9 1 0
  34408. // v = 0h 3 8 7 A
  34409. // u = 0 1 2 3 4 5 6 *a
  34410. // Second island of uv mapping
  34411. // v = 4h 0+ B+ 4+
  34412. // v = 3h A+ 2+
  34413. // v = 2h 7+ 6 3+
  34414. // v = 1h 8+ 3+
  34415. // v = 0h
  34416. // u = 0 1 2 3 4 5 6 *a
  34417. // Face layout on texture UV mapping
  34418. // ============
  34419. // \ 4 /\ 16 / ======
  34420. // \ / \ / /\ 11 /
  34421. // \/ 7 \/ / \ /
  34422. // ======= / 10 \/
  34423. // /\ 17 /\ =======
  34424. // / \ / \ \ 15 /\
  34425. // / 8 \/ 12 \ \ / \
  34426. // ============ \/ 6 \
  34427. // \ 18 /\ ============
  34428. // \ / \ \ 5 /\ 0 /
  34429. // \/ 13 \ \ / \ /
  34430. // ======= \/ 1 \/
  34431. // =============
  34432. // /\ 19 /\ 2 /\
  34433. // / \ / \ / \
  34434. // / 14 \/ 9 \/ 3 \
  34435. // ===================
  34436. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34437. var ustep = 138 / 1024;
  34438. var vstep = 239 / 1024;
  34439. var uoffset = 60 / 1024;
  34440. var voffset = 26 / 1024;
  34441. // Second island should have margin, not to touch the first island
  34442. // avoid any borderline artefact in pixel rounding
  34443. var island_u_offset = -40 / 1024;
  34444. var island_v_offset = +20 / 1024;
  34445. // face is either island 0 or 1 :
  34446. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34447. var island = [
  34448. 0, 0, 0, 0, 1,
  34449. 0, 0, 1, 1, 0,
  34450. 0, 0, 1, 1, 0,
  34451. 0, 1, 1, 1, 0 // 15 - 19
  34452. ];
  34453. var indices = new Array();
  34454. var positions = new Array();
  34455. var normals = new Array();
  34456. var uvs = new Array();
  34457. var current_indice = 0;
  34458. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34459. var face_vertex_pos = new Array(3);
  34460. var face_vertex_uv = new Array(3);
  34461. var v012;
  34462. for (v012 = 0; v012 < 3; v012++) {
  34463. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34464. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34465. }
  34466. // create all with normals
  34467. for (var face = 0; face < 20; face++) {
  34468. // 3 vertex per face
  34469. for (v012 = 0; v012 < 3; v012++) {
  34470. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34471. var v_id = ico_indices[3 * face + v012];
  34472. // vertex have 3D position (x,y,z)
  34473. 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]);
  34474. // Normalize to get normal, then scale to radius
  34475. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34476. // uv Coordinates from vertex ID
  34477. 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);
  34478. }
  34479. // Subdivide the face (interpolate pos, norm, uv)
  34480. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34481. // - norm is linear interpolation of vertex corner normal
  34482. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34483. // - uv is linear interpolation
  34484. //
  34485. // Topology is as below for sub-divide by 2
  34486. // vertex shown as v0,v1,v2
  34487. // interp index is i1 to progress in range [v0,v1[
  34488. // interp index is i2 to progress in range [v0,v2[
  34489. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34490. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34491. //
  34492. //
  34493. // i2 v2
  34494. // ^ ^
  34495. // / / \
  34496. // / / \
  34497. // / / \
  34498. // / / (0,1) \
  34499. // / #---------\
  34500. // / / \ (0,0)'/ \
  34501. // / / \ / \
  34502. // / / \ / \
  34503. // / / (0,0) \ / (1,0) \
  34504. // / #---------#---------\
  34505. // v0 v1
  34506. //
  34507. // --------------------> i1
  34508. //
  34509. // interp of (i1,i2):
  34510. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34511. // along i1 : lerp(x0,x1, i1/(S-i2))
  34512. //
  34513. // centroid of triangle is needed to get help normal computation
  34514. // (c1,c2) are used for centroid location
  34515. var interp_vertex = function (i1, i2, c1, c2) {
  34516. // vertex is interpolated from
  34517. // - face_vertex_pos[0..2]
  34518. // - face_vertex_uv[0..2]
  34519. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34520. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34521. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34522. pos_interp.normalize();
  34523. var vertex_normal;
  34524. if (flat) {
  34525. // in flat mode, recalculate normal as face centroid normal
  34526. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34527. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34528. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34529. }
  34530. else {
  34531. // in smooth mode, recalculate normal from each single vertex position
  34532. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34533. }
  34534. // Vertex normal need correction due to X,Y,Z radius scaling
  34535. vertex_normal.x /= radiusX;
  34536. vertex_normal.y /= radiusY;
  34537. vertex_normal.z /= radiusZ;
  34538. vertex_normal.normalize();
  34539. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34540. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34541. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34542. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34543. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34544. uvs.push(uv_interp.x, uv_interp.y);
  34545. // push each vertex has member of a face
  34546. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34547. indices.push(current_indice);
  34548. current_indice++;
  34549. };
  34550. for (var i2 = 0; i2 < subdivisions; i2++) {
  34551. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34552. // face : (i1,i2) for /\ :
  34553. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34554. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34555. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34556. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34557. if (i1 + i2 + 1 < subdivisions) {
  34558. // face : (i1,i2)' for \/ :
  34559. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34560. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34561. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34562. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34563. }
  34564. }
  34565. }
  34566. }
  34567. // Sides
  34568. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34569. // Result
  34570. var vertexData = new VertexData();
  34571. vertexData.indices = indices;
  34572. vertexData.positions = positions;
  34573. vertexData.normals = normals;
  34574. vertexData.uvs = uvs;
  34575. return vertexData;
  34576. };
  34577. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34578. /**
  34579. * Creates the VertexData of the Polyhedron.
  34580. */
  34581. VertexData.CreatePolyhedron = function (options) {
  34582. // provided polyhedron types :
  34583. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34584. // 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)
  34585. var polyhedra = [];
  34586. 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]] };
  34587. 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]] };
  34588. polyhedra[2] = {
  34589. 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]],
  34590. 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]]
  34591. };
  34592. polyhedra[3] = {
  34593. 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]],
  34594. 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]]
  34595. };
  34596. polyhedra[4] = {
  34597. 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]],
  34598. 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]]
  34599. };
  34600. 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]] };
  34601. 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]] };
  34602. 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]] };
  34603. 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]] };
  34604. 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]] };
  34605. 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]] };
  34606. 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]] };
  34607. 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]] };
  34608. 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]] };
  34609. polyhedra[14] = {
  34610. 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]],
  34611. 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]]
  34612. };
  34613. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34614. var size = options.size;
  34615. var sizeX = options.sizeX || size || 1;
  34616. var sizeY = options.sizeY || size || 1;
  34617. var sizeZ = options.sizeZ || size || 1;
  34618. var data = options.custom || polyhedra[type];
  34619. var nbfaces = data.face.length;
  34620. var faceUV = options.faceUV || new Array(nbfaces);
  34621. var faceColors = options.faceColors;
  34622. var flat = (options.flat === undefined) ? true : options.flat;
  34623. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34624. var positions = new Array();
  34625. var indices = new Array();
  34626. var normals = new Array();
  34627. var uvs = new Array();
  34628. var colors = new Array();
  34629. var index = 0;
  34630. var faceIdx = 0; // face cursor in the array "indexes"
  34631. var indexes = new Array();
  34632. var i = 0;
  34633. var f = 0;
  34634. var u, v, ang, x, y, tmp;
  34635. // default face colors and UV if undefined
  34636. if (flat) {
  34637. for (f = 0; f < nbfaces; f++) {
  34638. if (faceColors && faceColors[f] === undefined) {
  34639. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34640. }
  34641. if (faceUV && faceUV[f] === undefined) {
  34642. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34643. }
  34644. }
  34645. }
  34646. if (!flat) {
  34647. for (i = 0; i < data.vertex.length; i++) {
  34648. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34649. uvs.push(0, 0);
  34650. }
  34651. for (f = 0; f < nbfaces; f++) {
  34652. for (i = 0; i < data.face[f].length - 2; i++) {
  34653. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34654. }
  34655. }
  34656. }
  34657. else {
  34658. for (f = 0; f < nbfaces; f++) {
  34659. var fl = data.face[f].length; // number of vertices of the current face
  34660. ang = 2 * Math.PI / fl;
  34661. x = 0.5 * Math.tan(ang / 2);
  34662. y = 0.5;
  34663. // positions, uvs, colors
  34664. for (i = 0; i < fl; i++) {
  34665. // positions
  34666. 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);
  34667. indexes.push(index);
  34668. index++;
  34669. // uvs
  34670. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34671. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34672. uvs.push(u, v);
  34673. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34674. y = x * Math.sin(ang) + y * Math.cos(ang);
  34675. x = tmp;
  34676. // colors
  34677. if (faceColors) {
  34678. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34679. }
  34680. }
  34681. // indices from indexes
  34682. for (i = 0; i < fl - 2; i++) {
  34683. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34684. }
  34685. faceIdx += fl;
  34686. }
  34687. }
  34688. VertexData.ComputeNormals(positions, indices, normals);
  34689. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34690. var vertexData = new VertexData();
  34691. vertexData.positions = positions;
  34692. vertexData.indices = indices;
  34693. vertexData.normals = normals;
  34694. vertexData.uvs = uvs;
  34695. if (faceColors && flat) {
  34696. vertexData.colors = colors;
  34697. }
  34698. return vertexData;
  34699. };
  34700. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34701. /**
  34702. * Creates the VertexData of the Torus Knot.
  34703. */
  34704. VertexData.CreateTorusKnot = function (options) {
  34705. var indices = new Array();
  34706. var positions = new Array();
  34707. var normals = new Array();
  34708. var uvs = new Array();
  34709. var radius = options.radius || 2;
  34710. var tube = options.tube || 0.5;
  34711. var radialSegments = options.radialSegments || 32;
  34712. var tubularSegments = options.tubularSegments || 32;
  34713. var p = options.p || 2;
  34714. var q = options.q || 3;
  34715. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34716. // Helper
  34717. var getPos = function (angle) {
  34718. var cu = Math.cos(angle);
  34719. var su = Math.sin(angle);
  34720. var quOverP = q / p * angle;
  34721. var cs = Math.cos(quOverP);
  34722. var tx = radius * (2 + cs) * 0.5 * cu;
  34723. var ty = radius * (2 + cs) * su * 0.5;
  34724. var tz = radius * Math.sin(quOverP) * 0.5;
  34725. return new BABYLON.Vector3(tx, ty, tz);
  34726. };
  34727. // Vertices
  34728. var i;
  34729. var j;
  34730. for (i = 0; i <= radialSegments; i++) {
  34731. var modI = i % radialSegments;
  34732. var u = modI / radialSegments * 2 * p * Math.PI;
  34733. var p1 = getPos(u);
  34734. var p2 = getPos(u + 0.01);
  34735. var tang = p2.subtract(p1);
  34736. var n = p2.add(p1);
  34737. var bitan = BABYLON.Vector3.Cross(tang, n);
  34738. n = BABYLON.Vector3.Cross(bitan, tang);
  34739. bitan.normalize();
  34740. n.normalize();
  34741. for (j = 0; j < tubularSegments; j++) {
  34742. var modJ = j % tubularSegments;
  34743. var v = modJ / tubularSegments * 2 * Math.PI;
  34744. var cx = -tube * Math.cos(v);
  34745. var cy = tube * Math.sin(v);
  34746. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34747. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34748. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34749. uvs.push(i / radialSegments);
  34750. uvs.push(j / tubularSegments);
  34751. }
  34752. }
  34753. for (i = 0; i < radialSegments; i++) {
  34754. for (j = 0; j < tubularSegments; j++) {
  34755. var jNext = (j + 1) % tubularSegments;
  34756. var a = i * tubularSegments + j;
  34757. var b = (i + 1) * tubularSegments + j;
  34758. var c = (i + 1) * tubularSegments + jNext;
  34759. var d = i * tubularSegments + jNext;
  34760. indices.push(d);
  34761. indices.push(b);
  34762. indices.push(a);
  34763. indices.push(d);
  34764. indices.push(c);
  34765. indices.push(b);
  34766. }
  34767. }
  34768. // Normals
  34769. VertexData.ComputeNormals(positions, indices, normals);
  34770. // Sides
  34771. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34772. // Result
  34773. var vertexData = new VertexData();
  34774. vertexData.indices = indices;
  34775. vertexData.positions = positions;
  34776. vertexData.normals = normals;
  34777. vertexData.uvs = uvs;
  34778. return vertexData;
  34779. };
  34780. // Tools
  34781. /**
  34782. * @param {any} - positions (number[] or Float32Array)
  34783. * @param {any} - indices (number[] or Uint16Array)
  34784. * @param {any} - normals (number[] or Float32Array)
  34785. * options (optional) :
  34786. * facetPositions : optional array of facet positions (vector3)
  34787. * facetNormals : optional array of facet normals (vector3)
  34788. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34789. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34790. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34791. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34792. * bInfo : optional bounding info, required for facetPartitioning computation
  34793. * useRightHandedSystem: optional boolean to for right handed system computation
  34794. * depthSort : optional boolean to enable the facet depth sort computation
  34795. * distanceTo : optional Vector3 to compute the facet depth from this location
  34796. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34797. */
  34798. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34799. // temporary scalar variables
  34800. var index = 0; // facet index
  34801. var p1p2x = 0.0; // p1p2 vector x coordinate
  34802. var p1p2y = 0.0; // p1p2 vector y coordinate
  34803. var p1p2z = 0.0; // p1p2 vector z coordinate
  34804. var p3p2x = 0.0; // p3p2 vector x coordinate
  34805. var p3p2y = 0.0; // p3p2 vector y coordinate
  34806. var p3p2z = 0.0; // p3p2 vector z coordinate
  34807. var faceNormalx = 0.0; // facet normal x coordinate
  34808. var faceNormaly = 0.0; // facet normal y coordinate
  34809. var faceNormalz = 0.0; // facet normal z coordinate
  34810. var length = 0.0; // facet normal length before normalization
  34811. var v1x = 0; // vector1 x index in the positions array
  34812. var v1y = 0; // vector1 y index in the positions array
  34813. var v1z = 0; // vector1 z index in the positions array
  34814. var v2x = 0; // vector2 x index in the positions array
  34815. var v2y = 0; // vector2 y index in the positions array
  34816. var v2z = 0; // vector2 z index in the positions array
  34817. var v3x = 0; // vector3 x index in the positions array
  34818. var v3y = 0; // vector3 y index in the positions array
  34819. var v3z = 0; // vector3 z index in the positions array
  34820. var computeFacetNormals = false;
  34821. var computeFacetPositions = false;
  34822. var computeFacetPartitioning = false;
  34823. var computeDepthSort = false;
  34824. var faceNormalSign = 1;
  34825. var ratio = 0;
  34826. var distanceTo = null;
  34827. if (options) {
  34828. computeFacetNormals = (options.facetNormals) ? true : false;
  34829. computeFacetPositions = (options.facetPositions) ? true : false;
  34830. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34831. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34832. ratio = options.ratio || 0;
  34833. computeDepthSort = (options.depthSort) ? true : false;
  34834. distanceTo = (options.distanceTo);
  34835. if (computeDepthSort) {
  34836. if (distanceTo === undefined) {
  34837. distanceTo = BABYLON.Vector3.Zero();
  34838. }
  34839. var depthSortedFacets = options.depthSortedFacets;
  34840. }
  34841. }
  34842. // facetPartitioning reinit if needed
  34843. var xSubRatio = 0;
  34844. var ySubRatio = 0;
  34845. var zSubRatio = 0;
  34846. var subSq = 0;
  34847. if (computeFacetPartitioning && options && options.bbSize) {
  34848. var ox = 0; // X partitioning index for facet position
  34849. var oy = 0; // Y partinioning index for facet position
  34850. var oz = 0; // Z partinioning index for facet position
  34851. var b1x = 0; // X partitioning index for facet v1 vertex
  34852. var b1y = 0; // Y partitioning index for facet v1 vertex
  34853. var b1z = 0; // z partitioning index for facet v1 vertex
  34854. var b2x = 0; // X partitioning index for facet v2 vertex
  34855. var b2y = 0; // Y partitioning index for facet v2 vertex
  34856. var b2z = 0; // Z partitioning index for facet v2 vertex
  34857. var b3x = 0; // X partitioning index for facet v3 vertex
  34858. var b3y = 0; // Y partitioning index for facet v3 vertex
  34859. var b3z = 0; // Z partitioning index for facet v3 vertex
  34860. var block_idx_o = 0; // facet barycenter block index
  34861. var block_idx_v1 = 0; // v1 vertex block index
  34862. var block_idx_v2 = 0; // v2 vertex block index
  34863. var block_idx_v3 = 0; // v3 vertex block index
  34864. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34865. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34866. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34867. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34868. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34869. subSq = options.subDiv.max * options.subDiv.max;
  34870. options.facetPartitioning.length = 0;
  34871. }
  34872. // reset the normals
  34873. for (index = 0; index < positions.length; index++) {
  34874. normals[index] = 0.0;
  34875. }
  34876. // Loop : 1 indice triplet = 1 facet
  34877. var nbFaces = (indices.length / 3) | 0;
  34878. for (index = 0; index < nbFaces; index++) {
  34879. // get the indexes of the coordinates of each vertex of the facet
  34880. v1x = indices[index * 3] * 3;
  34881. v1y = v1x + 1;
  34882. v1z = v1x + 2;
  34883. v2x = indices[index * 3 + 1] * 3;
  34884. v2y = v2x + 1;
  34885. v2z = v2x + 2;
  34886. v3x = indices[index * 3 + 2] * 3;
  34887. v3y = v3x + 1;
  34888. v3z = v3x + 2;
  34889. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34890. p1p2y = positions[v1y] - positions[v2y];
  34891. p1p2z = positions[v1z] - positions[v2z];
  34892. p3p2x = positions[v3x] - positions[v2x];
  34893. p3p2y = positions[v3y] - positions[v2y];
  34894. p3p2z = positions[v3z] - positions[v2z];
  34895. // compute the face normal with the cross product
  34896. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34897. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34898. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34899. // normalize this normal and store it in the array facetData
  34900. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34901. length = (length === 0) ? 1.0 : length;
  34902. faceNormalx /= length;
  34903. faceNormaly /= length;
  34904. faceNormalz /= length;
  34905. if (computeFacetNormals && options) {
  34906. options.facetNormals[index].x = faceNormalx;
  34907. options.facetNormals[index].y = faceNormaly;
  34908. options.facetNormals[index].z = faceNormalz;
  34909. }
  34910. if (computeFacetPositions && options) {
  34911. // compute and the facet barycenter coordinates in the array facetPositions
  34912. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34913. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34914. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34915. }
  34916. if (computeFacetPartitioning && options) {
  34917. // store the facet indexes in arrays in the main facetPartitioning array :
  34918. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34919. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34920. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34921. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34922. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34923. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34924. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34925. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34926. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34927. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34928. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34929. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34930. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34931. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34932. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34933. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34934. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34935. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34936. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34937. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34938. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34939. // push each facet index in each block containing the vertex
  34940. options.facetPartitioning[block_idx_v1].push(index);
  34941. if (block_idx_v2 != block_idx_v1) {
  34942. options.facetPartitioning[block_idx_v2].push(index);
  34943. }
  34944. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34945. options.facetPartitioning[block_idx_v3].push(index);
  34946. }
  34947. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34948. options.facetPartitioning[block_idx_o].push(index);
  34949. }
  34950. }
  34951. if (computeDepthSort && options && options.facetPositions) {
  34952. var dsf = depthSortedFacets[index];
  34953. dsf.ind = index * 3;
  34954. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34955. }
  34956. // compute the normals anyway
  34957. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34958. normals[v1y] += faceNormaly;
  34959. normals[v1z] += faceNormalz;
  34960. normals[v2x] += faceNormalx;
  34961. normals[v2y] += faceNormaly;
  34962. normals[v2z] += faceNormalz;
  34963. normals[v3x] += faceNormalx;
  34964. normals[v3y] += faceNormaly;
  34965. normals[v3z] += faceNormalz;
  34966. }
  34967. // last normalization of each normal
  34968. for (index = 0; index < normals.length / 3; index++) {
  34969. faceNormalx = normals[index * 3];
  34970. faceNormaly = normals[index * 3 + 1];
  34971. faceNormalz = normals[index * 3 + 2];
  34972. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34973. length = (length === 0) ? 1.0 : length;
  34974. faceNormalx /= length;
  34975. faceNormaly /= length;
  34976. faceNormalz /= length;
  34977. normals[index * 3] = faceNormalx;
  34978. normals[index * 3 + 1] = faceNormaly;
  34979. normals[index * 3 + 2] = faceNormalz;
  34980. }
  34981. };
  34982. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34983. var li = indices.length;
  34984. var ln = normals.length;
  34985. var i;
  34986. var n;
  34987. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34988. switch (sideOrientation) {
  34989. case BABYLON.Mesh.FRONTSIDE:
  34990. // nothing changed
  34991. break;
  34992. case BABYLON.Mesh.BACKSIDE:
  34993. var tmp;
  34994. // indices
  34995. for (i = 0; i < li; i += 3) {
  34996. tmp = indices[i];
  34997. indices[i] = indices[i + 2];
  34998. indices[i + 2] = tmp;
  34999. }
  35000. // normals
  35001. for (n = 0; n < ln; n++) {
  35002. normals[n] = -normals[n];
  35003. }
  35004. break;
  35005. case BABYLON.Mesh.DOUBLESIDE:
  35006. // positions
  35007. var lp = positions.length;
  35008. var l = lp / 3;
  35009. for (var p = 0; p < lp; p++) {
  35010. positions[lp + p] = positions[p];
  35011. }
  35012. // indices
  35013. for (i = 0; i < li; i += 3) {
  35014. indices[i + li] = indices[i + 2] + l;
  35015. indices[i + 1 + li] = indices[i + 1] + l;
  35016. indices[i + 2 + li] = indices[i] + l;
  35017. }
  35018. // normals
  35019. for (n = 0; n < ln; n++) {
  35020. normals[ln + n] = -normals[n];
  35021. }
  35022. // uvs
  35023. var lu = uvs.length;
  35024. var u = 0;
  35025. for (u = 0; u < lu; u++) {
  35026. uvs[u + lu] = uvs[u];
  35027. }
  35028. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35029. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35030. u = 0;
  35031. for (i = 0; i < lu / 2; i++) {
  35032. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  35033. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  35034. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  35035. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  35036. u += 2;
  35037. }
  35038. break;
  35039. }
  35040. };
  35041. /**
  35042. * Creates a new VertexData from the imported parameters.
  35043. */
  35044. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35045. var vertexData = new VertexData();
  35046. // positions
  35047. var positions = parsedVertexData.positions;
  35048. if (positions) {
  35049. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35050. }
  35051. // normals
  35052. var normals = parsedVertexData.normals;
  35053. if (normals) {
  35054. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35055. }
  35056. // tangents
  35057. var tangents = parsedVertexData.tangents;
  35058. if (tangents) {
  35059. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35060. }
  35061. // uvs
  35062. var uvs = parsedVertexData.uvs;
  35063. if (uvs) {
  35064. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35065. }
  35066. // uv2s
  35067. var uv2s = parsedVertexData.uv2s;
  35068. if (uv2s) {
  35069. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35070. }
  35071. // uv3s
  35072. var uv3s = parsedVertexData.uv3s;
  35073. if (uv3s) {
  35074. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35075. }
  35076. // uv4s
  35077. var uv4s = parsedVertexData.uv4s;
  35078. if (uv4s) {
  35079. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35080. }
  35081. // uv5s
  35082. var uv5s = parsedVertexData.uv5s;
  35083. if (uv5s) {
  35084. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35085. }
  35086. // uv6s
  35087. var uv6s = parsedVertexData.uv6s;
  35088. if (uv6s) {
  35089. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35090. }
  35091. // colors
  35092. var colors = parsedVertexData.colors;
  35093. if (colors) {
  35094. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35095. }
  35096. // matricesIndices
  35097. var matricesIndices = parsedVertexData.matricesIndices;
  35098. if (matricesIndices) {
  35099. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35100. }
  35101. // matricesWeights
  35102. var matricesWeights = parsedVertexData.matricesWeights;
  35103. if (matricesWeights) {
  35104. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35105. }
  35106. // indices
  35107. var indices = parsedVertexData.indices;
  35108. if (indices) {
  35109. vertexData.indices = indices;
  35110. }
  35111. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35112. };
  35113. return VertexData;
  35114. }());
  35115. BABYLON.VertexData = VertexData;
  35116. })(BABYLON || (BABYLON = {}));
  35117. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35118. "use strict";
  35119. var BABYLON;
  35120. (function (BABYLON) {
  35121. /**
  35122. * Class used to store geometry data (vertex buffers + index buffer)
  35123. */
  35124. var Geometry = /** @class */ (function () {
  35125. /**
  35126. * Creates a new geometry
  35127. * @param id defines the unique ID
  35128. * @param scene defines the hosting scene
  35129. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35130. * @param updatable defines if geometry must be updatable (false by default)
  35131. * @param mesh defines the mesh that will be associated with the geometry
  35132. */
  35133. function Geometry(id, scene, vertexData, updatable, mesh) {
  35134. if (updatable === void 0) { updatable = false; }
  35135. if (mesh === void 0) { mesh = null; }
  35136. /**
  35137. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35138. */
  35139. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35140. this._totalVertices = 0;
  35141. this._isDisposed = false;
  35142. this._indexBufferIsUpdatable = false;
  35143. this.id = id;
  35144. this._engine = scene.getEngine();
  35145. this._meshes = [];
  35146. this._scene = scene;
  35147. //Init vertex buffer cache
  35148. this._vertexBuffers = {};
  35149. this._indices = [];
  35150. this._updatable = updatable;
  35151. // vertexData
  35152. if (vertexData) {
  35153. this.setAllVerticesData(vertexData, updatable);
  35154. }
  35155. else {
  35156. this._totalVertices = 0;
  35157. this._indices = [];
  35158. }
  35159. if (this._engine.getCaps().vertexArrayObject) {
  35160. this._vertexArrayObjects = {};
  35161. }
  35162. // applyToMesh
  35163. if (mesh) {
  35164. if (mesh.getClassName() === "LinesMesh") {
  35165. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35166. this.updateExtend();
  35167. }
  35168. this.applyToMesh(mesh);
  35169. mesh.computeWorldMatrix(true);
  35170. }
  35171. }
  35172. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35173. /**
  35174. * 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
  35175. */
  35176. get: function () {
  35177. return this._boundingBias;
  35178. },
  35179. /**
  35180. * 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
  35181. */
  35182. set: function (value) {
  35183. if (this._boundingBias && this._boundingBias.equals(value)) {
  35184. return;
  35185. }
  35186. this._boundingBias = value.clone();
  35187. this.updateBoundingInfo(true, null);
  35188. },
  35189. enumerable: true,
  35190. configurable: true
  35191. });
  35192. /**
  35193. * Static function used to attach a new empty geometry to a mesh
  35194. * @param mesh defines the mesh to attach the geometry to
  35195. * @returns the new {BABYLON.Geometry}
  35196. */
  35197. Geometry.CreateGeometryForMesh = function (mesh) {
  35198. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35199. geometry.applyToMesh(mesh);
  35200. return geometry;
  35201. };
  35202. Object.defineProperty(Geometry.prototype, "extend", {
  35203. /**
  35204. * Gets the current extend of the geometry
  35205. */
  35206. get: function () {
  35207. return this._extend;
  35208. },
  35209. enumerable: true,
  35210. configurable: true
  35211. });
  35212. /**
  35213. * Gets the hosting scene
  35214. * @returns the hosting {BABYLON.Scene}
  35215. */
  35216. Geometry.prototype.getScene = function () {
  35217. return this._scene;
  35218. };
  35219. /**
  35220. * Gets the hosting engine
  35221. * @returns the hosting {BABYLON.Engine}
  35222. */
  35223. Geometry.prototype.getEngine = function () {
  35224. return this._engine;
  35225. };
  35226. /**
  35227. * Defines if the geometry is ready to use
  35228. * @returns true if the geometry is ready to be used
  35229. */
  35230. Geometry.prototype.isReady = function () {
  35231. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35232. };
  35233. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35234. /**
  35235. * Gets a value indicating that the geometry should not be serialized
  35236. */
  35237. get: function () {
  35238. for (var index = 0; index < this._meshes.length; index++) {
  35239. if (!this._meshes[index].doNotSerialize) {
  35240. return false;
  35241. }
  35242. }
  35243. return true;
  35244. },
  35245. enumerable: true,
  35246. configurable: true
  35247. });
  35248. /** @ignore */
  35249. Geometry.prototype._rebuild = function () {
  35250. if (this._vertexArrayObjects) {
  35251. this._vertexArrayObjects = {};
  35252. }
  35253. // Index buffer
  35254. if (this._meshes.length !== 0 && this._indices) {
  35255. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35256. }
  35257. // Vertex buffers
  35258. for (var key in this._vertexBuffers) {
  35259. var vertexBuffer = this._vertexBuffers[key];
  35260. vertexBuffer._rebuild();
  35261. }
  35262. };
  35263. /**
  35264. * Affects all gemetry data in one call
  35265. * @param vertexData defines the geometry data
  35266. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35267. */
  35268. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35269. vertexData.applyToGeometry(this, updatable);
  35270. this.notifyUpdate();
  35271. };
  35272. /**
  35273. * Set specific vertex data
  35274. * @param kind defines the data kind (Position, normal, etc...)
  35275. * @param data defines the vertex data to use
  35276. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35277. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35278. */
  35279. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35280. if (updatable === void 0) { updatable = false; }
  35281. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35282. this.setVerticesBuffer(buffer);
  35283. };
  35284. /**
  35285. * Removes a specific vertex data
  35286. * @param kind defines the data kind (Position, normal, etc...)
  35287. */
  35288. Geometry.prototype.removeVerticesData = function (kind) {
  35289. if (this._vertexBuffers[kind]) {
  35290. this._vertexBuffers[kind].dispose();
  35291. delete this._vertexBuffers[kind];
  35292. }
  35293. };
  35294. /**
  35295. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35296. * @param buffer defines the vertex buffer to use
  35297. */
  35298. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35299. var kind = buffer.getKind();
  35300. if (this._vertexBuffers[kind]) {
  35301. this._vertexBuffers[kind].dispose();
  35302. }
  35303. this._vertexBuffers[kind] = buffer;
  35304. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35305. var data = buffer.getData();
  35306. var stride = buffer.getStrideSize();
  35307. this._totalVertices = data.length / stride;
  35308. this.updateExtend(data, stride);
  35309. this._resetPointsArrayCache();
  35310. var meshes = this._meshes;
  35311. var numOfMeshes = meshes.length;
  35312. for (var index = 0; index < numOfMeshes; index++) {
  35313. var mesh = meshes[index];
  35314. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35315. mesh._createGlobalSubMesh(false);
  35316. mesh.computeWorldMatrix(true);
  35317. }
  35318. }
  35319. this.notifyUpdate(kind);
  35320. if (this._vertexArrayObjects) {
  35321. this._disposeVertexArrayObjects();
  35322. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35323. }
  35324. };
  35325. /**
  35326. * Update a specific vertex buffer
  35327. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35328. * It will do nothing if the buffer is not updatable
  35329. * @param kind defines the data kind (Position, normal, etc...)
  35330. * @param data defines the data to use
  35331. * @param offset defines the offset in the target buffer where to store the data
  35332. */
  35333. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35334. var vertexBuffer = this.getVertexBuffer(kind);
  35335. if (!vertexBuffer) {
  35336. return;
  35337. }
  35338. vertexBuffer.updateDirectly(data, offset);
  35339. this.notifyUpdate(kind);
  35340. };
  35341. /**
  35342. * Update a specific vertex buffer
  35343. * This function will create a new buffer if the current one is not updatable
  35344. * @param kind defines the data kind (Position, normal, etc...)
  35345. * @param data defines the data to use
  35346. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35347. */
  35348. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35349. if (updateExtends === void 0) { updateExtends = false; }
  35350. var vertexBuffer = this.getVertexBuffer(kind);
  35351. if (!vertexBuffer) {
  35352. return;
  35353. }
  35354. vertexBuffer.update(data);
  35355. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35356. var stride = vertexBuffer.getStrideSize();
  35357. this._totalVertices = data.length / stride;
  35358. this.updateBoundingInfo(updateExtends, data);
  35359. }
  35360. this.notifyUpdate(kind);
  35361. };
  35362. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35363. if (updateExtends) {
  35364. this.updateExtend(data);
  35365. }
  35366. var meshes = this._meshes;
  35367. var numOfMeshes = meshes.length;
  35368. this._resetPointsArrayCache();
  35369. for (var index = 0; index < numOfMeshes; index++) {
  35370. var mesh = meshes[index];
  35371. if (updateExtends) {
  35372. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35373. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35374. var subMesh = mesh.subMeshes[subIndex];
  35375. subMesh.refreshBoundingInfo();
  35376. }
  35377. }
  35378. }
  35379. };
  35380. /** @ignore */
  35381. Geometry.prototype._bind = function (effect, indexToBind) {
  35382. if (!effect) {
  35383. return;
  35384. }
  35385. if (indexToBind === undefined) {
  35386. indexToBind = this._indexBuffer;
  35387. }
  35388. var vbs = this.getVertexBuffers();
  35389. if (!vbs) {
  35390. return;
  35391. }
  35392. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35393. this._engine.bindBuffers(vbs, indexToBind, effect);
  35394. return;
  35395. }
  35396. // Using VAO
  35397. if (!this._vertexArrayObjects[effect.key]) {
  35398. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35399. }
  35400. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35401. };
  35402. /**
  35403. * Gets total number of vertices
  35404. * @returns the total number of vertices
  35405. */
  35406. Geometry.prototype.getTotalVertices = function () {
  35407. if (!this.isReady()) {
  35408. return 0;
  35409. }
  35410. return this._totalVertices;
  35411. };
  35412. /**
  35413. * Gets a specific vertex data attached to this geometry
  35414. * @param kind defines the data kind (Position, normal, etc...)
  35415. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35416. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35417. * @returns a float array containing vertex data
  35418. */
  35419. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35420. var vertexBuffer = this.getVertexBuffer(kind);
  35421. if (!vertexBuffer) {
  35422. return null;
  35423. }
  35424. var orig = vertexBuffer.getData();
  35425. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35426. return orig;
  35427. }
  35428. else {
  35429. var len = orig.length;
  35430. var copy = [];
  35431. for (var i = 0; i < len; i++) {
  35432. copy.push(orig[i]);
  35433. }
  35434. return copy;
  35435. }
  35436. };
  35437. /**
  35438. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35439. * @param kind defines the data kind (Position, normal, etc...)
  35440. * @returns true if the vertex buffer with the specified kind is updatable
  35441. */
  35442. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35443. var vb = this._vertexBuffers[kind];
  35444. if (!vb) {
  35445. return false;
  35446. }
  35447. return vb.isUpdatable();
  35448. };
  35449. /**
  35450. * Gets a specific vertex buffer
  35451. * @param kind defines the data kind (Position, normal, etc...)
  35452. * @returns a {BABYLON.VertexBuffer}
  35453. */
  35454. Geometry.prototype.getVertexBuffer = function (kind) {
  35455. if (!this.isReady()) {
  35456. return null;
  35457. }
  35458. return this._vertexBuffers[kind];
  35459. };
  35460. /**
  35461. * Returns all vertex buffers
  35462. * @return an object holding all vertex buffers indexed by kind
  35463. */
  35464. Geometry.prototype.getVertexBuffers = function () {
  35465. if (!this.isReady()) {
  35466. return null;
  35467. }
  35468. return this._vertexBuffers;
  35469. };
  35470. /**
  35471. * Gets a boolean indicating if specific vertex buffer is present
  35472. * @param kind defines the data kind (Position, normal, etc...)
  35473. * @returns true if data is present
  35474. */
  35475. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35476. if (!this._vertexBuffers) {
  35477. if (this._delayInfo) {
  35478. return this._delayInfo.indexOf(kind) !== -1;
  35479. }
  35480. return false;
  35481. }
  35482. return this._vertexBuffers[kind] !== undefined;
  35483. };
  35484. /**
  35485. * Gets a list of all attached data kinds (Position, normal, etc...)
  35486. * @returns a list of string containing all kinds
  35487. */
  35488. Geometry.prototype.getVerticesDataKinds = function () {
  35489. var result = [];
  35490. var kind;
  35491. if (!this._vertexBuffers && this._delayInfo) {
  35492. for (kind in this._delayInfo) {
  35493. result.push(kind);
  35494. }
  35495. }
  35496. else {
  35497. for (kind in this._vertexBuffers) {
  35498. result.push(kind);
  35499. }
  35500. }
  35501. return result;
  35502. };
  35503. /**
  35504. * Update index buffer
  35505. * @param indices defines the indices to store in the index buffer
  35506. * @param offset defines the offset in the target buffer where to store the data
  35507. */
  35508. Geometry.prototype.updateIndices = function (indices, offset) {
  35509. if (!this._indexBuffer) {
  35510. return;
  35511. }
  35512. if (!this._indexBufferIsUpdatable) {
  35513. this.setIndices(indices, null, true);
  35514. }
  35515. else {
  35516. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35517. }
  35518. };
  35519. /**
  35520. * Creates a new index buffer
  35521. * @param indices defines the indices to store in the index buffer
  35522. * @param totalVertices defines the total number of vertices (could be null)
  35523. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35524. */
  35525. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35526. if (totalVertices === void 0) { totalVertices = null; }
  35527. if (updatable === void 0) { updatable = false; }
  35528. if (this._indexBuffer) {
  35529. this._engine._releaseBuffer(this._indexBuffer);
  35530. }
  35531. this._disposeVertexArrayObjects();
  35532. this._indices = indices;
  35533. this._indexBufferIsUpdatable = updatable;
  35534. if (this._meshes.length !== 0 && this._indices) {
  35535. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35536. }
  35537. if (totalVertices != undefined) {
  35538. this._totalVertices = totalVertices;
  35539. }
  35540. var meshes = this._meshes;
  35541. var numOfMeshes = meshes.length;
  35542. for (var index = 0; index < numOfMeshes; index++) {
  35543. meshes[index]._createGlobalSubMesh(true);
  35544. }
  35545. this.notifyUpdate();
  35546. };
  35547. /**
  35548. * Return the total number of indices
  35549. * @returns the total number of indices
  35550. */
  35551. Geometry.prototype.getTotalIndices = function () {
  35552. if (!this.isReady()) {
  35553. return 0;
  35554. }
  35555. return this._indices.length;
  35556. };
  35557. /**
  35558. * Gets the index buffer array
  35559. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35560. * @returns the index buffer array
  35561. */
  35562. Geometry.prototype.getIndices = function (copyWhenShared) {
  35563. if (!this.isReady()) {
  35564. return null;
  35565. }
  35566. var orig = this._indices;
  35567. if (!copyWhenShared || this._meshes.length === 1) {
  35568. return orig;
  35569. }
  35570. else {
  35571. var len = orig.length;
  35572. var copy = [];
  35573. for (var i = 0; i < len; i++) {
  35574. copy.push(orig[i]);
  35575. }
  35576. return copy;
  35577. }
  35578. };
  35579. /**
  35580. * Gets the index buffer
  35581. * @return the index buffer
  35582. */
  35583. Geometry.prototype.getIndexBuffer = function () {
  35584. if (!this.isReady()) {
  35585. return null;
  35586. }
  35587. return this._indexBuffer;
  35588. };
  35589. /** @ignore */
  35590. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35591. if (effect === void 0) { effect = null; }
  35592. if (!effect || !this._vertexArrayObjects) {
  35593. return;
  35594. }
  35595. if (this._vertexArrayObjects[effect.key]) {
  35596. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35597. delete this._vertexArrayObjects[effect.key];
  35598. }
  35599. };
  35600. /**
  35601. * Release the associated resources for a specific mesh
  35602. * @param mesh defines the source mesh
  35603. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35604. */
  35605. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35606. var meshes = this._meshes;
  35607. var index = meshes.indexOf(mesh);
  35608. if (index === -1) {
  35609. return;
  35610. }
  35611. meshes.splice(index, 1);
  35612. mesh._geometry = null;
  35613. if (meshes.length === 0 && shouldDispose) {
  35614. this.dispose();
  35615. }
  35616. };
  35617. /**
  35618. * Apply current geometry to a given mesh
  35619. * @param mesh defines the mesh to apply geometry to
  35620. */
  35621. Geometry.prototype.applyToMesh = function (mesh) {
  35622. if (mesh._geometry === this) {
  35623. return;
  35624. }
  35625. var previousGeometry = mesh._geometry;
  35626. if (previousGeometry) {
  35627. previousGeometry.releaseForMesh(mesh);
  35628. }
  35629. var meshes = this._meshes;
  35630. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35631. mesh._geometry = this;
  35632. this._scene.pushGeometry(this);
  35633. meshes.push(mesh);
  35634. if (this.isReady()) {
  35635. this._applyToMesh(mesh);
  35636. }
  35637. else {
  35638. mesh._boundingInfo = this._boundingInfo;
  35639. }
  35640. };
  35641. Geometry.prototype.updateExtend = function (data, stride) {
  35642. if (data === void 0) { data = null; }
  35643. if (!data) {
  35644. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35645. }
  35646. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35647. };
  35648. Geometry.prototype._applyToMesh = function (mesh) {
  35649. var numOfMeshes = this._meshes.length;
  35650. // vertexBuffers
  35651. for (var kind in this._vertexBuffers) {
  35652. if (numOfMeshes === 1) {
  35653. this._vertexBuffers[kind].create();
  35654. }
  35655. var buffer = this._vertexBuffers[kind].getBuffer();
  35656. if (buffer)
  35657. buffer.references = numOfMeshes;
  35658. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35659. if (!this._extend) {
  35660. this.updateExtend(this._vertexBuffers[kind].getData());
  35661. }
  35662. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35663. mesh._createGlobalSubMesh(false);
  35664. //bounding info was just created again, world matrix should be applied again.
  35665. mesh._updateBoundingInfo();
  35666. }
  35667. }
  35668. // indexBuffer
  35669. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35670. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35671. }
  35672. if (this._indexBuffer) {
  35673. this._indexBuffer.references = numOfMeshes;
  35674. }
  35675. };
  35676. Geometry.prototype.notifyUpdate = function (kind) {
  35677. if (this.onGeometryUpdated) {
  35678. this.onGeometryUpdated(this, kind);
  35679. }
  35680. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35681. var mesh = _a[_i];
  35682. mesh._markSubMeshesAsAttributesDirty();
  35683. }
  35684. };
  35685. /**
  35686. * Load the geometry if it was flagged as delay loaded
  35687. * @param scene defines the hosting scene
  35688. * @param onLoaded defines a callback called when the geometry is loaded
  35689. */
  35690. Geometry.prototype.load = function (scene, onLoaded) {
  35691. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35692. return;
  35693. }
  35694. if (this.isReady()) {
  35695. if (onLoaded) {
  35696. onLoaded();
  35697. }
  35698. return;
  35699. }
  35700. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35701. this._queueLoad(scene, onLoaded);
  35702. };
  35703. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35704. var _this = this;
  35705. if (!this.delayLoadingFile) {
  35706. return;
  35707. }
  35708. scene._addPendingData(this);
  35709. scene._loadFile(this.delayLoadingFile, function (data) {
  35710. if (!_this._delayLoadingFunction) {
  35711. return;
  35712. }
  35713. _this._delayLoadingFunction(JSON.parse(data), _this);
  35714. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35715. _this._delayInfo = [];
  35716. scene._removePendingData(_this);
  35717. var meshes = _this._meshes;
  35718. var numOfMeshes = meshes.length;
  35719. for (var index = 0; index < numOfMeshes; index++) {
  35720. _this._applyToMesh(meshes[index]);
  35721. }
  35722. if (onLoaded) {
  35723. onLoaded();
  35724. }
  35725. }, undefined, true);
  35726. };
  35727. /**
  35728. * Invert the geometry to move from a right handed system to a left handed one.
  35729. */
  35730. Geometry.prototype.toLeftHanded = function () {
  35731. // Flip faces
  35732. var tIndices = this.getIndices(false);
  35733. if (tIndices != null && tIndices.length > 0) {
  35734. for (var i = 0; i < tIndices.length; i += 3) {
  35735. var tTemp = tIndices[i + 0];
  35736. tIndices[i + 0] = tIndices[i + 2];
  35737. tIndices[i + 2] = tTemp;
  35738. }
  35739. this.setIndices(tIndices);
  35740. }
  35741. // Negate position.z
  35742. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35743. if (tPositions != null && tPositions.length > 0) {
  35744. for (var i = 0; i < tPositions.length; i += 3) {
  35745. tPositions[i + 2] = -tPositions[i + 2];
  35746. }
  35747. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35748. }
  35749. // Negate normal.z
  35750. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35751. if (tNormals != null && tNormals.length > 0) {
  35752. for (var i = 0; i < tNormals.length; i += 3) {
  35753. tNormals[i + 2] = -tNormals[i + 2];
  35754. }
  35755. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35756. }
  35757. };
  35758. // Cache
  35759. /** @ignore */
  35760. Geometry.prototype._resetPointsArrayCache = function () {
  35761. this._positions = null;
  35762. };
  35763. /** @ignore */
  35764. Geometry.prototype._generatePointsArray = function () {
  35765. if (this._positions)
  35766. return true;
  35767. this._positions = [];
  35768. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35769. if (!data) {
  35770. return false;
  35771. }
  35772. for (var index = 0; index < data.length; index += 3) {
  35773. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35774. }
  35775. return true;
  35776. };
  35777. /**
  35778. * Gets a value indicating if the geometry is disposed
  35779. * @returns true if the geometry was disposed
  35780. */
  35781. Geometry.prototype.isDisposed = function () {
  35782. return this._isDisposed;
  35783. };
  35784. Geometry.prototype._disposeVertexArrayObjects = function () {
  35785. if (this._vertexArrayObjects) {
  35786. for (var kind in this._vertexArrayObjects) {
  35787. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35788. }
  35789. this._vertexArrayObjects = {};
  35790. }
  35791. };
  35792. /**
  35793. * Free all associated resources
  35794. */
  35795. Geometry.prototype.dispose = function () {
  35796. var meshes = this._meshes;
  35797. var numOfMeshes = meshes.length;
  35798. var index;
  35799. for (index = 0; index < numOfMeshes; index++) {
  35800. this.releaseForMesh(meshes[index]);
  35801. }
  35802. this._meshes = [];
  35803. this._disposeVertexArrayObjects();
  35804. for (var kind in this._vertexBuffers) {
  35805. this._vertexBuffers[kind].dispose();
  35806. }
  35807. this._vertexBuffers = {};
  35808. this._totalVertices = 0;
  35809. if (this._indexBuffer) {
  35810. this._engine._releaseBuffer(this._indexBuffer);
  35811. }
  35812. this._indexBuffer = null;
  35813. this._indices = [];
  35814. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35815. this.delayLoadingFile = null;
  35816. this._delayLoadingFunction = null;
  35817. this._delayInfo = [];
  35818. this._boundingInfo = null;
  35819. this._scene.removeGeometry(this);
  35820. this._isDisposed = true;
  35821. };
  35822. /**
  35823. * Clone the current geometry into a new geometry
  35824. * @param id defines the unique ID of the new geometry
  35825. * @returns a new geometry object
  35826. */
  35827. Geometry.prototype.copy = function (id) {
  35828. var vertexData = new BABYLON.VertexData();
  35829. vertexData.indices = [];
  35830. var indices = this.getIndices();
  35831. if (indices) {
  35832. for (var index = 0; index < indices.length; index++) {
  35833. vertexData.indices.push(indices[index]);
  35834. }
  35835. }
  35836. var updatable = false;
  35837. var stopChecking = false;
  35838. var kind;
  35839. for (kind in this._vertexBuffers) {
  35840. // using slice() to make a copy of the array and not just reference it
  35841. var data = this.getVerticesData(kind);
  35842. if (data instanceof Float32Array) {
  35843. vertexData.set(new Float32Array(data), kind);
  35844. }
  35845. else {
  35846. vertexData.set(data.slice(0), kind);
  35847. }
  35848. if (!stopChecking) {
  35849. var vb = this.getVertexBuffer(kind);
  35850. if (vb) {
  35851. updatable = vb.isUpdatable();
  35852. stopChecking = !updatable;
  35853. }
  35854. }
  35855. }
  35856. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35857. geometry.delayLoadState = this.delayLoadState;
  35858. geometry.delayLoadingFile = this.delayLoadingFile;
  35859. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35860. for (kind in this._delayInfo) {
  35861. geometry._delayInfo = geometry._delayInfo || [];
  35862. geometry._delayInfo.push(kind);
  35863. }
  35864. // Bounding info
  35865. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35866. return geometry;
  35867. };
  35868. /**
  35869. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35870. * @return a JSON representation of the current geometry data (without the vertices data)
  35871. */
  35872. Geometry.prototype.serialize = function () {
  35873. var serializationObject = {};
  35874. serializationObject.id = this.id;
  35875. serializationObject.updatable = this._updatable;
  35876. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35877. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35878. }
  35879. return serializationObject;
  35880. };
  35881. Geometry.prototype.toNumberArray = function (origin) {
  35882. if (Array.isArray(origin)) {
  35883. return origin;
  35884. }
  35885. else {
  35886. return Array.prototype.slice.call(origin);
  35887. }
  35888. };
  35889. /**
  35890. * Serialize all vertices data into a JSON oject
  35891. * @returns a JSON representation of the current geometry data
  35892. */
  35893. Geometry.prototype.serializeVerticeData = function () {
  35894. var serializationObject = this.serialize();
  35895. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35896. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35897. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35898. serializationObject.positions._updatable = true;
  35899. }
  35900. }
  35901. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35902. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35903. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35904. serializationObject.normals._updatable = true;
  35905. }
  35906. }
  35907. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35908. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35909. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35910. serializationObject.tangets._updatable = true;
  35911. }
  35912. }
  35913. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35914. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35915. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35916. serializationObject.uvs._updatable = true;
  35917. }
  35918. }
  35919. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35920. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35921. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35922. serializationObject.uv2s._updatable = true;
  35923. }
  35924. }
  35925. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35926. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35927. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35928. serializationObject.uv3s._updatable = true;
  35929. }
  35930. }
  35931. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35932. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35933. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35934. serializationObject.uv4s._updatable = true;
  35935. }
  35936. }
  35937. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35938. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35939. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35940. serializationObject.uv5s._updatable = true;
  35941. }
  35942. }
  35943. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35944. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35945. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35946. serializationObject.uv6s._updatable = true;
  35947. }
  35948. }
  35949. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35950. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35951. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35952. serializationObject.colors._updatable = true;
  35953. }
  35954. }
  35955. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35956. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35957. serializationObject.matricesIndices._isExpanded = true;
  35958. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35959. serializationObject.matricesIndices._updatable = true;
  35960. }
  35961. }
  35962. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35963. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35964. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35965. serializationObject.matricesWeights._updatable = true;
  35966. }
  35967. }
  35968. serializationObject.indices = this.toNumberArray(this.getIndices());
  35969. return serializationObject;
  35970. };
  35971. // Statics
  35972. /**
  35973. * Extracts a clone of a mesh geometry
  35974. * @param mesh defines the source mesh
  35975. * @param id defines the unique ID of the new geometry object
  35976. * @returns the new geometry object
  35977. */
  35978. Geometry.ExtractFromMesh = function (mesh, id) {
  35979. var geometry = mesh._geometry;
  35980. if (!geometry) {
  35981. return null;
  35982. }
  35983. return geometry.copy(id);
  35984. };
  35985. /**
  35986. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35987. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35988. * Be aware Math.random() could cause collisions, but:
  35989. * "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"
  35990. * @returns a string containing a new GUID
  35991. */
  35992. Geometry.RandomId = function () {
  35993. return BABYLON.Tools.RandomId();
  35994. };
  35995. /** @ignore */
  35996. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35997. var scene = mesh.getScene();
  35998. // Geometry
  35999. var geometryId = parsedGeometry.geometryId;
  36000. if (geometryId) {
  36001. var geometry = scene.getGeometryByID(geometryId);
  36002. if (geometry) {
  36003. geometry.applyToMesh(mesh);
  36004. }
  36005. }
  36006. else if (parsedGeometry instanceof ArrayBuffer) {
  36007. var binaryInfo = mesh._binaryInfo;
  36008. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36009. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36010. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36011. }
  36012. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36013. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36014. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36015. }
  36016. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  36017. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  36018. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  36019. }
  36020. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36021. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36022. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36023. }
  36024. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36025. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36026. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36027. }
  36028. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36029. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36030. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36031. }
  36032. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36033. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36034. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36035. }
  36036. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36037. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36038. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36039. }
  36040. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36041. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36042. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36043. }
  36044. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36045. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36046. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36047. }
  36048. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36049. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36050. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36051. }
  36052. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36053. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36054. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36055. }
  36056. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36057. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36058. mesh.setIndices(indicesData, null);
  36059. }
  36060. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36061. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36062. mesh.subMeshes = [];
  36063. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36064. var materialIndex = subMeshesData[(i * 5) + 0];
  36065. var verticesStart = subMeshesData[(i * 5) + 1];
  36066. var verticesCount = subMeshesData[(i * 5) + 2];
  36067. var indexStart = subMeshesData[(i * 5) + 3];
  36068. var indexCount = subMeshesData[(i * 5) + 4];
  36069. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36070. }
  36071. }
  36072. }
  36073. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36074. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36075. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36076. if (parsedGeometry.tangents) {
  36077. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36078. }
  36079. if (parsedGeometry.uvs) {
  36080. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36081. }
  36082. if (parsedGeometry.uvs2) {
  36083. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36084. }
  36085. if (parsedGeometry.uvs3) {
  36086. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36087. }
  36088. if (parsedGeometry.uvs4) {
  36089. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36090. }
  36091. if (parsedGeometry.uvs5) {
  36092. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36093. }
  36094. if (parsedGeometry.uvs6) {
  36095. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36096. }
  36097. if (parsedGeometry.colors) {
  36098. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36099. }
  36100. if (parsedGeometry.matricesIndices) {
  36101. if (!parsedGeometry.matricesIndices._isExpanded) {
  36102. var floatIndices = [];
  36103. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36104. var matricesIndex = parsedGeometry.matricesIndices[i];
  36105. floatIndices.push(matricesIndex & 0x000000FF);
  36106. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36107. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36108. floatIndices.push(matricesIndex >> 24);
  36109. }
  36110. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36111. }
  36112. else {
  36113. delete parsedGeometry.matricesIndices._isExpanded;
  36114. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36115. }
  36116. }
  36117. if (parsedGeometry.matricesIndicesExtra) {
  36118. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36119. var floatIndices = [];
  36120. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36121. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36122. floatIndices.push(matricesIndex & 0x000000FF);
  36123. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36124. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36125. floatIndices.push(matricesIndex >> 24);
  36126. }
  36127. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36128. }
  36129. else {
  36130. delete parsedGeometry.matricesIndices._isExpanded;
  36131. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36132. }
  36133. }
  36134. if (parsedGeometry.matricesWeights) {
  36135. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36136. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36137. }
  36138. if (parsedGeometry.matricesWeightsExtra) {
  36139. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36140. }
  36141. mesh.setIndices(parsedGeometry.indices, null);
  36142. }
  36143. // SubMeshes
  36144. if (parsedGeometry.subMeshes) {
  36145. mesh.subMeshes = [];
  36146. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36147. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36148. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36149. }
  36150. }
  36151. // Flat shading
  36152. if (mesh._shouldGenerateFlatShading) {
  36153. mesh.convertToFlatShadedMesh();
  36154. delete mesh._shouldGenerateFlatShading;
  36155. }
  36156. // Update
  36157. mesh.computeWorldMatrix(true);
  36158. // Octree
  36159. var sceneOctree = scene.selectionOctree;
  36160. if (sceneOctree !== undefined && sceneOctree !== null) {
  36161. sceneOctree.addMesh(mesh);
  36162. }
  36163. };
  36164. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36165. var epsilon = 1e-3;
  36166. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36167. return;
  36168. }
  36169. var noInfluenceBoneIndex = 0.0;
  36170. if (parsedGeometry.skeletonId > -1) {
  36171. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36172. if (!skeleton) {
  36173. return;
  36174. }
  36175. noInfluenceBoneIndex = skeleton.bones.length;
  36176. }
  36177. else {
  36178. return;
  36179. }
  36180. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36181. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36182. var matricesWeights = parsedGeometry.matricesWeights;
  36183. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36184. var influencers = parsedGeometry.numBoneInfluencer;
  36185. var size = matricesWeights.length;
  36186. for (var i = 0; i < size; i += 4) {
  36187. var weight = 0.0;
  36188. var firstZeroWeight = -1;
  36189. for (var j = 0; j < 4; j++) {
  36190. var w = matricesWeights[i + j];
  36191. weight += w;
  36192. if (w < epsilon && firstZeroWeight < 0) {
  36193. firstZeroWeight = j;
  36194. }
  36195. }
  36196. if (matricesWeightsExtra) {
  36197. for (var j = 0; j < 4; j++) {
  36198. var w = matricesWeightsExtra[i + j];
  36199. weight += w;
  36200. if (w < epsilon && firstZeroWeight < 0) {
  36201. firstZeroWeight = j + 4;
  36202. }
  36203. }
  36204. }
  36205. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36206. firstZeroWeight = influencers - 1;
  36207. }
  36208. if (weight > epsilon) {
  36209. var mweight = 1.0 / weight;
  36210. for (var j = 0; j < 4; j++) {
  36211. matricesWeights[i + j] *= mweight;
  36212. }
  36213. if (matricesWeightsExtra) {
  36214. for (var j = 0; j < 4; j++) {
  36215. matricesWeightsExtra[i + j] *= mweight;
  36216. }
  36217. }
  36218. }
  36219. else {
  36220. if (firstZeroWeight >= 4) {
  36221. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36222. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36223. }
  36224. else {
  36225. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36226. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36227. }
  36228. }
  36229. }
  36230. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36231. if (parsedGeometry.matricesWeightsExtra) {
  36232. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36233. }
  36234. };
  36235. /**
  36236. * Create a new geometry from persisted data (Using .babylon file format)
  36237. * @param parsedVertexData defines the persisted data
  36238. * @param scene defines the hosting scene
  36239. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36240. * @returns the new geometry object
  36241. */
  36242. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36243. if (scene.getGeometryByID(parsedVertexData.id)) {
  36244. return null; // null since geometry could be something else than a box...
  36245. }
  36246. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36247. if (BABYLON.Tags) {
  36248. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36249. }
  36250. if (parsedVertexData.delayLoadingFile) {
  36251. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36252. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36253. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36254. geometry._delayInfo = [];
  36255. if (parsedVertexData.hasUVs) {
  36256. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36257. }
  36258. if (parsedVertexData.hasUVs2) {
  36259. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36260. }
  36261. if (parsedVertexData.hasUVs3) {
  36262. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36263. }
  36264. if (parsedVertexData.hasUVs4) {
  36265. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36266. }
  36267. if (parsedVertexData.hasUVs5) {
  36268. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36269. }
  36270. if (parsedVertexData.hasUVs6) {
  36271. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36272. }
  36273. if (parsedVertexData.hasColors) {
  36274. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36275. }
  36276. if (parsedVertexData.hasMatricesIndices) {
  36277. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36278. }
  36279. if (parsedVertexData.hasMatricesWeights) {
  36280. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36281. }
  36282. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36283. }
  36284. else {
  36285. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36286. }
  36287. scene.pushGeometry(geometry, true);
  36288. return geometry;
  36289. };
  36290. return Geometry;
  36291. }());
  36292. BABYLON.Geometry = Geometry;
  36293. // Primitives
  36294. /// Abstract class
  36295. /**
  36296. * Abstract class used to provide common services for all typed geometries
  36297. */
  36298. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36299. __extends(_PrimitiveGeometry, _super);
  36300. /**
  36301. * Creates a new typed geometry
  36302. * @param id defines the unique ID of the geometry
  36303. * @param scene defines the hosting scene
  36304. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36305. * @param mesh defines the hosting mesh (can be null)
  36306. */
  36307. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36308. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36309. if (mesh === void 0) { mesh = null; }
  36310. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36311. _this._canBeRegenerated = _canBeRegenerated;
  36312. _this._beingRegenerated = true;
  36313. _this.regenerate();
  36314. _this._beingRegenerated = false;
  36315. return _this;
  36316. }
  36317. /**
  36318. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36319. * @returns true if the geometry can be regenerated
  36320. */
  36321. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36322. return this._canBeRegenerated;
  36323. };
  36324. /**
  36325. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36326. */
  36327. _PrimitiveGeometry.prototype.regenerate = function () {
  36328. if (!this._canBeRegenerated) {
  36329. return;
  36330. }
  36331. this._beingRegenerated = true;
  36332. this.setAllVerticesData(this._regenerateVertexData(), false);
  36333. this._beingRegenerated = false;
  36334. };
  36335. /**
  36336. * Clone the geometry
  36337. * @param id defines the unique ID of the new geometry
  36338. * @returns the new geometry
  36339. */
  36340. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36341. return _super.prototype.copy.call(this, id);
  36342. };
  36343. // overrides
  36344. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36345. if (!this._beingRegenerated) {
  36346. return;
  36347. }
  36348. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36349. };
  36350. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36351. if (!this._beingRegenerated) {
  36352. return;
  36353. }
  36354. _super.prototype.setVerticesData.call(this, kind, data, false);
  36355. };
  36356. // to override
  36357. /** @ignore */
  36358. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36359. throw new Error("Abstract method");
  36360. };
  36361. _PrimitiveGeometry.prototype.copy = function (id) {
  36362. throw new Error("Must be overriden in sub-classes.");
  36363. };
  36364. _PrimitiveGeometry.prototype.serialize = function () {
  36365. var serializationObject = _super.prototype.serialize.call(this);
  36366. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36367. return serializationObject;
  36368. };
  36369. return _PrimitiveGeometry;
  36370. }(Geometry));
  36371. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36372. /**
  36373. * Creates a ribbon geometry
  36374. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36375. */
  36376. var RibbonGeometry = /** @class */ (function (_super) {
  36377. __extends(RibbonGeometry, _super);
  36378. /**
  36379. * Creates a ribbon geometry
  36380. * @param id defines the unique ID of the geometry
  36381. * @param scene defines the hosting scene
  36382. * @param pathArray defines the array of paths to use
  36383. * @param closeArray defines if the last path and the first path must be joined
  36384. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36385. * @param offset defines the offset between points
  36386. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36387. * @param mesh defines the hosting mesh (can be null)
  36388. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36389. */
  36390. function RibbonGeometry(id, scene,
  36391. /**
  36392. * Defines the array of paths to use
  36393. */
  36394. pathArray,
  36395. /**
  36396. * Defines if the last and first points of each path in your pathArray must be joined
  36397. */
  36398. closeArray,
  36399. /**
  36400. * Defines if the last and first points of each path in your pathArray must be joined
  36401. */
  36402. closePath,
  36403. /**
  36404. * Defines the offset between points
  36405. */
  36406. offset, canBeRegenerated, mesh,
  36407. /**
  36408. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36409. */
  36410. side) {
  36411. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36412. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36413. _this.pathArray = pathArray;
  36414. _this.closeArray = closeArray;
  36415. _this.closePath = closePath;
  36416. _this.offset = offset;
  36417. _this.side = side;
  36418. return _this;
  36419. }
  36420. /** @ignore */
  36421. RibbonGeometry.prototype._regenerateVertexData = function () {
  36422. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36423. };
  36424. RibbonGeometry.prototype.copy = function (id) {
  36425. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36426. };
  36427. return RibbonGeometry;
  36428. }(_PrimitiveGeometry));
  36429. BABYLON.RibbonGeometry = RibbonGeometry;
  36430. /**
  36431. * Creates a box geometry
  36432. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36433. */
  36434. var BoxGeometry = /** @class */ (function (_super) {
  36435. __extends(BoxGeometry, _super);
  36436. /**
  36437. * Creates a box geometry
  36438. * @param id defines the unique ID of the geometry
  36439. * @param scene defines the hosting scene
  36440. * @param size defines the zise of the box (width, height and depth are the same)
  36441. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36442. * @param mesh defines the hosting mesh (can be null)
  36443. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36444. */
  36445. function BoxGeometry(id, scene,
  36446. /**
  36447. * Defines the zise of the box (width, height and depth are the same)
  36448. */
  36449. size, canBeRegenerated, mesh,
  36450. /**
  36451. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36452. */
  36453. side) {
  36454. if (mesh === void 0) { mesh = null; }
  36455. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36456. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36457. _this.size = size;
  36458. _this.side = side;
  36459. return _this;
  36460. }
  36461. BoxGeometry.prototype._regenerateVertexData = function () {
  36462. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36463. };
  36464. BoxGeometry.prototype.copy = function (id) {
  36465. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36466. };
  36467. BoxGeometry.prototype.serialize = function () {
  36468. var serializationObject = _super.prototype.serialize.call(this);
  36469. serializationObject.size = this.size;
  36470. return serializationObject;
  36471. };
  36472. BoxGeometry.Parse = function (parsedBox, scene) {
  36473. if (scene.getGeometryByID(parsedBox.id)) {
  36474. return null; // null since geometry could be something else than a box...
  36475. }
  36476. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36477. if (BABYLON.Tags) {
  36478. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36479. }
  36480. scene.pushGeometry(box, true);
  36481. return box;
  36482. };
  36483. return BoxGeometry;
  36484. }(_PrimitiveGeometry));
  36485. BABYLON.BoxGeometry = BoxGeometry;
  36486. /**
  36487. * Creates a sphere geometry
  36488. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36489. */
  36490. var SphereGeometry = /** @class */ (function (_super) {
  36491. __extends(SphereGeometry, _super);
  36492. /**
  36493. * Create a new sphere geometry
  36494. * @param id defines the unique ID of the geometry
  36495. * @param scene defines the hosting scene
  36496. * @param segments defines the number of segments to use to create the sphere
  36497. * @param diameter defines the diameter of the sphere
  36498. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36499. * @param mesh defines the hosting mesh (can be null)
  36500. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36501. */
  36502. function SphereGeometry(id, scene,
  36503. /**
  36504. * Defines the number of segments to use to create the sphere
  36505. */
  36506. segments,
  36507. /**
  36508. * Defines the diameter of the sphere
  36509. */
  36510. diameter, canBeRegenerated, mesh,
  36511. /**
  36512. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36513. */
  36514. side) {
  36515. if (mesh === void 0) { mesh = null; }
  36516. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36517. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36518. _this.segments = segments;
  36519. _this.diameter = diameter;
  36520. _this.side = side;
  36521. return _this;
  36522. }
  36523. SphereGeometry.prototype._regenerateVertexData = function () {
  36524. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36525. };
  36526. SphereGeometry.prototype.copy = function (id) {
  36527. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36528. };
  36529. SphereGeometry.prototype.serialize = function () {
  36530. var serializationObject = _super.prototype.serialize.call(this);
  36531. serializationObject.segments = this.segments;
  36532. serializationObject.diameter = this.diameter;
  36533. return serializationObject;
  36534. };
  36535. SphereGeometry.Parse = function (parsedSphere, scene) {
  36536. if (scene.getGeometryByID(parsedSphere.id)) {
  36537. return null; // null since geometry could be something else than a sphere...
  36538. }
  36539. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36540. if (BABYLON.Tags) {
  36541. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36542. }
  36543. scene.pushGeometry(sphere, true);
  36544. return sphere;
  36545. };
  36546. return SphereGeometry;
  36547. }(_PrimitiveGeometry));
  36548. BABYLON.SphereGeometry = SphereGeometry;
  36549. /**
  36550. * Creates a disc geometry
  36551. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36552. */
  36553. var DiscGeometry = /** @class */ (function (_super) {
  36554. __extends(DiscGeometry, _super);
  36555. /**
  36556. * Creates a new disc geometry
  36557. * @param id defines the unique ID of the geometry
  36558. * @param scene defines the hosting scene
  36559. * @param radius defines the radius of the disc
  36560. * @param tessellation defines the tesselation factor to apply to the disc
  36561. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36562. * @param mesh defines the hosting mesh (can be null)
  36563. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36564. */
  36565. function DiscGeometry(id, scene,
  36566. /**
  36567. * Defines the radius of the disc
  36568. */
  36569. radius,
  36570. /**
  36571. * Defines the tesselation factor to apply to the disc
  36572. */
  36573. tessellation, canBeRegenerated, mesh,
  36574. /**
  36575. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36576. */
  36577. side) {
  36578. if (mesh === void 0) { mesh = null; }
  36579. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36580. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36581. _this.radius = radius;
  36582. _this.tessellation = tessellation;
  36583. _this.side = side;
  36584. return _this;
  36585. }
  36586. DiscGeometry.prototype._regenerateVertexData = function () {
  36587. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36588. };
  36589. DiscGeometry.prototype.copy = function (id) {
  36590. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36591. };
  36592. return DiscGeometry;
  36593. }(_PrimitiveGeometry));
  36594. BABYLON.DiscGeometry = DiscGeometry;
  36595. /**
  36596. * Creates a new cylinder geometry
  36597. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36598. */
  36599. var CylinderGeometry = /** @class */ (function (_super) {
  36600. __extends(CylinderGeometry, _super);
  36601. /**
  36602. * Creates a new cylinder geometry
  36603. * @param id defines the unique ID of the geometry
  36604. * @param scene defines the hosting scene
  36605. * @param height defines the height of the cylinder
  36606. * @param diameterTop defines the diameter of the cylinder's top cap
  36607. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36608. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36609. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36610. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36611. * @param mesh defines the hosting mesh (can be null)
  36612. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36613. */
  36614. function CylinderGeometry(id, scene,
  36615. /**
  36616. * Defines the height of the cylinder
  36617. */
  36618. height,
  36619. /**
  36620. * Defines the diameter of the cylinder's top cap
  36621. */
  36622. diameterTop,
  36623. /**
  36624. * Defines the diameter of the cylinder's bottom cap
  36625. */
  36626. diameterBottom,
  36627. /**
  36628. * Defines the tessellation factor to apply to the cylinder
  36629. */
  36630. tessellation,
  36631. /**
  36632. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36633. */
  36634. subdivisions, canBeRegenerated, mesh,
  36635. /**
  36636. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36637. */
  36638. side) {
  36639. if (subdivisions === void 0) { subdivisions = 1; }
  36640. if (mesh === void 0) { mesh = null; }
  36641. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36642. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36643. _this.height = height;
  36644. _this.diameterTop = diameterTop;
  36645. _this.diameterBottom = diameterBottom;
  36646. _this.tessellation = tessellation;
  36647. _this.subdivisions = subdivisions;
  36648. _this.side = side;
  36649. return _this;
  36650. }
  36651. CylinderGeometry.prototype._regenerateVertexData = function () {
  36652. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36653. };
  36654. CylinderGeometry.prototype.copy = function (id) {
  36655. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36656. };
  36657. CylinderGeometry.prototype.serialize = function () {
  36658. var serializationObject = _super.prototype.serialize.call(this);
  36659. serializationObject.height = this.height;
  36660. serializationObject.diameterTop = this.diameterTop;
  36661. serializationObject.diameterBottom = this.diameterBottom;
  36662. serializationObject.tessellation = this.tessellation;
  36663. return serializationObject;
  36664. };
  36665. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36666. if (scene.getGeometryByID(parsedCylinder.id)) {
  36667. return null; // null since geometry could be something else than a cylinder...
  36668. }
  36669. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36670. if (BABYLON.Tags) {
  36671. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36672. }
  36673. scene.pushGeometry(cylinder, true);
  36674. return cylinder;
  36675. };
  36676. return CylinderGeometry;
  36677. }(_PrimitiveGeometry));
  36678. BABYLON.CylinderGeometry = CylinderGeometry;
  36679. /**
  36680. * Creates a new torus geometry
  36681. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36682. */
  36683. var TorusGeometry = /** @class */ (function (_super) {
  36684. __extends(TorusGeometry, _super);
  36685. /**
  36686. * Creates a new torus geometry
  36687. * @param id defines the unique ID of the geometry
  36688. * @param scene defines the hosting scene
  36689. * @param diameter defines the diameter of the torus
  36690. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36691. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36692. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36693. * @param mesh defines the hosting mesh (can be null)
  36694. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36695. */
  36696. function TorusGeometry(id, scene,
  36697. /**
  36698. * Defines the diameter of the torus
  36699. */
  36700. diameter,
  36701. /**
  36702. * Defines the thickness of the torus (ie. internal diameter)
  36703. */
  36704. thickness,
  36705. /**
  36706. * Defines the tesselation factor to apply to the torus
  36707. */
  36708. tessellation, canBeRegenerated, mesh,
  36709. /**
  36710. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36711. */
  36712. side) {
  36713. if (mesh === void 0) { mesh = null; }
  36714. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36715. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36716. _this.diameter = diameter;
  36717. _this.thickness = thickness;
  36718. _this.tessellation = tessellation;
  36719. _this.side = side;
  36720. return _this;
  36721. }
  36722. TorusGeometry.prototype._regenerateVertexData = function () {
  36723. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36724. };
  36725. TorusGeometry.prototype.copy = function (id) {
  36726. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36727. };
  36728. TorusGeometry.prototype.serialize = function () {
  36729. var serializationObject = _super.prototype.serialize.call(this);
  36730. serializationObject.diameter = this.diameter;
  36731. serializationObject.thickness = this.thickness;
  36732. serializationObject.tessellation = this.tessellation;
  36733. return serializationObject;
  36734. };
  36735. TorusGeometry.Parse = function (parsedTorus, scene) {
  36736. if (scene.getGeometryByID(parsedTorus.id)) {
  36737. return null; // null since geometry could be something else than a torus...
  36738. }
  36739. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36740. if (BABYLON.Tags) {
  36741. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36742. }
  36743. scene.pushGeometry(torus, true);
  36744. return torus;
  36745. };
  36746. return TorusGeometry;
  36747. }(_PrimitiveGeometry));
  36748. BABYLON.TorusGeometry = TorusGeometry;
  36749. /**
  36750. * Creates a new ground geometry
  36751. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36752. */
  36753. var GroundGeometry = /** @class */ (function (_super) {
  36754. __extends(GroundGeometry, _super);
  36755. /**
  36756. * Creates a new ground geometry
  36757. * @param id defines the unique ID of the geometry
  36758. * @param scene defines the hosting scene
  36759. * @param width defines the width of the ground
  36760. * @param height defines the height of the ground
  36761. * @param subdivisions defines the subdivisions to apply to the ground
  36762. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36763. * @param mesh defines the hosting mesh (can be null)
  36764. */
  36765. function GroundGeometry(id, scene,
  36766. /**
  36767. * Defines the width of the ground
  36768. */
  36769. width,
  36770. /**
  36771. * Defines the height of the ground
  36772. */
  36773. height,
  36774. /**
  36775. * Defines the subdivisions to apply to the ground
  36776. */
  36777. subdivisions, canBeRegenerated, mesh) {
  36778. if (mesh === void 0) { mesh = null; }
  36779. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36780. _this.width = width;
  36781. _this.height = height;
  36782. _this.subdivisions = subdivisions;
  36783. return _this;
  36784. }
  36785. GroundGeometry.prototype._regenerateVertexData = function () {
  36786. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36787. };
  36788. GroundGeometry.prototype.copy = function (id) {
  36789. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36790. };
  36791. GroundGeometry.prototype.serialize = function () {
  36792. var serializationObject = _super.prototype.serialize.call(this);
  36793. serializationObject.width = this.width;
  36794. serializationObject.height = this.height;
  36795. serializationObject.subdivisions = this.subdivisions;
  36796. return serializationObject;
  36797. };
  36798. GroundGeometry.Parse = function (parsedGround, scene) {
  36799. if (scene.getGeometryByID(parsedGround.id)) {
  36800. return null; // null since geometry could be something else than a ground...
  36801. }
  36802. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36803. if (BABYLON.Tags) {
  36804. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36805. }
  36806. scene.pushGeometry(ground, true);
  36807. return ground;
  36808. };
  36809. return GroundGeometry;
  36810. }(_PrimitiveGeometry));
  36811. BABYLON.GroundGeometry = GroundGeometry;
  36812. /**
  36813. * Creates a tiled ground geometry
  36814. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36815. */
  36816. var TiledGroundGeometry = /** @class */ (function (_super) {
  36817. __extends(TiledGroundGeometry, _super);
  36818. /**
  36819. * Creates a tiled ground geometry
  36820. * @param id defines the unique ID of the geometry
  36821. * @param scene defines the hosting scene
  36822. * @param xmin defines the minimum value on X axis
  36823. * @param zmin defines the minimum value on Z axis
  36824. * @param xmax defines the maximum value on X axis
  36825. * @param zmax defines the maximum value on Z axis
  36826. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36827. * @param precision defines the precision to use when computing the tiles
  36828. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36829. * @param mesh defines the hosting mesh (can be null)
  36830. */
  36831. function TiledGroundGeometry(id, scene,
  36832. /**
  36833. * Defines the minimum value on X axis
  36834. */
  36835. xmin,
  36836. /**
  36837. * Defines the minimum value on Z axis
  36838. */
  36839. zmin,
  36840. /**
  36841. * Defines the maximum value on X axis
  36842. */
  36843. xmax,
  36844. /**
  36845. * Defines the maximum value on Z axis
  36846. */
  36847. zmax,
  36848. /**
  36849. * Defines the subdivisions to apply to the ground
  36850. */
  36851. subdivisions,
  36852. /**
  36853. * Defines the precision to use when computing the tiles
  36854. */
  36855. precision, canBeRegenerated, mesh) {
  36856. if (mesh === void 0) { mesh = null; }
  36857. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36858. _this.xmin = xmin;
  36859. _this.zmin = zmin;
  36860. _this.xmax = xmax;
  36861. _this.zmax = zmax;
  36862. _this.subdivisions = subdivisions;
  36863. _this.precision = precision;
  36864. return _this;
  36865. }
  36866. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36867. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36868. };
  36869. TiledGroundGeometry.prototype.copy = function (id) {
  36870. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36871. };
  36872. return TiledGroundGeometry;
  36873. }(_PrimitiveGeometry));
  36874. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36875. /**
  36876. * Creates a plane geometry
  36877. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36878. */
  36879. var PlaneGeometry = /** @class */ (function (_super) {
  36880. __extends(PlaneGeometry, _super);
  36881. /**
  36882. * Creates a plane geometry
  36883. * @param id defines the unique ID of the geometry
  36884. * @param scene defines the hosting scene
  36885. * @param size defines the size of the plane (width === height)
  36886. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36887. * @param mesh defines the hosting mesh (can be null)
  36888. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36889. */
  36890. function PlaneGeometry(id, scene,
  36891. /**
  36892. * Defines the size of the plane (width === height)
  36893. */
  36894. size, canBeRegenerated, mesh,
  36895. /**
  36896. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36897. */
  36898. side) {
  36899. if (mesh === void 0) { mesh = null; }
  36900. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36901. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36902. _this.size = size;
  36903. _this.side = side;
  36904. return _this;
  36905. }
  36906. PlaneGeometry.prototype._regenerateVertexData = function () {
  36907. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36908. };
  36909. PlaneGeometry.prototype.copy = function (id) {
  36910. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36911. };
  36912. PlaneGeometry.prototype.serialize = function () {
  36913. var serializationObject = _super.prototype.serialize.call(this);
  36914. serializationObject.size = this.size;
  36915. return serializationObject;
  36916. };
  36917. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36918. if (scene.getGeometryByID(parsedPlane.id)) {
  36919. return null; // null since geometry could be something else than a ground...
  36920. }
  36921. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36922. if (BABYLON.Tags) {
  36923. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36924. }
  36925. scene.pushGeometry(plane, true);
  36926. return plane;
  36927. };
  36928. return PlaneGeometry;
  36929. }(_PrimitiveGeometry));
  36930. BABYLON.PlaneGeometry = PlaneGeometry;
  36931. /**
  36932. * Creates a torus knot geometry
  36933. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36934. */
  36935. var TorusKnotGeometry = /** @class */ (function (_super) {
  36936. __extends(TorusKnotGeometry, _super);
  36937. /**
  36938. * Creates a torus knot geometry
  36939. * @param id defines the unique ID of the geometry
  36940. * @param scene defines the hosting scene
  36941. * @param radius defines the radius of the torus knot
  36942. * @param tube defines the thickness of the torus knot tube
  36943. * @param radialSegments defines the number of radial segments
  36944. * @param tubularSegments defines the number of tubular segments
  36945. * @param p defines the first number of windings
  36946. * @param q defines the second number of windings
  36947. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36948. * @param mesh defines the hosting mesh (can be null)
  36949. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36950. */
  36951. function TorusKnotGeometry(id, scene,
  36952. /**
  36953. * Defines the radius of the torus knot
  36954. */
  36955. radius,
  36956. /**
  36957. * Defines the thickness of the torus knot tube
  36958. */
  36959. tube,
  36960. /**
  36961. * Defines the number of radial segments
  36962. */
  36963. radialSegments,
  36964. /**
  36965. * Defines the number of tubular segments
  36966. */
  36967. tubularSegments,
  36968. /**
  36969. * Defines the first number of windings
  36970. */
  36971. p,
  36972. /**
  36973. * Defines the second number of windings
  36974. */
  36975. q, canBeRegenerated, mesh,
  36976. /**
  36977. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36978. */
  36979. side) {
  36980. if (mesh === void 0) { mesh = null; }
  36981. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36982. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36983. _this.radius = radius;
  36984. _this.tube = tube;
  36985. _this.radialSegments = radialSegments;
  36986. _this.tubularSegments = tubularSegments;
  36987. _this.p = p;
  36988. _this.q = q;
  36989. _this.side = side;
  36990. return _this;
  36991. }
  36992. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36993. 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 });
  36994. };
  36995. TorusKnotGeometry.prototype.copy = function (id) {
  36996. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36997. };
  36998. TorusKnotGeometry.prototype.serialize = function () {
  36999. var serializationObject = _super.prototype.serialize.call(this);
  37000. serializationObject.radius = this.radius;
  37001. serializationObject.tube = this.tube;
  37002. serializationObject.radialSegments = this.radialSegments;
  37003. serializationObject.tubularSegments = this.tubularSegments;
  37004. serializationObject.p = this.p;
  37005. serializationObject.q = this.q;
  37006. return serializationObject;
  37007. };
  37008. ;
  37009. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  37010. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37011. return null; // null since geometry could be something else than a ground...
  37012. }
  37013. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37014. if (BABYLON.Tags) {
  37015. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37016. }
  37017. scene.pushGeometry(torusKnot, true);
  37018. return torusKnot;
  37019. };
  37020. return TorusKnotGeometry;
  37021. }(_PrimitiveGeometry));
  37022. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  37023. //}
  37024. })(BABYLON || (BABYLON = {}));
  37025. //# sourceMappingURL=babylon.geometry.js.map
  37026. "use strict";
  37027. var BABYLON;
  37028. (function (BABYLON) {
  37029. /**
  37030. * PostProcessManager is used to manage one or more post processes or post process pipelines
  37031. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  37032. */
  37033. var PostProcessManager = /** @class */ (function () {
  37034. /**
  37035. * Creates a new instance of @see PostProcess
  37036. * @param scene The scene that the post process is associated with.
  37037. */
  37038. function PostProcessManager(scene) {
  37039. this._vertexBuffers = {};
  37040. this._scene = scene;
  37041. }
  37042. PostProcessManager.prototype._prepareBuffers = function () {
  37043. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37044. return;
  37045. }
  37046. // VBO
  37047. var vertices = [];
  37048. vertices.push(1, 1);
  37049. vertices.push(-1, 1);
  37050. vertices.push(-1, -1);
  37051. vertices.push(1, -1);
  37052. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37053. this._buildIndexBuffer();
  37054. };
  37055. PostProcessManager.prototype._buildIndexBuffer = function () {
  37056. // Indices
  37057. var indices = [];
  37058. indices.push(0);
  37059. indices.push(1);
  37060. indices.push(2);
  37061. indices.push(0);
  37062. indices.push(2);
  37063. indices.push(3);
  37064. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37065. };
  37066. /**
  37067. * Rebuilds the vertex buffers of the manager.
  37068. */
  37069. PostProcessManager.prototype._rebuild = function () {
  37070. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37071. if (!vb) {
  37072. return;
  37073. }
  37074. vb._rebuild();
  37075. this._buildIndexBuffer();
  37076. };
  37077. // Methods
  37078. /**
  37079. * Prepares a frame to be run through a post process.
  37080. * @param sourceTexture The input texture to the post procesess. (default: null)
  37081. * @param postProcesses An array of post processes to be run. (default: null)
  37082. * @returns True if the post processes were able to be run.
  37083. */
  37084. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37085. if (sourceTexture === void 0) { sourceTexture = null; }
  37086. if (postProcesses === void 0) { postProcesses = null; }
  37087. var camera = this._scene.activeCamera;
  37088. if (!camera) {
  37089. return false;
  37090. }
  37091. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37092. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37093. return false;
  37094. }
  37095. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37096. return true;
  37097. };
  37098. /**
  37099. * Manually render a set of post processes to a texture.
  37100. * @param postProcesses An array of post processes to be run.
  37101. * @param targetTexture The target texture to render to.
  37102. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37103. */
  37104. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37105. if (targetTexture === void 0) { targetTexture = null; }
  37106. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37107. var engine = this._scene.getEngine();
  37108. for (var index = 0; index < postProcesses.length; index++) {
  37109. if (index < postProcesses.length - 1) {
  37110. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37111. }
  37112. else {
  37113. if (targetTexture) {
  37114. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37115. }
  37116. else {
  37117. engine.restoreDefaultFramebuffer();
  37118. }
  37119. }
  37120. var pp = postProcesses[index];
  37121. var effect = pp.apply();
  37122. if (effect) {
  37123. pp.onBeforeRenderObservable.notifyObservers(effect);
  37124. // VBOs
  37125. this._prepareBuffers();
  37126. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37127. // Draw order
  37128. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37129. pp.onAfterRenderObservable.notifyObservers(effect);
  37130. }
  37131. }
  37132. // Restore depth buffer
  37133. engine.setDepthBuffer(true);
  37134. engine.setDepthWrite(true);
  37135. };
  37136. /**
  37137. * Finalize the result of the output of the postprocesses.
  37138. * @param doNotPresent If true the result will not be displayed to the screen.
  37139. * @param targetTexture The target texture to render to.
  37140. * @param faceIndex The index of the face to bind the target texture to.
  37141. * @param postProcesses The array of post processes to render.
  37142. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37143. */
  37144. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37145. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37146. var camera = this._scene.activeCamera;
  37147. if (!camera) {
  37148. return;
  37149. }
  37150. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37151. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37152. return;
  37153. }
  37154. var engine = this._scene.getEngine();
  37155. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37156. var pp = postProcesses[index];
  37157. if (index < len - 1) {
  37158. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  37159. }
  37160. else {
  37161. if (targetTexture) {
  37162. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37163. }
  37164. else {
  37165. engine.restoreDefaultFramebuffer();
  37166. }
  37167. }
  37168. if (doNotPresent) {
  37169. break;
  37170. }
  37171. var effect = pp.apply();
  37172. if (effect) {
  37173. pp.onBeforeRenderObservable.notifyObservers(effect);
  37174. // VBOs
  37175. this._prepareBuffers();
  37176. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37177. // Draw order
  37178. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37179. pp.onAfterRenderObservable.notifyObservers(effect);
  37180. }
  37181. }
  37182. // Restore states
  37183. engine.setDepthBuffer(true);
  37184. engine.setDepthWrite(true);
  37185. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37186. };
  37187. /**
  37188. * Disposes of the post process manager.
  37189. */
  37190. PostProcessManager.prototype.dispose = function () {
  37191. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37192. if (buffer) {
  37193. buffer.dispose();
  37194. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37195. }
  37196. if (this._indexBuffer) {
  37197. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37198. this._indexBuffer = null;
  37199. }
  37200. };
  37201. return PostProcessManager;
  37202. }());
  37203. BABYLON.PostProcessManager = PostProcessManager;
  37204. })(BABYLON || (BABYLON = {}));
  37205. //# sourceMappingURL=babylon.postProcessManager.js.map
  37206. "use strict";
  37207. var BABYLON;
  37208. (function (BABYLON) {
  37209. /**
  37210. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37211. */
  37212. var PerformanceMonitor = /** @class */ (function () {
  37213. /**
  37214. * constructor
  37215. * @param frameSampleSize The number of samples required to saturate the sliding window
  37216. */
  37217. function PerformanceMonitor(frameSampleSize) {
  37218. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37219. this._enabled = true;
  37220. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37221. }
  37222. /**
  37223. * Samples current frame
  37224. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37225. */
  37226. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37227. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37228. if (!this._enabled)
  37229. return;
  37230. if (this._lastFrameTimeMs != null) {
  37231. var dt = timeMs - this._lastFrameTimeMs;
  37232. this._rollingFrameTime.add(dt);
  37233. }
  37234. this._lastFrameTimeMs = timeMs;
  37235. };
  37236. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37237. /**
  37238. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37239. * @return Average frame time in milliseconds
  37240. */
  37241. get: function () {
  37242. return this._rollingFrameTime.average;
  37243. },
  37244. enumerable: true,
  37245. configurable: true
  37246. });
  37247. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37248. /**
  37249. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37250. * @return Frame time variance in milliseconds squared
  37251. */
  37252. get: function () {
  37253. return this._rollingFrameTime.variance;
  37254. },
  37255. enumerable: true,
  37256. configurable: true
  37257. });
  37258. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37259. /**
  37260. * Returns the frame time of the most recent frame
  37261. * @return Frame time in milliseconds
  37262. */
  37263. get: function () {
  37264. return this._rollingFrameTime.history(0);
  37265. },
  37266. enumerable: true,
  37267. configurable: true
  37268. });
  37269. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37270. /**
  37271. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37272. * @return Framerate in frames per second
  37273. */
  37274. get: function () {
  37275. return 1000.0 / this._rollingFrameTime.average;
  37276. },
  37277. enumerable: true,
  37278. configurable: true
  37279. });
  37280. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37281. /**
  37282. * Returns the average framerate in frames per second using the most recent frame time
  37283. * @return Framerate in frames per second
  37284. */
  37285. get: function () {
  37286. var history = this._rollingFrameTime.history(0);
  37287. if (history === 0) {
  37288. return 0;
  37289. }
  37290. return 1000.0 / history;
  37291. },
  37292. enumerable: true,
  37293. configurable: true
  37294. });
  37295. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37296. /**
  37297. * Returns true if enough samples have been taken to completely fill the sliding window
  37298. * @return true if saturated
  37299. */
  37300. get: function () {
  37301. return this._rollingFrameTime.isSaturated();
  37302. },
  37303. enumerable: true,
  37304. configurable: true
  37305. });
  37306. /**
  37307. * Enables contributions to the sliding window sample set
  37308. */
  37309. PerformanceMonitor.prototype.enable = function () {
  37310. this._enabled = true;
  37311. };
  37312. /**
  37313. * Disables contributions to the sliding window sample set
  37314. * Samples will not be interpolated over the disabled period
  37315. */
  37316. PerformanceMonitor.prototype.disable = function () {
  37317. this._enabled = false;
  37318. //clear last sample to avoid interpolating over the disabled period when next enabled
  37319. this._lastFrameTimeMs = null;
  37320. };
  37321. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37322. /**
  37323. * Returns true if sampling is enabled
  37324. * @return true if enabled
  37325. */
  37326. get: function () {
  37327. return this._enabled;
  37328. },
  37329. enumerable: true,
  37330. configurable: true
  37331. });
  37332. /**
  37333. * Resets performance monitor
  37334. */
  37335. PerformanceMonitor.prototype.reset = function () {
  37336. //clear last sample to avoid interpolating over the disabled period when next enabled
  37337. this._lastFrameTimeMs = null;
  37338. //wipe record
  37339. this._rollingFrameTime.reset();
  37340. };
  37341. return PerformanceMonitor;
  37342. }());
  37343. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37344. /**
  37345. * RollingAverage
  37346. *
  37347. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37348. */
  37349. var RollingAverage = /** @class */ (function () {
  37350. /**
  37351. * constructor
  37352. * @param length The number of samples required to saturate the sliding window
  37353. */
  37354. function RollingAverage(length) {
  37355. this._samples = new Array(length);
  37356. this.reset();
  37357. }
  37358. /**
  37359. * Adds a sample to the sample set
  37360. * @param v The sample value
  37361. */
  37362. RollingAverage.prototype.add = function (v) {
  37363. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37364. var delta;
  37365. //we need to check if we've already wrapped round
  37366. if (this.isSaturated()) {
  37367. //remove bottom of stack from mean
  37368. var bottomValue = this._samples[this._pos];
  37369. delta = bottomValue - this.average;
  37370. this.average -= delta / (this._sampleCount - 1);
  37371. this._m2 -= delta * (bottomValue - this.average);
  37372. }
  37373. else {
  37374. this._sampleCount++;
  37375. }
  37376. //add new value to mean
  37377. delta = v - this.average;
  37378. this.average += delta / (this._sampleCount);
  37379. this._m2 += delta * (v - this.average);
  37380. //set the new variance
  37381. this.variance = this._m2 / (this._sampleCount - 1);
  37382. this._samples[this._pos] = v;
  37383. this._pos++;
  37384. this._pos %= this._samples.length; //positive wrap around
  37385. };
  37386. /**
  37387. * Returns previously added values or null if outside of history or outside the sliding window domain
  37388. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37389. * @return Value previously recorded with add() or null if outside of range
  37390. */
  37391. RollingAverage.prototype.history = function (i) {
  37392. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37393. return 0;
  37394. }
  37395. var i0 = this._wrapPosition(this._pos - 1.0);
  37396. return this._samples[this._wrapPosition(i0 - i)];
  37397. };
  37398. /**
  37399. * Returns true if enough samples have been taken to completely fill the sliding window
  37400. * @return true if sample-set saturated
  37401. */
  37402. RollingAverage.prototype.isSaturated = function () {
  37403. return this._sampleCount >= this._samples.length;
  37404. };
  37405. /**
  37406. * Resets the rolling average (equivalent to 0 samples taken so far)
  37407. */
  37408. RollingAverage.prototype.reset = function () {
  37409. this.average = 0;
  37410. this.variance = 0;
  37411. this._sampleCount = 0;
  37412. this._pos = 0;
  37413. this._m2 = 0;
  37414. };
  37415. /**
  37416. * Wraps a value around the sample range boundaries
  37417. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37418. * @return Wrapped position in sample range
  37419. */
  37420. RollingAverage.prototype._wrapPosition = function (i) {
  37421. var max = this._samples.length;
  37422. return ((i % max) + max) % max;
  37423. };
  37424. return RollingAverage;
  37425. }());
  37426. BABYLON.RollingAverage = RollingAverage;
  37427. })(BABYLON || (BABYLON = {}));
  37428. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37429. "use strict";
  37430. var BABYLON;
  37431. (function (BABYLON) {
  37432. /**
  37433. * This groups together the common properties used for image processing either in direct forward pass
  37434. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37435. * or not.
  37436. */
  37437. var ImageProcessingConfiguration = /** @class */ (function () {
  37438. function ImageProcessingConfiguration() {
  37439. /**
  37440. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37441. */
  37442. this.colorCurves = new BABYLON.ColorCurves();
  37443. this._colorCurvesEnabled = false;
  37444. this._colorGradingEnabled = false;
  37445. this._colorGradingWithGreenDepth = true;
  37446. this._colorGradingBGR = true;
  37447. this._exposure = 1.0;
  37448. this._toneMappingEnabled = false;
  37449. this._contrast = 1.0;
  37450. /**
  37451. * Vignette stretch size.
  37452. */
  37453. this.vignetteStretch = 0;
  37454. /**
  37455. * Vignette centre X Offset.
  37456. */
  37457. this.vignetteCentreX = 0;
  37458. /**
  37459. * Vignette centre Y Offset.
  37460. */
  37461. this.vignetteCentreY = 0;
  37462. /**
  37463. * Vignette weight or intensity of the vignette effect.
  37464. */
  37465. this.vignetteWeight = 1.5;
  37466. /**
  37467. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37468. * if vignetteEnabled is set to true.
  37469. */
  37470. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37471. /**
  37472. * Camera field of view used by the Vignette effect.
  37473. */
  37474. this.vignetteCameraFov = 0.5;
  37475. this._grainEnabled = false;
  37476. this._grainIntensity = 30;
  37477. this._grainAnimated = false;
  37478. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37479. this._vignetteEnabled = false;
  37480. this._applyByPostProcess = false;
  37481. this._isEnabled = true;
  37482. /**
  37483. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37484. * @type {BABYLON.Observable}
  37485. */
  37486. this.onUpdateParameters = new BABYLON.Observable();
  37487. }
  37488. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37489. /**
  37490. * Gets wether the color curves effect is enabled.
  37491. */
  37492. get: function () {
  37493. return this._colorCurvesEnabled;
  37494. },
  37495. /**
  37496. * Sets wether the color curves effect is enabled.
  37497. */
  37498. set: function (value) {
  37499. if (this._colorCurvesEnabled === value) {
  37500. return;
  37501. }
  37502. this._colorCurvesEnabled = value;
  37503. this._updateParameters();
  37504. },
  37505. enumerable: true,
  37506. configurable: true
  37507. });
  37508. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37509. /**
  37510. * Gets wether the color grading effect is enabled.
  37511. */
  37512. get: function () {
  37513. return this._colorGradingEnabled;
  37514. },
  37515. /**
  37516. * Sets wether the color grading effect is enabled.
  37517. */
  37518. set: function (value) {
  37519. if (this._colorGradingEnabled === value) {
  37520. return;
  37521. }
  37522. this._colorGradingEnabled = value;
  37523. this._updateParameters();
  37524. },
  37525. enumerable: true,
  37526. configurable: true
  37527. });
  37528. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37529. /**
  37530. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37531. */
  37532. get: function () {
  37533. return this._colorGradingWithGreenDepth;
  37534. },
  37535. /**
  37536. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37537. */
  37538. set: function (value) {
  37539. if (this._colorGradingWithGreenDepth === value) {
  37540. return;
  37541. }
  37542. this._colorGradingWithGreenDepth = value;
  37543. this._updateParameters();
  37544. },
  37545. enumerable: true,
  37546. configurable: true
  37547. });
  37548. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37549. /**
  37550. * Gets wether the color grading texture contains BGR values.
  37551. */
  37552. get: function () {
  37553. return this._colorGradingBGR;
  37554. },
  37555. /**
  37556. * Sets wether the color grading texture contains BGR values.
  37557. */
  37558. set: function (value) {
  37559. if (this._colorGradingBGR === value) {
  37560. return;
  37561. }
  37562. this._colorGradingBGR = value;
  37563. this._updateParameters();
  37564. },
  37565. enumerable: true,
  37566. configurable: true
  37567. });
  37568. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37569. /**
  37570. * Gets the Exposure used in the effect.
  37571. */
  37572. get: function () {
  37573. return this._exposure;
  37574. },
  37575. /**
  37576. * Sets the Exposure used in the effect.
  37577. */
  37578. set: function (value) {
  37579. if (this._exposure === value) {
  37580. return;
  37581. }
  37582. this._exposure = value;
  37583. this._updateParameters();
  37584. },
  37585. enumerable: true,
  37586. configurable: true
  37587. });
  37588. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37589. /**
  37590. * Gets wether the tone mapping effect is enabled.
  37591. */
  37592. get: function () {
  37593. return this._toneMappingEnabled;
  37594. },
  37595. /**
  37596. * Sets wether the tone mapping effect is enabled.
  37597. */
  37598. set: function (value) {
  37599. if (this._toneMappingEnabled === value) {
  37600. return;
  37601. }
  37602. this._toneMappingEnabled = value;
  37603. this._updateParameters();
  37604. },
  37605. enumerable: true,
  37606. configurable: true
  37607. });
  37608. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37609. /**
  37610. * Gets the contrast used in the effect.
  37611. */
  37612. get: function () {
  37613. return this._contrast;
  37614. },
  37615. /**
  37616. * Sets the contrast used in the effect.
  37617. */
  37618. set: function (value) {
  37619. if (this._contrast === value) {
  37620. return;
  37621. }
  37622. this._contrast = value;
  37623. this._updateParameters();
  37624. },
  37625. enumerable: true,
  37626. configurable: true
  37627. });
  37628. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37629. /**
  37630. * If the grain effect should be enabled.
  37631. */
  37632. get: function () {
  37633. return this._grainEnabled;
  37634. },
  37635. set: function (value) {
  37636. if (this._grainEnabled === value) {
  37637. return;
  37638. }
  37639. this._grainEnabled = value;
  37640. this._updateParameters();
  37641. },
  37642. enumerable: true,
  37643. configurable: true
  37644. });
  37645. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37646. /**
  37647. * Amount of grain to be applied by the grain effect.
  37648. */
  37649. get: function () {
  37650. return this._grainIntensity;
  37651. },
  37652. set: function (value) {
  37653. if (this._grainIntensity === value) {
  37654. return;
  37655. }
  37656. this._grainIntensity = value;
  37657. },
  37658. enumerable: true,
  37659. configurable: true
  37660. });
  37661. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37662. /**
  37663. * If the grain effect should be animated.
  37664. */
  37665. get: function () {
  37666. return this._grainAnimated;
  37667. },
  37668. set: function (value) {
  37669. if (this._grainAnimated === value) {
  37670. return;
  37671. }
  37672. this._grainAnimated = value;
  37673. this._updateParameters();
  37674. },
  37675. enumerable: true,
  37676. configurable: true
  37677. });
  37678. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37679. /**
  37680. * Gets the vignette blend mode allowing different kind of effect.
  37681. */
  37682. get: function () {
  37683. return this._vignetteBlendMode;
  37684. },
  37685. /**
  37686. * Sets the vignette blend mode allowing different kind of effect.
  37687. */
  37688. set: function (value) {
  37689. if (this._vignetteBlendMode === value) {
  37690. return;
  37691. }
  37692. this._vignetteBlendMode = value;
  37693. this._updateParameters();
  37694. },
  37695. enumerable: true,
  37696. configurable: true
  37697. });
  37698. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37699. /**
  37700. * Gets wether the vignette effect is enabled.
  37701. */
  37702. get: function () {
  37703. return this._vignetteEnabled;
  37704. },
  37705. /**
  37706. * Sets wether the vignette effect is enabled.
  37707. */
  37708. set: function (value) {
  37709. if (this._vignetteEnabled === value) {
  37710. return;
  37711. }
  37712. this._vignetteEnabled = value;
  37713. this._updateParameters();
  37714. },
  37715. enumerable: true,
  37716. configurable: true
  37717. });
  37718. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37719. /**
  37720. * Gets wether the image processing is applied through a post process or not.
  37721. */
  37722. get: function () {
  37723. return this._applyByPostProcess;
  37724. },
  37725. /**
  37726. * Sets wether the image processing is applied through a post process or not.
  37727. */
  37728. set: function (value) {
  37729. if (this._applyByPostProcess === value) {
  37730. return;
  37731. }
  37732. this._applyByPostProcess = value;
  37733. this._updateParameters();
  37734. },
  37735. enumerable: true,
  37736. configurable: true
  37737. });
  37738. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37739. /**
  37740. * Gets wether the image processing is enabled or not.
  37741. */
  37742. get: function () {
  37743. return this._isEnabled;
  37744. },
  37745. /**
  37746. * Sets wether the image processing is enabled or not.
  37747. */
  37748. set: function (value) {
  37749. if (this._isEnabled === value) {
  37750. return;
  37751. }
  37752. this._isEnabled = value;
  37753. this._updateParameters();
  37754. },
  37755. enumerable: true,
  37756. configurable: true
  37757. });
  37758. /**
  37759. * Method called each time the image processing information changes requires to recompile the effect.
  37760. */
  37761. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37762. this.onUpdateParameters.notifyObservers(this);
  37763. };
  37764. ImageProcessingConfiguration.prototype.getClassName = function () {
  37765. return "ImageProcessingConfiguration";
  37766. };
  37767. /**
  37768. * Prepare the list of uniforms associated with the Image Processing effects.
  37769. * @param uniformsList The list of uniforms used in the effect
  37770. * @param defines the list of defines currently in use
  37771. */
  37772. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37773. if (defines.EXPOSURE) {
  37774. uniforms.push("exposureLinear");
  37775. }
  37776. if (defines.CONTRAST) {
  37777. uniforms.push("contrast");
  37778. }
  37779. if (defines.COLORGRADING) {
  37780. uniforms.push("colorTransformSettings");
  37781. }
  37782. if (defines.VIGNETTE) {
  37783. uniforms.push("vInverseScreenSize");
  37784. uniforms.push("vignetteSettings1");
  37785. uniforms.push("vignetteSettings2");
  37786. }
  37787. if (defines.COLORCURVES) {
  37788. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37789. }
  37790. if (defines.GRAIN) {
  37791. uniforms.push("grainVarianceAmount");
  37792. uniforms.push("grainAnimatedSeed");
  37793. }
  37794. };
  37795. /**
  37796. * Prepare the list of samplers associated with the Image Processing effects.
  37797. * @param uniformsList The list of uniforms used in the effect
  37798. * @param defines the list of defines currently in use
  37799. */
  37800. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37801. if (defines.COLORGRADING) {
  37802. samplersList.push("txColorTransform");
  37803. }
  37804. };
  37805. /**
  37806. * Prepare the list of defines associated to the shader.
  37807. * @param defines the list of defines to complete
  37808. */
  37809. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37810. if (forPostProcess === void 0) { forPostProcess = false; }
  37811. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37812. defines.VIGNETTE = false;
  37813. defines.TONEMAPPING = false;
  37814. defines.CONTRAST = false;
  37815. defines.EXPOSURE = false;
  37816. defines.COLORCURVES = false;
  37817. defines.COLORGRADING = false;
  37818. defines.COLORGRADING3D = false;
  37819. defines.IMAGEPROCESSING = false;
  37820. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37821. return;
  37822. }
  37823. defines.VIGNETTE = this.vignetteEnabled;
  37824. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37825. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37826. defines.TONEMAPPING = this.toneMappingEnabled;
  37827. defines.CONTRAST = (this.contrast !== 1.0);
  37828. defines.EXPOSURE = (this.exposure !== 1.0);
  37829. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37830. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37831. if (defines.COLORGRADING) {
  37832. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37833. }
  37834. else {
  37835. defines.COLORGRADING3D = false;
  37836. }
  37837. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37838. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37839. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37840. defines.GRAIN = this.grainEnabled;
  37841. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37842. };
  37843. /**
  37844. * Returns true if all the image processing information are ready.
  37845. */
  37846. ImageProcessingConfiguration.prototype.isReady = function () {
  37847. // Color Grading texure can not be none blocking.
  37848. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37849. };
  37850. /**
  37851. * Binds the image processing to the shader.
  37852. * @param effect The effect to bind to
  37853. */
  37854. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37855. if (aspectRatio === void 0) { aspectRatio = 1; }
  37856. // Color Curves
  37857. if (this._colorCurvesEnabled && this.colorCurves) {
  37858. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37859. }
  37860. // Vignette
  37861. if (this._vignetteEnabled) {
  37862. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37863. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37864. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37865. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37866. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37867. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37868. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37869. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37870. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37871. var vignettePower = -2.0 * this.vignetteWeight;
  37872. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37873. }
  37874. // Exposure
  37875. effect.setFloat("exposureLinear", this.exposure);
  37876. // Contrast
  37877. effect.setFloat("contrast", this.contrast);
  37878. // Color transform settings
  37879. if (this.colorGradingTexture) {
  37880. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37881. var textureSize = this.colorGradingTexture.getSize().height;
  37882. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37883. 0.5 / textureSize, // textureOffset
  37884. textureSize, // textureSize
  37885. this.colorGradingTexture.level // weight
  37886. );
  37887. }
  37888. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37889. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37890. };
  37891. /**
  37892. * Clones the current image processing instance.
  37893. * @return The cloned image processing
  37894. */
  37895. ImageProcessingConfiguration.prototype.clone = function () {
  37896. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37897. };
  37898. /**
  37899. * Serializes the current image processing instance to a json representation.
  37900. * @return a JSON representation
  37901. */
  37902. ImageProcessingConfiguration.prototype.serialize = function () {
  37903. return BABYLON.SerializationHelper.Serialize(this);
  37904. };
  37905. /**
  37906. * Parses the image processing from a json representation.
  37907. * @param source the JSON source to parse
  37908. * @return The parsed image processing
  37909. */
  37910. ImageProcessingConfiguration.Parse = function (source) {
  37911. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37912. };
  37913. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37914. /**
  37915. * Used to apply the vignette as a mix with the pixel color.
  37916. */
  37917. get: function () {
  37918. return this._VIGNETTEMODE_MULTIPLY;
  37919. },
  37920. enumerable: true,
  37921. configurable: true
  37922. });
  37923. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37924. /**
  37925. * Used to apply the vignette as a replacement of the pixel color.
  37926. */
  37927. get: function () {
  37928. return this._VIGNETTEMODE_OPAQUE;
  37929. },
  37930. enumerable: true,
  37931. configurable: true
  37932. });
  37933. // Static constants associated to the image processing.
  37934. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37935. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37936. __decorate([
  37937. BABYLON.serializeAsColorCurves()
  37938. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37939. __decorate([
  37940. BABYLON.serialize()
  37941. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37942. __decorate([
  37943. BABYLON.serializeAsTexture()
  37944. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37945. __decorate([
  37946. BABYLON.serialize()
  37947. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37948. __decorate([
  37949. BABYLON.serialize()
  37950. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37951. __decorate([
  37952. BABYLON.serialize()
  37953. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37954. __decorate([
  37955. BABYLON.serialize()
  37956. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37957. __decorate([
  37958. BABYLON.serialize()
  37959. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37960. __decorate([
  37961. BABYLON.serialize()
  37962. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37963. __decorate([
  37964. BABYLON.serialize()
  37965. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37966. __decorate([
  37967. BABYLON.serialize()
  37968. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37969. __decorate([
  37970. BABYLON.serialize()
  37971. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37972. __decorate([
  37973. BABYLON.serialize()
  37974. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37975. __decorate([
  37976. BABYLON.serializeAsColor4()
  37977. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37978. __decorate([
  37979. BABYLON.serialize()
  37980. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37981. __decorate([
  37982. BABYLON.serialize()
  37983. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37984. __decorate([
  37985. BABYLON.serialize()
  37986. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37987. __decorate([
  37988. BABYLON.serialize()
  37989. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37990. __decorate([
  37991. BABYLON.serialize()
  37992. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37993. __decorate([
  37994. BABYLON.serialize()
  37995. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37996. __decorate([
  37997. BABYLON.serialize()
  37998. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37999. __decorate([
  38000. BABYLON.serialize()
  38001. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  38002. return ImageProcessingConfiguration;
  38003. }());
  38004. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  38005. })(BABYLON || (BABYLON = {}));
  38006. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  38007. "use strict";
  38008. var BABYLON;
  38009. (function (BABYLON) {
  38010. /**
  38011. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38012. * It can help converting any input color in a desired output one. This can then be used to create effects
  38013. * from sepia, black and white to sixties or futuristic rendering...
  38014. *
  38015. * The only supported format is currently 3dl.
  38016. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38017. */
  38018. var ColorGradingTexture = /** @class */ (function (_super) {
  38019. __extends(ColorGradingTexture, _super);
  38020. /**
  38021. * Instantiates a ColorGradingTexture from the following parameters.
  38022. *
  38023. * @param url The location of the color gradind data (currently only supporting 3dl)
  38024. * @param scene The scene the texture will be used in
  38025. */
  38026. function ColorGradingTexture(url, scene) {
  38027. var _this = _super.call(this, scene) || this;
  38028. if (!url) {
  38029. return _this;
  38030. }
  38031. _this._engine = scene.getEngine();
  38032. _this._textureMatrix = BABYLON.Matrix.Identity();
  38033. _this.name = url;
  38034. _this.url = url;
  38035. _this.hasAlpha = false;
  38036. _this.isCube = false;
  38037. _this.is3D = _this._engine.webGLVersion > 1;
  38038. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38039. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38040. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38041. _this.anisotropicFilteringLevel = 1;
  38042. _this._texture = _this._getFromCache(url, true);
  38043. if (!_this._texture) {
  38044. if (!scene.useDelayedTextureLoading) {
  38045. _this.loadTexture();
  38046. }
  38047. else {
  38048. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38049. }
  38050. }
  38051. return _this;
  38052. }
  38053. /**
  38054. * Returns the texture matrix used in most of the material.
  38055. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38056. */
  38057. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38058. return this._textureMatrix;
  38059. };
  38060. /**
  38061. * Occurs when the file being loaded is a .3dl LUT file.
  38062. */
  38063. ColorGradingTexture.prototype.load3dlTexture = function () {
  38064. var engine = this._engine;
  38065. var texture;
  38066. if (engine.webGLVersion === 1) {
  38067. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38068. }
  38069. else {
  38070. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38071. }
  38072. this._texture = texture;
  38073. var callback = function (text) {
  38074. if (typeof text !== "string") {
  38075. return;
  38076. }
  38077. var data = null;
  38078. var tempData = null;
  38079. var line;
  38080. var lines = text.split('\n');
  38081. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38082. var maxColor = 0;
  38083. for (var i = 0; i < lines.length; i++) {
  38084. line = lines[i];
  38085. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38086. continue;
  38087. if (line.indexOf('#') === 0)
  38088. continue;
  38089. var words = line.split(" ");
  38090. if (size === 0) {
  38091. // Number of space + one
  38092. size = words.length;
  38093. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38094. tempData = new Float32Array(size * size * size * 4);
  38095. continue;
  38096. }
  38097. if (size != 0) {
  38098. var r = Math.max(parseInt(words[0]), 0);
  38099. var g = Math.max(parseInt(words[1]), 0);
  38100. var b = Math.max(parseInt(words[2]), 0);
  38101. maxColor = Math.max(r, maxColor);
  38102. maxColor = Math.max(g, maxColor);
  38103. maxColor = Math.max(b, maxColor);
  38104. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38105. if (tempData) {
  38106. tempData[pixelStorageIndex + 0] = r;
  38107. tempData[pixelStorageIndex + 1] = g;
  38108. tempData[pixelStorageIndex + 2] = b;
  38109. }
  38110. pixelIndexSlice++;
  38111. if (pixelIndexSlice % size == 0) {
  38112. pixelIndexH++;
  38113. pixelIndexSlice = 0;
  38114. if (pixelIndexH % size == 0) {
  38115. pixelIndexW++;
  38116. pixelIndexH = 0;
  38117. }
  38118. }
  38119. }
  38120. }
  38121. if (tempData && data) {
  38122. for (var i = 0; i < tempData.length; i++) {
  38123. if (i > 0 && (i + 1) % 4 === 0) {
  38124. data[i] = 255;
  38125. }
  38126. else {
  38127. var value = tempData[i];
  38128. data[i] = (value / maxColor * 255);
  38129. }
  38130. }
  38131. }
  38132. if (texture.is3D) {
  38133. texture.updateSize(size, size, size);
  38134. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38135. }
  38136. else {
  38137. texture.updateSize(size * size, size);
  38138. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38139. }
  38140. };
  38141. var scene = this.getScene();
  38142. if (scene) {
  38143. scene._loadFile(this.url, callback);
  38144. }
  38145. else {
  38146. this._engine._loadFile(this.url, callback);
  38147. }
  38148. return this._texture;
  38149. };
  38150. /**
  38151. * Starts the loading process of the texture.
  38152. */
  38153. ColorGradingTexture.prototype.loadTexture = function () {
  38154. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38155. this.load3dlTexture();
  38156. }
  38157. };
  38158. /**
  38159. * Clones the color gradind texture.
  38160. */
  38161. ColorGradingTexture.prototype.clone = function () {
  38162. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38163. // Base texture
  38164. newTexture.level = this.level;
  38165. return newTexture;
  38166. };
  38167. /**
  38168. * Called during delayed load for textures.
  38169. */
  38170. ColorGradingTexture.prototype.delayLoad = function () {
  38171. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38172. return;
  38173. }
  38174. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38175. this._texture = this._getFromCache(this.url, true);
  38176. if (!this._texture) {
  38177. this.loadTexture();
  38178. }
  38179. };
  38180. /**
  38181. * Parses a color grading texture serialized by Babylon.
  38182. * @param parsedTexture The texture information being parsedTexture
  38183. * @param scene The scene to load the texture in
  38184. * @param rootUrl The root url of the data assets to load
  38185. * @return A color gradind texture
  38186. */
  38187. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38188. var texture = null;
  38189. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38190. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38191. texture.name = parsedTexture.name;
  38192. texture.level = parsedTexture.level;
  38193. }
  38194. return texture;
  38195. };
  38196. /**
  38197. * Serializes the LUT texture to json format.
  38198. */
  38199. ColorGradingTexture.prototype.serialize = function () {
  38200. if (!this.name) {
  38201. return null;
  38202. }
  38203. var serializationObject = {};
  38204. serializationObject.name = this.name;
  38205. serializationObject.level = this.level;
  38206. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38207. return serializationObject;
  38208. };
  38209. /**
  38210. * Empty line regex stored for GC.
  38211. */
  38212. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38213. return ColorGradingTexture;
  38214. }(BABYLON.BaseTexture));
  38215. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38216. })(BABYLON || (BABYLON = {}));
  38217. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38218. "use strict";
  38219. var BABYLON;
  38220. (function (BABYLON) {
  38221. /**
  38222. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38223. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38224. * 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;
  38225. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38226. */
  38227. var ColorCurves = /** @class */ (function () {
  38228. function ColorCurves() {
  38229. this._dirty = true;
  38230. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38231. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38232. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38233. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38234. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38235. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38236. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38237. this._globalHue = 30;
  38238. this._globalDensity = 0;
  38239. this._globalSaturation = 0;
  38240. this._globalExposure = 0;
  38241. this._highlightsHue = 30;
  38242. this._highlightsDensity = 0;
  38243. this._highlightsSaturation = 0;
  38244. this._highlightsExposure = 0;
  38245. this._midtonesHue = 30;
  38246. this._midtonesDensity = 0;
  38247. this._midtonesSaturation = 0;
  38248. this._midtonesExposure = 0;
  38249. this._shadowsHue = 30;
  38250. this._shadowsDensity = 0;
  38251. this._shadowsSaturation = 0;
  38252. this._shadowsExposure = 0;
  38253. }
  38254. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38255. /**
  38256. * Gets the global Hue value.
  38257. * 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).
  38258. */
  38259. get: function () {
  38260. return this._globalHue;
  38261. },
  38262. /**
  38263. * Sets the global Hue value.
  38264. * 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).
  38265. */
  38266. set: function (value) {
  38267. this._globalHue = value;
  38268. this._dirty = true;
  38269. },
  38270. enumerable: true,
  38271. configurable: true
  38272. });
  38273. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38274. /**
  38275. * Gets the global Density value.
  38276. * 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.
  38277. * Values less than zero provide a filter of opposite hue.
  38278. */
  38279. get: function () {
  38280. return this._globalDensity;
  38281. },
  38282. /**
  38283. * Sets the global Density value.
  38284. * 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.
  38285. * Values less than zero provide a filter of opposite hue.
  38286. */
  38287. set: function (value) {
  38288. this._globalDensity = value;
  38289. this._dirty = true;
  38290. },
  38291. enumerable: true,
  38292. configurable: true
  38293. });
  38294. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38295. /**
  38296. * Gets the global Saturation value.
  38297. * 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.
  38298. */
  38299. get: function () {
  38300. return this._globalSaturation;
  38301. },
  38302. /**
  38303. * Sets the global Saturation value.
  38304. * 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.
  38305. */
  38306. set: function (value) {
  38307. this._globalSaturation = value;
  38308. this._dirty = true;
  38309. },
  38310. enumerable: true,
  38311. configurable: true
  38312. });
  38313. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38314. /**
  38315. * Gets the highlights Hue value.
  38316. * 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).
  38317. */
  38318. get: function () {
  38319. return this._highlightsHue;
  38320. },
  38321. /**
  38322. * Sets the highlights Hue value.
  38323. * 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).
  38324. */
  38325. set: function (value) {
  38326. this._highlightsHue = value;
  38327. this._dirty = true;
  38328. },
  38329. enumerable: true,
  38330. configurable: true
  38331. });
  38332. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38333. /**
  38334. * Gets the highlights Density value.
  38335. * 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.
  38336. * Values less than zero provide a filter of opposite hue.
  38337. */
  38338. get: function () {
  38339. return this._highlightsDensity;
  38340. },
  38341. /**
  38342. * Sets the highlights Density value.
  38343. * 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.
  38344. * Values less than zero provide a filter of opposite hue.
  38345. */
  38346. set: function (value) {
  38347. this._highlightsDensity = value;
  38348. this._dirty = true;
  38349. },
  38350. enumerable: true,
  38351. configurable: true
  38352. });
  38353. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38354. /**
  38355. * Gets the highlights Saturation value.
  38356. * 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.
  38357. */
  38358. get: function () {
  38359. return this._highlightsSaturation;
  38360. },
  38361. /**
  38362. * Sets the highlights Saturation value.
  38363. * 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.
  38364. */
  38365. set: function (value) {
  38366. this._highlightsSaturation = value;
  38367. this._dirty = true;
  38368. },
  38369. enumerable: true,
  38370. configurable: true
  38371. });
  38372. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38373. /**
  38374. * Gets the highlights Exposure value.
  38375. * 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.
  38376. */
  38377. get: function () {
  38378. return this._highlightsExposure;
  38379. },
  38380. /**
  38381. * Sets the highlights Exposure value.
  38382. * 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.
  38383. */
  38384. set: function (value) {
  38385. this._highlightsExposure = value;
  38386. this._dirty = true;
  38387. },
  38388. enumerable: true,
  38389. configurable: true
  38390. });
  38391. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38392. /**
  38393. * Gets the midtones Hue value.
  38394. * 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).
  38395. */
  38396. get: function () {
  38397. return this._midtonesHue;
  38398. },
  38399. /**
  38400. * Sets the midtones Hue value.
  38401. * 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).
  38402. */
  38403. set: function (value) {
  38404. this._midtonesHue = value;
  38405. this._dirty = true;
  38406. },
  38407. enumerable: true,
  38408. configurable: true
  38409. });
  38410. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38411. /**
  38412. * Gets the midtones Density value.
  38413. * 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.
  38414. * Values less than zero provide a filter of opposite hue.
  38415. */
  38416. get: function () {
  38417. return this._midtonesDensity;
  38418. },
  38419. /**
  38420. * Sets the midtones Density value.
  38421. * 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.
  38422. * Values less than zero provide a filter of opposite hue.
  38423. */
  38424. set: function (value) {
  38425. this._midtonesDensity = value;
  38426. this._dirty = true;
  38427. },
  38428. enumerable: true,
  38429. configurable: true
  38430. });
  38431. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38432. /**
  38433. * Gets the midtones Saturation value.
  38434. * 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.
  38435. */
  38436. get: function () {
  38437. return this._midtonesSaturation;
  38438. },
  38439. /**
  38440. * Sets the midtones Saturation value.
  38441. * 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.
  38442. */
  38443. set: function (value) {
  38444. this._midtonesSaturation = value;
  38445. this._dirty = true;
  38446. },
  38447. enumerable: true,
  38448. configurable: true
  38449. });
  38450. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38451. /**
  38452. * Gets the midtones Exposure value.
  38453. * 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.
  38454. */
  38455. get: function () {
  38456. return this._midtonesExposure;
  38457. },
  38458. /**
  38459. * Sets the midtones Exposure value.
  38460. * 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.
  38461. */
  38462. set: function (value) {
  38463. this._midtonesExposure = value;
  38464. this._dirty = true;
  38465. },
  38466. enumerable: true,
  38467. configurable: true
  38468. });
  38469. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38470. /**
  38471. * Gets the shadows Hue value.
  38472. * 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).
  38473. */
  38474. get: function () {
  38475. return this._shadowsHue;
  38476. },
  38477. /**
  38478. * Sets the shadows Hue value.
  38479. * 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).
  38480. */
  38481. set: function (value) {
  38482. this._shadowsHue = value;
  38483. this._dirty = true;
  38484. },
  38485. enumerable: true,
  38486. configurable: true
  38487. });
  38488. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38489. /**
  38490. * Gets the shadows Density value.
  38491. * 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.
  38492. * Values less than zero provide a filter of opposite hue.
  38493. */
  38494. get: function () {
  38495. return this._shadowsDensity;
  38496. },
  38497. /**
  38498. * Sets the shadows Density value.
  38499. * 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.
  38500. * Values less than zero provide a filter of opposite hue.
  38501. */
  38502. set: function (value) {
  38503. this._shadowsDensity = value;
  38504. this._dirty = true;
  38505. },
  38506. enumerable: true,
  38507. configurable: true
  38508. });
  38509. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38510. /**
  38511. * Gets the shadows Saturation value.
  38512. * 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.
  38513. */
  38514. get: function () {
  38515. return this._shadowsSaturation;
  38516. },
  38517. /**
  38518. * Sets the shadows Saturation value.
  38519. * 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.
  38520. */
  38521. set: function (value) {
  38522. this._shadowsSaturation = value;
  38523. this._dirty = true;
  38524. },
  38525. enumerable: true,
  38526. configurable: true
  38527. });
  38528. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38529. /**
  38530. * Gets the shadows Exposure value.
  38531. * 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.
  38532. */
  38533. get: function () {
  38534. return this._shadowsExposure;
  38535. },
  38536. /**
  38537. * Sets the shadows Exposure value.
  38538. * 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.
  38539. */
  38540. set: function (value) {
  38541. this._shadowsExposure = value;
  38542. this._dirty = true;
  38543. },
  38544. enumerable: true,
  38545. configurable: true
  38546. });
  38547. ColorCurves.prototype.getClassName = function () {
  38548. return "ColorCurves";
  38549. };
  38550. /**
  38551. * Binds the color curves to the shader.
  38552. * @param colorCurves The color curve to bind
  38553. * @param effect The effect to bind to
  38554. */
  38555. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38556. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38557. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38558. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38559. if (colorCurves._dirty) {
  38560. colorCurves._dirty = false;
  38561. // Fill in global info.
  38562. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38563. // Compute highlights info.
  38564. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38565. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38566. // Compute midtones info.
  38567. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38568. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38569. // Compute shadows info.
  38570. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38571. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38572. // Compute deltas (neutral is midtones).
  38573. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38574. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38575. }
  38576. if (effect) {
  38577. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38578. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38579. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38580. }
  38581. };
  38582. /**
  38583. * Prepare the list of uniforms associated with the ColorCurves effects.
  38584. * @param uniformsList The list of uniforms used in the effect
  38585. */
  38586. ColorCurves.PrepareUniforms = function (uniformsList) {
  38587. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38588. };
  38589. /**
  38590. * Returns color grading data based on a hue, density, saturation and exposure value.
  38591. * @param filterHue The hue of the color filter.
  38592. * @param filterDensity The density of the color filter.
  38593. * @param saturation The saturation.
  38594. * @param exposure The exposure.
  38595. * @param result The result data container.
  38596. */
  38597. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38598. if (hue == null) {
  38599. return;
  38600. }
  38601. hue = ColorCurves.clamp(hue, 0, 360);
  38602. density = ColorCurves.clamp(density, -100, 100);
  38603. saturation = ColorCurves.clamp(saturation, -100, 100);
  38604. exposure = ColorCurves.clamp(exposure, -100, 100);
  38605. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38606. // so that the maximum filter density is only 50% control. This provides fine control
  38607. // for small values and reasonable range.
  38608. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38609. density *= 0.5;
  38610. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38611. if (density < 0) {
  38612. density *= -1;
  38613. hue = (hue + 180) % 360;
  38614. }
  38615. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38616. result.scaleToRef(2, result);
  38617. result.a = 1 + 0.01 * saturation;
  38618. };
  38619. /**
  38620. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38621. * @param value The input slider value in range [-100,100].
  38622. * @returns Adjusted value.
  38623. */
  38624. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38625. value /= 100;
  38626. var x = Math.abs(value);
  38627. x = Math.pow(x, 2);
  38628. if (value < 0) {
  38629. x *= -1;
  38630. }
  38631. x *= 100;
  38632. return x;
  38633. };
  38634. /**
  38635. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38636. * @param hue The hue (H) input.
  38637. * @param saturation The saturation (S) input.
  38638. * @param brightness The brightness (B) input.
  38639. * @result An RGBA color represented as Vector4.
  38640. */
  38641. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38642. var h = ColorCurves.clamp(hue, 0, 360);
  38643. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38644. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38645. if (s === 0) {
  38646. result.r = v;
  38647. result.g = v;
  38648. result.b = v;
  38649. }
  38650. else {
  38651. // sector 0 to 5
  38652. h /= 60;
  38653. var i = Math.floor(h);
  38654. // fractional part of h
  38655. var f = h - i;
  38656. var p = v * (1 - s);
  38657. var q = v * (1 - s * f);
  38658. var t = v * (1 - s * (1 - f));
  38659. switch (i) {
  38660. case 0:
  38661. result.r = v;
  38662. result.g = t;
  38663. result.b = p;
  38664. break;
  38665. case 1:
  38666. result.r = q;
  38667. result.g = v;
  38668. result.b = p;
  38669. break;
  38670. case 2:
  38671. result.r = p;
  38672. result.g = v;
  38673. result.b = t;
  38674. break;
  38675. case 3:
  38676. result.r = p;
  38677. result.g = q;
  38678. result.b = v;
  38679. break;
  38680. case 4:
  38681. result.r = t;
  38682. result.g = p;
  38683. result.b = v;
  38684. break;
  38685. default:// case 5:
  38686. result.r = v;
  38687. result.g = p;
  38688. result.b = q;
  38689. break;
  38690. }
  38691. }
  38692. result.a = 1;
  38693. };
  38694. /**
  38695. * Returns a value clamped between min and max
  38696. * @param value The value to clamp
  38697. * @param min The minimum of value
  38698. * @param max The maximum of value
  38699. * @returns The clamped value.
  38700. */
  38701. ColorCurves.clamp = function (value, min, max) {
  38702. return Math.min(Math.max(value, min), max);
  38703. };
  38704. /**
  38705. * Clones the current color curve instance.
  38706. * @return The cloned curves
  38707. */
  38708. ColorCurves.prototype.clone = function () {
  38709. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38710. };
  38711. /**
  38712. * Serializes the current color curve instance to a json representation.
  38713. * @return a JSON representation
  38714. */
  38715. ColorCurves.prototype.serialize = function () {
  38716. return BABYLON.SerializationHelper.Serialize(this);
  38717. };
  38718. /**
  38719. * Parses the color curve from a json representation.
  38720. * @param source the JSON source to parse
  38721. * @return The parsed curves
  38722. */
  38723. ColorCurves.Parse = function (source) {
  38724. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38725. };
  38726. __decorate([
  38727. BABYLON.serialize()
  38728. ], ColorCurves.prototype, "_globalHue", void 0);
  38729. __decorate([
  38730. BABYLON.serialize()
  38731. ], ColorCurves.prototype, "_globalDensity", void 0);
  38732. __decorate([
  38733. BABYLON.serialize()
  38734. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38735. __decorate([
  38736. BABYLON.serialize()
  38737. ], ColorCurves.prototype, "_globalExposure", void 0);
  38738. __decorate([
  38739. BABYLON.serialize()
  38740. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38741. __decorate([
  38742. BABYLON.serialize()
  38743. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38744. __decorate([
  38745. BABYLON.serialize()
  38746. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38747. __decorate([
  38748. BABYLON.serialize()
  38749. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38750. __decorate([
  38751. BABYLON.serialize()
  38752. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38753. __decorate([
  38754. BABYLON.serialize()
  38755. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38756. __decorate([
  38757. BABYLON.serialize()
  38758. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38759. __decorate([
  38760. BABYLON.serialize()
  38761. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38762. return ColorCurves;
  38763. }());
  38764. BABYLON.ColorCurves = ColorCurves;
  38765. })(BABYLON || (BABYLON = {}));
  38766. //# sourceMappingURL=babylon.colorCurves.js.map
  38767. "use strict";
  38768. //# sourceMappingURL=babylon.behavior.js.map
  38769. "use strict";
  38770. var BABYLON;
  38771. (function (BABYLON) {
  38772. /**
  38773. * "Static Class" containing the most commonly used helper while dealing with material for
  38774. * rendering purpose.
  38775. *
  38776. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38777. *
  38778. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38779. */
  38780. var MaterialHelper = /** @class */ (function () {
  38781. function MaterialHelper() {
  38782. }
  38783. /**
  38784. * Bind the current view position to an effect.
  38785. * @param effect The effect to be bound
  38786. * @param scene The scene the eyes position is used from
  38787. */
  38788. MaterialHelper.BindEyePosition = function (effect, scene) {
  38789. if (scene._forcedViewPosition) {
  38790. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38791. return;
  38792. }
  38793. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38794. };
  38795. /**
  38796. * Helps preparing the defines values about the UVs in used in the effect.
  38797. * UVs are shared as much as we can accross chanels in the shaders.
  38798. * @param texture The texture we are preparing the UVs for
  38799. * @param defines The defines to update
  38800. * @param key The chanel key "diffuse", "specular"... used in the shader
  38801. */
  38802. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38803. defines._needUVs = true;
  38804. defines[key] = true;
  38805. if (texture.getTextureMatrix().isIdentity(true)) {
  38806. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38807. if (texture.coordinatesIndex === 0) {
  38808. defines["MAINUV1"] = true;
  38809. }
  38810. else {
  38811. defines["MAINUV2"] = true;
  38812. }
  38813. }
  38814. else {
  38815. defines[key + "DIRECTUV"] = 0;
  38816. }
  38817. };
  38818. /**
  38819. * Binds a texture matrix value to its corrsponding uniform
  38820. * @param texture The texture to bind the matrix for
  38821. * @param uniformBuffer The uniform buffer receivin the data
  38822. * @param key The chanel key "diffuse", "specular"... used in the shader
  38823. */
  38824. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38825. var matrix = texture.getTextureMatrix();
  38826. if (!matrix.isIdentity(true)) {
  38827. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38828. }
  38829. };
  38830. /**
  38831. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38832. * @param mesh defines the current mesh
  38833. * @param scene defines the current scene
  38834. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38835. * @param pointsCloud defines if point cloud rendering has to be turned on
  38836. * @param fogEnabled defines if fog has to be turned on
  38837. * @param alphaTest defines if alpha testing has to be turned on
  38838. * @param defines defines the current list of defines
  38839. */
  38840. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38841. if (defines._areMiscDirty) {
  38842. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38843. defines["POINTSIZE"] = pointsCloud;
  38844. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38845. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38846. defines["ALPHATEST"] = alphaTest;
  38847. }
  38848. };
  38849. /**
  38850. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38851. * @param scene defines the current scene
  38852. * @param engine defines the current engine
  38853. * @param defines specifies the list of active defines
  38854. * @param useInstances defines if instances have to be turned on
  38855. * @param useClipPlane defines if clip plane have to be turned on
  38856. */
  38857. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38858. if (useClipPlane === void 0) { useClipPlane = null; }
  38859. var changed = false;
  38860. if (useClipPlane == null) {
  38861. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38862. }
  38863. if (defines["CLIPPLANE"] !== useClipPlane) {
  38864. defines["CLIPPLANE"] = useClipPlane;
  38865. changed = true;
  38866. }
  38867. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38868. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38869. changed = true;
  38870. }
  38871. if (defines["INSTANCES"] !== useInstances) {
  38872. defines["INSTANCES"] = useInstances;
  38873. changed = true;
  38874. }
  38875. if (changed) {
  38876. defines.markAsUnprocessed();
  38877. }
  38878. };
  38879. /**
  38880. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38881. * @param mesh The mesh containing the geometry data we will draw
  38882. * @param defines The defines to update
  38883. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38884. * @param useBones Precise whether bones should be used or not (override mesh info)
  38885. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38886. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38887. * @returns false if defines are considered not dirty and have not been checked
  38888. */
  38889. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38890. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38891. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38892. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38893. return false;
  38894. }
  38895. defines._normals = defines._needNormals;
  38896. defines._uvs = defines._needUVs;
  38897. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38898. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38899. defines["TANGENT"] = true;
  38900. }
  38901. if (defines._needUVs) {
  38902. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38903. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38904. }
  38905. else {
  38906. defines["UV1"] = false;
  38907. defines["UV2"] = false;
  38908. }
  38909. if (useVertexColor) {
  38910. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38911. defines["VERTEXCOLOR"] = hasVertexColors;
  38912. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38913. }
  38914. if (useBones) {
  38915. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38916. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38917. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38918. }
  38919. else {
  38920. defines["NUM_BONE_INFLUENCERS"] = 0;
  38921. defines["BonesPerMesh"] = 0;
  38922. }
  38923. }
  38924. if (useMorphTargets) {
  38925. var manager = mesh.morphTargetManager;
  38926. if (manager) {
  38927. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38928. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38929. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38930. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38931. }
  38932. else {
  38933. defines["MORPHTARGETS_TANGENT"] = false;
  38934. defines["MORPHTARGETS_NORMAL"] = false;
  38935. defines["MORPHTARGETS"] = false;
  38936. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38937. }
  38938. }
  38939. return true;
  38940. };
  38941. /**
  38942. * Prepares the defines related to the light information passed in parameter
  38943. * @param scene The scene we are intending to draw
  38944. * @param mesh The mesh the effect is compiling for
  38945. * @param defines The defines to update
  38946. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38947. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38948. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38949. * @returns true if normals will be required for the rest of the effect
  38950. */
  38951. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38952. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38953. if (disableLighting === void 0) { disableLighting = false; }
  38954. if (!defines._areLightsDirty) {
  38955. return defines._needNormals;
  38956. }
  38957. var lightIndex = 0;
  38958. var needNormals = false;
  38959. var needRebuild = false;
  38960. var lightmapMode = false;
  38961. var shadowEnabled = false;
  38962. var specularEnabled = false;
  38963. if (scene.lightsEnabled && !disableLighting) {
  38964. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38965. var light = _a[_i];
  38966. needNormals = true;
  38967. if (defines["LIGHT" + lightIndex] === undefined) {
  38968. needRebuild = true;
  38969. }
  38970. defines["LIGHT" + lightIndex] = true;
  38971. defines["SPOTLIGHT" + lightIndex] = false;
  38972. defines["HEMILIGHT" + lightIndex] = false;
  38973. defines["POINTLIGHT" + lightIndex] = false;
  38974. defines["DIRLIGHT" + lightIndex] = false;
  38975. var type;
  38976. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38977. type = "SPOTLIGHT" + lightIndex;
  38978. var spotLight = light;
  38979. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38980. }
  38981. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38982. type = "HEMILIGHT" + lightIndex;
  38983. }
  38984. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38985. type = "POINTLIGHT" + lightIndex;
  38986. }
  38987. else {
  38988. type = "DIRLIGHT" + lightIndex;
  38989. }
  38990. defines[type] = true;
  38991. // Specular
  38992. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38993. specularEnabled = true;
  38994. }
  38995. // Shadows
  38996. defines["SHADOW" + lightIndex] = false;
  38997. defines["SHADOWPCF" + lightIndex] = false;
  38998. defines["SHADOWPCSS" + lightIndex] = false;
  38999. defines["SHADOWPOISSON" + lightIndex] = false;
  39000. defines["SHADOWESM" + lightIndex] = false;
  39001. defines["SHADOWCUBE" + lightIndex] = false;
  39002. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  39003. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  39004. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  39005. var shadowGenerator = light.getShadowGenerator();
  39006. if (shadowGenerator) {
  39007. shadowEnabled = true;
  39008. shadowGenerator.prepareDefines(defines, lightIndex);
  39009. }
  39010. }
  39011. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  39012. lightmapMode = true;
  39013. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  39014. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  39015. }
  39016. else {
  39017. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  39018. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  39019. }
  39020. lightIndex++;
  39021. if (lightIndex === maxSimultaneousLights)
  39022. break;
  39023. }
  39024. }
  39025. defines["SPECULARTERM"] = specularEnabled;
  39026. defines["SHADOWS"] = shadowEnabled;
  39027. // Resetting all other lights if any
  39028. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  39029. if (defines["LIGHT" + index] !== undefined) {
  39030. defines["LIGHT" + index] = false;
  39031. defines["HEMILIGHT" + lightIndex] = false;
  39032. defines["POINTLIGHT" + lightIndex] = false;
  39033. defines["DIRLIGHT" + lightIndex] = false;
  39034. defines["SPOTLIGHT" + lightIndex] = false;
  39035. defines["SHADOW" + lightIndex] = false;
  39036. }
  39037. }
  39038. var caps = scene.getEngine().getCaps();
  39039. if (defines["SHADOWFLOAT"] === undefined) {
  39040. needRebuild = true;
  39041. }
  39042. defines["SHADOWFLOAT"] = shadowEnabled &&
  39043. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  39044. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  39045. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  39046. if (needRebuild) {
  39047. defines.rebuild();
  39048. }
  39049. return needNormals;
  39050. };
  39051. /**
  39052. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  39053. * that won t be acctive due to defines being turned off.
  39054. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  39055. * @param samplersList The samplers list
  39056. * @param defines The defines helping in the list generation
  39057. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  39058. */
  39059. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  39060. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39061. var uniformsList;
  39062. var uniformBuffersList = null;
  39063. if (uniformsListOrOptions.uniformsNames) {
  39064. var options = uniformsListOrOptions;
  39065. uniformsList = options.uniformsNames;
  39066. uniformBuffersList = options.uniformBuffersNames;
  39067. samplersList = options.samplers;
  39068. defines = options.defines;
  39069. maxSimultaneousLights = options.maxSimultaneousLights;
  39070. }
  39071. else {
  39072. uniformsList = uniformsListOrOptions;
  39073. if (!samplersList) {
  39074. samplersList = [];
  39075. }
  39076. }
  39077. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39078. if (!defines["LIGHT" + lightIndex]) {
  39079. break;
  39080. }
  39081. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39082. if (uniformBuffersList) {
  39083. uniformBuffersList.push("Light" + lightIndex);
  39084. }
  39085. samplersList.push("shadowSampler" + lightIndex);
  39086. samplersList.push("depthSampler" + lightIndex);
  39087. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39088. samplersList.push("projectionLightSampler" + lightIndex);
  39089. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39090. }
  39091. }
  39092. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39093. uniformsList.push("morphTargetInfluences");
  39094. }
  39095. };
  39096. /**
  39097. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39098. * @param defines The defines to update while falling back
  39099. * @param fallbacks The authorized effect fallbacks
  39100. * @param maxSimultaneousLights The maximum number of lights allowed
  39101. * @param rank the current rank of the Effect
  39102. * @returns The newly affected rank
  39103. */
  39104. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39105. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39106. if (rank === void 0) { rank = 0; }
  39107. var lightFallbackRank = 0;
  39108. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39109. if (!defines["LIGHT" + lightIndex]) {
  39110. break;
  39111. }
  39112. if (lightIndex > 0) {
  39113. lightFallbackRank = rank + lightIndex;
  39114. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39115. }
  39116. if (!defines["SHADOWS"]) {
  39117. if (defines["SHADOW" + lightIndex]) {
  39118. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39119. }
  39120. if (defines["SHADOWPCF" + lightIndex]) {
  39121. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39122. }
  39123. if (defines["SHADOWPCSS" + lightIndex]) {
  39124. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39125. }
  39126. if (defines["SHADOWPOISSON" + lightIndex]) {
  39127. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39128. }
  39129. if (defines["SHADOWESM" + lightIndex]) {
  39130. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39131. }
  39132. }
  39133. }
  39134. return lightFallbackRank++;
  39135. };
  39136. /**
  39137. * Prepares the list of attributes required for morph targets according to the effect defines.
  39138. * @param attribs The current list of supported attribs
  39139. * @param mesh The mesh to prepare the morph targets attributes for
  39140. * @param defines The current Defines of the effect
  39141. */
  39142. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39143. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39144. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39145. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39146. var manager = mesh.morphTargetManager;
  39147. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39148. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39149. for (var index = 0; index < influencers; index++) {
  39150. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39151. if (normal) {
  39152. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39153. }
  39154. if (tangent) {
  39155. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39156. }
  39157. if (attribs.length > maxAttributesCount) {
  39158. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39159. }
  39160. }
  39161. }
  39162. };
  39163. /**
  39164. * Prepares the list of attributes required for bones according to the effect defines.
  39165. * @param attribs The current list of supported attribs
  39166. * @param mesh The mesh to prepare the bones attributes for
  39167. * @param defines The current Defines of the effect
  39168. * @param fallbacks The current efffect fallback strategy
  39169. */
  39170. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39171. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39172. fallbacks.addCPUSkinningFallback(0, mesh);
  39173. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39174. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39175. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39176. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39177. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39178. }
  39179. }
  39180. };
  39181. /**
  39182. * Prepares the list of attributes required for instances according to the effect defines.
  39183. * @param attribs The current list of supported attribs
  39184. * @param defines The current Defines of the effect
  39185. */
  39186. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39187. if (defines["INSTANCES"]) {
  39188. attribs.push("world0");
  39189. attribs.push("world1");
  39190. attribs.push("world2");
  39191. attribs.push("world3");
  39192. }
  39193. };
  39194. /**
  39195. * Binds the light shadow information to the effect for the given mesh.
  39196. * @param light The light containing the generator
  39197. * @param scene The scene the lights belongs to
  39198. * @param mesh The mesh we are binding the information to render
  39199. * @param lightIndex The light index in the effect used to render the mesh
  39200. * @param effect The effect we are binding the data to
  39201. */
  39202. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39203. if (light.shadowEnabled && mesh.receiveShadows) {
  39204. var shadowGenerator = light.getShadowGenerator();
  39205. if (shadowGenerator) {
  39206. shadowGenerator.bindShadowLight(lightIndex, effect);
  39207. }
  39208. }
  39209. };
  39210. /**
  39211. * Binds the light information to the effect.
  39212. * @param light The light containing the generator
  39213. * @param effect The effect we are binding the data to
  39214. * @param lightIndex The light index in the effect used to render
  39215. */
  39216. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39217. light.transferToEffect(effect, lightIndex + "");
  39218. };
  39219. /**
  39220. * Binds the lights information from the scene to the effect for the given mesh.
  39221. * @param scene The scene the lights belongs to
  39222. * @param mesh The mesh we are binding the information to render
  39223. * @param effect The effect we are binding the data to
  39224. * @param defines The generated defines for the effect
  39225. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39226. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39227. */
  39228. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39229. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39230. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39231. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39232. for (var i = 0; i < len; i++) {
  39233. var light = mesh._lightSources[i];
  39234. var iAsString = i.toString();
  39235. var scaledIntensity = light.getScaledIntensity();
  39236. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39237. MaterialHelper.BindLightProperties(light, effect, i);
  39238. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39239. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39240. if (defines["SPECULARTERM"]) {
  39241. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39242. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39243. }
  39244. // Shadows
  39245. if (scene.shadowsEnabled) {
  39246. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39247. }
  39248. light._uniformBuffer.update();
  39249. }
  39250. };
  39251. /**
  39252. * Binds the fog information from the scene to the effect for the given mesh.
  39253. * @param scene The scene the lights belongs to
  39254. * @param mesh The mesh we are binding the information to render
  39255. * @param effect The effect we are binding the data to
  39256. */
  39257. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39258. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39259. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39260. effect.setColor3("vFogColor", scene.fogColor);
  39261. }
  39262. };
  39263. /**
  39264. * Binds the bones information from the mesh to the effect.
  39265. * @param mesh The mesh we are binding the information to render
  39266. * @param effect The effect we are binding the data to
  39267. */
  39268. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39269. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39270. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39271. if (matrices && effect) {
  39272. effect.setMatrices("mBones", matrices);
  39273. }
  39274. }
  39275. };
  39276. /**
  39277. * Binds the morph targets information from the mesh to the effect.
  39278. * @param abstractMesh The mesh we are binding the information to render
  39279. * @param effect The effect we are binding the data to
  39280. */
  39281. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39282. var manager = abstractMesh.morphTargetManager;
  39283. if (!abstractMesh || !manager) {
  39284. return;
  39285. }
  39286. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39287. };
  39288. /**
  39289. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39290. * @param defines The generated defines used in the effect
  39291. * @param effect The effect we are binding the data to
  39292. * @param scene The scene we are willing to render with logarithmic scale for
  39293. */
  39294. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39295. if (defines["LOGARITHMICDEPTH"]) {
  39296. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39297. }
  39298. };
  39299. /**
  39300. * Binds the clip plane information from the scene to the effect.
  39301. * @param scene The scene the clip plane information are extracted from
  39302. * @param effect The effect we are binding the data to
  39303. */
  39304. MaterialHelper.BindClipPlane = function (effect, scene) {
  39305. if (scene.clipPlane) {
  39306. var clipPlane = scene.clipPlane;
  39307. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39308. }
  39309. };
  39310. return MaterialHelper;
  39311. }());
  39312. BABYLON.MaterialHelper = MaterialHelper;
  39313. })(BABYLON || (BABYLON = {}));
  39314. //# sourceMappingURL=babylon.materialHelper.js.map
  39315. "use strict";
  39316. var BABYLON;
  39317. (function (BABYLON) {
  39318. var PushMaterial = /** @class */ (function (_super) {
  39319. __extends(PushMaterial, _super);
  39320. function PushMaterial(name, scene) {
  39321. var _this = _super.call(this, name, scene) || this;
  39322. _this._normalMatrix = new BABYLON.Matrix();
  39323. _this.storeEffectOnSubMeshes = true;
  39324. return _this;
  39325. }
  39326. PushMaterial.prototype.getEffect = function () {
  39327. return this._activeEffect;
  39328. };
  39329. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39330. if (!mesh) {
  39331. return false;
  39332. }
  39333. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39334. return true;
  39335. }
  39336. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39337. };
  39338. /**
  39339. * Binds the given world matrix to the active effect
  39340. *
  39341. * @param world the matrix to bind
  39342. */
  39343. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39344. this._activeEffect.setMatrix("world", world);
  39345. };
  39346. /**
  39347. * Binds the given normal matrix to the active effect
  39348. *
  39349. * @param normalMatrix the matrix to bind
  39350. */
  39351. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39352. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39353. };
  39354. PushMaterial.prototype.bind = function (world, mesh) {
  39355. if (!mesh) {
  39356. return;
  39357. }
  39358. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39359. };
  39360. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39361. if (effect === void 0) { effect = null; }
  39362. _super.prototype._afterBind.call(this, mesh);
  39363. this.getScene()._cachedEffect = effect;
  39364. };
  39365. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39366. if (visibility === void 0) { visibility = 1; }
  39367. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39368. };
  39369. return PushMaterial;
  39370. }(BABYLON.Material));
  39371. BABYLON.PushMaterial = PushMaterial;
  39372. })(BABYLON || (BABYLON = {}));
  39373. //# sourceMappingURL=babylon.pushMaterial.js.map
  39374. "use strict";
  39375. var BABYLON;
  39376. (function (BABYLON) {
  39377. /** @ignore */
  39378. var StandardMaterialDefines = /** @class */ (function (_super) {
  39379. __extends(StandardMaterialDefines, _super);
  39380. function StandardMaterialDefines() {
  39381. var _this = _super.call(this) || this;
  39382. _this.MAINUV1 = false;
  39383. _this.MAINUV2 = false;
  39384. _this.DIFFUSE = false;
  39385. _this.DIFFUSEDIRECTUV = 0;
  39386. _this.AMBIENT = false;
  39387. _this.AMBIENTDIRECTUV = 0;
  39388. _this.OPACITY = false;
  39389. _this.OPACITYDIRECTUV = 0;
  39390. _this.OPACITYRGB = false;
  39391. _this.REFLECTION = false;
  39392. _this.EMISSIVE = false;
  39393. _this.EMISSIVEDIRECTUV = 0;
  39394. _this.SPECULAR = false;
  39395. _this.SPECULARDIRECTUV = 0;
  39396. _this.BUMP = false;
  39397. _this.BUMPDIRECTUV = 0;
  39398. _this.PARALLAX = false;
  39399. _this.PARALLAXOCCLUSION = false;
  39400. _this.SPECULAROVERALPHA = false;
  39401. _this.CLIPPLANE = false;
  39402. _this.ALPHATEST = false;
  39403. _this.DEPTHPREPASS = false;
  39404. _this.ALPHAFROMDIFFUSE = false;
  39405. _this.POINTSIZE = false;
  39406. _this.FOG = false;
  39407. _this.SPECULARTERM = false;
  39408. _this.DIFFUSEFRESNEL = false;
  39409. _this.OPACITYFRESNEL = false;
  39410. _this.REFLECTIONFRESNEL = false;
  39411. _this.REFRACTIONFRESNEL = false;
  39412. _this.EMISSIVEFRESNEL = false;
  39413. _this.FRESNEL = false;
  39414. _this.NORMAL = false;
  39415. _this.UV1 = false;
  39416. _this.UV2 = false;
  39417. _this.VERTEXCOLOR = false;
  39418. _this.VERTEXALPHA = false;
  39419. _this.NUM_BONE_INFLUENCERS = 0;
  39420. _this.BonesPerMesh = 0;
  39421. _this.INSTANCES = false;
  39422. _this.GLOSSINESS = false;
  39423. _this.ROUGHNESS = false;
  39424. _this.EMISSIVEASILLUMINATION = false;
  39425. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39426. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39427. _this.LIGHTMAP = false;
  39428. _this.LIGHTMAPDIRECTUV = 0;
  39429. _this.OBJECTSPACE_NORMALMAP = false;
  39430. _this.USELIGHTMAPASSHADOWMAP = false;
  39431. _this.REFLECTIONMAP_3D = false;
  39432. _this.REFLECTIONMAP_SPHERICAL = false;
  39433. _this.REFLECTIONMAP_PLANAR = false;
  39434. _this.REFLECTIONMAP_CUBIC = false;
  39435. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39436. _this.REFLECTIONMAP_PROJECTION = false;
  39437. _this.REFLECTIONMAP_SKYBOX = false;
  39438. _this.REFLECTIONMAP_EXPLICIT = false;
  39439. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39440. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39441. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39442. _this.INVERTCUBICMAP = false;
  39443. _this.LOGARITHMICDEPTH = false;
  39444. _this.REFRACTION = false;
  39445. _this.REFRACTIONMAP_3D = false;
  39446. _this.REFLECTIONOVERALPHA = false;
  39447. _this.TWOSIDEDLIGHTING = false;
  39448. _this.SHADOWFLOAT = false;
  39449. _this.MORPHTARGETS = false;
  39450. _this.MORPHTARGETS_NORMAL = false;
  39451. _this.MORPHTARGETS_TANGENT = false;
  39452. _this.NUM_MORPH_INFLUENCERS = 0;
  39453. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39454. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39455. _this.IMAGEPROCESSING = false;
  39456. _this.VIGNETTE = false;
  39457. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39458. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39459. _this.TONEMAPPING = false;
  39460. _this.CONTRAST = false;
  39461. _this.COLORCURVES = false;
  39462. _this.COLORGRADING = false;
  39463. _this.COLORGRADING3D = false;
  39464. _this.SAMPLER3DGREENDEPTH = false;
  39465. _this.SAMPLER3DBGRMAP = false;
  39466. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39467. _this.EXPOSURE = false;
  39468. _this.GRAIN = false;
  39469. _this.rebuild();
  39470. return _this;
  39471. }
  39472. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39473. var modes = [
  39474. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39475. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39476. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39477. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39478. ];
  39479. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39480. var mode = modes_1[_i];
  39481. this[mode] = (mode === modeToEnable);
  39482. }
  39483. };
  39484. return StandardMaterialDefines;
  39485. }(BABYLON.MaterialDefines));
  39486. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39487. var StandardMaterial = /** @class */ (function (_super) {
  39488. __extends(StandardMaterial, _super);
  39489. function StandardMaterial(name, scene) {
  39490. var _this = _super.call(this, name, scene) || this;
  39491. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39492. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39493. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39494. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39495. _this.specularPower = 64;
  39496. _this._useAlphaFromDiffuseTexture = false;
  39497. _this._useEmissiveAsIllumination = false;
  39498. _this._linkEmissiveWithDiffuse = false;
  39499. _this._useSpecularOverAlpha = false;
  39500. _this._useReflectionOverAlpha = false;
  39501. _this._disableLighting = false;
  39502. _this._useObjectSpaceNormalMap = false;
  39503. _this._useParallax = false;
  39504. _this._useParallaxOcclusion = false;
  39505. _this.parallaxScaleBias = 0.05;
  39506. _this._roughness = 0;
  39507. _this.indexOfRefraction = 0.98;
  39508. _this.invertRefractionY = true;
  39509. _this._useLightmapAsShadowmap = false;
  39510. _this._useReflectionFresnelFromSpecular = false;
  39511. _this._useGlossinessFromSpecularMapAlpha = false;
  39512. _this._maxSimultaneousLights = 4;
  39513. /**
  39514. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39515. */
  39516. _this._invertNormalMapX = false;
  39517. /**
  39518. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39519. */
  39520. _this._invertNormalMapY = false;
  39521. /**
  39522. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39523. */
  39524. _this._twoSidedLighting = false;
  39525. _this._renderTargets = new BABYLON.SmartArray(16);
  39526. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39527. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39528. // Setup the default processing configuration to the scene.
  39529. _this._attachImageProcessingConfiguration(null);
  39530. _this.getRenderTargetTextures = function () {
  39531. _this._renderTargets.reset();
  39532. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39533. _this._renderTargets.push(_this._reflectionTexture);
  39534. }
  39535. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39536. _this._renderTargets.push(_this._refractionTexture);
  39537. }
  39538. return _this._renderTargets;
  39539. };
  39540. return _this;
  39541. }
  39542. ;
  39543. ;
  39544. ;
  39545. ;
  39546. ;
  39547. ;
  39548. ;
  39549. ;
  39550. ;
  39551. ;
  39552. ;
  39553. ;
  39554. ;
  39555. ;
  39556. ;
  39557. ;
  39558. ;
  39559. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39560. /**
  39561. * Gets the image processing configuration used either in this material.
  39562. */
  39563. get: function () {
  39564. return this._imageProcessingConfiguration;
  39565. },
  39566. /**
  39567. * Sets the Default image processing configuration used either in the this material.
  39568. *
  39569. * If sets to null, the scene one is in use.
  39570. */
  39571. set: function (value) {
  39572. this._attachImageProcessingConfiguration(value);
  39573. // Ensure the effect will be rebuilt.
  39574. this._markAllSubMeshesAsTexturesDirty();
  39575. },
  39576. enumerable: true,
  39577. configurable: true
  39578. });
  39579. /**
  39580. * Attaches a new image processing configuration to the Standard Material.
  39581. * @param configuration
  39582. */
  39583. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39584. var _this = this;
  39585. if (configuration === this._imageProcessingConfiguration) {
  39586. return;
  39587. }
  39588. // Detaches observer.
  39589. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39590. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39591. }
  39592. // Pick the scene configuration if needed.
  39593. if (!configuration) {
  39594. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39595. }
  39596. else {
  39597. this._imageProcessingConfiguration = configuration;
  39598. }
  39599. // Attaches observer.
  39600. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39601. _this._markAllSubMeshesAsImageProcessingDirty();
  39602. });
  39603. };
  39604. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39605. /**
  39606. * Gets wether the color curves effect is enabled.
  39607. */
  39608. get: function () {
  39609. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39610. },
  39611. /**
  39612. * Sets wether the color curves effect is enabled.
  39613. */
  39614. set: function (value) {
  39615. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39616. },
  39617. enumerable: true,
  39618. configurable: true
  39619. });
  39620. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39621. /**
  39622. * Gets wether the color grading effect is enabled.
  39623. */
  39624. get: function () {
  39625. return this.imageProcessingConfiguration.colorGradingEnabled;
  39626. },
  39627. /**
  39628. * Gets wether the color grading effect is enabled.
  39629. */
  39630. set: function (value) {
  39631. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39632. },
  39633. enumerable: true,
  39634. configurable: true
  39635. });
  39636. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39637. /**
  39638. * Gets wether tonemapping is enabled or not.
  39639. */
  39640. get: function () {
  39641. return this._imageProcessingConfiguration.toneMappingEnabled;
  39642. },
  39643. /**
  39644. * Sets wether tonemapping is enabled or not
  39645. */
  39646. set: function (value) {
  39647. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39648. },
  39649. enumerable: true,
  39650. configurable: true
  39651. });
  39652. ;
  39653. ;
  39654. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39655. /**
  39656. * The camera exposure used on this material.
  39657. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39658. * This corresponds to a photographic exposure.
  39659. */
  39660. get: function () {
  39661. return this._imageProcessingConfiguration.exposure;
  39662. },
  39663. /**
  39664. * The camera exposure used on this material.
  39665. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39666. * This corresponds to a photographic exposure.
  39667. */
  39668. set: function (value) {
  39669. this._imageProcessingConfiguration.exposure = value;
  39670. },
  39671. enumerable: true,
  39672. configurable: true
  39673. });
  39674. ;
  39675. ;
  39676. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39677. /**
  39678. * Gets The camera contrast used on this material.
  39679. */
  39680. get: function () {
  39681. return this._imageProcessingConfiguration.contrast;
  39682. },
  39683. /**
  39684. * Sets The camera contrast used on this material.
  39685. */
  39686. set: function (value) {
  39687. this._imageProcessingConfiguration.contrast = value;
  39688. },
  39689. enumerable: true,
  39690. configurable: true
  39691. });
  39692. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39693. /**
  39694. * Gets the Color Grading 2D Lookup Texture.
  39695. */
  39696. get: function () {
  39697. return this._imageProcessingConfiguration.colorGradingTexture;
  39698. },
  39699. /**
  39700. * Sets the Color Grading 2D Lookup Texture.
  39701. */
  39702. set: function (value) {
  39703. this._imageProcessingConfiguration.colorGradingTexture = value;
  39704. },
  39705. enumerable: true,
  39706. configurable: true
  39707. });
  39708. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39709. /**
  39710. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39711. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39712. * 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;
  39713. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39714. */
  39715. get: function () {
  39716. return this._imageProcessingConfiguration.colorCurves;
  39717. },
  39718. /**
  39719. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39720. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39721. * 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;
  39722. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39723. */
  39724. set: function (value) {
  39725. this._imageProcessingConfiguration.colorCurves = value;
  39726. },
  39727. enumerable: true,
  39728. configurable: true
  39729. });
  39730. StandardMaterial.prototype.getClassName = function () {
  39731. return "StandardMaterial";
  39732. };
  39733. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39734. get: function () {
  39735. return this._useLogarithmicDepth;
  39736. },
  39737. set: function (value) {
  39738. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39739. this._markAllSubMeshesAsMiscDirty();
  39740. },
  39741. enumerable: true,
  39742. configurable: true
  39743. });
  39744. StandardMaterial.prototype.needAlphaBlending = function () {
  39745. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39746. };
  39747. StandardMaterial.prototype.needAlphaTesting = function () {
  39748. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39749. };
  39750. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39751. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39752. };
  39753. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39754. return this._diffuseTexture;
  39755. };
  39756. /**
  39757. * Child classes can use it to update shaders
  39758. */
  39759. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39760. if (useInstances === void 0) { useInstances = false; }
  39761. if (subMesh.effect && this.isFrozen) {
  39762. if (this._wasPreviouslyReady && subMesh.effect) {
  39763. return true;
  39764. }
  39765. }
  39766. if (!subMesh._materialDefines) {
  39767. subMesh._materialDefines = new StandardMaterialDefines();
  39768. }
  39769. var scene = this.getScene();
  39770. var defines = subMesh._materialDefines;
  39771. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39772. if (defines._renderId === scene.getRenderId()) {
  39773. return true;
  39774. }
  39775. }
  39776. var engine = scene.getEngine();
  39777. // Lights
  39778. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39779. // Textures
  39780. if (defines._areTexturesDirty) {
  39781. defines._needUVs = false;
  39782. defines.MAINUV1 = false;
  39783. defines.MAINUV2 = false;
  39784. if (scene.texturesEnabled) {
  39785. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39786. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39787. return false;
  39788. }
  39789. else {
  39790. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39791. }
  39792. }
  39793. else {
  39794. defines.DIFFUSE = false;
  39795. }
  39796. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39797. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39798. return false;
  39799. }
  39800. else {
  39801. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39802. }
  39803. }
  39804. else {
  39805. defines.AMBIENT = false;
  39806. }
  39807. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39808. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39809. return false;
  39810. }
  39811. else {
  39812. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39813. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39814. }
  39815. }
  39816. else {
  39817. defines.OPACITY = false;
  39818. }
  39819. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39820. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39821. return false;
  39822. }
  39823. else {
  39824. defines._needNormals = true;
  39825. defines.REFLECTION = true;
  39826. defines.ROUGHNESS = (this._roughness > 0);
  39827. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39828. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39829. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39830. switch (this._reflectionTexture.coordinatesMode) {
  39831. case BABYLON.Texture.CUBIC_MODE:
  39832. case BABYLON.Texture.INVCUBIC_MODE:
  39833. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39834. break;
  39835. case BABYLON.Texture.EXPLICIT_MODE:
  39836. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39837. break;
  39838. case BABYLON.Texture.PLANAR_MODE:
  39839. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39840. break;
  39841. case BABYLON.Texture.PROJECTION_MODE:
  39842. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39843. break;
  39844. case BABYLON.Texture.SKYBOX_MODE:
  39845. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39846. break;
  39847. case BABYLON.Texture.SPHERICAL_MODE:
  39848. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39849. break;
  39850. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39851. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39852. break;
  39853. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39854. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39855. break;
  39856. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39857. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39858. break;
  39859. }
  39860. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39861. }
  39862. }
  39863. else {
  39864. defines.REFLECTION = false;
  39865. }
  39866. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39867. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39868. return false;
  39869. }
  39870. else {
  39871. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39872. }
  39873. }
  39874. else {
  39875. defines.EMISSIVE = false;
  39876. }
  39877. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39878. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39879. return false;
  39880. }
  39881. else {
  39882. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39883. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39884. }
  39885. }
  39886. else {
  39887. defines.LIGHTMAP = false;
  39888. }
  39889. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39890. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39891. return false;
  39892. }
  39893. else {
  39894. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39895. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39896. }
  39897. }
  39898. else {
  39899. defines.SPECULAR = false;
  39900. }
  39901. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39902. // Bump texure can not be not blocking.
  39903. if (!this._bumpTexture.isReady()) {
  39904. return false;
  39905. }
  39906. else {
  39907. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39908. defines.PARALLAX = this._useParallax;
  39909. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39910. }
  39911. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39912. }
  39913. else {
  39914. defines.BUMP = false;
  39915. }
  39916. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39917. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39918. return false;
  39919. }
  39920. else {
  39921. defines._needUVs = true;
  39922. defines.REFRACTION = true;
  39923. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39924. }
  39925. }
  39926. else {
  39927. defines.REFRACTION = false;
  39928. }
  39929. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39930. }
  39931. else {
  39932. defines.DIFFUSE = false;
  39933. defines.AMBIENT = false;
  39934. defines.OPACITY = false;
  39935. defines.REFLECTION = false;
  39936. defines.EMISSIVE = false;
  39937. defines.LIGHTMAP = false;
  39938. defines.BUMP = false;
  39939. defines.REFRACTION = false;
  39940. }
  39941. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39942. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39943. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39944. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39945. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39946. }
  39947. if (defines._areImageProcessingDirty) {
  39948. if (!this._imageProcessingConfiguration.isReady()) {
  39949. return false;
  39950. }
  39951. this._imageProcessingConfiguration.prepareDefines(defines);
  39952. }
  39953. if (defines._areFresnelDirty) {
  39954. if (StandardMaterial.FresnelEnabled) {
  39955. // Fresnel
  39956. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39957. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39958. this._reflectionFresnelParameters) {
  39959. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39960. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39961. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39962. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39963. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39964. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39965. defines._needNormals = true;
  39966. defines.FRESNEL = true;
  39967. }
  39968. }
  39969. else {
  39970. defines.FRESNEL = false;
  39971. }
  39972. }
  39973. // Misc.
  39974. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39975. // Attribs
  39976. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39977. // Values that need to be evaluated on every frame
  39978. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39979. // Get correct effect
  39980. if (defines.isDirty) {
  39981. defines.markAsProcessed();
  39982. scene.resetCachedMaterial();
  39983. // Fallbacks
  39984. var fallbacks = new BABYLON.EffectFallbacks();
  39985. if (defines.REFLECTION) {
  39986. fallbacks.addFallback(0, "REFLECTION");
  39987. }
  39988. if (defines.SPECULAR) {
  39989. fallbacks.addFallback(0, "SPECULAR");
  39990. }
  39991. if (defines.BUMP) {
  39992. fallbacks.addFallback(0, "BUMP");
  39993. }
  39994. if (defines.PARALLAX) {
  39995. fallbacks.addFallback(1, "PARALLAX");
  39996. }
  39997. if (defines.PARALLAXOCCLUSION) {
  39998. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39999. }
  40000. if (defines.SPECULAROVERALPHA) {
  40001. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  40002. }
  40003. if (defines.FOG) {
  40004. fallbacks.addFallback(1, "FOG");
  40005. }
  40006. if (defines.POINTSIZE) {
  40007. fallbacks.addFallback(0, "POINTSIZE");
  40008. }
  40009. if (defines.LOGARITHMICDEPTH) {
  40010. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  40011. }
  40012. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  40013. if (defines.SPECULARTERM) {
  40014. fallbacks.addFallback(0, "SPECULARTERM");
  40015. }
  40016. if (defines.DIFFUSEFRESNEL) {
  40017. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  40018. }
  40019. if (defines.OPACITYFRESNEL) {
  40020. fallbacks.addFallback(2, "OPACITYFRESNEL");
  40021. }
  40022. if (defines.REFLECTIONFRESNEL) {
  40023. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  40024. }
  40025. if (defines.EMISSIVEFRESNEL) {
  40026. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  40027. }
  40028. if (defines.FRESNEL) {
  40029. fallbacks.addFallback(4, "FRESNEL");
  40030. }
  40031. //Attributes
  40032. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40033. if (defines.NORMAL) {
  40034. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40035. }
  40036. if (defines.UV1) {
  40037. attribs.push(BABYLON.VertexBuffer.UVKind);
  40038. }
  40039. if (defines.UV2) {
  40040. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40041. }
  40042. if (defines.VERTEXCOLOR) {
  40043. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40044. }
  40045. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40046. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40047. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40048. var shaderName = "default";
  40049. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  40050. "vFogInfos", "vFogColor", "pointSize",
  40051. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40052. "mBones",
  40053. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  40054. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  40055. "vReflectionPosition", "vReflectionSize",
  40056. "logarithmicDepthConstant", "vTangentSpaceParams"
  40057. ];
  40058. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40059. var uniformBuffers = ["Material", "Scene"];
  40060. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40061. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40062. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40063. uniformsNames: uniforms,
  40064. uniformBuffersNames: uniformBuffers,
  40065. samplers: samplers,
  40066. defines: defines,
  40067. maxSimultaneousLights: this._maxSimultaneousLights
  40068. });
  40069. if (this.customShaderNameResolve) {
  40070. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40071. }
  40072. var join = defines.toString();
  40073. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40074. attributes: attribs,
  40075. uniformsNames: uniforms,
  40076. uniformBuffersNames: uniformBuffers,
  40077. samplers: samplers,
  40078. defines: join,
  40079. fallbacks: fallbacks,
  40080. onCompiled: this.onCompiled,
  40081. onError: this.onError,
  40082. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40083. }, engine), defines);
  40084. this.buildUniformLayout();
  40085. }
  40086. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40087. return false;
  40088. }
  40089. defines._renderId = scene.getRenderId();
  40090. this._wasPreviouslyReady = true;
  40091. return true;
  40092. };
  40093. StandardMaterial.prototype.buildUniformLayout = function () {
  40094. // Order is important !
  40095. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40096. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40097. this._uniformBuffer.addUniform("opacityParts", 4);
  40098. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40099. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40100. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40101. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40102. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40103. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40104. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40105. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40106. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40107. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40108. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40109. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40110. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40111. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40112. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40113. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40114. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40115. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40116. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40117. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40118. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40119. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40120. this._uniformBuffer.addUniform("specularMatrix", 16);
  40121. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40122. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40123. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40124. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40125. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40126. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40127. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40128. this._uniformBuffer.addUniform("pointSize", 1);
  40129. this._uniformBuffer.create();
  40130. };
  40131. StandardMaterial.prototype.unbind = function () {
  40132. if (this._activeEffect) {
  40133. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40134. this._activeEffect.setTexture("reflection2DSampler", null);
  40135. }
  40136. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40137. this._activeEffect.setTexture("refraction2DSampler", null);
  40138. }
  40139. }
  40140. _super.prototype.unbind.call(this);
  40141. };
  40142. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40143. var scene = this.getScene();
  40144. var defines = subMesh._materialDefines;
  40145. if (!defines) {
  40146. return;
  40147. }
  40148. var effect = subMesh.effect;
  40149. if (!effect) {
  40150. return;
  40151. }
  40152. this._activeEffect = effect;
  40153. // Matrices
  40154. this.bindOnlyWorldMatrix(world);
  40155. // Normal Matrix
  40156. if (defines.OBJECTSPACE_NORMALMAP) {
  40157. world.toNormalMatrix(this._normalMatrix);
  40158. this.bindOnlyNormalMatrix(this._normalMatrix);
  40159. }
  40160. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40161. // Bones
  40162. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40163. if (mustRebind) {
  40164. this._uniformBuffer.bindToEffect(effect, "Material");
  40165. this.bindViewProjection(effect);
  40166. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40167. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40168. // Fresnel
  40169. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40170. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40171. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40172. }
  40173. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40174. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40175. }
  40176. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40177. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40178. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40179. }
  40180. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40181. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40182. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40183. }
  40184. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40185. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40186. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40187. }
  40188. }
  40189. // Textures
  40190. if (scene.texturesEnabled) {
  40191. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40192. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40193. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40194. }
  40195. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40196. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40197. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40198. }
  40199. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40200. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40201. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40202. }
  40203. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40204. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40205. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40206. if (this._reflectionTexture.boundingBoxSize) {
  40207. var cubeTexture = this._reflectionTexture;
  40208. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40209. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40210. }
  40211. }
  40212. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40213. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40214. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40215. }
  40216. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40217. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40218. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40219. }
  40220. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40221. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40222. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40223. }
  40224. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40225. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40226. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40227. if (scene._mirroredCameraPosition) {
  40228. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40229. }
  40230. else {
  40231. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40232. }
  40233. }
  40234. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40235. var depth = 1.0;
  40236. if (!this._refractionTexture.isCube) {
  40237. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40238. if (this._refractionTexture.depth) {
  40239. depth = this._refractionTexture.depth;
  40240. }
  40241. }
  40242. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40243. }
  40244. }
  40245. // Point size
  40246. if (this.pointsCloud) {
  40247. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40248. }
  40249. if (defines.SPECULARTERM) {
  40250. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40251. }
  40252. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40253. // Diffuse
  40254. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40255. }
  40256. // Textures
  40257. if (scene.texturesEnabled) {
  40258. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40259. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40260. }
  40261. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40262. effect.setTexture("ambientSampler", this._ambientTexture);
  40263. }
  40264. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40265. effect.setTexture("opacitySampler", this._opacityTexture);
  40266. }
  40267. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40268. if (this._reflectionTexture.isCube) {
  40269. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40270. }
  40271. else {
  40272. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40273. }
  40274. }
  40275. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40276. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40277. }
  40278. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40279. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40280. }
  40281. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40282. effect.setTexture("specularSampler", this._specularTexture);
  40283. }
  40284. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40285. effect.setTexture("bumpSampler", this._bumpTexture);
  40286. }
  40287. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40288. var depth = 1.0;
  40289. if (this._refractionTexture.isCube) {
  40290. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40291. }
  40292. else {
  40293. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40294. }
  40295. }
  40296. }
  40297. // Clip plane
  40298. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40299. // Colors
  40300. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40301. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40302. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40303. }
  40304. if (mustRebind || !this.isFrozen) {
  40305. // Lights
  40306. if (scene.lightsEnabled && !this._disableLighting) {
  40307. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40308. }
  40309. // View
  40310. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40311. this.bindView(effect);
  40312. }
  40313. // Fog
  40314. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40315. // Morph targets
  40316. if (defines.NUM_MORPH_INFLUENCERS) {
  40317. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40318. }
  40319. // Log. depth
  40320. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40321. // image processing
  40322. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40323. this._imageProcessingConfiguration.bind(this._activeEffect);
  40324. }
  40325. }
  40326. this._uniformBuffer.update();
  40327. this._afterBind(mesh, this._activeEffect);
  40328. };
  40329. StandardMaterial.prototype.getAnimatables = function () {
  40330. var results = [];
  40331. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40332. results.push(this._diffuseTexture);
  40333. }
  40334. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40335. results.push(this._ambientTexture);
  40336. }
  40337. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40338. results.push(this._opacityTexture);
  40339. }
  40340. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40341. results.push(this._reflectionTexture);
  40342. }
  40343. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40344. results.push(this._emissiveTexture);
  40345. }
  40346. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40347. results.push(this._specularTexture);
  40348. }
  40349. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40350. results.push(this._bumpTexture);
  40351. }
  40352. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40353. results.push(this._lightmapTexture);
  40354. }
  40355. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40356. results.push(this._refractionTexture);
  40357. }
  40358. return results;
  40359. };
  40360. StandardMaterial.prototype.getActiveTextures = function () {
  40361. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40362. if (this._diffuseTexture) {
  40363. activeTextures.push(this._diffuseTexture);
  40364. }
  40365. if (this._ambientTexture) {
  40366. activeTextures.push(this._ambientTexture);
  40367. }
  40368. if (this._opacityTexture) {
  40369. activeTextures.push(this._opacityTexture);
  40370. }
  40371. if (this._reflectionTexture) {
  40372. activeTextures.push(this._reflectionTexture);
  40373. }
  40374. if (this._emissiveTexture) {
  40375. activeTextures.push(this._emissiveTexture);
  40376. }
  40377. if (this._specularTexture) {
  40378. activeTextures.push(this._specularTexture);
  40379. }
  40380. if (this._bumpTexture) {
  40381. activeTextures.push(this._bumpTexture);
  40382. }
  40383. if (this._lightmapTexture) {
  40384. activeTextures.push(this._lightmapTexture);
  40385. }
  40386. if (this._refractionTexture) {
  40387. activeTextures.push(this._refractionTexture);
  40388. }
  40389. return activeTextures;
  40390. };
  40391. StandardMaterial.prototype.hasTexture = function (texture) {
  40392. if (_super.prototype.hasTexture.call(this, texture)) {
  40393. return true;
  40394. }
  40395. if (this._diffuseTexture === texture) {
  40396. return true;
  40397. }
  40398. if (this._ambientTexture === texture) {
  40399. return true;
  40400. }
  40401. if (this._opacityTexture === texture) {
  40402. return true;
  40403. }
  40404. if (this._reflectionTexture === texture) {
  40405. return true;
  40406. }
  40407. if (this._emissiveTexture === texture) {
  40408. return true;
  40409. }
  40410. if (this._specularTexture === texture) {
  40411. return true;
  40412. }
  40413. if (this._bumpTexture === texture) {
  40414. return true;
  40415. }
  40416. if (this._lightmapTexture === texture) {
  40417. return true;
  40418. }
  40419. if (this._refractionTexture === texture) {
  40420. return true;
  40421. }
  40422. return false;
  40423. };
  40424. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40425. if (forceDisposeTextures) {
  40426. if (this._diffuseTexture) {
  40427. this._diffuseTexture.dispose();
  40428. }
  40429. if (this._ambientTexture) {
  40430. this._ambientTexture.dispose();
  40431. }
  40432. if (this._opacityTexture) {
  40433. this._opacityTexture.dispose();
  40434. }
  40435. if (this._reflectionTexture) {
  40436. this._reflectionTexture.dispose();
  40437. }
  40438. if (this._emissiveTexture) {
  40439. this._emissiveTexture.dispose();
  40440. }
  40441. if (this._specularTexture) {
  40442. this._specularTexture.dispose();
  40443. }
  40444. if (this._bumpTexture) {
  40445. this._bumpTexture.dispose();
  40446. }
  40447. if (this._lightmapTexture) {
  40448. this._lightmapTexture.dispose();
  40449. }
  40450. if (this._refractionTexture) {
  40451. this._refractionTexture.dispose();
  40452. }
  40453. }
  40454. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40455. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40456. }
  40457. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40458. };
  40459. StandardMaterial.prototype.clone = function (name) {
  40460. var _this = this;
  40461. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40462. result.name = name;
  40463. result.id = name;
  40464. return result;
  40465. };
  40466. StandardMaterial.prototype.serialize = function () {
  40467. return BABYLON.SerializationHelper.Serialize(this);
  40468. };
  40469. // Statics
  40470. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40471. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40472. };
  40473. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40474. get: function () {
  40475. return StandardMaterial._DiffuseTextureEnabled;
  40476. },
  40477. set: function (value) {
  40478. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40479. return;
  40480. }
  40481. StandardMaterial._DiffuseTextureEnabled = value;
  40482. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40483. },
  40484. enumerable: true,
  40485. configurable: true
  40486. });
  40487. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40488. get: function () {
  40489. return StandardMaterial._AmbientTextureEnabled;
  40490. },
  40491. set: function (value) {
  40492. if (StandardMaterial._AmbientTextureEnabled === value) {
  40493. return;
  40494. }
  40495. StandardMaterial._AmbientTextureEnabled = value;
  40496. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40497. },
  40498. enumerable: true,
  40499. configurable: true
  40500. });
  40501. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40502. get: function () {
  40503. return StandardMaterial._OpacityTextureEnabled;
  40504. },
  40505. set: function (value) {
  40506. if (StandardMaterial._OpacityTextureEnabled === value) {
  40507. return;
  40508. }
  40509. StandardMaterial._OpacityTextureEnabled = value;
  40510. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40511. },
  40512. enumerable: true,
  40513. configurable: true
  40514. });
  40515. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40516. get: function () {
  40517. return StandardMaterial._ReflectionTextureEnabled;
  40518. },
  40519. set: function (value) {
  40520. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40521. return;
  40522. }
  40523. StandardMaterial._ReflectionTextureEnabled = value;
  40524. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40525. },
  40526. enumerable: true,
  40527. configurable: true
  40528. });
  40529. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40530. get: function () {
  40531. return StandardMaterial._EmissiveTextureEnabled;
  40532. },
  40533. set: function (value) {
  40534. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40535. return;
  40536. }
  40537. StandardMaterial._EmissiveTextureEnabled = value;
  40538. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40539. },
  40540. enumerable: true,
  40541. configurable: true
  40542. });
  40543. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40544. get: function () {
  40545. return StandardMaterial._SpecularTextureEnabled;
  40546. },
  40547. set: function (value) {
  40548. if (StandardMaterial._SpecularTextureEnabled === value) {
  40549. return;
  40550. }
  40551. StandardMaterial._SpecularTextureEnabled = value;
  40552. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40553. },
  40554. enumerable: true,
  40555. configurable: true
  40556. });
  40557. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40558. get: function () {
  40559. return StandardMaterial._BumpTextureEnabled;
  40560. },
  40561. set: function (value) {
  40562. if (StandardMaterial._BumpTextureEnabled === value) {
  40563. return;
  40564. }
  40565. StandardMaterial._BumpTextureEnabled = value;
  40566. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40567. },
  40568. enumerable: true,
  40569. configurable: true
  40570. });
  40571. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40572. get: function () {
  40573. return StandardMaterial._LightmapTextureEnabled;
  40574. },
  40575. set: function (value) {
  40576. if (StandardMaterial._LightmapTextureEnabled === value) {
  40577. return;
  40578. }
  40579. StandardMaterial._LightmapTextureEnabled = value;
  40580. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40581. },
  40582. enumerable: true,
  40583. configurable: true
  40584. });
  40585. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40586. get: function () {
  40587. return StandardMaterial._RefractionTextureEnabled;
  40588. },
  40589. set: function (value) {
  40590. if (StandardMaterial._RefractionTextureEnabled === value) {
  40591. return;
  40592. }
  40593. StandardMaterial._RefractionTextureEnabled = value;
  40594. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40595. },
  40596. enumerable: true,
  40597. configurable: true
  40598. });
  40599. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40600. get: function () {
  40601. return StandardMaterial._ColorGradingTextureEnabled;
  40602. },
  40603. set: function (value) {
  40604. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40605. return;
  40606. }
  40607. StandardMaterial._ColorGradingTextureEnabled = value;
  40608. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40609. },
  40610. enumerable: true,
  40611. configurable: true
  40612. });
  40613. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40614. get: function () {
  40615. return StandardMaterial._FresnelEnabled;
  40616. },
  40617. set: function (value) {
  40618. if (StandardMaterial._FresnelEnabled === value) {
  40619. return;
  40620. }
  40621. StandardMaterial._FresnelEnabled = value;
  40622. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40623. },
  40624. enumerable: true,
  40625. configurable: true
  40626. });
  40627. // Flags used to enable or disable a type of texture for all Standard Materials
  40628. StandardMaterial._DiffuseTextureEnabled = true;
  40629. StandardMaterial._AmbientTextureEnabled = true;
  40630. StandardMaterial._OpacityTextureEnabled = true;
  40631. StandardMaterial._ReflectionTextureEnabled = true;
  40632. StandardMaterial._EmissiveTextureEnabled = true;
  40633. StandardMaterial._SpecularTextureEnabled = true;
  40634. StandardMaterial._BumpTextureEnabled = true;
  40635. StandardMaterial._LightmapTextureEnabled = true;
  40636. StandardMaterial._RefractionTextureEnabled = true;
  40637. StandardMaterial._ColorGradingTextureEnabled = true;
  40638. StandardMaterial._FresnelEnabled = true;
  40639. __decorate([
  40640. BABYLON.serializeAsTexture("diffuseTexture")
  40641. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40642. __decorate([
  40643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40644. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40645. __decorate([
  40646. BABYLON.serializeAsTexture("ambientTexture")
  40647. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40648. __decorate([
  40649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40650. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40651. __decorate([
  40652. BABYLON.serializeAsTexture("opacityTexture")
  40653. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40654. __decorate([
  40655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40656. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40657. __decorate([
  40658. BABYLON.serializeAsTexture("reflectionTexture")
  40659. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40660. __decorate([
  40661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40662. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40663. __decorate([
  40664. BABYLON.serializeAsTexture("emissiveTexture")
  40665. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40666. __decorate([
  40667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40668. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40669. __decorate([
  40670. BABYLON.serializeAsTexture("specularTexture")
  40671. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40672. __decorate([
  40673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40674. ], StandardMaterial.prototype, "specularTexture", void 0);
  40675. __decorate([
  40676. BABYLON.serializeAsTexture("bumpTexture")
  40677. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40678. __decorate([
  40679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40680. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40681. __decorate([
  40682. BABYLON.serializeAsTexture("lightmapTexture")
  40683. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40684. __decorate([
  40685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40686. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40687. __decorate([
  40688. BABYLON.serializeAsTexture("refractionTexture")
  40689. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40690. __decorate([
  40691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40692. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40693. __decorate([
  40694. BABYLON.serializeAsColor3("ambient")
  40695. ], StandardMaterial.prototype, "ambientColor", void 0);
  40696. __decorate([
  40697. BABYLON.serializeAsColor3("diffuse")
  40698. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40699. __decorate([
  40700. BABYLON.serializeAsColor3("specular")
  40701. ], StandardMaterial.prototype, "specularColor", void 0);
  40702. __decorate([
  40703. BABYLON.serializeAsColor3("emissive")
  40704. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40705. __decorate([
  40706. BABYLON.serialize()
  40707. ], StandardMaterial.prototype, "specularPower", void 0);
  40708. __decorate([
  40709. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40710. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40711. __decorate([
  40712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40713. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40714. __decorate([
  40715. BABYLON.serialize("useEmissiveAsIllumination")
  40716. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40717. __decorate([
  40718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40719. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40720. __decorate([
  40721. BABYLON.serialize("linkEmissiveWithDiffuse")
  40722. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40723. __decorate([
  40724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40725. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40726. __decorate([
  40727. BABYLON.serialize("useSpecularOverAlpha")
  40728. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40729. __decorate([
  40730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40731. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40732. __decorate([
  40733. BABYLON.serialize("useReflectionOverAlpha")
  40734. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40735. __decorate([
  40736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40737. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40738. __decorate([
  40739. BABYLON.serialize("disableLighting")
  40740. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40741. __decorate([
  40742. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40743. ], StandardMaterial.prototype, "disableLighting", void 0);
  40744. __decorate([
  40745. BABYLON.serialize("useObjectSpaceNormalMap")
  40746. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40747. __decorate([
  40748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40749. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40750. __decorate([
  40751. BABYLON.serialize("useParallax")
  40752. ], StandardMaterial.prototype, "_useParallax", void 0);
  40753. __decorate([
  40754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40755. ], StandardMaterial.prototype, "useParallax", void 0);
  40756. __decorate([
  40757. BABYLON.serialize("useParallaxOcclusion")
  40758. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40759. __decorate([
  40760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40761. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40762. __decorate([
  40763. BABYLON.serialize()
  40764. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40765. __decorate([
  40766. BABYLON.serialize("roughness")
  40767. ], StandardMaterial.prototype, "_roughness", void 0);
  40768. __decorate([
  40769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40770. ], StandardMaterial.prototype, "roughness", void 0);
  40771. __decorate([
  40772. BABYLON.serialize()
  40773. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40774. __decorate([
  40775. BABYLON.serialize()
  40776. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40777. __decorate([
  40778. BABYLON.serialize("useLightmapAsShadowmap")
  40779. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40780. __decorate([
  40781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40782. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40783. __decorate([
  40784. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40785. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40786. __decorate([
  40787. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40788. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40789. __decorate([
  40790. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40791. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40792. __decorate([
  40793. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40794. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40795. __decorate([
  40796. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40797. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40798. __decorate([
  40799. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40800. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40801. __decorate([
  40802. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40803. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40804. __decorate([
  40805. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40806. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40807. __decorate([
  40808. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40809. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40810. __decorate([
  40811. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40812. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40813. __decorate([
  40814. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40815. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40816. __decorate([
  40817. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40818. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40819. __decorate([
  40820. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40821. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40822. __decorate([
  40823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40824. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40825. __decorate([
  40826. BABYLON.serialize("maxSimultaneousLights")
  40827. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40828. __decorate([
  40829. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40830. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40831. __decorate([
  40832. BABYLON.serialize("invertNormalMapX")
  40833. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40834. __decorate([
  40835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40836. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40837. __decorate([
  40838. BABYLON.serialize("invertNormalMapY")
  40839. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40840. __decorate([
  40841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40842. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40843. __decorate([
  40844. BABYLON.serialize("twoSidedLighting")
  40845. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40846. __decorate([
  40847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40848. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40849. __decorate([
  40850. BABYLON.serialize()
  40851. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40852. return StandardMaterial;
  40853. }(BABYLON.PushMaterial));
  40854. BABYLON.StandardMaterial = StandardMaterial;
  40855. })(BABYLON || (BABYLON = {}));
  40856. //# sourceMappingURL=babylon.standardMaterial.js.map
  40857. "use strict";
  40858. var BABYLON;
  40859. (function (BABYLON) {
  40860. /**
  40861. * Manages the defines for the PBR Material.
  40862. */
  40863. var PBRMaterialDefines = /** @class */ (function (_super) {
  40864. __extends(PBRMaterialDefines, _super);
  40865. /**
  40866. * Initializes the PBR Material defines.
  40867. */
  40868. function PBRMaterialDefines() {
  40869. var _this = _super.call(this) || this;
  40870. _this.PBR = true;
  40871. _this.MAINUV1 = false;
  40872. _this.MAINUV2 = false;
  40873. _this.UV1 = false;
  40874. _this.UV2 = false;
  40875. _this.ALBEDO = false;
  40876. _this.ALBEDODIRECTUV = 0;
  40877. _this.VERTEXCOLOR = false;
  40878. _this.AMBIENT = false;
  40879. _this.AMBIENTDIRECTUV = 0;
  40880. _this.AMBIENTINGRAYSCALE = false;
  40881. _this.OPACITY = false;
  40882. _this.VERTEXALPHA = false;
  40883. _this.OPACITYDIRECTUV = 0;
  40884. _this.OPACITYRGB = false;
  40885. _this.ALPHATEST = false;
  40886. _this.DEPTHPREPASS = false;
  40887. _this.ALPHABLEND = false;
  40888. _this.ALPHAFROMALBEDO = false;
  40889. _this.ALPHATESTVALUE = "0.5";
  40890. _this.SPECULAROVERALPHA = false;
  40891. _this.RADIANCEOVERALPHA = false;
  40892. _this.ALPHAFRESNEL = false;
  40893. _this.LINEARALPHAFRESNEL = false;
  40894. _this.PREMULTIPLYALPHA = false;
  40895. _this.EMISSIVE = false;
  40896. _this.EMISSIVEDIRECTUV = 0;
  40897. _this.REFLECTIVITY = false;
  40898. _this.REFLECTIVITYDIRECTUV = 0;
  40899. _this.SPECULARTERM = false;
  40900. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40901. _this.MICROSURFACEAUTOMATIC = false;
  40902. _this.LODBASEDMICROSFURACE = false;
  40903. _this.MICROSURFACEMAP = false;
  40904. _this.MICROSURFACEMAPDIRECTUV = 0;
  40905. _this.METALLICWORKFLOW = false;
  40906. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40907. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40908. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40909. _this.AOSTOREINMETALMAPRED = false;
  40910. _this.ENVIRONMENTBRDF = false;
  40911. _this.NORMAL = false;
  40912. _this.TANGENT = false;
  40913. _this.BUMP = false;
  40914. _this.BUMPDIRECTUV = 0;
  40915. _this.OBJECTSPACE_NORMALMAP = false;
  40916. _this.PARALLAX = false;
  40917. _this.PARALLAXOCCLUSION = false;
  40918. _this.NORMALXYSCALE = true;
  40919. _this.LIGHTMAP = false;
  40920. _this.LIGHTMAPDIRECTUV = 0;
  40921. _this.USELIGHTMAPASSHADOWMAP = false;
  40922. _this.GAMMALIGHTMAP = false;
  40923. _this.REFLECTION = false;
  40924. _this.REFLECTIONMAP_3D = false;
  40925. _this.REFLECTIONMAP_SPHERICAL = false;
  40926. _this.REFLECTIONMAP_PLANAR = false;
  40927. _this.REFLECTIONMAP_CUBIC = false;
  40928. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40929. _this.REFLECTIONMAP_PROJECTION = false;
  40930. _this.REFLECTIONMAP_SKYBOX = false;
  40931. _this.REFLECTIONMAP_EXPLICIT = false;
  40932. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40933. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40934. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40935. _this.INVERTCUBICMAP = false;
  40936. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40937. _this.USESPHERICALINVERTEX = false;
  40938. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40939. _this.LODINREFLECTIONALPHA = false;
  40940. _this.GAMMAREFLECTION = false;
  40941. _this.RADIANCEOCCLUSION = false;
  40942. _this.HORIZONOCCLUSION = false;
  40943. _this.REFRACTION = false;
  40944. _this.REFRACTIONMAP_3D = false;
  40945. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40946. _this.LODINREFRACTIONALPHA = false;
  40947. _this.GAMMAREFRACTION = false;
  40948. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40949. _this.INSTANCES = false;
  40950. _this.NUM_BONE_INFLUENCERS = 0;
  40951. _this.BonesPerMesh = 0;
  40952. _this.NONUNIFORMSCALING = false;
  40953. _this.MORPHTARGETS = false;
  40954. _this.MORPHTARGETS_NORMAL = false;
  40955. _this.MORPHTARGETS_TANGENT = false;
  40956. _this.NUM_MORPH_INFLUENCERS = 0;
  40957. _this.IMAGEPROCESSING = false;
  40958. _this.VIGNETTE = false;
  40959. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40960. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40961. _this.TONEMAPPING = false;
  40962. _this.CONTRAST = false;
  40963. _this.COLORCURVES = false;
  40964. _this.COLORGRADING = false;
  40965. _this.COLORGRADING3D = false;
  40966. _this.SAMPLER3DGREENDEPTH = false;
  40967. _this.SAMPLER3DBGRMAP = false;
  40968. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40969. _this.EXPOSURE = false;
  40970. _this.GRAIN = false;
  40971. _this.USEPHYSICALLIGHTFALLOFF = false;
  40972. _this.TWOSIDEDLIGHTING = false;
  40973. _this.SHADOWFLOAT = false;
  40974. _this.CLIPPLANE = false;
  40975. _this.POINTSIZE = false;
  40976. _this.FOG = false;
  40977. _this.LOGARITHMICDEPTH = false;
  40978. _this.FORCENORMALFORWARD = false;
  40979. _this.UNLIT = false;
  40980. _this.rebuild();
  40981. return _this;
  40982. }
  40983. /**
  40984. * Resets the PBR Material defines.
  40985. */
  40986. PBRMaterialDefines.prototype.reset = function () {
  40987. _super.prototype.reset.call(this);
  40988. this.ALPHATESTVALUE = "0.5";
  40989. this.PBR = true;
  40990. };
  40991. return PBRMaterialDefines;
  40992. }(BABYLON.MaterialDefines));
  40993. /**
  40994. * The Physically based material base class of BJS.
  40995. *
  40996. * This offers the main features of a standard PBR material.
  40997. * For more information, please refer to the documentation :
  40998. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40999. */
  41000. var PBRBaseMaterial = /** @class */ (function (_super) {
  41001. __extends(PBRBaseMaterial, _super);
  41002. /**
  41003. * Instantiates a new PBRMaterial instance.
  41004. *
  41005. * @param name The material name
  41006. * @param scene The scene the material will be use in.
  41007. */
  41008. function PBRBaseMaterial(name, scene) {
  41009. var _this = _super.call(this, name, scene) || this;
  41010. /**
  41011. * Intensity of the direct lights e.g. the four lights available in your scene.
  41012. * This impacts both the direct diffuse and specular highlights.
  41013. */
  41014. _this._directIntensity = 1.0;
  41015. /**
  41016. * Intensity of the emissive part of the material.
  41017. * This helps controlling the emissive effect without modifying the emissive color.
  41018. */
  41019. _this._emissiveIntensity = 1.0;
  41020. /**
  41021. * Intensity of the environment e.g. how much the environment will light the object
  41022. * either through harmonics for rough material or through the refelction for shiny ones.
  41023. */
  41024. _this._environmentIntensity = 1.0;
  41025. /**
  41026. * This is a special control allowing the reduction of the specular highlights coming from the
  41027. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41028. */
  41029. _this._specularIntensity = 1.0;
  41030. /**
  41031. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  41032. */
  41033. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  41034. /**
  41035. * Debug Control allowing disabling the bump map on this material.
  41036. */
  41037. _this._disableBumpMap = false;
  41038. /**
  41039. * AKA Occlusion Texture Intensity in other nomenclature.
  41040. */
  41041. _this._ambientTextureStrength = 1.0;
  41042. /**
  41043. * The color of a material in ambient lighting.
  41044. */
  41045. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  41046. /**
  41047. * AKA Diffuse Color in other nomenclature.
  41048. */
  41049. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  41050. /**
  41051. * AKA Specular Color in other nomenclature.
  41052. */
  41053. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41054. /**
  41055. * The color applied when light is reflected from a material.
  41056. */
  41057. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  41058. /**
  41059. * The color applied when light is emitted from a material.
  41060. */
  41061. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  41062. /**
  41063. * AKA Glossiness in other nomenclature.
  41064. */
  41065. _this._microSurface = 0.9;
  41066. /**
  41067. * source material index of refraction (IOR)' / 'destination material IOR.
  41068. */
  41069. _this._indexOfRefraction = 0.66;
  41070. /**
  41071. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41072. */
  41073. _this._invertRefractionY = false;
  41074. /**
  41075. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41076. * Materials half opaque for instance using refraction could benefit from this control.
  41077. */
  41078. _this._linkRefractionWithTransparency = false;
  41079. /**
  41080. * Specifies that the material will use the light map as a show map.
  41081. */
  41082. _this._useLightmapAsShadowmap = false;
  41083. /**
  41084. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41085. * makes the reflect vector face the model (under horizon).
  41086. */
  41087. _this._useHorizonOcclusion = true;
  41088. /**
  41089. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41090. * too much the area relying on ambient texture to define their ambient occlusion.
  41091. */
  41092. _this._useRadianceOcclusion = true;
  41093. /**
  41094. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41095. */
  41096. _this._useAlphaFromAlbedoTexture = false;
  41097. /**
  41098. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41099. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41100. */
  41101. _this._useSpecularOverAlpha = true;
  41102. /**
  41103. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41104. */
  41105. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41106. /**
  41107. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41108. */
  41109. _this._useRoughnessFromMetallicTextureAlpha = true;
  41110. /**
  41111. * Specifies if the metallic texture contains the roughness information in its green channel.
  41112. */
  41113. _this._useRoughnessFromMetallicTextureGreen = false;
  41114. /**
  41115. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41116. */
  41117. _this._useMetallnessFromMetallicTextureBlue = false;
  41118. /**
  41119. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41120. */
  41121. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41122. /**
  41123. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41124. */
  41125. _this._useAmbientInGrayScale = false;
  41126. /**
  41127. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41128. * The material will try to infer what glossiness each pixel should be.
  41129. */
  41130. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41131. /**
  41132. * BJS is using an harcoded light falloff based on a manually sets up range.
  41133. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41134. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41135. */
  41136. _this._usePhysicalLightFalloff = true;
  41137. /**
  41138. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41139. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41140. */
  41141. _this._useRadianceOverAlpha = true;
  41142. /**
  41143. * Allows using an object space normal map (instead of tangent space).
  41144. */
  41145. _this._useObjectSpaceNormalMap = false;
  41146. /**
  41147. * Allows using the bump map in parallax mode.
  41148. */
  41149. _this._useParallax = false;
  41150. /**
  41151. * Allows using the bump map in parallax occlusion mode.
  41152. */
  41153. _this._useParallaxOcclusion = false;
  41154. /**
  41155. * Controls the scale bias of the parallax mode.
  41156. */
  41157. _this._parallaxScaleBias = 0.05;
  41158. /**
  41159. * If sets to true, disables all the lights affecting the material.
  41160. */
  41161. _this._disableLighting = false;
  41162. /**
  41163. * Number of Simultaneous lights allowed on the material.
  41164. */
  41165. _this._maxSimultaneousLights = 4;
  41166. /**
  41167. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41168. */
  41169. _this._invertNormalMapX = false;
  41170. /**
  41171. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41172. */
  41173. _this._invertNormalMapY = false;
  41174. /**
  41175. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41176. */
  41177. _this._twoSidedLighting = false;
  41178. /**
  41179. * Defines the alpha limits in alpha test mode.
  41180. */
  41181. _this._alphaCutOff = 0.4;
  41182. /**
  41183. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41184. */
  41185. _this._forceAlphaTest = false;
  41186. /**
  41187. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41188. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41189. */
  41190. _this._useAlphaFresnel = false;
  41191. /**
  41192. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41193. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41194. */
  41195. _this._useLinearAlphaFresnel = false;
  41196. /**
  41197. * The transparency mode of the material.
  41198. */
  41199. _this._transparencyMode = null;
  41200. /**
  41201. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41202. * from cos thetav and roughness:
  41203. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41204. */
  41205. _this._environmentBRDFTexture = null;
  41206. /**
  41207. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41208. */
  41209. _this._forceIrradianceInFragment = false;
  41210. /**
  41211. * Force normal to face away from face.
  41212. */
  41213. _this._forceNormalForward = false;
  41214. /**
  41215. * Stores the available render targets.
  41216. */
  41217. _this._renderTargets = new BABYLON.SmartArray(16);
  41218. /**
  41219. * Sets the global ambient color for the material used in lighting calculations.
  41220. */
  41221. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41222. /**
  41223. * If set to true, no lighting calculations will be applied.
  41224. */
  41225. _this._unlit = false;
  41226. // Setup the default processing configuration to the scene.
  41227. _this._attachImageProcessingConfiguration(null);
  41228. _this.getRenderTargetTextures = function () {
  41229. _this._renderTargets.reset();
  41230. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41231. _this._renderTargets.push(_this._reflectionTexture);
  41232. }
  41233. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41234. _this._renderTargets.push(_this._refractionTexture);
  41235. }
  41236. return _this._renderTargets;
  41237. };
  41238. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41239. return _this;
  41240. }
  41241. /**
  41242. * Attaches a new image processing configuration to the PBR Material.
  41243. * @param configuration
  41244. */
  41245. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41246. var _this = this;
  41247. if (configuration === this._imageProcessingConfiguration) {
  41248. return;
  41249. }
  41250. // Detaches observer.
  41251. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41252. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41253. }
  41254. // Pick the scene configuration if needed.
  41255. if (!configuration) {
  41256. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41257. }
  41258. else {
  41259. this._imageProcessingConfiguration = configuration;
  41260. }
  41261. // Attaches observer.
  41262. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41263. _this._markAllSubMeshesAsImageProcessingDirty();
  41264. });
  41265. };
  41266. /**
  41267. * Gets the name of the material class.
  41268. */
  41269. PBRBaseMaterial.prototype.getClassName = function () {
  41270. return "PBRBaseMaterial";
  41271. };
  41272. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41273. /**
  41274. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41275. */
  41276. get: function () {
  41277. return this._useLogarithmicDepth;
  41278. },
  41279. /**
  41280. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41281. */
  41282. set: function (value) {
  41283. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41284. },
  41285. enumerable: true,
  41286. configurable: true
  41287. });
  41288. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41289. /**
  41290. * Gets the current transparency mode.
  41291. */
  41292. get: function () {
  41293. return this._transparencyMode;
  41294. },
  41295. /**
  41296. * Sets the transparency mode of the material.
  41297. */
  41298. set: function (value) {
  41299. if (this._transparencyMode === value) {
  41300. return;
  41301. }
  41302. this._transparencyMode = value;
  41303. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41304. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41305. },
  41306. enumerable: true,
  41307. configurable: true
  41308. });
  41309. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41310. /**
  41311. * Returns true if alpha blending should be disabled.
  41312. */
  41313. get: function () {
  41314. return (this._linkRefractionWithTransparency ||
  41315. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41316. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41317. },
  41318. enumerable: true,
  41319. configurable: true
  41320. });
  41321. /**
  41322. * Specifies whether or not this material should be rendered in alpha blend mode.
  41323. */
  41324. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41325. if (this._disableAlphaBlending) {
  41326. return false;
  41327. }
  41328. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41329. };
  41330. /**
  41331. * Specifies if the mesh will require alpha blending.
  41332. * @param mesh - BJS mesh.
  41333. */
  41334. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41335. if (this._disableAlphaBlending) {
  41336. return false;
  41337. }
  41338. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41339. };
  41340. /**
  41341. * Specifies whether or not this material should be rendered in alpha test mode.
  41342. */
  41343. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41344. if (this._forceAlphaTest) {
  41345. return true;
  41346. }
  41347. if (this._linkRefractionWithTransparency) {
  41348. return false;
  41349. }
  41350. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41351. };
  41352. /**
  41353. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41354. */
  41355. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41356. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41357. };
  41358. /**
  41359. * Gets the texture used for the alpha test.
  41360. */
  41361. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41362. return this._albedoTexture;
  41363. };
  41364. /**
  41365. * Specifies that the submesh is ready to be used.
  41366. * @param mesh - BJS mesh.
  41367. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41368. * @param useInstances - Specifies that instances should be used.
  41369. * @returns - boolean indicating that the submesh is ready or not.
  41370. */
  41371. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41372. if (subMesh.effect && this.isFrozen) {
  41373. if (this._wasPreviouslyReady) {
  41374. return true;
  41375. }
  41376. }
  41377. if (!subMesh._materialDefines) {
  41378. subMesh._materialDefines = new PBRMaterialDefines();
  41379. }
  41380. var defines = subMesh._materialDefines;
  41381. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41382. if (defines._renderId === this.getScene().getRenderId()) {
  41383. return true;
  41384. }
  41385. }
  41386. var scene = this.getScene();
  41387. var engine = scene.getEngine();
  41388. if (defines._areTexturesDirty) {
  41389. if (scene.texturesEnabled) {
  41390. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41391. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41392. return false;
  41393. }
  41394. }
  41395. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41396. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41397. return false;
  41398. }
  41399. }
  41400. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41401. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41402. return false;
  41403. }
  41404. }
  41405. var reflectionTexture = this._getReflectionTexture();
  41406. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41407. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41408. return false;
  41409. }
  41410. }
  41411. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41412. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41413. return false;
  41414. }
  41415. }
  41416. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41417. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41418. return false;
  41419. }
  41420. }
  41421. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41422. if (this._metallicTexture) {
  41423. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41424. return false;
  41425. }
  41426. }
  41427. else if (this._reflectivityTexture) {
  41428. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41429. return false;
  41430. }
  41431. }
  41432. if (this._microSurfaceTexture) {
  41433. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41434. return false;
  41435. }
  41436. }
  41437. }
  41438. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41439. // Bump texture cannot be not blocking.
  41440. if (!this._bumpTexture.isReady()) {
  41441. return false;
  41442. }
  41443. }
  41444. var refractionTexture = this._getRefractionTexture();
  41445. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41446. if (!refractionTexture.isReadyOrNotBlocking()) {
  41447. return false;
  41448. }
  41449. }
  41450. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41451. // This is blocking.
  41452. if (!this._environmentBRDFTexture.isReady()) {
  41453. return false;
  41454. }
  41455. }
  41456. }
  41457. }
  41458. if (defines._areImageProcessingDirty) {
  41459. if (!this._imageProcessingConfiguration.isReady()) {
  41460. return false;
  41461. }
  41462. }
  41463. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41464. mesh.createNormals(true);
  41465. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  41466. }
  41467. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41468. if (effect) {
  41469. scene.resetCachedMaterial();
  41470. subMesh.setEffect(effect, defines);
  41471. this.buildUniformLayout();
  41472. }
  41473. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41474. return false;
  41475. }
  41476. defines._renderId = scene.getRenderId();
  41477. this._wasPreviouslyReady = true;
  41478. return true;
  41479. };
  41480. /**
  41481. * Specifies if the material uses metallic roughness workflow.
  41482. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41483. */
  41484. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41485. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41486. return true;
  41487. }
  41488. return false;
  41489. };
  41490. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41491. if (onCompiled === void 0) { onCompiled = null; }
  41492. if (onError === void 0) { onError = null; }
  41493. if (useInstances === void 0) { useInstances = null; }
  41494. if (useClipPlane === void 0) { useClipPlane = null; }
  41495. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41496. if (!defines.isDirty) {
  41497. return null;
  41498. }
  41499. defines.markAsProcessed();
  41500. var scene = this.getScene();
  41501. var engine = scene.getEngine();
  41502. // Fallbacks
  41503. var fallbacks = new BABYLON.EffectFallbacks();
  41504. var fallbackRank = 0;
  41505. if (defines.USESPHERICALINVERTEX) {
  41506. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41507. }
  41508. if (defines.FOG) {
  41509. fallbacks.addFallback(fallbackRank, "FOG");
  41510. }
  41511. if (defines.POINTSIZE) {
  41512. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41513. }
  41514. if (defines.LOGARITHMICDEPTH) {
  41515. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41516. }
  41517. if (defines.PARALLAX) {
  41518. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41519. }
  41520. if (defines.PARALLAXOCCLUSION) {
  41521. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41522. }
  41523. if (defines.ENVIRONMENTBRDF) {
  41524. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41525. }
  41526. if (defines.TANGENT) {
  41527. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41528. }
  41529. if (defines.BUMP) {
  41530. fallbacks.addFallback(fallbackRank++, "BUMP");
  41531. }
  41532. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41533. if (defines.SPECULARTERM) {
  41534. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41535. }
  41536. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41537. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41538. }
  41539. if (defines.LIGHTMAP) {
  41540. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41541. }
  41542. if (defines.NORMAL) {
  41543. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41544. }
  41545. if (defines.AMBIENT) {
  41546. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41547. }
  41548. if (defines.EMISSIVE) {
  41549. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41550. }
  41551. if (defines.VERTEXCOLOR) {
  41552. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41553. }
  41554. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41555. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41556. }
  41557. if (defines.MORPHTARGETS) {
  41558. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41559. }
  41560. //Attributes
  41561. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41562. if (defines.NORMAL) {
  41563. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41564. }
  41565. if (defines.TANGENT) {
  41566. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41567. }
  41568. if (defines.UV1) {
  41569. attribs.push(BABYLON.VertexBuffer.UVKind);
  41570. }
  41571. if (defines.UV2) {
  41572. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41573. }
  41574. if (defines.VERTEXCOLOR) {
  41575. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41576. }
  41577. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41578. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41579. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41580. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41581. "vFogInfos", "vFogColor", "pointSize",
  41582. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41583. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41584. "mBones",
  41585. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41586. "vLightingIntensity",
  41587. "logarithmicDepthConstant",
  41588. "vSphericalX", "vSphericalY", "vSphericalZ",
  41589. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41590. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41591. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41592. "vTangentSpaceParams"
  41593. ];
  41594. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41595. "bumpSampler", "lightmapSampler", "opacitySampler",
  41596. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41597. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41598. "microSurfaceSampler", "environmentBrdfSampler"];
  41599. var uniformBuffers = ["Material", "Scene"];
  41600. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41601. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41602. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41603. uniformsNames: uniforms,
  41604. uniformBuffersNames: uniformBuffers,
  41605. samplers: samplers,
  41606. defines: defines,
  41607. maxSimultaneousLights: this._maxSimultaneousLights
  41608. });
  41609. var join = defines.toString();
  41610. return engine.createEffect("pbr", {
  41611. attributes: attribs,
  41612. uniformsNames: uniforms,
  41613. uniformBuffersNames: uniformBuffers,
  41614. samplers: samplers,
  41615. defines: join,
  41616. fallbacks: fallbacks,
  41617. onCompiled: onCompiled,
  41618. onError: onError,
  41619. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41620. }, engine);
  41621. };
  41622. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41623. if (useInstances === void 0) { useInstances = null; }
  41624. if (useClipPlane === void 0) { useClipPlane = null; }
  41625. var scene = this.getScene();
  41626. var engine = scene.getEngine();
  41627. // Lights
  41628. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41629. defines._needNormals = true;
  41630. // Textures
  41631. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41632. if (defines._areTexturesDirty) {
  41633. defines._needUVs = false;
  41634. if (scene.texturesEnabled) {
  41635. if (scene.getEngine().getCaps().textureLOD) {
  41636. defines.LODBASEDMICROSFURACE = true;
  41637. }
  41638. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41639. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41640. }
  41641. else {
  41642. defines.ALBEDO = false;
  41643. }
  41644. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41645. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41646. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41647. }
  41648. else {
  41649. defines.AMBIENT = false;
  41650. }
  41651. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41652. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41653. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41654. }
  41655. else {
  41656. defines.OPACITY = false;
  41657. }
  41658. var reflectionTexture = this._getReflectionTexture();
  41659. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41660. defines.REFLECTION = true;
  41661. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41662. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41663. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41664. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41665. defines.INVERTCUBICMAP = true;
  41666. }
  41667. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41668. switch (reflectionTexture.coordinatesMode) {
  41669. case BABYLON.Texture.CUBIC_MODE:
  41670. case BABYLON.Texture.INVCUBIC_MODE:
  41671. defines.REFLECTIONMAP_CUBIC = true;
  41672. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41673. break;
  41674. case BABYLON.Texture.EXPLICIT_MODE:
  41675. defines.REFLECTIONMAP_EXPLICIT = true;
  41676. break;
  41677. case BABYLON.Texture.PLANAR_MODE:
  41678. defines.REFLECTIONMAP_PLANAR = true;
  41679. break;
  41680. case BABYLON.Texture.PROJECTION_MODE:
  41681. defines.REFLECTIONMAP_PROJECTION = true;
  41682. break;
  41683. case BABYLON.Texture.SKYBOX_MODE:
  41684. defines.REFLECTIONMAP_SKYBOX = true;
  41685. break;
  41686. case BABYLON.Texture.SPHERICAL_MODE:
  41687. defines.REFLECTIONMAP_SPHERICAL = true;
  41688. break;
  41689. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41690. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41691. break;
  41692. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41693. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41694. break;
  41695. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41696. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41697. break;
  41698. }
  41699. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41700. if (reflectionTexture.sphericalPolynomial) {
  41701. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41702. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41703. defines.USESPHERICALINVERTEX = false;
  41704. }
  41705. else {
  41706. defines.USESPHERICALINVERTEX = true;
  41707. }
  41708. }
  41709. }
  41710. }
  41711. else {
  41712. defines.REFLECTION = false;
  41713. defines.REFLECTIONMAP_3D = false;
  41714. defines.REFLECTIONMAP_SPHERICAL = false;
  41715. defines.REFLECTIONMAP_PLANAR = false;
  41716. defines.REFLECTIONMAP_CUBIC = false;
  41717. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41718. defines.REFLECTIONMAP_PROJECTION = false;
  41719. defines.REFLECTIONMAP_SKYBOX = false;
  41720. defines.REFLECTIONMAP_EXPLICIT = false;
  41721. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41722. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41723. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41724. defines.INVERTCUBICMAP = false;
  41725. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41726. defines.USESPHERICALINVERTEX = false;
  41727. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41728. defines.LODINREFLECTIONALPHA = false;
  41729. defines.GAMMAREFLECTION = false;
  41730. }
  41731. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41732. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41733. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41734. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41735. }
  41736. else {
  41737. defines.LIGHTMAP = false;
  41738. }
  41739. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41740. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41741. }
  41742. else {
  41743. defines.EMISSIVE = false;
  41744. }
  41745. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41746. if (this._metallicTexture) {
  41747. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41748. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41749. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41750. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41751. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41752. }
  41753. else if (this._reflectivityTexture) {
  41754. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41755. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41756. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41757. }
  41758. else {
  41759. defines.REFLECTIVITY = false;
  41760. }
  41761. if (this._microSurfaceTexture) {
  41762. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41763. }
  41764. else {
  41765. defines.MICROSURFACEMAP = false;
  41766. }
  41767. }
  41768. else {
  41769. defines.REFLECTIVITY = false;
  41770. defines.MICROSURFACEMAP = false;
  41771. }
  41772. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41773. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41774. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41775. defines.PARALLAX = true;
  41776. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41777. }
  41778. else {
  41779. defines.PARALLAX = false;
  41780. }
  41781. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41782. }
  41783. else {
  41784. defines.BUMP = false;
  41785. }
  41786. var refractionTexture = this._getRefractionTexture();
  41787. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41788. defines.REFRACTION = true;
  41789. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41790. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41791. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41792. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41793. if (this._linkRefractionWithTransparency) {
  41794. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41795. }
  41796. }
  41797. else {
  41798. defines.REFRACTION = false;
  41799. }
  41800. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41801. defines.ENVIRONMENTBRDF = true;
  41802. }
  41803. else {
  41804. defines.ENVIRONMENTBRDF = false;
  41805. }
  41806. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41807. defines.ALPHAFROMALBEDO = true;
  41808. }
  41809. else {
  41810. defines.ALPHAFROMALBEDO = false;
  41811. }
  41812. }
  41813. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41814. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41815. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41816. if (!this.backFaceCulling && this._twoSidedLighting) {
  41817. defines.TWOSIDEDLIGHTING = true;
  41818. }
  41819. else {
  41820. defines.TWOSIDEDLIGHTING = false;
  41821. }
  41822. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  41823. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41824. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41825. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41826. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41827. }
  41828. if (defines._areImageProcessingDirty) {
  41829. this._imageProcessingConfiguration.prepareDefines(defines);
  41830. }
  41831. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41832. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41833. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41834. // Misc.
  41835. if (defines._areMiscDirty) {
  41836. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41837. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41838. }
  41839. // Values that need to be evaluated on every frame
  41840. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41841. // Attribs
  41842. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41843. };
  41844. /**
  41845. * Force shader compilation
  41846. */
  41847. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41848. var _this = this;
  41849. var localOptions = __assign({ clipPlane: false }, options);
  41850. var defines = new PBRMaterialDefines();
  41851. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41852. if (effect.isReady()) {
  41853. if (onCompiled) {
  41854. onCompiled(this);
  41855. }
  41856. }
  41857. else {
  41858. effect.onCompileObservable.add(function () {
  41859. if (onCompiled) {
  41860. onCompiled(_this);
  41861. }
  41862. });
  41863. }
  41864. };
  41865. /**
  41866. * Initializes the uniform buffer layout for the shader.
  41867. */
  41868. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41869. // Order is important !
  41870. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41871. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41872. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41873. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41874. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41875. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41876. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41877. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41878. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41879. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41880. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41881. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41882. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41883. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41884. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41885. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41886. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41887. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41888. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41889. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41890. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41891. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41892. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41893. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41894. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41895. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41896. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41897. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41898. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41899. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41900. this._uniformBuffer.addUniform("pointSize", 1);
  41901. this._uniformBuffer.create();
  41902. };
  41903. /**
  41904. * Unbinds the textures.
  41905. */
  41906. PBRBaseMaterial.prototype.unbind = function () {
  41907. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41908. this._uniformBuffer.setTexture("reflectionSampler", null);
  41909. }
  41910. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41911. this._uniformBuffer.setTexture("refractionSampler", null);
  41912. }
  41913. _super.prototype.unbind.call(this);
  41914. };
  41915. /**
  41916. * Binds the submesh data.
  41917. * @param world - The world matrix.
  41918. * @param mesh - The BJS mesh.
  41919. * @param subMesh - A submesh of the BJS mesh.
  41920. */
  41921. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41922. var scene = this.getScene();
  41923. var defines = subMesh._materialDefines;
  41924. if (!defines) {
  41925. return;
  41926. }
  41927. var effect = subMesh.effect;
  41928. if (!effect) {
  41929. return;
  41930. }
  41931. this._activeEffect = effect;
  41932. // Matrices
  41933. this.bindOnlyWorldMatrix(world);
  41934. // Normal Matrix
  41935. if (defines.OBJECTSPACE_NORMALMAP) {
  41936. world.toNormalMatrix(this._normalMatrix);
  41937. this.bindOnlyNormalMatrix(this._normalMatrix);
  41938. }
  41939. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41940. // Bones
  41941. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41942. var reflectionTexture = null;
  41943. if (mustRebind) {
  41944. this._uniformBuffer.bindToEffect(effect, "Material");
  41945. this.bindViewProjection(effect);
  41946. reflectionTexture = this._getReflectionTexture();
  41947. var refractionTexture = this._getRefractionTexture();
  41948. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41949. // Texture uniforms
  41950. if (scene.texturesEnabled) {
  41951. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41952. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41953. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41954. }
  41955. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41956. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41957. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41958. }
  41959. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41960. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41961. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41962. }
  41963. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41964. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41965. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41966. if (reflectionTexture.boundingBoxSize) {
  41967. var cubeTexture = reflectionTexture;
  41968. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41969. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41970. }
  41971. var polynomials = reflectionTexture.sphericalPolynomial;
  41972. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41973. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41974. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41975. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41976. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41977. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41978. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41979. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41980. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41981. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41982. }
  41983. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41984. }
  41985. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41986. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41987. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41988. }
  41989. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41990. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41991. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41992. }
  41993. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41994. if (this._metallicTexture) {
  41995. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41996. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41997. }
  41998. else if (this._reflectivityTexture) {
  41999. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  42000. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  42001. }
  42002. if (this._microSurfaceTexture) {
  42003. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  42004. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  42005. }
  42006. }
  42007. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42008. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  42009. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42010. if (scene._mirroredCameraPosition) {
  42011. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42012. }
  42013. else {
  42014. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42015. }
  42016. }
  42017. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42018. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  42019. var depth = 1.0;
  42020. if (!refractionTexture.isCube) {
  42021. if (refractionTexture.depth) {
  42022. depth = refractionTexture.depth;
  42023. }
  42024. }
  42025. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  42026. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  42027. }
  42028. }
  42029. // Point size
  42030. if (this.pointsCloud) {
  42031. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42032. }
  42033. // Colors
  42034. if (defines.METALLICWORKFLOW) {
  42035. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  42036. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  42037. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  42038. }
  42039. else {
  42040. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  42041. }
  42042. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  42043. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  42044. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  42045. // Misc
  42046. this._lightingInfos.x = this._directIntensity;
  42047. this._lightingInfos.y = this._emissiveIntensity;
  42048. this._lightingInfos.z = this._environmentIntensity;
  42049. this._lightingInfos.w = this._specularIntensity;
  42050. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  42051. }
  42052. // Textures
  42053. if (scene.texturesEnabled) {
  42054. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42055. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  42056. }
  42057. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42058. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  42059. }
  42060. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42061. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  42062. }
  42063. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42064. if (defines.LODBASEDMICROSFURACE) {
  42065. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  42066. }
  42067. else {
  42068. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  42069. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  42070. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  42071. }
  42072. }
  42073. if (defines.ENVIRONMENTBRDF) {
  42074. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  42075. }
  42076. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42077. if (defines.LODBASEDMICROSFURACE) {
  42078. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  42079. }
  42080. else {
  42081. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42082. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42083. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42084. }
  42085. }
  42086. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42087. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42088. }
  42089. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42090. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42091. }
  42092. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42093. if (this._metallicTexture) {
  42094. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42095. }
  42096. else if (this._reflectivityTexture) {
  42097. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42098. }
  42099. if (this._microSurfaceTexture) {
  42100. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42101. }
  42102. }
  42103. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42104. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42105. }
  42106. }
  42107. // Clip plane
  42108. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42109. // Colors
  42110. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42111. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42112. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42113. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42114. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42115. }
  42116. if (mustRebind || !this.isFrozen) {
  42117. // Lights
  42118. if (scene.lightsEnabled && !this._disableLighting) {
  42119. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42120. }
  42121. // View
  42122. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42123. this.bindView(effect);
  42124. }
  42125. // Fog
  42126. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42127. // Morph targets
  42128. if (defines.NUM_MORPH_INFLUENCERS) {
  42129. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42130. }
  42131. // image processing
  42132. this._imageProcessingConfiguration.bind(this._activeEffect);
  42133. // Log. depth
  42134. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42135. }
  42136. this._uniformBuffer.update();
  42137. this._afterBind(mesh);
  42138. };
  42139. /**
  42140. * Returns the animatable textures.
  42141. * @returns - Array of animatable textures.
  42142. */
  42143. PBRBaseMaterial.prototype.getAnimatables = function () {
  42144. var results = [];
  42145. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42146. results.push(this._albedoTexture);
  42147. }
  42148. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42149. results.push(this._ambientTexture);
  42150. }
  42151. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42152. results.push(this._opacityTexture);
  42153. }
  42154. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42155. results.push(this._reflectionTexture);
  42156. }
  42157. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42158. results.push(this._emissiveTexture);
  42159. }
  42160. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42161. results.push(this._metallicTexture);
  42162. }
  42163. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42164. results.push(this._reflectivityTexture);
  42165. }
  42166. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42167. results.push(this._bumpTexture);
  42168. }
  42169. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42170. results.push(this._lightmapTexture);
  42171. }
  42172. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42173. results.push(this._refractionTexture);
  42174. }
  42175. return results;
  42176. };
  42177. /**
  42178. * Returns the texture used for reflections.
  42179. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42180. */
  42181. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42182. if (this._reflectionTexture) {
  42183. return this._reflectionTexture;
  42184. }
  42185. return this.getScene().environmentTexture;
  42186. };
  42187. /**
  42188. * Returns the texture used for refraction or null if none is used.
  42189. * @returns - Refection texture if present. If no refraction texture and refraction
  42190. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42191. */
  42192. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42193. if (this._refractionTexture) {
  42194. return this._refractionTexture;
  42195. }
  42196. if (this._linkRefractionWithTransparency) {
  42197. return this.getScene().environmentTexture;
  42198. }
  42199. return null;
  42200. };
  42201. /**
  42202. * Disposes the resources of the material.
  42203. * @param forceDisposeEffect - Forces the disposal of effects.
  42204. * @param forceDisposeTextures - Forces the disposal of all textures.
  42205. */
  42206. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42207. if (forceDisposeTextures) {
  42208. if (this._albedoTexture) {
  42209. this._albedoTexture.dispose();
  42210. }
  42211. if (this._ambientTexture) {
  42212. this._ambientTexture.dispose();
  42213. }
  42214. if (this._opacityTexture) {
  42215. this._opacityTexture.dispose();
  42216. }
  42217. if (this._reflectionTexture) {
  42218. this._reflectionTexture.dispose();
  42219. }
  42220. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42221. this._environmentBRDFTexture.dispose();
  42222. }
  42223. if (this._emissiveTexture) {
  42224. this._emissiveTexture.dispose();
  42225. }
  42226. if (this._metallicTexture) {
  42227. this._metallicTexture.dispose();
  42228. }
  42229. if (this._reflectivityTexture) {
  42230. this._reflectivityTexture.dispose();
  42231. }
  42232. if (this._bumpTexture) {
  42233. this._bumpTexture.dispose();
  42234. }
  42235. if (this._lightmapTexture) {
  42236. this._lightmapTexture.dispose();
  42237. }
  42238. if (this._refractionTexture) {
  42239. this._refractionTexture.dispose();
  42240. }
  42241. }
  42242. this._renderTargets.dispose();
  42243. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42244. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42245. }
  42246. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42247. };
  42248. /**
  42249. * Stores the reflectivity values based on metallic roughness workflow.
  42250. */
  42251. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42252. __decorate([
  42253. BABYLON.serializeAsImageProcessingConfiguration()
  42254. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42255. __decorate([
  42256. BABYLON.serialize()
  42257. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42258. __decorate([
  42259. BABYLON.serialize()
  42260. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42261. return PBRBaseMaterial;
  42262. }(BABYLON.PushMaterial));
  42263. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42264. })(BABYLON || (BABYLON = {}));
  42265. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42266. "use strict";
  42267. var BABYLON;
  42268. (function (BABYLON) {
  42269. /**
  42270. * The Physically based simple base material of BJS.
  42271. *
  42272. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42273. * It is used as the base class for both the specGloss and metalRough conventions.
  42274. */
  42275. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42276. __extends(PBRBaseSimpleMaterial, _super);
  42277. /**
  42278. * Instantiates a new PBRMaterial instance.
  42279. *
  42280. * @param name The material name
  42281. * @param scene The scene the material will be use in.
  42282. */
  42283. function PBRBaseSimpleMaterial(name, scene) {
  42284. var _this = _super.call(this, name, scene) || this;
  42285. /**
  42286. * Number of Simultaneous lights allowed on the material.
  42287. */
  42288. _this.maxSimultaneousLights = 4;
  42289. /**
  42290. * If sets to true, disables all the lights affecting the material.
  42291. */
  42292. _this.disableLighting = false;
  42293. /**
  42294. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42295. */
  42296. _this.invertNormalMapX = false;
  42297. /**
  42298. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42299. */
  42300. _this.invertNormalMapY = false;
  42301. /**
  42302. * Emissivie color used to self-illuminate the model.
  42303. */
  42304. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42305. /**
  42306. * Occlusion Channel Strenght.
  42307. */
  42308. _this.occlusionStrength = 1.0;
  42309. _this.useLightmapAsShadowmap = false;
  42310. _this._useAlphaFromAlbedoTexture = true;
  42311. _this._useAmbientInGrayScale = true;
  42312. return _this;
  42313. }
  42314. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42315. /**
  42316. * Gets the current double sided mode.
  42317. */
  42318. get: function () {
  42319. return this._twoSidedLighting;
  42320. },
  42321. /**
  42322. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42323. */
  42324. set: function (value) {
  42325. if (this._twoSidedLighting === value) {
  42326. return;
  42327. }
  42328. this._twoSidedLighting = value;
  42329. this.backFaceCulling = !value;
  42330. this._markAllSubMeshesAsTexturesDirty();
  42331. },
  42332. enumerable: true,
  42333. configurable: true
  42334. });
  42335. /**
  42336. * Return the active textures of the material.
  42337. */
  42338. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42339. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42340. if (this.environmentTexture) {
  42341. activeTextures.push(this.environmentTexture);
  42342. }
  42343. if (this.normalTexture) {
  42344. activeTextures.push(this.normalTexture);
  42345. }
  42346. if (this.emissiveTexture) {
  42347. activeTextures.push(this.emissiveTexture);
  42348. }
  42349. if (this.occlusionTexture) {
  42350. activeTextures.push(this.occlusionTexture);
  42351. }
  42352. if (this.lightmapTexture) {
  42353. activeTextures.push(this.lightmapTexture);
  42354. }
  42355. return activeTextures;
  42356. };
  42357. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42358. if (_super.prototype.hasTexture.call(this, texture)) {
  42359. return true;
  42360. }
  42361. if (this.lightmapTexture === texture) {
  42362. return true;
  42363. }
  42364. return false;
  42365. };
  42366. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42367. return "PBRBaseSimpleMaterial";
  42368. };
  42369. __decorate([
  42370. BABYLON.serialize(),
  42371. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42372. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42373. __decorate([
  42374. BABYLON.serialize(),
  42375. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42376. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42377. __decorate([
  42378. BABYLON.serializeAsTexture(),
  42379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42380. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42381. __decorate([
  42382. BABYLON.serialize(),
  42383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42384. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42385. __decorate([
  42386. BABYLON.serialize(),
  42387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42388. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42389. __decorate([
  42390. BABYLON.serializeAsTexture(),
  42391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42392. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42393. __decorate([
  42394. BABYLON.serializeAsColor3("emissive"),
  42395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42396. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42397. __decorate([
  42398. BABYLON.serializeAsTexture(),
  42399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42400. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42401. __decorate([
  42402. BABYLON.serialize(),
  42403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42404. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42405. __decorate([
  42406. BABYLON.serializeAsTexture(),
  42407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42408. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42409. __decorate([
  42410. BABYLON.serialize(),
  42411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42412. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42413. __decorate([
  42414. BABYLON.serialize()
  42415. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42416. __decorate([
  42417. BABYLON.serializeAsTexture(),
  42418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42419. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42420. __decorate([
  42421. BABYLON.serialize(),
  42422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42423. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42424. return PBRBaseSimpleMaterial;
  42425. }(BABYLON.PBRBaseMaterial));
  42426. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42427. })(BABYLON || (BABYLON = {}));
  42428. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42429. "use strict";
  42430. var BABYLON;
  42431. (function (BABYLON) {
  42432. /**
  42433. * The Physically based material of BJS.
  42434. *
  42435. * This offers the main features of a standard PBR material.
  42436. * For more information, please refer to the documentation :
  42437. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42438. */
  42439. var PBRMaterial = /** @class */ (function (_super) {
  42440. __extends(PBRMaterial, _super);
  42441. /**
  42442. * Instantiates a new PBRMaterial instance.
  42443. *
  42444. * @param name The material name
  42445. * @param scene The scene the material will be use in.
  42446. */
  42447. function PBRMaterial(name, scene) {
  42448. var _this = _super.call(this, name, scene) || this;
  42449. /**
  42450. * Intensity of the direct lights e.g. the four lights available in your scene.
  42451. * This impacts both the direct diffuse and specular highlights.
  42452. */
  42453. _this.directIntensity = 1.0;
  42454. /**
  42455. * Intensity of the emissive part of the material.
  42456. * This helps controlling the emissive effect without modifying the emissive color.
  42457. */
  42458. _this.emissiveIntensity = 1.0;
  42459. /**
  42460. * Intensity of the environment e.g. how much the environment will light the object
  42461. * either through harmonics for rough material or through the refelction for shiny ones.
  42462. */
  42463. _this.environmentIntensity = 1.0;
  42464. /**
  42465. * This is a special control allowing the reduction of the specular highlights coming from the
  42466. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42467. */
  42468. _this.specularIntensity = 1.0;
  42469. /**
  42470. * Debug Control allowing disabling the bump map on this material.
  42471. */
  42472. _this.disableBumpMap = false;
  42473. /**
  42474. * AKA Occlusion Texture Intensity in other nomenclature.
  42475. */
  42476. _this.ambientTextureStrength = 1.0;
  42477. /**
  42478. * The color of a material in ambient lighting.
  42479. */
  42480. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42481. /**
  42482. * AKA Diffuse Color in other nomenclature.
  42483. */
  42484. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42485. /**
  42486. * AKA Specular Color in other nomenclature.
  42487. */
  42488. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42489. /**
  42490. * The color reflected from the material.
  42491. */
  42492. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42493. /**
  42494. * The color emitted from the material.
  42495. */
  42496. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42497. /**
  42498. * AKA Glossiness in other nomenclature.
  42499. */
  42500. _this.microSurface = 1.0;
  42501. /**
  42502. * source material index of refraction (IOR)' / 'destination material IOR.
  42503. */
  42504. _this.indexOfRefraction = 0.66;
  42505. /**
  42506. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42507. */
  42508. _this.invertRefractionY = false;
  42509. /**
  42510. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42511. * Materials half opaque for instance using refraction could benefit from this control.
  42512. */
  42513. _this.linkRefractionWithTransparency = false;
  42514. _this.useLightmapAsShadowmap = false;
  42515. /**
  42516. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42517. */
  42518. _this.useAlphaFromAlbedoTexture = false;
  42519. /**
  42520. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42521. */
  42522. _this.forceAlphaTest = false;
  42523. /**
  42524. * Defines the alpha limits in alpha test mode.
  42525. */
  42526. _this.alphaCutOff = 0.4;
  42527. /**
  42528. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42529. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42530. */
  42531. _this.useSpecularOverAlpha = true;
  42532. /**
  42533. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42534. */
  42535. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42536. /**
  42537. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42538. */
  42539. _this.useRoughnessFromMetallicTextureAlpha = true;
  42540. /**
  42541. * Specifies if the metallic texture contains the roughness information in its green channel.
  42542. */
  42543. _this.useRoughnessFromMetallicTextureGreen = false;
  42544. /**
  42545. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42546. */
  42547. _this.useMetallnessFromMetallicTextureBlue = false;
  42548. /**
  42549. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42550. */
  42551. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42552. /**
  42553. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42554. */
  42555. _this.useAmbientInGrayScale = false;
  42556. /**
  42557. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42558. * The material will try to infer what glossiness each pixel should be.
  42559. */
  42560. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42561. /**
  42562. * BJS is using an harcoded light falloff based on a manually sets up range.
  42563. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42564. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42565. */
  42566. _this.usePhysicalLightFalloff = true;
  42567. /**
  42568. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42569. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42570. */
  42571. _this.useRadianceOverAlpha = true;
  42572. /**
  42573. * Allows using an object space normal map (instead of tangent space).
  42574. */
  42575. _this.useObjectSpaceNormalMap = false;
  42576. /**
  42577. * Allows using the bump map in parallax mode.
  42578. */
  42579. _this.useParallax = false;
  42580. /**
  42581. * Allows using the bump map in parallax occlusion mode.
  42582. */
  42583. _this.useParallaxOcclusion = false;
  42584. /**
  42585. * Controls the scale bias of the parallax mode.
  42586. */
  42587. _this.parallaxScaleBias = 0.05;
  42588. /**
  42589. * If sets to true, disables all the lights affecting the material.
  42590. */
  42591. _this.disableLighting = false;
  42592. /**
  42593. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42594. */
  42595. _this.forceIrradianceInFragment = false;
  42596. /**
  42597. * Number of Simultaneous lights allowed on the material.
  42598. */
  42599. _this.maxSimultaneousLights = 4;
  42600. /**
  42601. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42602. */
  42603. _this.invertNormalMapX = false;
  42604. /**
  42605. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42606. */
  42607. _this.invertNormalMapY = false;
  42608. /**
  42609. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42610. */
  42611. _this.twoSidedLighting = false;
  42612. /**
  42613. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42614. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42615. */
  42616. _this.useAlphaFresnel = false;
  42617. /**
  42618. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42619. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42620. */
  42621. _this.useLinearAlphaFresnel = false;
  42622. /**
  42623. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42624. * And/Or occlude the blended part.
  42625. */
  42626. _this.environmentBRDFTexture = null;
  42627. /**
  42628. * Force normal to face away from face.
  42629. */
  42630. _this.forceNormalForward = false;
  42631. /**
  42632. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42633. * makes the reflect vector face the model (under horizon).
  42634. */
  42635. _this.useHorizonOcclusion = true;
  42636. /**
  42637. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42638. * too much the area relying on ambient texture to define their ambient occlusion.
  42639. */
  42640. _this.useRadianceOcclusion = true;
  42641. /**
  42642. * If set to true, no lighting calculations will be applied.
  42643. */
  42644. _this.unlit = false;
  42645. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42646. return _this;
  42647. }
  42648. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42649. /**
  42650. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42651. */
  42652. get: function () {
  42653. return this._PBRMATERIAL_OPAQUE;
  42654. },
  42655. enumerable: true,
  42656. configurable: true
  42657. });
  42658. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42659. /**
  42660. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42661. */
  42662. get: function () {
  42663. return this._PBRMATERIAL_ALPHATEST;
  42664. },
  42665. enumerable: true,
  42666. configurable: true
  42667. });
  42668. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42669. /**
  42670. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42671. */
  42672. get: function () {
  42673. return this._PBRMATERIAL_ALPHABLEND;
  42674. },
  42675. enumerable: true,
  42676. configurable: true
  42677. });
  42678. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42679. /**
  42680. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42681. * They are also discarded below the alpha cutoff threshold to improve performances.
  42682. */
  42683. get: function () {
  42684. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42685. },
  42686. enumerable: true,
  42687. configurable: true
  42688. });
  42689. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42690. /**
  42691. * Gets the image processing configuration used either in this material.
  42692. */
  42693. get: function () {
  42694. return this._imageProcessingConfiguration;
  42695. },
  42696. /**
  42697. * Sets the Default image processing configuration used either in the this material.
  42698. *
  42699. * If sets to null, the scene one is in use.
  42700. */
  42701. set: function (value) {
  42702. this._attachImageProcessingConfiguration(value);
  42703. // Ensure the effect will be rebuilt.
  42704. this._markAllSubMeshesAsTexturesDirty();
  42705. },
  42706. enumerable: true,
  42707. configurable: true
  42708. });
  42709. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42710. /**
  42711. * Gets wether the color curves effect is enabled.
  42712. */
  42713. get: function () {
  42714. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42715. },
  42716. /**
  42717. * Sets wether the color curves effect is enabled.
  42718. */
  42719. set: function (value) {
  42720. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42721. },
  42722. enumerable: true,
  42723. configurable: true
  42724. });
  42725. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42726. /**
  42727. * Gets wether the color grading effect is enabled.
  42728. */
  42729. get: function () {
  42730. return this.imageProcessingConfiguration.colorGradingEnabled;
  42731. },
  42732. /**
  42733. * Gets wether the color grading effect is enabled.
  42734. */
  42735. set: function (value) {
  42736. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42737. },
  42738. enumerable: true,
  42739. configurable: true
  42740. });
  42741. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42742. /**
  42743. * Gets wether tonemapping is enabled or not.
  42744. */
  42745. get: function () {
  42746. return this._imageProcessingConfiguration.toneMappingEnabled;
  42747. },
  42748. /**
  42749. * Sets wether tonemapping is enabled or not
  42750. */
  42751. set: function (value) {
  42752. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42753. },
  42754. enumerable: true,
  42755. configurable: true
  42756. });
  42757. ;
  42758. ;
  42759. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42760. /**
  42761. * The camera exposure used on this material.
  42762. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42763. * This corresponds to a photographic exposure.
  42764. */
  42765. get: function () {
  42766. return this._imageProcessingConfiguration.exposure;
  42767. },
  42768. /**
  42769. * The camera exposure used on this material.
  42770. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42771. * This corresponds to a photographic exposure.
  42772. */
  42773. set: function (value) {
  42774. this._imageProcessingConfiguration.exposure = value;
  42775. },
  42776. enumerable: true,
  42777. configurable: true
  42778. });
  42779. ;
  42780. ;
  42781. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42782. /**
  42783. * Gets The camera contrast used on this material.
  42784. */
  42785. get: function () {
  42786. return this._imageProcessingConfiguration.contrast;
  42787. },
  42788. /**
  42789. * Sets The camera contrast used on this material.
  42790. */
  42791. set: function (value) {
  42792. this._imageProcessingConfiguration.contrast = value;
  42793. },
  42794. enumerable: true,
  42795. configurable: true
  42796. });
  42797. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42798. /**
  42799. * Gets the Color Grading 2D Lookup Texture.
  42800. */
  42801. get: function () {
  42802. return this._imageProcessingConfiguration.colorGradingTexture;
  42803. },
  42804. /**
  42805. * Sets the Color Grading 2D Lookup Texture.
  42806. */
  42807. set: function (value) {
  42808. this._imageProcessingConfiguration.colorGradingTexture = value;
  42809. },
  42810. enumerable: true,
  42811. configurable: true
  42812. });
  42813. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42814. /**
  42815. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42816. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42817. * 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;
  42818. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42819. */
  42820. get: function () {
  42821. return this._imageProcessingConfiguration.colorCurves;
  42822. },
  42823. /**
  42824. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42825. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42826. * 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;
  42827. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42828. */
  42829. set: function (value) {
  42830. this._imageProcessingConfiguration.colorCurves = value;
  42831. },
  42832. enumerable: true,
  42833. configurable: true
  42834. });
  42835. /**
  42836. * Returns the name of this material class.
  42837. */
  42838. PBRMaterial.prototype.getClassName = function () {
  42839. return "PBRMaterial";
  42840. };
  42841. /**
  42842. * Returns an array of the actively used textures.
  42843. * @returns - Array of BaseTextures
  42844. */
  42845. PBRMaterial.prototype.getActiveTextures = function () {
  42846. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42847. if (this._albedoTexture) {
  42848. activeTextures.push(this._albedoTexture);
  42849. }
  42850. if (this._ambientTexture) {
  42851. activeTextures.push(this._ambientTexture);
  42852. }
  42853. if (this._opacityTexture) {
  42854. activeTextures.push(this._opacityTexture);
  42855. }
  42856. if (this._reflectionTexture) {
  42857. activeTextures.push(this._reflectionTexture);
  42858. }
  42859. if (this._emissiveTexture) {
  42860. activeTextures.push(this._emissiveTexture);
  42861. }
  42862. if (this._reflectivityTexture) {
  42863. activeTextures.push(this._reflectivityTexture);
  42864. }
  42865. if (this._metallicTexture) {
  42866. activeTextures.push(this._metallicTexture);
  42867. }
  42868. if (this._microSurfaceTexture) {
  42869. activeTextures.push(this._microSurfaceTexture);
  42870. }
  42871. if (this._bumpTexture) {
  42872. activeTextures.push(this._bumpTexture);
  42873. }
  42874. if (this._lightmapTexture) {
  42875. activeTextures.push(this._lightmapTexture);
  42876. }
  42877. if (this._refractionTexture) {
  42878. activeTextures.push(this._refractionTexture);
  42879. }
  42880. return activeTextures;
  42881. };
  42882. /**
  42883. * Checks to see if a texture is used in the material.
  42884. * @param texture - Base texture to use.
  42885. * @returns - Boolean specifying if a texture is used in the material.
  42886. */
  42887. PBRMaterial.prototype.hasTexture = function (texture) {
  42888. if (_super.prototype.hasTexture.call(this, texture)) {
  42889. return true;
  42890. }
  42891. if (this._albedoTexture === texture) {
  42892. return true;
  42893. }
  42894. if (this._ambientTexture === texture) {
  42895. return true;
  42896. }
  42897. if (this._opacityTexture === texture) {
  42898. return true;
  42899. }
  42900. if (this._reflectionTexture === texture) {
  42901. return true;
  42902. }
  42903. if (this._reflectivityTexture === texture) {
  42904. return true;
  42905. }
  42906. if (this._metallicTexture === texture) {
  42907. return true;
  42908. }
  42909. if (this._microSurfaceTexture === texture) {
  42910. return true;
  42911. }
  42912. if (this._bumpTexture === texture) {
  42913. return true;
  42914. }
  42915. if (this._lightmapTexture === texture) {
  42916. return true;
  42917. }
  42918. if (this._refractionTexture === texture) {
  42919. return true;
  42920. }
  42921. return false;
  42922. };
  42923. /**
  42924. * Makes a duplicate of the current material.
  42925. * @param name - name to use for the new material.
  42926. */
  42927. PBRMaterial.prototype.clone = function (name) {
  42928. var _this = this;
  42929. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42930. clone.id = name;
  42931. clone.name = name;
  42932. return clone;
  42933. };
  42934. /**
  42935. * Serializes this PBR Material.
  42936. * @returns - An object with the serialized material.
  42937. */
  42938. PBRMaterial.prototype.serialize = function () {
  42939. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42940. serializationObject.customType = "BABYLON.PBRMaterial";
  42941. return serializationObject;
  42942. };
  42943. // Statics
  42944. /**
  42945. * Parses a PBR Material from a serialized object.
  42946. * @param source - Serialized object.
  42947. * @param scene - BJS scene instance.
  42948. * @param rootUrl - url for the scene object
  42949. * @returns - PBRMaterial
  42950. */
  42951. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42952. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42953. };
  42954. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42955. /**
  42956. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42957. */
  42958. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42959. /**
  42960. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42961. */
  42962. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42963. /**
  42964. * 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.
  42965. * They are also discarded below the alpha cutoff threshold to improve performances.
  42966. */
  42967. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42968. __decorate([
  42969. BABYLON.serialize(),
  42970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42971. ], PBRMaterial.prototype, "directIntensity", void 0);
  42972. __decorate([
  42973. BABYLON.serialize(),
  42974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42975. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42976. __decorate([
  42977. BABYLON.serialize(),
  42978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42979. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42980. __decorate([
  42981. BABYLON.serialize(),
  42982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42983. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42984. __decorate([
  42985. BABYLON.serialize(),
  42986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42987. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42988. __decorate([
  42989. BABYLON.serializeAsTexture(),
  42990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42991. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42992. __decorate([
  42993. BABYLON.serializeAsTexture(),
  42994. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42995. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42996. __decorate([
  42997. BABYLON.serialize(),
  42998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42999. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  43000. __decorate([
  43001. BABYLON.serializeAsTexture(),
  43002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43003. ], PBRMaterial.prototype, "opacityTexture", void 0);
  43004. __decorate([
  43005. BABYLON.serializeAsTexture(),
  43006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43007. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  43008. __decorate([
  43009. BABYLON.serializeAsTexture(),
  43010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43011. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  43012. __decorate([
  43013. BABYLON.serializeAsTexture(),
  43014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43015. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  43016. __decorate([
  43017. BABYLON.serializeAsTexture(),
  43018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43019. ], PBRMaterial.prototype, "metallicTexture", void 0);
  43020. __decorate([
  43021. BABYLON.serialize(),
  43022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43023. ], PBRMaterial.prototype, "metallic", void 0);
  43024. __decorate([
  43025. BABYLON.serialize(),
  43026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43027. ], PBRMaterial.prototype, "roughness", void 0);
  43028. __decorate([
  43029. BABYLON.serializeAsTexture(),
  43030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43031. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  43032. __decorate([
  43033. BABYLON.serializeAsTexture(),
  43034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43035. ], PBRMaterial.prototype, "bumpTexture", void 0);
  43036. __decorate([
  43037. BABYLON.serializeAsTexture(),
  43038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43039. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  43040. __decorate([
  43041. BABYLON.serializeAsTexture(),
  43042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43043. ], PBRMaterial.prototype, "refractionTexture", void 0);
  43044. __decorate([
  43045. BABYLON.serializeAsColor3("ambient"),
  43046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43047. ], PBRMaterial.prototype, "ambientColor", void 0);
  43048. __decorate([
  43049. BABYLON.serializeAsColor3("albedo"),
  43050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43051. ], PBRMaterial.prototype, "albedoColor", void 0);
  43052. __decorate([
  43053. BABYLON.serializeAsColor3("reflectivity"),
  43054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43055. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  43056. __decorate([
  43057. BABYLON.serializeAsColor3("reflection"),
  43058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43059. ], PBRMaterial.prototype, "reflectionColor", void 0);
  43060. __decorate([
  43061. BABYLON.serializeAsColor3("emissive"),
  43062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43063. ], PBRMaterial.prototype, "emissiveColor", void 0);
  43064. __decorate([
  43065. BABYLON.serialize(),
  43066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43067. ], PBRMaterial.prototype, "microSurface", void 0);
  43068. __decorate([
  43069. BABYLON.serialize(),
  43070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43071. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  43072. __decorate([
  43073. BABYLON.serialize(),
  43074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43075. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  43076. __decorate([
  43077. BABYLON.serialize(),
  43078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43079. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  43080. __decorate([
  43081. BABYLON.serialize(),
  43082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43083. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43084. __decorate([
  43085. BABYLON.serialize(),
  43086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43087. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43088. __decorate([
  43089. BABYLON.serialize(),
  43090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43091. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43092. __decorate([
  43093. BABYLON.serialize(),
  43094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43095. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43096. __decorate([
  43097. BABYLON.serialize(),
  43098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43099. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43100. __decorate([
  43101. BABYLON.serialize(),
  43102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43103. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43104. __decorate([
  43105. BABYLON.serialize(),
  43106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43107. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43108. __decorate([
  43109. BABYLON.serialize(),
  43110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43111. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43112. __decorate([
  43113. BABYLON.serialize(),
  43114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43115. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43116. __decorate([
  43117. BABYLON.serialize(),
  43118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43119. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43120. __decorate([
  43121. BABYLON.serialize(),
  43122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43123. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43124. __decorate([
  43125. BABYLON.serialize(),
  43126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43127. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43128. __decorate([
  43129. BABYLON.serialize(),
  43130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43131. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43132. __decorate([
  43133. BABYLON.serialize(),
  43134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43135. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43136. __decorate([
  43137. BABYLON.serialize(),
  43138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43139. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43140. __decorate([
  43141. BABYLON.serialize(),
  43142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43143. ], PBRMaterial.prototype, "useParallax", void 0);
  43144. __decorate([
  43145. BABYLON.serialize(),
  43146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43147. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43148. __decorate([
  43149. BABYLON.serialize(),
  43150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43151. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43152. __decorate([
  43153. BABYLON.serialize(),
  43154. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43155. ], PBRMaterial.prototype, "disableLighting", void 0);
  43156. __decorate([
  43157. BABYLON.serialize(),
  43158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43159. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43160. __decorate([
  43161. BABYLON.serialize(),
  43162. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43163. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43164. __decorate([
  43165. BABYLON.serialize(),
  43166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43167. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43168. __decorate([
  43169. BABYLON.serialize(),
  43170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43171. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43172. __decorate([
  43173. BABYLON.serialize(),
  43174. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43175. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43176. __decorate([
  43177. BABYLON.serialize(),
  43178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43179. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43180. __decorate([
  43181. BABYLON.serialize(),
  43182. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43183. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43184. __decorate([
  43185. BABYLON.serializeAsTexture(),
  43186. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43187. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43188. __decorate([
  43189. BABYLON.serialize(),
  43190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43191. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43192. __decorate([
  43193. BABYLON.serialize(),
  43194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43195. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43196. __decorate([
  43197. BABYLON.serialize(),
  43198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43199. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43200. __decorate([
  43201. BABYLON.serialize(),
  43202. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43203. ], PBRMaterial.prototype, "unlit", void 0);
  43204. return PBRMaterial;
  43205. }(BABYLON.PBRBaseMaterial));
  43206. BABYLON.PBRMaterial = PBRMaterial;
  43207. })(BABYLON || (BABYLON = {}));
  43208. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43209. "use strict";
  43210. var BABYLON;
  43211. (function (BABYLON) {
  43212. /**
  43213. * The PBR material of BJS following the metal roughness convention.
  43214. *
  43215. * This fits to the PBR convention in the GLTF definition:
  43216. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43217. */
  43218. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43219. __extends(PBRMetallicRoughnessMaterial, _super);
  43220. /**
  43221. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43222. *
  43223. * @param name The material name
  43224. * @param scene The scene the material will be use in.
  43225. */
  43226. function PBRMetallicRoughnessMaterial(name, scene) {
  43227. var _this = _super.call(this, name, scene) || this;
  43228. _this._useRoughnessFromMetallicTextureAlpha = false;
  43229. _this._useRoughnessFromMetallicTextureGreen = true;
  43230. _this._useMetallnessFromMetallicTextureBlue = true;
  43231. _this.metallic = 1.0;
  43232. _this.roughness = 1.0;
  43233. return _this;
  43234. }
  43235. /**
  43236. * Return the currrent class name of the material.
  43237. */
  43238. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43239. return "PBRMetallicRoughnessMaterial";
  43240. };
  43241. /**
  43242. * Return the active textures of the material.
  43243. */
  43244. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43245. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43246. if (this.baseTexture) {
  43247. activeTextures.push(this.baseTexture);
  43248. }
  43249. if (this.metallicRoughnessTexture) {
  43250. activeTextures.push(this.metallicRoughnessTexture);
  43251. }
  43252. return activeTextures;
  43253. };
  43254. /**
  43255. * Checks to see if a texture is used in the material.
  43256. * @param texture - Base texture to use.
  43257. * @returns - Boolean specifying if a texture is used in the material.
  43258. */
  43259. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43260. if (_super.prototype.hasTexture.call(this, texture)) {
  43261. return true;
  43262. }
  43263. if (this.baseTexture === texture) {
  43264. return true;
  43265. }
  43266. if (this.metallicRoughnessTexture === texture) {
  43267. return true;
  43268. }
  43269. return false;
  43270. };
  43271. /**
  43272. * Makes a duplicate of the current material.
  43273. * @param name - name to use for the new material.
  43274. */
  43275. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43276. var _this = this;
  43277. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43278. clone.id = name;
  43279. clone.name = name;
  43280. return clone;
  43281. };
  43282. /**
  43283. * Serialize the material to a parsable JSON object.
  43284. */
  43285. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43286. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43287. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43288. return serializationObject;
  43289. };
  43290. /**
  43291. * Parses a JSON object correponding to the serialize function.
  43292. */
  43293. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43294. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43295. };
  43296. __decorate([
  43297. BABYLON.serializeAsColor3(),
  43298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43299. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43300. __decorate([
  43301. BABYLON.serializeAsTexture(),
  43302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43303. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43304. __decorate([
  43305. BABYLON.serialize(),
  43306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43307. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43308. __decorate([
  43309. BABYLON.serialize(),
  43310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43311. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43312. __decorate([
  43313. BABYLON.serializeAsTexture(),
  43314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43315. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43316. return PBRMetallicRoughnessMaterial;
  43317. }(BABYLON.PBRBaseSimpleMaterial));
  43318. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43319. })(BABYLON || (BABYLON = {}));
  43320. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43321. "use strict";
  43322. var BABYLON;
  43323. (function (BABYLON) {
  43324. /**
  43325. * The PBR material of BJS following the specular glossiness convention.
  43326. *
  43327. * This fits to the PBR convention in the GLTF definition:
  43328. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43329. */
  43330. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43331. __extends(PBRSpecularGlossinessMaterial, _super);
  43332. /**
  43333. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43334. *
  43335. * @param name The material name
  43336. * @param scene The scene the material will be use in.
  43337. */
  43338. function PBRSpecularGlossinessMaterial(name, scene) {
  43339. var _this = _super.call(this, name, scene) || this;
  43340. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43341. return _this;
  43342. }
  43343. /**
  43344. * Return the currrent class name of the material.
  43345. */
  43346. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43347. return "PBRSpecularGlossinessMaterial";
  43348. };
  43349. /**
  43350. * Return the active textures of the material.
  43351. */
  43352. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43353. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43354. if (this.diffuseTexture) {
  43355. activeTextures.push(this.diffuseTexture);
  43356. }
  43357. if (this.specularGlossinessTexture) {
  43358. activeTextures.push(this.specularGlossinessTexture);
  43359. }
  43360. return activeTextures;
  43361. };
  43362. /**
  43363. * Checks to see if a texture is used in the material.
  43364. * @param texture - Base texture to use.
  43365. * @returns - Boolean specifying if a texture is used in the material.
  43366. */
  43367. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43368. if (_super.prototype.hasTexture.call(this, texture)) {
  43369. return true;
  43370. }
  43371. if (this.diffuseTexture === texture) {
  43372. return true;
  43373. }
  43374. if (this.specularGlossinessTexture === texture) {
  43375. return true;
  43376. }
  43377. return false;
  43378. };
  43379. /**
  43380. * Makes a duplicate of the current material.
  43381. * @param name - name to use for the new material.
  43382. */
  43383. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43384. var _this = this;
  43385. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43386. clone.id = name;
  43387. clone.name = name;
  43388. return clone;
  43389. };
  43390. /**
  43391. * Serialize the material to a parsable JSON object.
  43392. */
  43393. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43394. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43395. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43396. return serializationObject;
  43397. };
  43398. /**
  43399. * Parses a JSON object correponding to the serialize function.
  43400. */
  43401. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43402. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43403. };
  43404. __decorate([
  43405. BABYLON.serializeAsColor3("diffuse"),
  43406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43407. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43408. __decorate([
  43409. BABYLON.serializeAsTexture(),
  43410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43411. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43412. __decorate([
  43413. BABYLON.serializeAsColor3("specular"),
  43414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43415. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43416. __decorate([
  43417. BABYLON.serialize(),
  43418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43419. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43420. __decorate([
  43421. BABYLON.serializeAsTexture(),
  43422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43423. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43424. return PBRSpecularGlossinessMaterial;
  43425. }(BABYLON.PBRBaseSimpleMaterial));
  43426. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43427. })(BABYLON || (BABYLON = {}));
  43428. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43429. "use strict";
  43430. var BABYLON;
  43431. (function (BABYLON) {
  43432. BABYLON.CameraInputTypes = {};
  43433. var CameraInputsManager = /** @class */ (function () {
  43434. function CameraInputsManager(camera) {
  43435. this.attached = {};
  43436. this.camera = camera;
  43437. this.checkInputs = function () { };
  43438. }
  43439. /**
  43440. * Add an input method to a camera.
  43441. * builtin inputs example: camera.inputs.addGamepad();
  43442. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43443. * @param input camera input method
  43444. */
  43445. CameraInputsManager.prototype.add = function (input) {
  43446. var type = input.getSimpleName();
  43447. if (this.attached[type]) {
  43448. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43449. return;
  43450. }
  43451. this.attached[type] = input;
  43452. input.camera = this.camera;
  43453. //for checkInputs, we are dynamically creating a function
  43454. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43455. if (input.checkInputs) {
  43456. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43457. }
  43458. if (this.attachedElement) {
  43459. input.attachControl(this.attachedElement);
  43460. }
  43461. };
  43462. /**
  43463. * Remove a specific input method from a camera
  43464. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43465. * @param inputToRemove camera input method
  43466. */
  43467. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43468. for (var cam in this.attached) {
  43469. var input = this.attached[cam];
  43470. if (input === inputToRemove) {
  43471. input.detachControl(this.attachedElement);
  43472. input.camera = null;
  43473. delete this.attached[cam];
  43474. this.rebuildInputCheck();
  43475. }
  43476. }
  43477. };
  43478. CameraInputsManager.prototype.removeByType = function (inputType) {
  43479. for (var cam in this.attached) {
  43480. var input = this.attached[cam];
  43481. if (input.getClassName() === inputType) {
  43482. input.detachControl(this.attachedElement);
  43483. input.camera = null;
  43484. delete this.attached[cam];
  43485. this.rebuildInputCheck();
  43486. }
  43487. }
  43488. };
  43489. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43490. var current = this.checkInputs;
  43491. return function () {
  43492. current();
  43493. fn();
  43494. };
  43495. };
  43496. CameraInputsManager.prototype.attachInput = function (input) {
  43497. if (this.attachedElement) {
  43498. input.attachControl(this.attachedElement, this.noPreventDefault);
  43499. }
  43500. };
  43501. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43502. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43503. if (this.attachedElement) {
  43504. return;
  43505. }
  43506. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43507. this.attachedElement = element;
  43508. this.noPreventDefault = noPreventDefault;
  43509. for (var cam in this.attached) {
  43510. this.attached[cam].attachControl(element, noPreventDefault);
  43511. }
  43512. };
  43513. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43514. if (disconnect === void 0) { disconnect = false; }
  43515. if (this.attachedElement !== element) {
  43516. return;
  43517. }
  43518. for (var cam in this.attached) {
  43519. this.attached[cam].detachControl(element);
  43520. if (disconnect) {
  43521. this.attached[cam].camera = null;
  43522. }
  43523. }
  43524. this.attachedElement = null;
  43525. };
  43526. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43527. this.checkInputs = function () { };
  43528. for (var cam in this.attached) {
  43529. var input = this.attached[cam];
  43530. if (input.checkInputs) {
  43531. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43532. }
  43533. }
  43534. };
  43535. /**
  43536. * Remove all attached input methods from a camera
  43537. */
  43538. CameraInputsManager.prototype.clear = function () {
  43539. if (this.attachedElement) {
  43540. this.detachElement(this.attachedElement, true);
  43541. }
  43542. this.attached = {};
  43543. this.attachedElement = null;
  43544. this.checkInputs = function () { };
  43545. };
  43546. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43547. var inputs = {};
  43548. for (var cam in this.attached) {
  43549. var input = this.attached[cam];
  43550. var res = BABYLON.SerializationHelper.Serialize(input);
  43551. inputs[input.getClassName()] = res;
  43552. }
  43553. serializedCamera.inputsmgr = inputs;
  43554. };
  43555. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43556. var parsedInputs = parsedCamera.inputsmgr;
  43557. if (parsedInputs) {
  43558. this.clear();
  43559. for (var n in parsedInputs) {
  43560. var construct = BABYLON.CameraInputTypes[n];
  43561. if (construct) {
  43562. var parsedinput = parsedInputs[n];
  43563. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43564. this.add(input);
  43565. }
  43566. }
  43567. }
  43568. else {
  43569. //2016-03-08 this part is for managing backward compatibility
  43570. for (var n in this.attached) {
  43571. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43572. if (construct) {
  43573. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43574. this.remove(this.attached[n]);
  43575. this.add(input);
  43576. }
  43577. }
  43578. }
  43579. };
  43580. return CameraInputsManager;
  43581. }());
  43582. BABYLON.CameraInputsManager = CameraInputsManager;
  43583. })(BABYLON || (BABYLON = {}));
  43584. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43585. "use strict";
  43586. var BABYLON;
  43587. (function (BABYLON) {
  43588. var TargetCamera = /** @class */ (function (_super) {
  43589. __extends(TargetCamera, _super);
  43590. function TargetCamera(name, position, scene) {
  43591. var _this = _super.call(this, name, position, scene) || this;
  43592. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43593. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43594. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43595. _this.speed = 2.0;
  43596. _this.noRotationConstraint = false;
  43597. _this.lockedTarget = null;
  43598. _this._currentTarget = BABYLON.Vector3.Zero();
  43599. _this._viewMatrix = BABYLON.Matrix.Zero();
  43600. _this._camMatrix = BABYLON.Matrix.Zero();
  43601. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43602. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43603. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43604. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43605. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43606. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43607. _this._tempMatrix = BABYLON.Matrix.Zero();
  43608. return _this;
  43609. }
  43610. TargetCamera.prototype.getFrontPosition = function (distance) {
  43611. this.getWorldMatrix();
  43612. var direction = this.getTarget().subtract(this.position);
  43613. direction.normalize();
  43614. direction.scaleInPlace(distance);
  43615. return this.globalPosition.add(direction);
  43616. };
  43617. TargetCamera.prototype._getLockedTargetPosition = function () {
  43618. if (!this.lockedTarget) {
  43619. return null;
  43620. }
  43621. if (this.lockedTarget.absolutePosition) {
  43622. this.lockedTarget.computeWorldMatrix();
  43623. }
  43624. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43625. };
  43626. TargetCamera.prototype.storeState = function () {
  43627. this._storedPosition = this.position.clone();
  43628. this._storedRotation = this.rotation.clone();
  43629. if (this.rotationQuaternion) {
  43630. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43631. }
  43632. return _super.prototype.storeState.call(this);
  43633. };
  43634. /**
  43635. * Restored camera state. You must call storeState() first
  43636. */
  43637. TargetCamera.prototype._restoreStateValues = function () {
  43638. if (!_super.prototype._restoreStateValues.call(this)) {
  43639. return false;
  43640. }
  43641. this.position = this._storedPosition.clone();
  43642. this.rotation = this._storedRotation.clone();
  43643. if (this.rotationQuaternion) {
  43644. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43645. }
  43646. this.cameraDirection.copyFromFloats(0, 0, 0);
  43647. this.cameraRotation.copyFromFloats(0, 0);
  43648. return true;
  43649. };
  43650. // Cache
  43651. TargetCamera.prototype._initCache = function () {
  43652. _super.prototype._initCache.call(this);
  43653. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43654. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43655. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43656. };
  43657. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43658. if (!ignoreParentClass) {
  43659. _super.prototype._updateCache.call(this);
  43660. }
  43661. var lockedTargetPosition = this._getLockedTargetPosition();
  43662. if (!lockedTargetPosition) {
  43663. this._cache.lockedTarget = null;
  43664. }
  43665. else {
  43666. if (!this._cache.lockedTarget) {
  43667. this._cache.lockedTarget = lockedTargetPosition.clone();
  43668. }
  43669. else {
  43670. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43671. }
  43672. }
  43673. this._cache.rotation.copyFrom(this.rotation);
  43674. if (this.rotationQuaternion)
  43675. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43676. };
  43677. // Synchronized
  43678. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43679. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43680. return false;
  43681. }
  43682. var lockedTargetPosition = this._getLockedTargetPosition();
  43683. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43684. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43685. };
  43686. // Methods
  43687. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43688. var engine = this.getEngine();
  43689. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43690. };
  43691. // Target
  43692. TargetCamera.prototype.setTarget = function (target) {
  43693. this.upVector.normalize();
  43694. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43695. this._camMatrix.invert();
  43696. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43697. var vDir = target.subtract(this.position);
  43698. if (vDir.x >= 0.0) {
  43699. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43700. }
  43701. else {
  43702. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43703. }
  43704. this.rotation.z = 0;
  43705. if (isNaN(this.rotation.x)) {
  43706. this.rotation.x = 0;
  43707. }
  43708. if (isNaN(this.rotation.y)) {
  43709. this.rotation.y = 0;
  43710. }
  43711. if (isNaN(this.rotation.z)) {
  43712. this.rotation.z = 0;
  43713. }
  43714. if (this.rotationQuaternion) {
  43715. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43716. }
  43717. };
  43718. /**
  43719. * Return the current target position of the camera. This value is expressed in local space.
  43720. */
  43721. TargetCamera.prototype.getTarget = function () {
  43722. return this._currentTarget;
  43723. };
  43724. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43725. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43726. };
  43727. TargetCamera.prototype._updatePosition = function () {
  43728. if (this.parent) {
  43729. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43730. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43731. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43732. return;
  43733. }
  43734. this.position.addInPlace(this.cameraDirection);
  43735. };
  43736. TargetCamera.prototype._checkInputs = function () {
  43737. var needToMove = this._decideIfNeedsToMove();
  43738. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43739. // Move
  43740. if (needToMove) {
  43741. this._updatePosition();
  43742. }
  43743. // Rotate
  43744. if (needToRotate) {
  43745. this.rotation.x += this.cameraRotation.x;
  43746. this.rotation.y += this.cameraRotation.y;
  43747. //rotate, if quaternion is set and rotation was used
  43748. if (this.rotationQuaternion) {
  43749. var len = this.rotation.lengthSquared();
  43750. if (len) {
  43751. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43752. }
  43753. }
  43754. if (!this.noRotationConstraint) {
  43755. var limit = (Math.PI / 2) * 0.95;
  43756. if (this.rotation.x > limit)
  43757. this.rotation.x = limit;
  43758. if (this.rotation.x < -limit)
  43759. this.rotation.x = -limit;
  43760. }
  43761. }
  43762. // Inertia
  43763. if (needToMove) {
  43764. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43765. this.cameraDirection.x = 0;
  43766. }
  43767. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43768. this.cameraDirection.y = 0;
  43769. }
  43770. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43771. this.cameraDirection.z = 0;
  43772. }
  43773. this.cameraDirection.scaleInPlace(this.inertia);
  43774. }
  43775. if (needToRotate) {
  43776. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43777. this.cameraRotation.x = 0;
  43778. }
  43779. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43780. this.cameraRotation.y = 0;
  43781. }
  43782. this.cameraRotation.scaleInPlace(this.inertia);
  43783. }
  43784. _super.prototype._checkInputs.call(this);
  43785. };
  43786. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43787. if (this.rotationQuaternion) {
  43788. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43789. }
  43790. else {
  43791. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43792. }
  43793. //update the up vector!
  43794. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43795. };
  43796. TargetCamera.prototype._getViewMatrix = function () {
  43797. if (this.lockedTarget) {
  43798. this.setTarget(this._getLockedTargetPosition());
  43799. }
  43800. // Compute
  43801. this._updateCameraRotationMatrix();
  43802. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43803. // Computing target and final matrix
  43804. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43805. if (this.getScene().useRightHandedSystem) {
  43806. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43807. }
  43808. else {
  43809. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43810. }
  43811. return this._viewMatrix;
  43812. };
  43813. /**
  43814. * @override
  43815. * Override Camera.createRigCamera
  43816. */
  43817. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43818. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43819. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43820. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43821. if (!this.rotationQuaternion) {
  43822. this.rotationQuaternion = new BABYLON.Quaternion();
  43823. }
  43824. rigCamera._cameraRigParams = {};
  43825. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43826. }
  43827. return rigCamera;
  43828. }
  43829. return null;
  43830. };
  43831. /**
  43832. * @override
  43833. * Override Camera._updateRigCameras
  43834. */
  43835. TargetCamera.prototype._updateRigCameras = function () {
  43836. var camLeft = this._rigCameras[0];
  43837. var camRight = this._rigCameras[1];
  43838. switch (this.cameraRigMode) {
  43839. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43840. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43841. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43842. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43843. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43844. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43845. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43846. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43847. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43848. camLeft.setTarget(this.getTarget());
  43849. camRight.setTarget(this.getTarget());
  43850. break;
  43851. case BABYLON.Camera.RIG_MODE_VR:
  43852. if (camLeft.rotationQuaternion) {
  43853. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43854. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43855. }
  43856. else {
  43857. camLeft.rotation.copyFrom(this.rotation);
  43858. camRight.rotation.copyFrom(this.rotation);
  43859. }
  43860. camLeft.position.copyFrom(this.position);
  43861. camRight.position.copyFrom(this.position);
  43862. break;
  43863. }
  43864. _super.prototype._updateRigCameras.call(this);
  43865. };
  43866. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43867. if (!this._rigCamTransformMatrix) {
  43868. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43869. }
  43870. var target = this.getTarget();
  43871. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43872. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43873. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43874. };
  43875. TargetCamera.prototype.getClassName = function () {
  43876. return "TargetCamera";
  43877. };
  43878. __decorate([
  43879. BABYLON.serializeAsVector3()
  43880. ], TargetCamera.prototype, "rotation", void 0);
  43881. __decorate([
  43882. BABYLON.serialize()
  43883. ], TargetCamera.prototype, "speed", void 0);
  43884. __decorate([
  43885. BABYLON.serializeAsMeshReference("lockedTargetId")
  43886. ], TargetCamera.prototype, "lockedTarget", void 0);
  43887. return TargetCamera;
  43888. }(BABYLON.Camera));
  43889. BABYLON.TargetCamera = TargetCamera;
  43890. })(BABYLON || (BABYLON = {}));
  43891. //# sourceMappingURL=babylon.targetCamera.js.map
  43892. "use strict";
  43893. var BABYLON;
  43894. (function (BABYLON) {
  43895. var FreeCameraMouseInput = /** @class */ (function () {
  43896. function FreeCameraMouseInput(touchEnabled) {
  43897. if (touchEnabled === void 0) { touchEnabled = true; }
  43898. this.touchEnabled = touchEnabled;
  43899. this.buttons = [0, 1, 2];
  43900. this.angularSensibility = 2000.0;
  43901. this.previousPosition = null;
  43902. }
  43903. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43904. var _this = this;
  43905. var engine = this.camera.getEngine();
  43906. if (!this._pointerInput) {
  43907. this._pointerInput = function (p, s) {
  43908. var evt = p.event;
  43909. if (engine.isInVRExclusivePointerMode) {
  43910. return;
  43911. }
  43912. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43913. return;
  43914. }
  43915. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43916. return;
  43917. }
  43918. var srcElement = (evt.srcElement || evt.target);
  43919. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43920. try {
  43921. srcElement.setPointerCapture(evt.pointerId);
  43922. }
  43923. catch (e) {
  43924. //Nothing to do with the error. Execution will continue.
  43925. }
  43926. _this.previousPosition = {
  43927. x: evt.clientX,
  43928. y: evt.clientY
  43929. };
  43930. if (!noPreventDefault) {
  43931. evt.preventDefault();
  43932. element.focus();
  43933. }
  43934. }
  43935. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43936. try {
  43937. srcElement.releasePointerCapture(evt.pointerId);
  43938. }
  43939. catch (e) {
  43940. //Nothing to do with the error.
  43941. }
  43942. _this.previousPosition = null;
  43943. if (!noPreventDefault) {
  43944. evt.preventDefault();
  43945. }
  43946. }
  43947. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43948. if (!_this.previousPosition || engine.isPointerLock) {
  43949. return;
  43950. }
  43951. var offsetX = evt.clientX - _this.previousPosition.x;
  43952. var offsetY = evt.clientY - _this.previousPosition.y;
  43953. if (_this.camera.getScene().useRightHandedSystem) {
  43954. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43955. }
  43956. else {
  43957. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43958. }
  43959. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43960. _this.previousPosition = {
  43961. x: evt.clientX,
  43962. y: evt.clientY
  43963. };
  43964. if (!noPreventDefault) {
  43965. evt.preventDefault();
  43966. }
  43967. }
  43968. };
  43969. }
  43970. this._onMouseMove = function (evt) {
  43971. if (!engine.isPointerLock) {
  43972. return;
  43973. }
  43974. if (engine.isInVRExclusivePointerMode) {
  43975. return;
  43976. }
  43977. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43978. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43979. if (_this.camera.getScene().useRightHandedSystem) {
  43980. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43981. }
  43982. else {
  43983. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43984. }
  43985. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43986. _this.previousPosition = null;
  43987. if (!noPreventDefault) {
  43988. evt.preventDefault();
  43989. }
  43990. };
  43991. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43992. element.addEventListener("mousemove", this._onMouseMove, false);
  43993. };
  43994. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43995. if (this._observer && element) {
  43996. this.camera.getScene().onPointerObservable.remove(this._observer);
  43997. if (this._onMouseMove) {
  43998. element.removeEventListener("mousemove", this._onMouseMove);
  43999. }
  44000. this._observer = null;
  44001. this._onMouseMove = null;
  44002. this.previousPosition = null;
  44003. }
  44004. };
  44005. FreeCameraMouseInput.prototype.getClassName = function () {
  44006. return "FreeCameraMouseInput";
  44007. };
  44008. FreeCameraMouseInput.prototype.getSimpleName = function () {
  44009. return "mouse";
  44010. };
  44011. __decorate([
  44012. BABYLON.serialize()
  44013. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  44014. __decorate([
  44015. BABYLON.serialize()
  44016. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  44017. return FreeCameraMouseInput;
  44018. }());
  44019. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  44020. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  44021. })(BABYLON || (BABYLON = {}));
  44022. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  44023. "use strict";
  44024. var BABYLON;
  44025. (function (BABYLON) {
  44026. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  44027. function FreeCameraKeyboardMoveInput() {
  44028. this._keys = new Array();
  44029. this.keysUp = [38];
  44030. this.keysDown = [40];
  44031. this.keysLeft = [37];
  44032. this.keysRight = [39];
  44033. }
  44034. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44035. var _this = this;
  44036. if (this._onCanvasBlurObserver) {
  44037. return;
  44038. }
  44039. this._scene = this.camera.getScene();
  44040. this._engine = this._scene.getEngine();
  44041. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44042. _this._keys = [];
  44043. });
  44044. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44045. var evt = info.event;
  44046. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44047. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44048. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44049. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44050. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44051. var index = _this._keys.indexOf(evt.keyCode);
  44052. if (index === -1) {
  44053. _this._keys.push(evt.keyCode);
  44054. }
  44055. if (!noPreventDefault) {
  44056. evt.preventDefault();
  44057. }
  44058. }
  44059. }
  44060. else {
  44061. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44062. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44063. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44064. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44065. var index = _this._keys.indexOf(evt.keyCode);
  44066. if (index >= 0) {
  44067. _this._keys.splice(index, 1);
  44068. }
  44069. if (!noPreventDefault) {
  44070. evt.preventDefault();
  44071. }
  44072. }
  44073. }
  44074. });
  44075. };
  44076. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44077. if (this._scene) {
  44078. if (this._onKeyboardObserver) {
  44079. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44080. }
  44081. if (this._onCanvasBlurObserver) {
  44082. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44083. }
  44084. this._onKeyboardObserver = null;
  44085. this._onCanvasBlurObserver = null;
  44086. }
  44087. this._keys = [];
  44088. };
  44089. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44090. if (this._onKeyboardObserver) {
  44091. var camera = this.camera;
  44092. // Keyboard
  44093. for (var index = 0; index < this._keys.length; index++) {
  44094. var keyCode = this._keys[index];
  44095. var speed = camera._computeLocalCameraSpeed();
  44096. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44097. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44098. }
  44099. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44100. camera._localDirection.copyFromFloats(0, 0, speed);
  44101. }
  44102. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44103. camera._localDirection.copyFromFloats(speed, 0, 0);
  44104. }
  44105. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44106. camera._localDirection.copyFromFloats(0, 0, -speed);
  44107. }
  44108. if (camera.getScene().useRightHandedSystem) {
  44109. camera._localDirection.z *= -1;
  44110. }
  44111. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44112. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44113. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44114. }
  44115. }
  44116. };
  44117. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44118. return "FreeCameraKeyboardMoveInput";
  44119. };
  44120. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44121. this._keys = [];
  44122. };
  44123. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44124. return "keyboard";
  44125. };
  44126. __decorate([
  44127. BABYLON.serialize()
  44128. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44129. __decorate([
  44130. BABYLON.serialize()
  44131. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44132. __decorate([
  44133. BABYLON.serialize()
  44134. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44135. __decorate([
  44136. BABYLON.serialize()
  44137. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44138. return FreeCameraKeyboardMoveInput;
  44139. }());
  44140. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44141. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44142. })(BABYLON || (BABYLON = {}));
  44143. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44144. "use strict";
  44145. var BABYLON;
  44146. (function (BABYLON) {
  44147. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44148. __extends(FreeCameraInputsManager, _super);
  44149. function FreeCameraInputsManager(camera) {
  44150. return _super.call(this, camera) || this;
  44151. }
  44152. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44153. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44154. return this;
  44155. };
  44156. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44157. if (touchEnabled === void 0) { touchEnabled = true; }
  44158. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44159. return this;
  44160. };
  44161. FreeCameraInputsManager.prototype.addGamepad = function () {
  44162. this.add(new BABYLON.FreeCameraGamepadInput());
  44163. return this;
  44164. };
  44165. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44166. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44167. return this;
  44168. };
  44169. FreeCameraInputsManager.prototype.addTouch = function () {
  44170. this.add(new BABYLON.FreeCameraTouchInput());
  44171. return this;
  44172. };
  44173. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44174. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44175. return this;
  44176. };
  44177. return FreeCameraInputsManager;
  44178. }(BABYLON.CameraInputsManager));
  44179. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44180. })(BABYLON || (BABYLON = {}));
  44181. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44182. "use strict";
  44183. var BABYLON;
  44184. (function (BABYLON) {
  44185. var FreeCamera = /** @class */ (function (_super) {
  44186. __extends(FreeCamera, _super);
  44187. function FreeCamera(name, position, scene) {
  44188. var _this = _super.call(this, name, position, scene) || this;
  44189. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44190. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44191. _this.checkCollisions = false;
  44192. _this.applyGravity = false;
  44193. _this._needMoveForGravity = false;
  44194. _this._oldPosition = BABYLON.Vector3.Zero();
  44195. _this._diffPosition = BABYLON.Vector3.Zero();
  44196. _this._newPosition = BABYLON.Vector3.Zero();
  44197. // Collisions
  44198. _this._collisionMask = -1;
  44199. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44200. if (collidedMesh === void 0) { collidedMesh = null; }
  44201. //TODO move this to the collision coordinator!
  44202. if (_this.getScene().workerCollisions)
  44203. newPosition.multiplyInPlace(_this._collider._radius);
  44204. var updatePosition = function (newPos) {
  44205. _this._newPosition.copyFrom(newPos);
  44206. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44207. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44208. _this.position.addInPlace(_this._diffPosition);
  44209. if (_this.onCollide && collidedMesh) {
  44210. _this.onCollide(collidedMesh);
  44211. }
  44212. }
  44213. };
  44214. updatePosition(newPosition);
  44215. };
  44216. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44217. _this.inputs.addKeyboard().addMouse();
  44218. return _this;
  44219. }
  44220. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44221. //-- begin properties for backward compatibility for inputs
  44222. /**
  44223. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44224. * Higher values reduce sensitivity.
  44225. */
  44226. get: function () {
  44227. var mouse = this.inputs.attached["mouse"];
  44228. if (mouse)
  44229. return mouse.angularSensibility;
  44230. return 0;
  44231. },
  44232. /**
  44233. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44234. * Higher values reduce sensitivity.
  44235. */
  44236. set: function (value) {
  44237. var mouse = this.inputs.attached["mouse"];
  44238. if (mouse)
  44239. mouse.angularSensibility = value;
  44240. },
  44241. enumerable: true,
  44242. configurable: true
  44243. });
  44244. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44245. get: function () {
  44246. var keyboard = this.inputs.attached["keyboard"];
  44247. if (keyboard)
  44248. return keyboard.keysUp;
  44249. return [];
  44250. },
  44251. set: function (value) {
  44252. var keyboard = this.inputs.attached["keyboard"];
  44253. if (keyboard)
  44254. keyboard.keysUp = value;
  44255. },
  44256. enumerable: true,
  44257. configurable: true
  44258. });
  44259. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44260. get: function () {
  44261. var keyboard = this.inputs.attached["keyboard"];
  44262. if (keyboard)
  44263. return keyboard.keysDown;
  44264. return [];
  44265. },
  44266. set: function (value) {
  44267. var keyboard = this.inputs.attached["keyboard"];
  44268. if (keyboard)
  44269. keyboard.keysDown = value;
  44270. },
  44271. enumerable: true,
  44272. configurable: true
  44273. });
  44274. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44275. get: function () {
  44276. var keyboard = this.inputs.attached["keyboard"];
  44277. if (keyboard)
  44278. return keyboard.keysLeft;
  44279. return [];
  44280. },
  44281. set: function (value) {
  44282. var keyboard = this.inputs.attached["keyboard"];
  44283. if (keyboard)
  44284. keyboard.keysLeft = value;
  44285. },
  44286. enumerable: true,
  44287. configurable: true
  44288. });
  44289. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44290. get: function () {
  44291. var keyboard = this.inputs.attached["keyboard"];
  44292. if (keyboard)
  44293. return keyboard.keysRight;
  44294. return [];
  44295. },
  44296. set: function (value) {
  44297. var keyboard = this.inputs.attached["keyboard"];
  44298. if (keyboard)
  44299. keyboard.keysRight = value;
  44300. },
  44301. enumerable: true,
  44302. configurable: true
  44303. });
  44304. // Controls
  44305. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44306. this.inputs.attachElement(element, noPreventDefault);
  44307. };
  44308. FreeCamera.prototype.detachControl = function (element) {
  44309. this.inputs.detachElement(element);
  44310. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44311. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44312. };
  44313. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44314. get: function () {
  44315. return this._collisionMask;
  44316. },
  44317. set: function (mask) {
  44318. this._collisionMask = !isNaN(mask) ? mask : -1;
  44319. },
  44320. enumerable: true,
  44321. configurable: true
  44322. });
  44323. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44324. var globalPosition;
  44325. if (this.parent) {
  44326. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44327. }
  44328. else {
  44329. globalPosition = this.position;
  44330. }
  44331. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44332. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44333. if (!this._collider) {
  44334. this._collider = new BABYLON.Collider();
  44335. }
  44336. this._collider._radius = this.ellipsoid;
  44337. this._collider.collisionMask = this._collisionMask;
  44338. //no need for clone, as long as gravity is not on.
  44339. var actualDisplacement = displacement;
  44340. //add gravity to the direction to prevent the dual-collision checking
  44341. if (this.applyGravity) {
  44342. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44343. actualDisplacement = displacement.add(this.getScene().gravity);
  44344. }
  44345. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44346. };
  44347. FreeCamera.prototype._checkInputs = function () {
  44348. if (!this._localDirection) {
  44349. this._localDirection = BABYLON.Vector3.Zero();
  44350. this._transformedDirection = BABYLON.Vector3.Zero();
  44351. }
  44352. this.inputs.checkInputs();
  44353. _super.prototype._checkInputs.call(this);
  44354. };
  44355. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44356. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44357. };
  44358. FreeCamera.prototype._updatePosition = function () {
  44359. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44360. this._collideWithWorld(this.cameraDirection);
  44361. }
  44362. else {
  44363. _super.prototype._updatePosition.call(this);
  44364. }
  44365. };
  44366. FreeCamera.prototype.dispose = function () {
  44367. this.inputs.clear();
  44368. _super.prototype.dispose.call(this);
  44369. };
  44370. FreeCamera.prototype.getClassName = function () {
  44371. return "FreeCamera";
  44372. };
  44373. __decorate([
  44374. BABYLON.serializeAsVector3()
  44375. ], FreeCamera.prototype, "ellipsoid", void 0);
  44376. __decorate([
  44377. BABYLON.serializeAsVector3()
  44378. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44379. __decorate([
  44380. BABYLON.serialize()
  44381. ], FreeCamera.prototype, "checkCollisions", void 0);
  44382. __decorate([
  44383. BABYLON.serialize()
  44384. ], FreeCamera.prototype, "applyGravity", void 0);
  44385. return FreeCamera;
  44386. }(BABYLON.TargetCamera));
  44387. BABYLON.FreeCamera = FreeCamera;
  44388. })(BABYLON || (BABYLON = {}));
  44389. //# sourceMappingURL=babylon.freeCamera.js.map
  44390. "use strict";
  44391. var BABYLON;
  44392. (function (BABYLON) {
  44393. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44394. function ArcRotateCameraKeyboardMoveInput() {
  44395. this._keys = new Array();
  44396. this.keysUp = [38];
  44397. this.keysDown = [40];
  44398. this.keysLeft = [37];
  44399. this.keysRight = [39];
  44400. this.keysReset = [220];
  44401. this.panningSensibility = 50.0;
  44402. this.zoomingSensibility = 25.0;
  44403. this.useAltToZoom = true;
  44404. }
  44405. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44406. var _this = this;
  44407. if (this._onCanvasBlurObserver) {
  44408. return;
  44409. }
  44410. this._scene = this.camera.getScene();
  44411. this._engine = this._scene.getEngine();
  44412. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44413. _this._keys = [];
  44414. });
  44415. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44416. var evt = info.event;
  44417. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44418. _this._ctrlPressed = evt.ctrlKey;
  44419. _this._altPressed = evt.altKey;
  44420. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44421. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44422. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44423. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44424. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44425. var index = _this._keys.indexOf(evt.keyCode);
  44426. if (index === -1) {
  44427. _this._keys.push(evt.keyCode);
  44428. }
  44429. if (evt.preventDefault) {
  44430. if (!noPreventDefault) {
  44431. evt.preventDefault();
  44432. }
  44433. }
  44434. }
  44435. }
  44436. else {
  44437. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44438. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44439. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44440. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44441. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44442. var index = _this._keys.indexOf(evt.keyCode);
  44443. if (index >= 0) {
  44444. _this._keys.splice(index, 1);
  44445. }
  44446. if (evt.preventDefault) {
  44447. if (!noPreventDefault) {
  44448. evt.preventDefault();
  44449. }
  44450. }
  44451. }
  44452. }
  44453. });
  44454. };
  44455. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44456. if (this._scene) {
  44457. if (this._onKeyboardObserver) {
  44458. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44459. }
  44460. if (this._onCanvasBlurObserver) {
  44461. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44462. }
  44463. this._onKeyboardObserver = null;
  44464. this._onCanvasBlurObserver = null;
  44465. }
  44466. this._keys = [];
  44467. };
  44468. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44469. if (this._onKeyboardObserver) {
  44470. var camera = this.camera;
  44471. for (var index = 0; index < this._keys.length; index++) {
  44472. var keyCode = this._keys[index];
  44473. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44474. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44475. camera.inertialPanningX -= 1 / this.panningSensibility;
  44476. }
  44477. else {
  44478. camera.inertialAlphaOffset -= 0.01;
  44479. }
  44480. }
  44481. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44482. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44483. camera.inertialPanningY += 1 / this.panningSensibility;
  44484. }
  44485. else if (this._altPressed && this.useAltToZoom) {
  44486. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44487. }
  44488. else {
  44489. camera.inertialBetaOffset -= 0.01;
  44490. }
  44491. }
  44492. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44493. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44494. camera.inertialPanningX += 1 / this.panningSensibility;
  44495. }
  44496. else {
  44497. camera.inertialAlphaOffset += 0.01;
  44498. }
  44499. }
  44500. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44501. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44502. camera.inertialPanningY -= 1 / this.panningSensibility;
  44503. }
  44504. else if (this._altPressed && this.useAltToZoom) {
  44505. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44506. }
  44507. else {
  44508. camera.inertialBetaOffset += 0.01;
  44509. }
  44510. }
  44511. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44512. camera.restoreState();
  44513. }
  44514. }
  44515. }
  44516. };
  44517. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44518. return "ArcRotateCameraKeyboardMoveInput";
  44519. };
  44520. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44521. return "keyboard";
  44522. };
  44523. __decorate([
  44524. BABYLON.serialize()
  44525. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44526. __decorate([
  44527. BABYLON.serialize()
  44528. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44529. __decorate([
  44530. BABYLON.serialize()
  44531. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44532. __decorate([
  44533. BABYLON.serialize()
  44534. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44535. __decorate([
  44536. BABYLON.serialize()
  44537. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44538. __decorate([
  44539. BABYLON.serialize()
  44540. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44541. __decorate([
  44542. BABYLON.serialize()
  44543. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44544. __decorate([
  44545. BABYLON.serialize()
  44546. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44547. return ArcRotateCameraKeyboardMoveInput;
  44548. }());
  44549. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44550. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44551. })(BABYLON || (BABYLON = {}));
  44552. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44553. "use strict";
  44554. var BABYLON;
  44555. (function (BABYLON) {
  44556. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44557. function ArcRotateCameraMouseWheelInput() {
  44558. this.wheelPrecision = 3.0;
  44559. /**
  44560. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44561. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44562. */
  44563. this.wheelDeltaPercentage = 0;
  44564. }
  44565. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44566. var _this = this;
  44567. this._wheel = function (p, s) {
  44568. //sanity check - this should be a PointerWheel event.
  44569. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44570. return;
  44571. var event = p.event;
  44572. var delta = 0;
  44573. if (event.wheelDelta) {
  44574. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44575. }
  44576. else if (event.detail) {
  44577. delta = -event.detail / _this.wheelPrecision;
  44578. }
  44579. if (delta)
  44580. _this.camera.inertialRadiusOffset += delta;
  44581. if (event.preventDefault) {
  44582. if (!noPreventDefault) {
  44583. event.preventDefault();
  44584. }
  44585. }
  44586. };
  44587. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44588. };
  44589. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44590. if (this._observer && element) {
  44591. this.camera.getScene().onPointerObservable.remove(this._observer);
  44592. this._observer = null;
  44593. this._wheel = null;
  44594. }
  44595. };
  44596. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44597. return "ArcRotateCameraMouseWheelInput";
  44598. };
  44599. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44600. return "mousewheel";
  44601. };
  44602. __decorate([
  44603. BABYLON.serialize()
  44604. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44605. __decorate([
  44606. BABYLON.serialize()
  44607. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44608. return ArcRotateCameraMouseWheelInput;
  44609. }());
  44610. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44611. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44612. })(BABYLON || (BABYLON = {}));
  44613. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44614. "use strict";
  44615. var BABYLON;
  44616. (function (BABYLON) {
  44617. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44618. function ArcRotateCameraPointersInput() {
  44619. this.buttons = [0, 1, 2];
  44620. this.angularSensibilityX = 1000.0;
  44621. this.angularSensibilityY = 1000.0;
  44622. this.pinchPrecision = 12.0;
  44623. /**
  44624. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44625. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44626. */
  44627. this.pinchDeltaPercentage = 0;
  44628. this.panningSensibility = 1000.0;
  44629. this.multiTouchPanning = true;
  44630. this.multiTouchPanAndZoom = true;
  44631. this._isPanClick = false;
  44632. this.pinchInwards = true;
  44633. }
  44634. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44635. var _this = this;
  44636. var engine = this.camera.getEngine();
  44637. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44638. var pointA = null;
  44639. var pointB = null;
  44640. var previousPinchSquaredDistance = 0;
  44641. var initialDistance = 0;
  44642. var twoFingerActivityCount = 0;
  44643. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44644. this._pointerInput = function (p, s) {
  44645. var evt = p.event;
  44646. var isTouch = p.event.pointerType === "touch";
  44647. if (engine.isInVRExclusivePointerMode) {
  44648. return;
  44649. }
  44650. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44651. return;
  44652. }
  44653. var srcElement = (evt.srcElement || evt.target);
  44654. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44655. try {
  44656. srcElement.setPointerCapture(evt.pointerId);
  44657. }
  44658. catch (e) {
  44659. //Nothing to do with the error. Execution will continue.
  44660. }
  44661. // Manage panning with pan button click
  44662. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44663. // manage pointers
  44664. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44665. if (pointA === null) {
  44666. pointA = cacheSoloPointer;
  44667. }
  44668. else if (pointB === null) {
  44669. pointB = cacheSoloPointer;
  44670. }
  44671. if (!noPreventDefault) {
  44672. evt.preventDefault();
  44673. element.focus();
  44674. }
  44675. }
  44676. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44677. _this.camera.restoreState();
  44678. }
  44679. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44680. try {
  44681. srcElement.releasePointerCapture(evt.pointerId);
  44682. }
  44683. catch (e) {
  44684. //Nothing to do with the error.
  44685. }
  44686. cacheSoloPointer = null;
  44687. previousPinchSquaredDistance = 0;
  44688. previousMultiTouchPanPosition.isPaning = false;
  44689. previousMultiTouchPanPosition.isPinching = false;
  44690. twoFingerActivityCount = 0;
  44691. initialDistance = 0;
  44692. if (!isTouch) {
  44693. pointB = null; // Mouse and pen are mono pointer
  44694. }
  44695. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44696. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44697. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44698. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44699. if (engine.badOS) {
  44700. pointA = pointB = null;
  44701. }
  44702. else {
  44703. //only remove the impacted pointer in case of multitouch allowing on most
  44704. //platforms switching from rotate to zoom and pan seamlessly.
  44705. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44706. pointA = pointB;
  44707. pointB = null;
  44708. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44709. }
  44710. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44711. pointB = null;
  44712. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44713. }
  44714. else {
  44715. pointA = pointB = null;
  44716. }
  44717. }
  44718. if (!noPreventDefault) {
  44719. evt.preventDefault();
  44720. }
  44721. }
  44722. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44723. if (!noPreventDefault) {
  44724. evt.preventDefault();
  44725. }
  44726. // One button down
  44727. if (pointA && pointB === null && cacheSoloPointer) {
  44728. if (_this.panningSensibility !== 0 &&
  44729. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44730. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44731. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44732. }
  44733. else {
  44734. var offsetX = evt.clientX - cacheSoloPointer.x;
  44735. var offsetY = evt.clientY - cacheSoloPointer.y;
  44736. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44737. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44738. }
  44739. cacheSoloPointer.x = evt.clientX;
  44740. cacheSoloPointer.y = evt.clientY;
  44741. }
  44742. else if (pointA && pointB) {
  44743. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44744. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44745. ed.x = evt.clientX;
  44746. ed.y = evt.clientY;
  44747. var direction = _this.pinchInwards ? 1 : -1;
  44748. var distX = pointA.x - pointB.x;
  44749. var distY = pointA.y - pointB.y;
  44750. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44751. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44752. if (previousPinchSquaredDistance === 0) {
  44753. initialDistance = pinchDistance;
  44754. previousPinchSquaredDistance = pinchSquaredDistance;
  44755. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44756. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44757. return;
  44758. }
  44759. if (_this.multiTouchPanAndZoom) {
  44760. if (_this.pinchDeltaPercentage) {
  44761. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44762. }
  44763. else {
  44764. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44765. (_this.pinchPrecision *
  44766. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44767. direction);
  44768. }
  44769. if (_this.panningSensibility !== 0) {
  44770. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44771. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44772. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44773. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44774. previousMultiTouchPanPosition.x = pointersCenterX;
  44775. previousMultiTouchPanPosition.y = pointersCenterY;
  44776. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44777. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44778. }
  44779. }
  44780. else {
  44781. twoFingerActivityCount++;
  44782. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44783. if (_this.pinchDeltaPercentage) {
  44784. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44785. }
  44786. else {
  44787. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44788. (_this.pinchPrecision *
  44789. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44790. direction);
  44791. }
  44792. previousMultiTouchPanPosition.isPaning = false;
  44793. previousMultiTouchPanPosition.isPinching = true;
  44794. }
  44795. else {
  44796. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44797. if (!previousMultiTouchPanPosition.isPaning) {
  44798. previousMultiTouchPanPosition.isPaning = true;
  44799. previousMultiTouchPanPosition.isPinching = false;
  44800. previousMultiTouchPanPosition.x = ed.x;
  44801. previousMultiTouchPanPosition.y = ed.y;
  44802. return;
  44803. }
  44804. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44805. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44806. }
  44807. }
  44808. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44809. previousMultiTouchPanPosition.x = ed.x;
  44810. previousMultiTouchPanPosition.y = ed.y;
  44811. }
  44812. }
  44813. previousPinchSquaredDistance = pinchSquaredDistance;
  44814. }
  44815. }
  44816. };
  44817. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44818. this._onContextMenu = function (evt) {
  44819. evt.preventDefault();
  44820. };
  44821. if (!this.camera._useCtrlForPanning) {
  44822. element.addEventListener("contextmenu", this._onContextMenu, false);
  44823. }
  44824. this._onLostFocus = function () {
  44825. //this._keys = [];
  44826. pointA = pointB = null;
  44827. previousPinchSquaredDistance = 0;
  44828. previousMultiTouchPanPosition.isPaning = false;
  44829. previousMultiTouchPanPosition.isPinching = false;
  44830. twoFingerActivityCount = 0;
  44831. cacheSoloPointer = null;
  44832. initialDistance = 0;
  44833. };
  44834. this._onMouseMove = function (evt) {
  44835. if (!engine.isPointerLock) {
  44836. return;
  44837. }
  44838. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44839. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44840. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44841. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44842. if (!noPreventDefault) {
  44843. evt.preventDefault();
  44844. }
  44845. };
  44846. this._onGestureStart = function (e) {
  44847. if (window.MSGesture === undefined) {
  44848. return;
  44849. }
  44850. if (!_this._MSGestureHandler) {
  44851. _this._MSGestureHandler = new MSGesture();
  44852. _this._MSGestureHandler.target = element;
  44853. }
  44854. _this._MSGestureHandler.addPointer(e.pointerId);
  44855. };
  44856. this._onGesture = function (e) {
  44857. _this.camera.radius *= e.scale;
  44858. if (e.preventDefault) {
  44859. if (!noPreventDefault) {
  44860. e.stopPropagation();
  44861. e.preventDefault();
  44862. }
  44863. }
  44864. };
  44865. element.addEventListener("mousemove", this._onMouseMove, false);
  44866. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44867. element.addEventListener("MSGestureChange", this._onGesture, false);
  44868. BABYLON.Tools.RegisterTopRootEvents([
  44869. { name: "blur", handler: this._onLostFocus }
  44870. ]);
  44871. };
  44872. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44873. if (this._onLostFocus) {
  44874. BABYLON.Tools.UnregisterTopRootEvents([
  44875. { name: "blur", handler: this._onLostFocus }
  44876. ]);
  44877. }
  44878. if (element && this._observer) {
  44879. this.camera.getScene().onPointerObservable.remove(this._observer);
  44880. this._observer = null;
  44881. if (this._onContextMenu) {
  44882. element.removeEventListener("contextmenu", this._onContextMenu);
  44883. }
  44884. if (this._onMouseMove) {
  44885. element.removeEventListener("mousemove", this._onMouseMove);
  44886. }
  44887. if (this._onGestureStart) {
  44888. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44889. }
  44890. if (this._onGesture) {
  44891. element.removeEventListener("MSGestureChange", this._onGesture);
  44892. }
  44893. this._isPanClick = false;
  44894. this.pinchInwards = true;
  44895. this._onMouseMove = null;
  44896. this._onGestureStart = null;
  44897. this._onGesture = null;
  44898. this._MSGestureHandler = null;
  44899. this._onLostFocus = null;
  44900. this._onContextMenu = null;
  44901. }
  44902. };
  44903. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44904. return "ArcRotateCameraPointersInput";
  44905. };
  44906. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44907. return "pointers";
  44908. };
  44909. __decorate([
  44910. BABYLON.serialize()
  44911. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44912. __decorate([
  44913. BABYLON.serialize()
  44914. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44915. __decorate([
  44916. BABYLON.serialize()
  44917. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44918. __decorate([
  44919. BABYLON.serialize()
  44920. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44921. __decorate([
  44922. BABYLON.serialize()
  44923. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44924. __decorate([
  44925. BABYLON.serialize()
  44926. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44927. __decorate([
  44928. BABYLON.serialize()
  44929. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44930. __decorate([
  44931. BABYLON.serialize()
  44932. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44933. return ArcRotateCameraPointersInput;
  44934. }());
  44935. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44936. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44937. })(BABYLON || (BABYLON = {}));
  44938. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44939. "use strict";
  44940. var BABYLON;
  44941. (function (BABYLON) {
  44942. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44943. __extends(ArcRotateCameraInputsManager, _super);
  44944. function ArcRotateCameraInputsManager(camera) {
  44945. return _super.call(this, camera) || this;
  44946. }
  44947. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44948. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44949. return this;
  44950. };
  44951. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44952. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44953. return this;
  44954. };
  44955. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44956. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44957. return this;
  44958. };
  44959. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44960. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44961. return this;
  44962. };
  44963. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44964. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44965. return this;
  44966. };
  44967. return ArcRotateCameraInputsManager;
  44968. }(BABYLON.CameraInputsManager));
  44969. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44970. })(BABYLON || (BABYLON = {}));
  44971. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44972. "use strict";
  44973. var BABYLON;
  44974. (function (BABYLON) {
  44975. var ArcRotateCamera = /** @class */ (function (_super) {
  44976. __extends(ArcRotateCamera, _super);
  44977. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44978. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44979. _this.inertialAlphaOffset = 0;
  44980. _this.inertialBetaOffset = 0;
  44981. _this.inertialRadiusOffset = 0;
  44982. _this.lowerAlphaLimit = null;
  44983. _this.upperAlphaLimit = null;
  44984. _this.lowerBetaLimit = 0.01;
  44985. _this.upperBetaLimit = Math.PI;
  44986. _this.lowerRadiusLimit = null;
  44987. _this.upperRadiusLimit = null;
  44988. _this.inertialPanningX = 0;
  44989. _this.inertialPanningY = 0;
  44990. _this.pinchToPanMaxDistance = 20;
  44991. _this.panningDistanceLimit = null;
  44992. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44993. _this.panningInertia = 0.9;
  44994. //-- end properties for backward compatibility for inputs
  44995. _this.zoomOnFactor = 1;
  44996. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44997. _this.allowUpsideDown = true;
  44998. _this._viewMatrix = new BABYLON.Matrix();
  44999. // Panning
  45000. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  45001. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  45002. _this.checkCollisions = false;
  45003. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45004. _this._previousPosition = BABYLON.Vector3.Zero();
  45005. _this._collisionVelocity = BABYLON.Vector3.Zero();
  45006. _this._newPosition = BABYLON.Vector3.Zero();
  45007. _this._computationVector = BABYLON.Vector3.Zero();
  45008. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  45009. if (collidedMesh === void 0) { collidedMesh = null; }
  45010. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  45011. newPosition.multiplyInPlace(_this._collider._radius);
  45012. }
  45013. if (!collidedMesh) {
  45014. _this._previousPosition.copyFrom(_this.position);
  45015. }
  45016. else {
  45017. _this.setPosition(newPosition);
  45018. if (_this.onCollide) {
  45019. _this.onCollide(collidedMesh);
  45020. }
  45021. }
  45022. // Recompute because of constraints
  45023. var cosa = Math.cos(_this.alpha);
  45024. var sina = Math.sin(_this.alpha);
  45025. var cosb = Math.cos(_this.beta);
  45026. var sinb = Math.sin(_this.beta);
  45027. if (sinb === 0) {
  45028. sinb = 0.0001;
  45029. }
  45030. var target = _this._getTargetPosition();
  45031. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  45032. target.addToRef(_this._computationVector, _this._newPosition);
  45033. _this.position.copyFrom(_this._newPosition);
  45034. var up = _this.upVector;
  45035. if (_this.allowUpsideDown && _this.beta < 0) {
  45036. up = up.clone();
  45037. up = up.negate();
  45038. }
  45039. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  45040. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  45041. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  45042. _this._collisionTriggered = false;
  45043. };
  45044. _this._target = BABYLON.Vector3.Zero();
  45045. if (target) {
  45046. _this.setTarget(target);
  45047. }
  45048. _this.alpha = alpha;
  45049. _this.beta = beta;
  45050. _this.radius = radius;
  45051. _this.getViewMatrix();
  45052. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  45053. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  45054. return _this;
  45055. }
  45056. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  45057. get: function () {
  45058. return this._target;
  45059. },
  45060. set: function (value) {
  45061. this.setTarget(value);
  45062. },
  45063. enumerable: true,
  45064. configurable: true
  45065. });
  45066. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  45067. //-- begin properties for backward compatibility for inputs
  45068. get: function () {
  45069. var pointers = this.inputs.attached["pointers"];
  45070. if (pointers)
  45071. return pointers.angularSensibilityX;
  45072. return 0;
  45073. },
  45074. set: function (value) {
  45075. var pointers = this.inputs.attached["pointers"];
  45076. if (pointers) {
  45077. pointers.angularSensibilityX = value;
  45078. }
  45079. },
  45080. enumerable: true,
  45081. configurable: true
  45082. });
  45083. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45084. get: function () {
  45085. var pointers = this.inputs.attached["pointers"];
  45086. if (pointers)
  45087. return pointers.angularSensibilityY;
  45088. return 0;
  45089. },
  45090. set: function (value) {
  45091. var pointers = this.inputs.attached["pointers"];
  45092. if (pointers) {
  45093. pointers.angularSensibilityY = value;
  45094. }
  45095. },
  45096. enumerable: true,
  45097. configurable: true
  45098. });
  45099. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45100. get: function () {
  45101. var pointers = this.inputs.attached["pointers"];
  45102. if (pointers)
  45103. return pointers.pinchPrecision;
  45104. return 0;
  45105. },
  45106. set: function (value) {
  45107. var pointers = this.inputs.attached["pointers"];
  45108. if (pointers) {
  45109. pointers.pinchPrecision = value;
  45110. }
  45111. },
  45112. enumerable: true,
  45113. configurable: true
  45114. });
  45115. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45116. get: function () {
  45117. var pointers = this.inputs.attached["pointers"];
  45118. if (pointers)
  45119. return pointers.pinchDeltaPercentage;
  45120. return 0;
  45121. },
  45122. set: function (value) {
  45123. var pointers = this.inputs.attached["pointers"];
  45124. if (pointers) {
  45125. pointers.pinchDeltaPercentage = value;
  45126. }
  45127. },
  45128. enumerable: true,
  45129. configurable: true
  45130. });
  45131. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45132. get: function () {
  45133. var pointers = this.inputs.attached["pointers"];
  45134. if (pointers)
  45135. return pointers.panningSensibility;
  45136. return 0;
  45137. },
  45138. set: function (value) {
  45139. var pointers = this.inputs.attached["pointers"];
  45140. if (pointers) {
  45141. pointers.panningSensibility = value;
  45142. }
  45143. },
  45144. enumerable: true,
  45145. configurable: true
  45146. });
  45147. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45148. get: function () {
  45149. var keyboard = this.inputs.attached["keyboard"];
  45150. if (keyboard)
  45151. return keyboard.keysUp;
  45152. return [];
  45153. },
  45154. set: function (value) {
  45155. var keyboard = this.inputs.attached["keyboard"];
  45156. if (keyboard)
  45157. keyboard.keysUp = value;
  45158. },
  45159. enumerable: true,
  45160. configurable: true
  45161. });
  45162. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45163. get: function () {
  45164. var keyboard = this.inputs.attached["keyboard"];
  45165. if (keyboard)
  45166. return keyboard.keysDown;
  45167. return [];
  45168. },
  45169. set: function (value) {
  45170. var keyboard = this.inputs.attached["keyboard"];
  45171. if (keyboard)
  45172. keyboard.keysDown = value;
  45173. },
  45174. enumerable: true,
  45175. configurable: true
  45176. });
  45177. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45178. get: function () {
  45179. var keyboard = this.inputs.attached["keyboard"];
  45180. if (keyboard)
  45181. return keyboard.keysLeft;
  45182. return [];
  45183. },
  45184. set: function (value) {
  45185. var keyboard = this.inputs.attached["keyboard"];
  45186. if (keyboard)
  45187. keyboard.keysLeft = value;
  45188. },
  45189. enumerable: true,
  45190. configurable: true
  45191. });
  45192. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45193. get: function () {
  45194. var keyboard = this.inputs.attached["keyboard"];
  45195. if (keyboard)
  45196. return keyboard.keysRight;
  45197. return [];
  45198. },
  45199. set: function (value) {
  45200. var keyboard = this.inputs.attached["keyboard"];
  45201. if (keyboard)
  45202. keyboard.keysRight = value;
  45203. },
  45204. enumerable: true,
  45205. configurable: true
  45206. });
  45207. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45208. get: function () {
  45209. var mousewheel = this.inputs.attached["mousewheel"];
  45210. if (mousewheel)
  45211. return mousewheel.wheelPrecision;
  45212. return 0;
  45213. },
  45214. set: function (value) {
  45215. var mousewheel = this.inputs.attached["mousewheel"];
  45216. if (mousewheel)
  45217. mousewheel.wheelPrecision = value;
  45218. },
  45219. enumerable: true,
  45220. configurable: true
  45221. });
  45222. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45223. get: function () {
  45224. var mousewheel = this.inputs.attached["mousewheel"];
  45225. if (mousewheel)
  45226. return mousewheel.wheelDeltaPercentage;
  45227. return 0;
  45228. },
  45229. set: function (value) {
  45230. var mousewheel = this.inputs.attached["mousewheel"];
  45231. if (mousewheel)
  45232. mousewheel.wheelDeltaPercentage = value;
  45233. },
  45234. enumerable: true,
  45235. configurable: true
  45236. });
  45237. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45238. get: function () {
  45239. return this._bouncingBehavior;
  45240. },
  45241. enumerable: true,
  45242. configurable: true
  45243. });
  45244. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45245. get: function () {
  45246. return this._bouncingBehavior != null;
  45247. },
  45248. set: function (value) {
  45249. if (value === this.useBouncingBehavior) {
  45250. return;
  45251. }
  45252. if (value) {
  45253. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45254. this.addBehavior(this._bouncingBehavior);
  45255. }
  45256. else if (this._bouncingBehavior) {
  45257. this.removeBehavior(this._bouncingBehavior);
  45258. this._bouncingBehavior = null;
  45259. }
  45260. },
  45261. enumerable: true,
  45262. configurable: true
  45263. });
  45264. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45265. get: function () {
  45266. return this._framingBehavior;
  45267. },
  45268. enumerable: true,
  45269. configurable: true
  45270. });
  45271. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45272. get: function () {
  45273. return this._framingBehavior != null;
  45274. },
  45275. set: function (value) {
  45276. if (value === this.useFramingBehavior) {
  45277. return;
  45278. }
  45279. if (value) {
  45280. this._framingBehavior = new BABYLON.FramingBehavior();
  45281. this.addBehavior(this._framingBehavior);
  45282. }
  45283. else if (this._framingBehavior) {
  45284. this.removeBehavior(this._framingBehavior);
  45285. this._framingBehavior = null;
  45286. }
  45287. },
  45288. enumerable: true,
  45289. configurable: true
  45290. });
  45291. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45292. get: function () {
  45293. return this._autoRotationBehavior;
  45294. },
  45295. enumerable: true,
  45296. configurable: true
  45297. });
  45298. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45299. get: function () {
  45300. return this._autoRotationBehavior != null;
  45301. },
  45302. set: function (value) {
  45303. if (value === this.useAutoRotationBehavior) {
  45304. return;
  45305. }
  45306. if (value) {
  45307. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45308. this.addBehavior(this._autoRotationBehavior);
  45309. }
  45310. else if (this._autoRotationBehavior) {
  45311. this.removeBehavior(this._autoRotationBehavior);
  45312. this._autoRotationBehavior = null;
  45313. }
  45314. },
  45315. enumerable: true,
  45316. configurable: true
  45317. });
  45318. // Cache
  45319. ArcRotateCamera.prototype._initCache = function () {
  45320. _super.prototype._initCache.call(this);
  45321. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45322. this._cache.alpha = undefined;
  45323. this._cache.beta = undefined;
  45324. this._cache.radius = undefined;
  45325. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45326. };
  45327. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45328. if (!ignoreParentClass) {
  45329. _super.prototype._updateCache.call(this);
  45330. }
  45331. this._cache._target.copyFrom(this._getTargetPosition());
  45332. this._cache.alpha = this.alpha;
  45333. this._cache.beta = this.beta;
  45334. this._cache.radius = this.radius;
  45335. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45336. };
  45337. ArcRotateCamera.prototype._getTargetPosition = function () {
  45338. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45339. var pos = this._targetHost.getAbsolutePosition();
  45340. if (this._targetBoundingCenter) {
  45341. pos.addToRef(this._targetBoundingCenter, this._target);
  45342. }
  45343. else {
  45344. this._target.copyFrom(pos);
  45345. }
  45346. }
  45347. var lockedTargetPosition = this._getLockedTargetPosition();
  45348. if (lockedTargetPosition) {
  45349. return lockedTargetPosition;
  45350. }
  45351. return this._target;
  45352. };
  45353. ArcRotateCamera.prototype.storeState = function () {
  45354. this._storedAlpha = this.alpha;
  45355. this._storedBeta = this.beta;
  45356. this._storedRadius = this.radius;
  45357. this._storedTarget = this._getTargetPosition().clone();
  45358. return _super.prototype.storeState.call(this);
  45359. };
  45360. /**
  45361. * Restored camera state. You must call storeState() first
  45362. */
  45363. ArcRotateCamera.prototype._restoreStateValues = function () {
  45364. if (!_super.prototype._restoreStateValues.call(this)) {
  45365. return false;
  45366. }
  45367. this.alpha = this._storedAlpha;
  45368. this.beta = this._storedBeta;
  45369. this.radius = this._storedRadius;
  45370. this.setTarget(this._storedTarget.clone());
  45371. this.inertialAlphaOffset = 0;
  45372. this.inertialBetaOffset = 0;
  45373. this.inertialRadiusOffset = 0;
  45374. this.inertialPanningX = 0;
  45375. this.inertialPanningY = 0;
  45376. return true;
  45377. };
  45378. // Synchronized
  45379. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45380. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45381. return false;
  45382. return this._cache._target.equals(this._getTargetPosition())
  45383. && this._cache.alpha === this.alpha
  45384. && this._cache.beta === this.beta
  45385. && this._cache.radius === this.radius
  45386. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45387. };
  45388. // Methods
  45389. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45390. var _this = this;
  45391. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45392. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45393. this._useCtrlForPanning = useCtrlForPanning;
  45394. this._panningMouseButton = panningMouseButton;
  45395. this.inputs.attachElement(element, noPreventDefault);
  45396. this._reset = function () {
  45397. _this.inertialAlphaOffset = 0;
  45398. _this.inertialBetaOffset = 0;
  45399. _this.inertialRadiusOffset = 0;
  45400. _this.inertialPanningX = 0;
  45401. _this.inertialPanningY = 0;
  45402. };
  45403. };
  45404. ArcRotateCamera.prototype.detachControl = function (element) {
  45405. this.inputs.detachElement(element);
  45406. if (this._reset) {
  45407. this._reset();
  45408. }
  45409. };
  45410. ArcRotateCamera.prototype._checkInputs = function () {
  45411. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45412. if (this._collisionTriggered) {
  45413. return;
  45414. }
  45415. this.inputs.checkInputs();
  45416. // Inertia
  45417. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45418. if (this.getScene().useRightHandedSystem) {
  45419. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45420. }
  45421. else {
  45422. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45423. }
  45424. this.beta += this.inertialBetaOffset;
  45425. this.radius -= this.inertialRadiusOffset;
  45426. this.inertialAlphaOffset *= this.inertia;
  45427. this.inertialBetaOffset *= this.inertia;
  45428. this.inertialRadiusOffset *= this.inertia;
  45429. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45430. this.inertialAlphaOffset = 0;
  45431. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45432. this.inertialBetaOffset = 0;
  45433. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45434. this.inertialRadiusOffset = 0;
  45435. }
  45436. // Panning inertia
  45437. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45438. if (!this._localDirection) {
  45439. this._localDirection = BABYLON.Vector3.Zero();
  45440. this._transformedDirection = BABYLON.Vector3.Zero();
  45441. }
  45442. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45443. this._localDirection.multiplyInPlace(this.panningAxis);
  45444. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45445. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45446. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45447. if (!this.panningAxis.y) {
  45448. this._transformedDirection.y = 0;
  45449. }
  45450. if (!this._targetHost) {
  45451. if (this.panningDistanceLimit) {
  45452. this._transformedDirection.addInPlace(this._target);
  45453. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45454. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45455. this._target.copyFrom(this._transformedDirection);
  45456. }
  45457. }
  45458. else {
  45459. this._target.addInPlace(this._transformedDirection);
  45460. }
  45461. }
  45462. this.inertialPanningX *= this.panningInertia;
  45463. this.inertialPanningY *= this.panningInertia;
  45464. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45465. this.inertialPanningX = 0;
  45466. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45467. this.inertialPanningY = 0;
  45468. }
  45469. // Limits
  45470. this._checkLimits();
  45471. _super.prototype._checkInputs.call(this);
  45472. };
  45473. ArcRotateCamera.prototype._checkLimits = function () {
  45474. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45475. if (this.allowUpsideDown && this.beta > Math.PI) {
  45476. this.beta = this.beta - (2 * Math.PI);
  45477. }
  45478. }
  45479. else {
  45480. if (this.beta < this.lowerBetaLimit) {
  45481. this.beta = this.lowerBetaLimit;
  45482. }
  45483. }
  45484. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45485. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45486. this.beta = this.beta + (2 * Math.PI);
  45487. }
  45488. }
  45489. else {
  45490. if (this.beta > this.upperBetaLimit) {
  45491. this.beta = this.upperBetaLimit;
  45492. }
  45493. }
  45494. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45495. this.alpha = this.lowerAlphaLimit;
  45496. }
  45497. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45498. this.alpha = this.upperAlphaLimit;
  45499. }
  45500. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45501. this.radius = this.lowerRadiusLimit;
  45502. }
  45503. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45504. this.radius = this.upperRadiusLimit;
  45505. }
  45506. };
  45507. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45508. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45509. this.radius = this._computationVector.length();
  45510. if (this.radius === 0) {
  45511. this.radius = 0.0001; // Just to avoid division by zero
  45512. }
  45513. // Alpha
  45514. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45515. if (this._computationVector.z < 0) {
  45516. this.alpha = 2 * Math.PI - this.alpha;
  45517. }
  45518. // Beta
  45519. this.beta = Math.acos(this._computationVector.y / this.radius);
  45520. this._checkLimits();
  45521. };
  45522. ArcRotateCamera.prototype.setPosition = function (position) {
  45523. if (this.position.equals(position)) {
  45524. return;
  45525. }
  45526. this.position.copyFrom(position);
  45527. this.rebuildAnglesAndRadius();
  45528. };
  45529. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45530. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45531. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45532. if (target.getBoundingInfo) {
  45533. if (toBoundingCenter) {
  45534. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45535. }
  45536. else {
  45537. this._targetBoundingCenter = null;
  45538. }
  45539. this._targetHost = target;
  45540. this._target = this._getTargetPosition();
  45541. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45542. }
  45543. else {
  45544. var newTarget = target;
  45545. var currentTarget = this._getTargetPosition();
  45546. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45547. return;
  45548. }
  45549. this._targetHost = null;
  45550. this._target = newTarget;
  45551. this._targetBoundingCenter = null;
  45552. this.onMeshTargetChangedObservable.notifyObservers(null);
  45553. }
  45554. this.rebuildAnglesAndRadius();
  45555. };
  45556. ArcRotateCamera.prototype._getViewMatrix = function () {
  45557. // Compute
  45558. var cosa = Math.cos(this.alpha);
  45559. var sina = Math.sin(this.alpha);
  45560. var cosb = Math.cos(this.beta);
  45561. var sinb = Math.sin(this.beta);
  45562. if (sinb === 0) {
  45563. sinb = 0.0001;
  45564. }
  45565. var target = this._getTargetPosition();
  45566. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45567. target.addToRef(this._computationVector, this._newPosition);
  45568. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45569. if (!this._collider) {
  45570. this._collider = new BABYLON.Collider();
  45571. }
  45572. this._collider._radius = this.collisionRadius;
  45573. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45574. this._collisionTriggered = true;
  45575. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45576. }
  45577. else {
  45578. this.position.copyFrom(this._newPosition);
  45579. var up = this.upVector;
  45580. if (this.allowUpsideDown && sinb < 0) {
  45581. up = up.clone();
  45582. up = up.negate();
  45583. }
  45584. if (this.getScene().useRightHandedSystem) {
  45585. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45586. }
  45587. else {
  45588. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45589. }
  45590. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45591. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45592. }
  45593. this._currentTarget = target;
  45594. return this._viewMatrix;
  45595. };
  45596. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45597. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45598. meshes = meshes || this.getScene().meshes;
  45599. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45600. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45601. this.radius = distance * this.zoomOnFactor;
  45602. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45603. };
  45604. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45605. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45606. var meshesOrMinMaxVector;
  45607. var distance;
  45608. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45609. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45610. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45611. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45612. }
  45613. else {
  45614. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45615. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45616. distance = minMaxVectorAndDistance.distance;
  45617. }
  45618. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45619. if (!doNotUpdateMaxZ) {
  45620. this.maxZ = distance * 2;
  45621. }
  45622. };
  45623. /**
  45624. * @override
  45625. * Override Camera.createRigCamera
  45626. */
  45627. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45628. var alphaShift = 0;
  45629. switch (this.cameraRigMode) {
  45630. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45631. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45632. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45633. case BABYLON.Camera.RIG_MODE_VR:
  45634. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45635. break;
  45636. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45637. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45638. break;
  45639. }
  45640. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45641. rigCam._cameraRigParams = {};
  45642. return rigCam;
  45643. };
  45644. /**
  45645. * @override
  45646. * Override Camera._updateRigCameras
  45647. */
  45648. ArcRotateCamera.prototype._updateRigCameras = function () {
  45649. var camLeft = this._rigCameras[0];
  45650. var camRight = this._rigCameras[1];
  45651. camLeft.beta = camRight.beta = this.beta;
  45652. camLeft.radius = camRight.radius = this.radius;
  45653. switch (this.cameraRigMode) {
  45654. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45655. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45656. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45657. case BABYLON.Camera.RIG_MODE_VR:
  45658. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45659. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45660. break;
  45661. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45662. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45663. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45664. break;
  45665. }
  45666. _super.prototype._updateRigCameras.call(this);
  45667. };
  45668. ArcRotateCamera.prototype.dispose = function () {
  45669. this.inputs.clear();
  45670. _super.prototype.dispose.call(this);
  45671. };
  45672. ArcRotateCamera.prototype.getClassName = function () {
  45673. return "ArcRotateCamera";
  45674. };
  45675. __decorate([
  45676. BABYLON.serialize()
  45677. ], ArcRotateCamera.prototype, "alpha", void 0);
  45678. __decorate([
  45679. BABYLON.serialize()
  45680. ], ArcRotateCamera.prototype, "beta", void 0);
  45681. __decorate([
  45682. BABYLON.serialize()
  45683. ], ArcRotateCamera.prototype, "radius", void 0);
  45684. __decorate([
  45685. BABYLON.serializeAsVector3("target")
  45686. ], ArcRotateCamera.prototype, "_target", void 0);
  45687. __decorate([
  45688. BABYLON.serialize()
  45689. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45690. __decorate([
  45691. BABYLON.serialize()
  45692. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45693. __decorate([
  45694. BABYLON.serialize()
  45695. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45696. __decorate([
  45697. BABYLON.serialize()
  45698. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45699. __decorate([
  45700. BABYLON.serialize()
  45701. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45702. __decorate([
  45703. BABYLON.serialize()
  45704. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45705. __decorate([
  45706. BABYLON.serialize()
  45707. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45708. __decorate([
  45709. BABYLON.serialize()
  45710. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45711. __decorate([
  45712. BABYLON.serialize()
  45713. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45714. __decorate([
  45715. BABYLON.serialize()
  45716. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45717. __decorate([
  45718. BABYLON.serialize()
  45719. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45720. __decorate([
  45721. BABYLON.serialize()
  45722. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45723. __decorate([
  45724. BABYLON.serialize()
  45725. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45726. __decorate([
  45727. BABYLON.serializeAsVector3()
  45728. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45729. __decorate([
  45730. BABYLON.serialize()
  45731. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45732. __decorate([
  45733. BABYLON.serialize()
  45734. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45735. __decorate([
  45736. BABYLON.serialize()
  45737. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45738. return ArcRotateCamera;
  45739. }(BABYLON.TargetCamera));
  45740. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45741. })(BABYLON || (BABYLON = {}));
  45742. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45743. "use strict";
  45744. var BABYLON;
  45745. (function (BABYLON) {
  45746. /**
  45747. * The HemisphericLight simulates the ambient environment light,
  45748. * so the passed direction is the light reflection direction, not the incoming direction.
  45749. */
  45750. var HemisphericLight = /** @class */ (function (_super) {
  45751. __extends(HemisphericLight, _super);
  45752. /**
  45753. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45754. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45755. * The HemisphericLight can't cast shadows.
  45756. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45757. * @param name The friendly name of the light
  45758. * @param direction The direction of the light reflection
  45759. * @param scene The scene the light belongs to
  45760. */
  45761. function HemisphericLight(name, direction, scene) {
  45762. var _this = _super.call(this, name, scene) || this;
  45763. /**
  45764. * The groundColor is the light in the opposite direction to the one specified during creation.
  45765. * 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.
  45766. */
  45767. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45768. _this.direction = direction || BABYLON.Vector3.Up();
  45769. return _this;
  45770. }
  45771. HemisphericLight.prototype._buildUniformLayout = function () {
  45772. this._uniformBuffer.addUniform("vLightData", 4);
  45773. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45774. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45775. this._uniformBuffer.addUniform("vLightGround", 3);
  45776. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45777. this._uniformBuffer.addUniform("depthValues", 2);
  45778. this._uniformBuffer.create();
  45779. };
  45780. /**
  45781. * Returns the string "HemisphericLight".
  45782. * @return The class name
  45783. */
  45784. HemisphericLight.prototype.getClassName = function () {
  45785. return "HemisphericLight";
  45786. };
  45787. /**
  45788. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45789. * Returns the updated direction.
  45790. * @param target The target the direction should point to
  45791. * @return The computed direction
  45792. */
  45793. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45794. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45795. return this.direction;
  45796. };
  45797. /**
  45798. * Returns the shadow generator associated to the light.
  45799. * @returns Always null for hemispheric lights because it does not support shadows.
  45800. */
  45801. HemisphericLight.prototype.getShadowGenerator = function () {
  45802. return null;
  45803. };
  45804. /**
  45805. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45806. * @param effect The effect to update
  45807. * @param lightIndex The index of the light in the effect to update
  45808. * @returns The hemispheric light
  45809. */
  45810. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45811. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45812. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45813. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45814. return this;
  45815. };
  45816. /**
  45817. * @ignore internal use only.
  45818. */
  45819. HemisphericLight.prototype._getWorldMatrix = function () {
  45820. if (!this._worldMatrix) {
  45821. this._worldMatrix = BABYLON.Matrix.Identity();
  45822. }
  45823. return this._worldMatrix;
  45824. };
  45825. /**
  45826. * Returns the integer 3.
  45827. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45828. */
  45829. HemisphericLight.prototype.getTypeID = function () {
  45830. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45831. };
  45832. __decorate([
  45833. BABYLON.serializeAsColor3()
  45834. ], HemisphericLight.prototype, "groundColor", void 0);
  45835. __decorate([
  45836. BABYLON.serializeAsVector3()
  45837. ], HemisphericLight.prototype, "direction", void 0);
  45838. return HemisphericLight;
  45839. }(BABYLON.Light));
  45840. BABYLON.HemisphericLight = HemisphericLight;
  45841. })(BABYLON || (BABYLON = {}));
  45842. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45843. "use strict";
  45844. var BABYLON;
  45845. (function (BABYLON) {
  45846. /**
  45847. * Base implementation of @see IShadowLight
  45848. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45849. */
  45850. var ShadowLight = /** @class */ (function (_super) {
  45851. __extends(ShadowLight, _super);
  45852. function ShadowLight() {
  45853. var _this = _super !== null && _super.apply(this, arguments) || this;
  45854. _this._needProjectionMatrixCompute = true;
  45855. return _this;
  45856. }
  45857. ShadowLight.prototype._setPosition = function (value) {
  45858. this._position = value;
  45859. };
  45860. Object.defineProperty(ShadowLight.prototype, "position", {
  45861. /**
  45862. * Sets the position the shadow will be casted from. Also use as the light position for both
  45863. * point and spot lights.
  45864. */
  45865. get: function () {
  45866. return this._position;
  45867. },
  45868. /**
  45869. * Sets the position the shadow will be casted from. Also use as the light position for both
  45870. * point and spot lights.
  45871. */
  45872. set: function (value) {
  45873. this._setPosition(value);
  45874. },
  45875. enumerable: true,
  45876. configurable: true
  45877. });
  45878. ShadowLight.prototype._setDirection = function (value) {
  45879. this._direction = value;
  45880. };
  45881. Object.defineProperty(ShadowLight.prototype, "direction", {
  45882. /**
  45883. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45884. * Also use as the light direction on spot and directional lights.
  45885. */
  45886. get: function () {
  45887. return this._direction;
  45888. },
  45889. /**
  45890. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45891. * Also use as the light direction on spot and directional lights.
  45892. */
  45893. set: function (value) {
  45894. this._setDirection(value);
  45895. },
  45896. enumerable: true,
  45897. configurable: true
  45898. });
  45899. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45900. /**
  45901. * Gets the shadow projection clipping minimum z value.
  45902. */
  45903. get: function () {
  45904. return this._shadowMinZ;
  45905. },
  45906. /**
  45907. * Sets the shadow projection clipping minimum z value.
  45908. */
  45909. set: function (value) {
  45910. this._shadowMinZ = value;
  45911. this.forceProjectionMatrixCompute();
  45912. },
  45913. enumerable: true,
  45914. configurable: true
  45915. });
  45916. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45917. /**
  45918. * Sets the shadow projection clipping maximum z value.
  45919. */
  45920. get: function () {
  45921. return this._shadowMaxZ;
  45922. },
  45923. /**
  45924. * Gets the shadow projection clipping maximum z value.
  45925. */
  45926. set: function (value) {
  45927. this._shadowMaxZ = value;
  45928. this.forceProjectionMatrixCompute();
  45929. },
  45930. enumerable: true,
  45931. configurable: true
  45932. });
  45933. /**
  45934. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45935. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45936. */
  45937. ShadowLight.prototype.computeTransformedInformation = function () {
  45938. if (this.parent && this.parent.getWorldMatrix) {
  45939. if (!this.transformedPosition) {
  45940. this.transformedPosition = BABYLON.Vector3.Zero();
  45941. }
  45942. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45943. // In case the direction is present.
  45944. if (this.direction) {
  45945. if (!this.transformedDirection) {
  45946. this.transformedDirection = BABYLON.Vector3.Zero();
  45947. }
  45948. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45949. }
  45950. return true;
  45951. }
  45952. return false;
  45953. };
  45954. /**
  45955. * Return the depth scale used for the shadow map.
  45956. * @returns the depth scale.
  45957. */
  45958. ShadowLight.prototype.getDepthScale = function () {
  45959. return 50.0;
  45960. };
  45961. /**
  45962. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45963. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45964. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45965. */
  45966. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45967. return this.transformedDirection ? this.transformedDirection : this.direction;
  45968. };
  45969. /**
  45970. * Returns the ShadowLight absolute position in the World.
  45971. * @returns the position vector in world space
  45972. */
  45973. ShadowLight.prototype.getAbsolutePosition = function () {
  45974. return this.transformedPosition ? this.transformedPosition : this.position;
  45975. };
  45976. /**
  45977. * Sets the ShadowLight direction toward the passed target.
  45978. * @param target The point tot target in local space
  45979. * @returns the updated ShadowLight direction
  45980. */
  45981. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45982. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45983. return this.direction;
  45984. };
  45985. /**
  45986. * Returns the light rotation in euler definition.
  45987. * @returns the x y z rotation in local space.
  45988. */
  45989. ShadowLight.prototype.getRotation = function () {
  45990. this.direction.normalize();
  45991. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45992. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45993. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45994. };
  45995. /**
  45996. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45997. * @returns true if a cube texture needs to be use
  45998. */
  45999. ShadowLight.prototype.needCube = function () {
  46000. return false;
  46001. };
  46002. /**
  46003. * Detects if the projection matrix requires to be recomputed this frame.
  46004. * @returns true if it requires to be recomputed otherwise, false.
  46005. */
  46006. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  46007. return this._needProjectionMatrixCompute;
  46008. };
  46009. /**
  46010. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  46011. */
  46012. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  46013. this._needProjectionMatrixCompute = true;
  46014. };
  46015. /**
  46016. * Get the world matrix of the sahdow lights.
  46017. * @ignore Internal Use Only
  46018. */
  46019. ShadowLight.prototype._getWorldMatrix = function () {
  46020. if (!this._worldMatrix) {
  46021. this._worldMatrix = BABYLON.Matrix.Identity();
  46022. }
  46023. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  46024. return this._worldMatrix;
  46025. };
  46026. /**
  46027. * Gets the minZ used for shadow according to both the scene and the light.
  46028. * @param activeCamera The camera we are returning the min for
  46029. * @returns the depth min z
  46030. */
  46031. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  46032. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  46033. };
  46034. /**
  46035. * Gets the maxZ used for shadow according to both the scene and the light.
  46036. * @param activeCamera The camera we are returning the max for
  46037. * @returns the depth max z
  46038. */
  46039. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  46040. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  46041. };
  46042. /**
  46043. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  46044. * @param matrix The materix to updated with the projection information
  46045. * @param viewMatrix The transform matrix of the light
  46046. * @param renderList The list of mesh to render in the map
  46047. * @returns The current light
  46048. */
  46049. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46050. if (this.customProjectionMatrixBuilder) {
  46051. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  46052. }
  46053. else {
  46054. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46055. }
  46056. return this;
  46057. };
  46058. __decorate([
  46059. BABYLON.serializeAsVector3()
  46060. ], ShadowLight.prototype, "position", null);
  46061. __decorate([
  46062. BABYLON.serializeAsVector3()
  46063. ], ShadowLight.prototype, "direction", null);
  46064. __decorate([
  46065. BABYLON.serialize()
  46066. ], ShadowLight.prototype, "shadowMinZ", null);
  46067. __decorate([
  46068. BABYLON.serialize()
  46069. ], ShadowLight.prototype, "shadowMaxZ", null);
  46070. return ShadowLight;
  46071. }(BABYLON.Light));
  46072. BABYLON.ShadowLight = ShadowLight;
  46073. })(BABYLON || (BABYLON = {}));
  46074. //# sourceMappingURL=babylon.shadowLight.js.map
  46075. "use strict";
  46076. var BABYLON;
  46077. (function (BABYLON) {
  46078. /**
  46079. * A point light is a light defined by an unique point in world space.
  46080. * The light is emitted in every direction from this point.
  46081. * A good example of a point light is a standard light bulb.
  46082. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46083. */
  46084. var PointLight = /** @class */ (function (_super) {
  46085. __extends(PointLight, _super);
  46086. /**
  46087. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46088. * A PointLight emits the light in every direction.
  46089. * It can cast shadows.
  46090. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46091. * ```javascript
  46092. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46093. * ```
  46094. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46095. * @param name The light friendly name
  46096. * @param position The position of the point light in the scene
  46097. * @param scene The scene the lights belongs to
  46098. */
  46099. function PointLight(name, position, scene) {
  46100. var _this = _super.call(this, name, scene) || this;
  46101. _this._shadowAngle = Math.PI / 2;
  46102. _this.position = position;
  46103. return _this;
  46104. }
  46105. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46106. /**
  46107. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46108. * This specifies what angle the shadow will use to be created.
  46109. *
  46110. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46111. */
  46112. get: function () {
  46113. return this._shadowAngle;
  46114. },
  46115. /**
  46116. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46117. * This specifies what angle the shadow will use to be created.
  46118. *
  46119. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46120. */
  46121. set: function (value) {
  46122. this._shadowAngle = value;
  46123. this.forceProjectionMatrixCompute();
  46124. },
  46125. enumerable: true,
  46126. configurable: true
  46127. });
  46128. Object.defineProperty(PointLight.prototype, "direction", {
  46129. /**
  46130. * Gets the direction if it has been set.
  46131. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46132. */
  46133. get: function () {
  46134. return this._direction;
  46135. },
  46136. /**
  46137. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46138. */
  46139. set: function (value) {
  46140. var previousNeedCube = this.needCube();
  46141. this._direction = value;
  46142. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46143. this._shadowGenerator.recreateShadowMap();
  46144. }
  46145. },
  46146. enumerable: true,
  46147. configurable: true
  46148. });
  46149. /**
  46150. * Returns the string "PointLight"
  46151. * @returns the class name
  46152. */
  46153. PointLight.prototype.getClassName = function () {
  46154. return "PointLight";
  46155. };
  46156. /**
  46157. * Returns the integer 0.
  46158. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46159. */
  46160. PointLight.prototype.getTypeID = function () {
  46161. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46162. };
  46163. /**
  46164. * Specifies wether or not the shadowmap should be a cube texture.
  46165. * @returns true if the shadowmap needs to be a cube texture.
  46166. */
  46167. PointLight.prototype.needCube = function () {
  46168. return !this.direction;
  46169. };
  46170. /**
  46171. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46172. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46173. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46174. */
  46175. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46176. if (this.direction) {
  46177. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46178. }
  46179. else {
  46180. switch (faceIndex) {
  46181. case 0:
  46182. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46183. case 1:
  46184. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46185. case 2:
  46186. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46187. case 3:
  46188. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46189. case 4:
  46190. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46191. case 5:
  46192. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46193. }
  46194. }
  46195. return BABYLON.Vector3.Zero();
  46196. };
  46197. /**
  46198. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46199. * - fov = PI / 2
  46200. * - aspect ratio : 1.0
  46201. * - z-near and far equal to the active camera minZ and maxZ.
  46202. * Returns the PointLight.
  46203. */
  46204. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46205. var activeCamera = this.getScene().activeCamera;
  46206. if (!activeCamera) {
  46207. return;
  46208. }
  46209. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46210. };
  46211. PointLight.prototype._buildUniformLayout = function () {
  46212. this._uniformBuffer.addUniform("vLightData", 4);
  46213. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46214. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46215. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46216. this._uniformBuffer.addUniform("depthValues", 2);
  46217. this._uniformBuffer.create();
  46218. };
  46219. /**
  46220. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46221. * @param effect The effect to update
  46222. * @param lightIndex The index of the light in the effect to update
  46223. * @returns The point light
  46224. */
  46225. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46226. if (this.computeTransformedInformation()) {
  46227. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46228. return this;
  46229. }
  46230. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46231. return this;
  46232. };
  46233. __decorate([
  46234. BABYLON.serialize()
  46235. ], PointLight.prototype, "shadowAngle", null);
  46236. return PointLight;
  46237. }(BABYLON.ShadowLight));
  46238. BABYLON.PointLight = PointLight;
  46239. })(BABYLON || (BABYLON = {}));
  46240. //# sourceMappingURL=babylon.pointLight.js.map
  46241. "use strict";
  46242. var BABYLON;
  46243. (function (BABYLON) {
  46244. /**
  46245. * A directional light is defined by a direction (what a surprise!).
  46246. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46247. * 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.
  46248. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46249. */
  46250. var DirectionalLight = /** @class */ (function (_super) {
  46251. __extends(DirectionalLight, _super);
  46252. /**
  46253. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46254. * The directional light is emitted from everywhere in the given direction.
  46255. * It can cast shawdows.
  46256. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46257. * @param name The friendly name of the light
  46258. * @param direction The direction of the light
  46259. * @param scene The scene the light belongs to
  46260. */
  46261. function DirectionalLight(name, direction, scene) {
  46262. var _this = _super.call(this, name, scene) || this;
  46263. _this._shadowFrustumSize = 0;
  46264. _this._shadowOrthoScale = 0.1;
  46265. /**
  46266. * Automatically compute the projection matrix to best fit (including all the casters)
  46267. * on each frame.
  46268. */
  46269. _this.autoUpdateExtends = true;
  46270. // Cache
  46271. _this._orthoLeft = Number.MAX_VALUE;
  46272. _this._orthoRight = Number.MIN_VALUE;
  46273. _this._orthoTop = Number.MIN_VALUE;
  46274. _this._orthoBottom = Number.MAX_VALUE;
  46275. _this.position = direction.scale(-1.0);
  46276. _this.direction = direction;
  46277. return _this;
  46278. }
  46279. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46280. /**
  46281. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46282. */
  46283. get: function () {
  46284. return this._shadowFrustumSize;
  46285. },
  46286. /**
  46287. * Specifies a fix frustum size for the shadow generation.
  46288. */
  46289. set: function (value) {
  46290. this._shadowFrustumSize = value;
  46291. this.forceProjectionMatrixCompute();
  46292. },
  46293. enumerable: true,
  46294. configurable: true
  46295. });
  46296. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46297. /**
  46298. * Gets the shadow projection scale against the optimal computed one.
  46299. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46300. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46301. */
  46302. get: function () {
  46303. return this._shadowOrthoScale;
  46304. },
  46305. /**
  46306. * Sets the shadow projection scale against the optimal computed one.
  46307. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46308. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46309. */
  46310. set: function (value) {
  46311. this._shadowOrthoScale = value;
  46312. this.forceProjectionMatrixCompute();
  46313. },
  46314. enumerable: true,
  46315. configurable: true
  46316. });
  46317. /**
  46318. * Returns the string "DirectionalLight".
  46319. * @return The class name
  46320. */
  46321. DirectionalLight.prototype.getClassName = function () {
  46322. return "DirectionalLight";
  46323. };
  46324. /**
  46325. * Returns the integer 1.
  46326. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46327. */
  46328. DirectionalLight.prototype.getTypeID = function () {
  46329. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46330. };
  46331. /**
  46332. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46333. * Returns the DirectionalLight Shadow projection matrix.
  46334. */
  46335. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46336. if (this.shadowFrustumSize > 0) {
  46337. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46338. }
  46339. else {
  46340. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46341. }
  46342. };
  46343. /**
  46344. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46345. * Returns the DirectionalLight Shadow projection matrix.
  46346. */
  46347. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46348. var activeCamera = this.getScene().activeCamera;
  46349. if (!activeCamera) {
  46350. return;
  46351. }
  46352. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46353. };
  46354. /**
  46355. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46356. * Returns the DirectionalLight Shadow projection matrix.
  46357. */
  46358. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46359. var activeCamera = this.getScene().activeCamera;
  46360. if (!activeCamera) {
  46361. return;
  46362. }
  46363. // Check extends
  46364. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46365. var tempVector3 = BABYLON.Vector3.Zero();
  46366. this._orthoLeft = Number.MAX_VALUE;
  46367. this._orthoRight = Number.MIN_VALUE;
  46368. this._orthoTop = Number.MIN_VALUE;
  46369. this._orthoBottom = Number.MAX_VALUE;
  46370. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46371. var mesh = renderList[meshIndex];
  46372. if (!mesh) {
  46373. continue;
  46374. }
  46375. var boundingInfo = mesh.getBoundingInfo();
  46376. var boundingBox = boundingInfo.boundingBox;
  46377. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46378. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46379. if (tempVector3.x < this._orthoLeft)
  46380. this._orthoLeft = tempVector3.x;
  46381. if (tempVector3.y < this._orthoBottom)
  46382. this._orthoBottom = tempVector3.y;
  46383. if (tempVector3.x > this._orthoRight)
  46384. this._orthoRight = tempVector3.x;
  46385. if (tempVector3.y > this._orthoTop)
  46386. this._orthoTop = tempVector3.y;
  46387. }
  46388. }
  46389. }
  46390. var xOffset = this._orthoRight - this._orthoLeft;
  46391. var yOffset = this._orthoTop - this._orthoBottom;
  46392. 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);
  46393. };
  46394. DirectionalLight.prototype._buildUniformLayout = function () {
  46395. this._uniformBuffer.addUniform("vLightData", 4);
  46396. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46397. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46398. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46399. this._uniformBuffer.addUniform("depthValues", 2);
  46400. this._uniformBuffer.create();
  46401. };
  46402. /**
  46403. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46404. * @param effect The effect to update
  46405. * @param lightIndex The index of the light in the effect to update
  46406. * @returns The directional light
  46407. */
  46408. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46409. if (this.computeTransformedInformation()) {
  46410. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46411. return this;
  46412. }
  46413. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46414. return this;
  46415. };
  46416. /**
  46417. * Gets the minZ used for shadow according to both the scene and the light.
  46418. *
  46419. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46420. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46421. * @param activeCamera The camera we are returning the min for
  46422. * @returns the depth min z
  46423. */
  46424. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46425. return 1;
  46426. };
  46427. /**
  46428. * Gets the maxZ used for shadow according to both the scene and the light.
  46429. *
  46430. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46431. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46432. * @param activeCamera The camera we are returning the max for
  46433. * @returns the depth max z
  46434. */
  46435. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46436. return 1;
  46437. };
  46438. __decorate([
  46439. BABYLON.serialize()
  46440. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46441. __decorate([
  46442. BABYLON.serialize()
  46443. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46444. __decorate([
  46445. BABYLON.serialize()
  46446. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46447. return DirectionalLight;
  46448. }(BABYLON.ShadowLight));
  46449. BABYLON.DirectionalLight = DirectionalLight;
  46450. })(BABYLON || (BABYLON = {}));
  46451. //# sourceMappingURL=babylon.directionalLight.js.map
  46452. "use strict";
  46453. var BABYLON;
  46454. (function (BABYLON) {
  46455. /**
  46456. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46457. * These values define a cone of light starting from the position, emitting toward the direction.
  46458. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46459. * and the exponent defines the speed of the decay of the light with distance (reach).
  46460. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46461. */
  46462. var SpotLight = /** @class */ (function (_super) {
  46463. __extends(SpotLight, _super);
  46464. /**
  46465. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46466. * It can cast shadows.
  46467. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46468. * @param name The light friendly name
  46469. * @param position The position of the spot light in the scene
  46470. * @param direction The direction of the light in the scene
  46471. * @param angle The cone angle of the light in Radians
  46472. * @param exponent The light decay speed with the distance from the emission spot
  46473. * @param scene The scene the lights belongs to
  46474. */
  46475. function SpotLight(name, position, direction, angle, exponent, scene) {
  46476. var _this = _super.call(this, name, scene) || this;
  46477. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46478. _this._projectionTextureLightNear = 1e-6;
  46479. _this._projectionTextureLightFar = 1000.0;
  46480. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46481. _this._projectionTextureViewLightDirty = true;
  46482. _this._projectionTextureProjectionLightDirty = true;
  46483. _this._projectionTextureDirty = true;
  46484. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46485. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46486. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46487. _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);
  46488. _this.position = position;
  46489. _this.direction = direction;
  46490. _this.angle = angle;
  46491. _this.exponent = exponent;
  46492. return _this;
  46493. }
  46494. Object.defineProperty(SpotLight.prototype, "angle", {
  46495. /**
  46496. * Gets the cone angle of the spot light in Radians.
  46497. */
  46498. get: function () {
  46499. return this._angle;
  46500. },
  46501. /**
  46502. * Sets the cone angle of the spot light in Radians.
  46503. */
  46504. set: function (value) {
  46505. this._angle = value;
  46506. this._projectionTextureProjectionLightDirty = true;
  46507. this.forceProjectionMatrixCompute();
  46508. },
  46509. enumerable: true,
  46510. configurable: true
  46511. });
  46512. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46513. /**
  46514. * Allows scaling the angle of the light for shadow generation only.
  46515. */
  46516. get: function () {
  46517. return this._shadowAngleScale;
  46518. },
  46519. /**
  46520. * Allows scaling the angle of the light for shadow generation only.
  46521. */
  46522. set: function (value) {
  46523. this._shadowAngleScale = value;
  46524. this.forceProjectionMatrixCompute();
  46525. },
  46526. enumerable: true,
  46527. configurable: true
  46528. });
  46529. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46530. /**
  46531. * Allows reading the projecton texture
  46532. */
  46533. get: function () {
  46534. return this._projectionTextureMatrix;
  46535. },
  46536. enumerable: true,
  46537. configurable: true
  46538. });
  46539. ;
  46540. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46541. /**
  46542. * Gets the near clip of the Spotlight for texture projection.
  46543. */
  46544. get: function () {
  46545. return this._projectionTextureLightNear;
  46546. },
  46547. /**
  46548. * Sets the near clip of the Spotlight for texture projection.
  46549. */
  46550. set: function (value) {
  46551. this._projectionTextureLightNear = value;
  46552. this._projectionTextureProjectionLightDirty = true;
  46553. },
  46554. enumerable: true,
  46555. configurable: true
  46556. });
  46557. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46558. /**
  46559. * Gets the far clip of the Spotlight for texture projection.
  46560. */
  46561. get: function () {
  46562. return this._projectionTextureLightFar;
  46563. },
  46564. /**
  46565. * Sets the far clip of the Spotlight for texture projection.
  46566. */
  46567. set: function (value) {
  46568. this._projectionTextureLightFar = value;
  46569. this._projectionTextureProjectionLightDirty = true;
  46570. },
  46571. enumerable: true,
  46572. configurable: true
  46573. });
  46574. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46575. /**
  46576. * Gets the Up vector of the Spotlight for texture projection.
  46577. */
  46578. get: function () {
  46579. return this._projectionTextureUpDirection;
  46580. },
  46581. /**
  46582. * Sets the Up vector of the Spotlight for texture projection.
  46583. */
  46584. set: function (value) {
  46585. this._projectionTextureUpDirection = value;
  46586. this._projectionTextureProjectionLightDirty = true;
  46587. },
  46588. enumerable: true,
  46589. configurable: true
  46590. });
  46591. ;
  46592. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46593. /**
  46594. * Gets the projection texture of the light.
  46595. */
  46596. get: function () {
  46597. return this._projectionTexture;
  46598. },
  46599. /**
  46600. * Sets the projection texture of the light.
  46601. */
  46602. set: function (value) {
  46603. this._projectionTexture = value;
  46604. this._projectionTextureDirty = true;
  46605. },
  46606. enumerable: true,
  46607. configurable: true
  46608. });
  46609. /**
  46610. * Returns the string "SpotLight".
  46611. * @returns the class name
  46612. */
  46613. SpotLight.prototype.getClassName = function () {
  46614. return "SpotLight";
  46615. };
  46616. /**
  46617. * Returns the integer 2.
  46618. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46619. */
  46620. SpotLight.prototype.getTypeID = function () {
  46621. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46622. };
  46623. /**
  46624. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46625. */
  46626. SpotLight.prototype._setDirection = function (value) {
  46627. _super.prototype._setDirection.call(this, value);
  46628. this._projectionTextureViewLightDirty = true;
  46629. };
  46630. /**
  46631. * Overrides the position setter to recompute the projection texture view light Matrix.
  46632. */
  46633. SpotLight.prototype._setPosition = function (value) {
  46634. _super.prototype._setPosition.call(this, value);
  46635. this._projectionTextureViewLightDirty = true;
  46636. };
  46637. /**
  46638. * 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.
  46639. * Returns the SpotLight.
  46640. */
  46641. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46642. var activeCamera = this.getScene().activeCamera;
  46643. if (!activeCamera) {
  46644. return;
  46645. }
  46646. this._shadowAngleScale = this._shadowAngleScale || 1;
  46647. var angle = this._shadowAngleScale * this._angle;
  46648. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46649. };
  46650. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46651. this._projectionTextureViewLightDirty = false;
  46652. this._projectionTextureDirty = true;
  46653. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46654. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46655. };
  46656. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46657. this._projectionTextureProjectionLightDirty = false;
  46658. this._projectionTextureDirty = true;
  46659. var light_far = this.projectionTextureLightFar;
  46660. var light_near = this.projectionTextureLightNear;
  46661. var P = light_far / (light_far - light_near);
  46662. var Q = -P * light_near;
  46663. var S = 1.0 / Math.tan(this._angle / 2.0);
  46664. var A = 1.0;
  46665. 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);
  46666. };
  46667. /**
  46668. * Main function for light texture projection matrix computing.
  46669. */
  46670. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46671. this._projectionTextureDirty = false;
  46672. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46673. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46674. };
  46675. SpotLight.prototype._buildUniformLayout = function () {
  46676. this._uniformBuffer.addUniform("vLightData", 4);
  46677. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46678. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46679. this._uniformBuffer.addUniform("vLightDirection", 3);
  46680. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46681. this._uniformBuffer.addUniform("depthValues", 2);
  46682. this._uniformBuffer.create();
  46683. };
  46684. /**
  46685. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46686. * @param effect The effect to update
  46687. * @param lightIndex The index of the light in the effect to update
  46688. * @returns The spot light
  46689. */
  46690. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46691. var normalizeDirection;
  46692. if (this.computeTransformedInformation()) {
  46693. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46694. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46695. }
  46696. else {
  46697. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46698. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46699. }
  46700. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46701. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46702. if (this._projectionTextureViewLightDirty) {
  46703. this._computeProjectionTextureViewLightMatrix();
  46704. }
  46705. if (this._projectionTextureProjectionLightDirty) {
  46706. this._computeProjectionTextureProjectionLightMatrix();
  46707. }
  46708. if (this._projectionTextureDirty) {
  46709. this._computeProjectionTextureMatrix();
  46710. }
  46711. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46712. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46713. }
  46714. return this;
  46715. };
  46716. /**
  46717. * Disposes the light and the associated resources.
  46718. */
  46719. SpotLight.prototype.dispose = function () {
  46720. _super.prototype.dispose.call(this);
  46721. if (this._projectionTexture) {
  46722. this._projectionTexture.dispose();
  46723. }
  46724. };
  46725. __decorate([
  46726. BABYLON.serialize()
  46727. ], SpotLight.prototype, "angle", null);
  46728. __decorate([
  46729. BABYLON.serialize()
  46730. ], SpotLight.prototype, "shadowAngleScale", null);
  46731. __decorate([
  46732. BABYLON.serialize()
  46733. ], SpotLight.prototype, "exponent", void 0);
  46734. __decorate([
  46735. BABYLON.serialize()
  46736. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46737. __decorate([
  46738. BABYLON.serialize()
  46739. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46740. __decorate([
  46741. BABYLON.serialize()
  46742. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46743. __decorate([
  46744. BABYLON.serializeAsTexture("projectedLightTexture")
  46745. ], SpotLight.prototype, "_projectionTexture", void 0);
  46746. return SpotLight;
  46747. }(BABYLON.ShadowLight));
  46748. BABYLON.SpotLight = SpotLight;
  46749. })(BABYLON || (BABYLON = {}));
  46750. //# sourceMappingURL=babylon.spotLight.js.map
  46751. "use strict";
  46752. var BABYLON;
  46753. (function (BABYLON) {
  46754. /**
  46755. * Class used to override all child animations of a given target
  46756. */
  46757. var AnimationPropertiesOverride = /** @class */ (function () {
  46758. function AnimationPropertiesOverride() {
  46759. /**
  46760. * Gets or sets a value indicating if animation blending must be used
  46761. */
  46762. this.enableBlending = false;
  46763. /**
  46764. * Gets or sets the blending speed to use when enableBlending is true
  46765. */
  46766. this.blendingSpeed = 0.01;
  46767. /**
  46768. * Gets or sets the default loop mode to use
  46769. */
  46770. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46771. }
  46772. return AnimationPropertiesOverride;
  46773. }());
  46774. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46775. })(BABYLON || (BABYLON = {}));
  46776. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46777. "use strict";
  46778. var BABYLON;
  46779. (function (BABYLON) {
  46780. var AnimationRange = /** @class */ (function () {
  46781. function AnimationRange(name, from, to) {
  46782. this.name = name;
  46783. this.from = from;
  46784. this.to = to;
  46785. }
  46786. AnimationRange.prototype.clone = function () {
  46787. return new AnimationRange(this.name, this.from, this.to);
  46788. };
  46789. return AnimationRange;
  46790. }());
  46791. BABYLON.AnimationRange = AnimationRange;
  46792. /**
  46793. * Composed of a frame, and an action function
  46794. */
  46795. var AnimationEvent = /** @class */ (function () {
  46796. function AnimationEvent(frame, action, onlyOnce) {
  46797. this.frame = frame;
  46798. this.action = action;
  46799. this.onlyOnce = onlyOnce;
  46800. this.isDone = false;
  46801. }
  46802. return AnimationEvent;
  46803. }());
  46804. BABYLON.AnimationEvent = AnimationEvent;
  46805. var PathCursor = /** @class */ (function () {
  46806. function PathCursor(path) {
  46807. this.path = path;
  46808. this._onchange = new Array();
  46809. this.value = 0;
  46810. this.animations = new Array();
  46811. }
  46812. PathCursor.prototype.getPoint = function () {
  46813. var point = this.path.getPointAtLengthPosition(this.value);
  46814. return new BABYLON.Vector3(point.x, 0, point.y);
  46815. };
  46816. PathCursor.prototype.moveAhead = function (step) {
  46817. if (step === void 0) { step = 0.002; }
  46818. this.move(step);
  46819. return this;
  46820. };
  46821. PathCursor.prototype.moveBack = function (step) {
  46822. if (step === void 0) { step = 0.002; }
  46823. this.move(-step);
  46824. return this;
  46825. };
  46826. PathCursor.prototype.move = function (step) {
  46827. if (Math.abs(step) > 1) {
  46828. throw "step size should be less than 1.";
  46829. }
  46830. this.value += step;
  46831. this.ensureLimits();
  46832. this.raiseOnChange();
  46833. return this;
  46834. };
  46835. PathCursor.prototype.ensureLimits = function () {
  46836. while (this.value > 1) {
  46837. this.value -= 1;
  46838. }
  46839. while (this.value < 0) {
  46840. this.value += 1;
  46841. }
  46842. return this;
  46843. };
  46844. // used by animation engine
  46845. PathCursor.prototype.raiseOnChange = function () {
  46846. var _this = this;
  46847. this._onchange.forEach(function (f) { return f(_this); });
  46848. return this;
  46849. };
  46850. PathCursor.prototype.onchange = function (f) {
  46851. this._onchange.push(f);
  46852. return this;
  46853. };
  46854. return PathCursor;
  46855. }());
  46856. BABYLON.PathCursor = PathCursor;
  46857. var AnimationKeyInterpolation;
  46858. (function (AnimationKeyInterpolation) {
  46859. /**
  46860. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46861. */
  46862. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46863. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46864. var Animation = /** @class */ (function () {
  46865. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46866. this.name = name;
  46867. this.targetProperty = targetProperty;
  46868. this.framePerSecond = framePerSecond;
  46869. this.dataType = dataType;
  46870. this.loopMode = loopMode;
  46871. this.enableBlending = enableBlending;
  46872. this._runtimeAnimations = new Array();
  46873. // The set of event that will be linked to this animation
  46874. this._events = new Array();
  46875. this.blendingSpeed = 0.01;
  46876. this._ranges = {};
  46877. this.targetPropertyPath = targetProperty.split(".");
  46878. this.dataType = dataType;
  46879. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46880. }
  46881. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46882. var dataType = undefined;
  46883. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46884. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46885. }
  46886. else if (from instanceof BABYLON.Quaternion) {
  46887. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46888. }
  46889. else if (from instanceof BABYLON.Vector3) {
  46890. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46891. }
  46892. else if (from instanceof BABYLON.Vector2) {
  46893. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46894. }
  46895. else if (from instanceof BABYLON.Color3) {
  46896. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46897. }
  46898. else if (from instanceof BABYLON.Size) {
  46899. dataType = Animation.ANIMATIONTYPE_SIZE;
  46900. }
  46901. if (dataType == undefined) {
  46902. return null;
  46903. }
  46904. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46905. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46906. animation.setKeys(keys);
  46907. if (easingFunction !== undefined) {
  46908. animation.setEasingFunction(easingFunction);
  46909. }
  46910. return animation;
  46911. };
  46912. /**
  46913. * Sets up an animation.
  46914. * @param property the property to animate
  46915. * @param animationType the animation type to apply
  46916. * @param easingFunction the easing function used in the animation
  46917. * @returns The created animation
  46918. */
  46919. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46920. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46921. animation.setEasingFunction(easingFunction);
  46922. return animation;
  46923. };
  46924. /**
  46925. * Create and start an animation on a node
  46926. * @param {string} name defines the name of the global animation that will be run on all nodes
  46927. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46928. * @param {string} targetProperty defines property to animate
  46929. * @param {number} framePerSecond defines the number of frame per second yo use
  46930. * @param {number} totalFrame defines the number of frames in total
  46931. * @param {any} from defines the initial value
  46932. * @param {any} to defines the final value
  46933. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46934. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46935. * @param onAnimationEnd defines the callback to call when animation end
  46936. * @returns the animatable created for this animation
  46937. */
  46938. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46939. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46940. if (!animation) {
  46941. return null;
  46942. }
  46943. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46944. };
  46945. /**
  46946. * Create and start an animation on a node and its descendants
  46947. * @param {string} name defines the name of the global animation that will be run on all nodes
  46948. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46949. * @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.
  46950. * @param {string} targetProperty defines property to animate
  46951. * @param {number} framePerSecond defines the number of frame per second yo use
  46952. * @param {number} totalFrame defines the number of frames in total
  46953. * @param {any} from defines the initial value
  46954. * @param {any} to defines the final value
  46955. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46956. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46957. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46958. * @returns the list of animatables created for all nodes
  46959. * @example https://www.babylonjs-playground.com/#MH0VLI
  46960. */
  46961. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46962. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46963. if (!animation) {
  46964. return null;
  46965. }
  46966. var scene = node.getScene();
  46967. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46968. };
  46969. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46970. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46971. if (!animation) {
  46972. return null;
  46973. }
  46974. node.animations.push(animation);
  46975. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46976. };
  46977. /**
  46978. * Transition property of the Camera to the target Value.
  46979. * @param property The property to transition
  46980. * @param targetValue The target Value of the property
  46981. * @param host The object where the property to animate belongs
  46982. * @param scene Scene used to run the animation
  46983. * @param frameRate Framerate (in frame/s) to use
  46984. * @param transition The transition type we want to use
  46985. * @param duration The duration of the animation, in milliseconds
  46986. * @param onAnimationEnd Call back trigger at the end of the animation.
  46987. */
  46988. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46989. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46990. if (duration <= 0) {
  46991. host[property] = targetValue;
  46992. if (onAnimationEnd) {
  46993. onAnimationEnd();
  46994. }
  46995. return null;
  46996. }
  46997. var endFrame = frameRate * (duration / 1000);
  46998. transition.setKeys([{
  46999. frame: 0,
  47000. value: host[property].clone ? host[property].clone() : host[property]
  47001. },
  47002. {
  47003. frame: endFrame,
  47004. value: targetValue
  47005. }]);
  47006. if (!host.animations) {
  47007. host.animations = [];
  47008. }
  47009. host.animations.push(transition);
  47010. var animation = scene.beginAnimation(host, 0, endFrame, false);
  47011. animation.onAnimationEnd = onAnimationEnd;
  47012. return animation;
  47013. };
  47014. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  47015. /**
  47016. * Return the array of runtime animations currently using this animation
  47017. */
  47018. get: function () {
  47019. return this._runtimeAnimations;
  47020. },
  47021. enumerable: true,
  47022. configurable: true
  47023. });
  47024. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  47025. get: function () {
  47026. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  47027. var runtimeAnimation = _a[_i];
  47028. if (!runtimeAnimation.isStopped) {
  47029. return true;
  47030. }
  47031. }
  47032. return false;
  47033. },
  47034. enumerable: true,
  47035. configurable: true
  47036. });
  47037. // Methods
  47038. /**
  47039. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  47040. */
  47041. Animation.prototype.toString = function (fullDetails) {
  47042. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  47043. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  47044. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  47045. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  47046. if (fullDetails) {
  47047. ret += ", Ranges: {";
  47048. var first = true;
  47049. for (var name in this._ranges) {
  47050. if (first) {
  47051. ret += ", ";
  47052. first = false;
  47053. }
  47054. ret += name;
  47055. }
  47056. ret += "}";
  47057. }
  47058. return ret;
  47059. };
  47060. /**
  47061. * Add an event to this animation.
  47062. */
  47063. Animation.prototype.addEvent = function (event) {
  47064. this._events.push(event);
  47065. };
  47066. /**
  47067. * Remove all events found at the given frame
  47068. * @param frame
  47069. */
  47070. Animation.prototype.removeEvents = function (frame) {
  47071. for (var index = 0; index < this._events.length; index++) {
  47072. if (this._events[index].frame === frame) {
  47073. this._events.splice(index, 1);
  47074. index--;
  47075. }
  47076. }
  47077. };
  47078. Animation.prototype.getEvents = function () {
  47079. return this._events;
  47080. };
  47081. Animation.prototype.createRange = function (name, from, to) {
  47082. // check name not already in use; could happen for bones after serialized
  47083. if (!this._ranges[name]) {
  47084. this._ranges[name] = new AnimationRange(name, from, to);
  47085. }
  47086. };
  47087. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47088. if (deleteFrames === void 0) { deleteFrames = true; }
  47089. var range = this._ranges[name];
  47090. if (!range) {
  47091. return;
  47092. }
  47093. if (deleteFrames) {
  47094. var from = range.from;
  47095. var to = range.to;
  47096. // this loop MUST go high to low for multiple splices to work
  47097. for (var key = this._keys.length - 1; key >= 0; key--) {
  47098. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47099. this._keys.splice(key, 1);
  47100. }
  47101. }
  47102. }
  47103. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47104. };
  47105. Animation.prototype.getRange = function (name) {
  47106. return this._ranges[name];
  47107. };
  47108. Animation.prototype.getKeys = function () {
  47109. return this._keys;
  47110. };
  47111. Animation.prototype.getHighestFrame = function () {
  47112. var ret = 0;
  47113. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47114. if (ret < this._keys[key].frame) {
  47115. ret = this._keys[key].frame;
  47116. }
  47117. }
  47118. return ret;
  47119. };
  47120. Animation.prototype.getEasingFunction = function () {
  47121. return this._easingFunction;
  47122. };
  47123. Animation.prototype.setEasingFunction = function (easingFunction) {
  47124. this._easingFunction = easingFunction;
  47125. };
  47126. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47127. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47128. };
  47129. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47130. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47131. };
  47132. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47133. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47134. };
  47135. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47136. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47137. };
  47138. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47139. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47140. };
  47141. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47142. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47143. };
  47144. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47145. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47146. };
  47147. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47148. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47149. };
  47150. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47151. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47152. };
  47153. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47154. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47155. };
  47156. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47157. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47158. };
  47159. Animation.prototype.clone = function () {
  47160. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47161. clone.enableBlending = this.enableBlending;
  47162. clone.blendingSpeed = this.blendingSpeed;
  47163. if (this._keys) {
  47164. clone.setKeys(this._keys);
  47165. }
  47166. if (this._ranges) {
  47167. clone._ranges = {};
  47168. for (var name in this._ranges) {
  47169. var range = this._ranges[name];
  47170. if (!range) {
  47171. continue;
  47172. }
  47173. clone._ranges[name] = range.clone();
  47174. }
  47175. }
  47176. return clone;
  47177. };
  47178. Animation.prototype.setKeys = function (values) {
  47179. this._keys = values.slice(0);
  47180. };
  47181. Animation.prototype.serialize = function () {
  47182. var serializationObject = {};
  47183. serializationObject.name = this.name;
  47184. serializationObject.property = this.targetProperty;
  47185. serializationObject.framePerSecond = this.framePerSecond;
  47186. serializationObject.dataType = this.dataType;
  47187. serializationObject.loopBehavior = this.loopMode;
  47188. serializationObject.enableBlending = this.enableBlending;
  47189. serializationObject.blendingSpeed = this.blendingSpeed;
  47190. var dataType = this.dataType;
  47191. serializationObject.keys = [];
  47192. var keys = this.getKeys();
  47193. for (var index = 0; index < keys.length; index++) {
  47194. var animationKey = keys[index];
  47195. var key = {};
  47196. key.frame = animationKey.frame;
  47197. switch (dataType) {
  47198. case Animation.ANIMATIONTYPE_FLOAT:
  47199. key.values = [animationKey.value];
  47200. break;
  47201. case Animation.ANIMATIONTYPE_QUATERNION:
  47202. case Animation.ANIMATIONTYPE_MATRIX:
  47203. case Animation.ANIMATIONTYPE_VECTOR3:
  47204. case Animation.ANIMATIONTYPE_COLOR3:
  47205. key.values = animationKey.value.asArray();
  47206. break;
  47207. }
  47208. serializationObject.keys.push(key);
  47209. }
  47210. serializationObject.ranges = [];
  47211. for (var name in this._ranges) {
  47212. var source = this._ranges[name];
  47213. if (!source) {
  47214. continue;
  47215. }
  47216. var range = {};
  47217. range.name = name;
  47218. range.from = source.from;
  47219. range.to = source.to;
  47220. serializationObject.ranges.push(range);
  47221. }
  47222. return serializationObject;
  47223. };
  47224. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47225. get: function () {
  47226. return Animation._ANIMATIONTYPE_FLOAT;
  47227. },
  47228. enumerable: true,
  47229. configurable: true
  47230. });
  47231. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47232. get: function () {
  47233. return Animation._ANIMATIONTYPE_VECTOR3;
  47234. },
  47235. enumerable: true,
  47236. configurable: true
  47237. });
  47238. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47239. get: function () {
  47240. return Animation._ANIMATIONTYPE_VECTOR2;
  47241. },
  47242. enumerable: true,
  47243. configurable: true
  47244. });
  47245. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47246. get: function () {
  47247. return Animation._ANIMATIONTYPE_SIZE;
  47248. },
  47249. enumerable: true,
  47250. configurable: true
  47251. });
  47252. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47253. get: function () {
  47254. return Animation._ANIMATIONTYPE_QUATERNION;
  47255. },
  47256. enumerable: true,
  47257. configurable: true
  47258. });
  47259. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47260. get: function () {
  47261. return Animation._ANIMATIONTYPE_MATRIX;
  47262. },
  47263. enumerable: true,
  47264. configurable: true
  47265. });
  47266. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47267. get: function () {
  47268. return Animation._ANIMATIONTYPE_COLOR3;
  47269. },
  47270. enumerable: true,
  47271. configurable: true
  47272. });
  47273. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47274. get: function () {
  47275. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47276. },
  47277. enumerable: true,
  47278. configurable: true
  47279. });
  47280. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47281. get: function () {
  47282. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47283. },
  47284. enumerable: true,
  47285. configurable: true
  47286. });
  47287. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47288. get: function () {
  47289. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47290. },
  47291. enumerable: true,
  47292. configurable: true
  47293. });
  47294. Animation.Parse = function (parsedAnimation) {
  47295. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47296. var dataType = parsedAnimation.dataType;
  47297. var keys = [];
  47298. var data;
  47299. var index;
  47300. if (parsedAnimation.enableBlending) {
  47301. animation.enableBlending = parsedAnimation.enableBlending;
  47302. }
  47303. if (parsedAnimation.blendingSpeed) {
  47304. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47305. }
  47306. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47307. var key = parsedAnimation.keys[index];
  47308. var inTangent;
  47309. var outTangent;
  47310. switch (dataType) {
  47311. case Animation.ANIMATIONTYPE_FLOAT:
  47312. data = key.values[0];
  47313. if (key.values.length >= 1) {
  47314. inTangent = key.values[1];
  47315. }
  47316. if (key.values.length >= 2) {
  47317. outTangent = key.values[2];
  47318. }
  47319. break;
  47320. case Animation.ANIMATIONTYPE_QUATERNION:
  47321. data = BABYLON.Quaternion.FromArray(key.values);
  47322. if (key.values.length >= 8) {
  47323. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47324. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47325. inTangent = _inTangent;
  47326. }
  47327. }
  47328. if (key.values.length >= 12) {
  47329. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47330. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47331. outTangent = _outTangent;
  47332. }
  47333. }
  47334. break;
  47335. case Animation.ANIMATIONTYPE_MATRIX:
  47336. data = BABYLON.Matrix.FromArray(key.values);
  47337. break;
  47338. case Animation.ANIMATIONTYPE_COLOR3:
  47339. data = BABYLON.Color3.FromArray(key.values);
  47340. break;
  47341. case Animation.ANIMATIONTYPE_VECTOR3:
  47342. default:
  47343. data = BABYLON.Vector3.FromArray(key.values);
  47344. break;
  47345. }
  47346. var keyData = {};
  47347. keyData.frame = key.frame;
  47348. keyData.value = data;
  47349. if (inTangent != undefined) {
  47350. keyData.inTangent = inTangent;
  47351. }
  47352. if (outTangent != undefined) {
  47353. keyData.outTangent = outTangent;
  47354. }
  47355. keys.push(keyData);
  47356. }
  47357. animation.setKeys(keys);
  47358. if (parsedAnimation.ranges) {
  47359. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47360. data = parsedAnimation.ranges[index];
  47361. animation.createRange(data.name, data.from, data.to);
  47362. }
  47363. }
  47364. return animation;
  47365. };
  47366. Animation.AppendSerializedAnimations = function (source, destination) {
  47367. if (source.animations) {
  47368. destination.animations = [];
  47369. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47370. var animation = source.animations[animationIndex];
  47371. destination.animations.push(animation.serialize());
  47372. }
  47373. }
  47374. };
  47375. Animation.AllowMatricesInterpolation = false;
  47376. // Statics
  47377. Animation._ANIMATIONTYPE_FLOAT = 0;
  47378. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47379. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47380. Animation._ANIMATIONTYPE_MATRIX = 3;
  47381. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47382. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47383. Animation._ANIMATIONTYPE_SIZE = 6;
  47384. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47385. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47386. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47387. return Animation;
  47388. }());
  47389. BABYLON.Animation = Animation;
  47390. })(BABYLON || (BABYLON = {}));
  47391. //# sourceMappingURL=babylon.animation.js.map
  47392. "use strict";
  47393. var BABYLON;
  47394. (function (BABYLON) {
  47395. /**
  47396. * This class defines the direct association between an animation and a target
  47397. */
  47398. var TargetedAnimation = /** @class */ (function () {
  47399. function TargetedAnimation() {
  47400. }
  47401. return TargetedAnimation;
  47402. }());
  47403. BABYLON.TargetedAnimation = TargetedAnimation;
  47404. /**
  47405. * Use this class to create coordinated animations on multiple targets
  47406. */
  47407. var AnimationGroup = /** @class */ (function () {
  47408. function AnimationGroup(name, scene) {
  47409. if (scene === void 0) { scene = null; }
  47410. this.name = name;
  47411. this._targetedAnimations = new Array();
  47412. this._animatables = new Array();
  47413. this._from = Number.MAX_VALUE;
  47414. this._to = -Number.MAX_VALUE;
  47415. this._speedRatio = 1;
  47416. this.onAnimationEndObservable = new BABYLON.Observable();
  47417. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47418. this._scene.animationGroups.push(this);
  47419. }
  47420. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47421. /**
  47422. * Define if the animations are started
  47423. */
  47424. get: function () {
  47425. return this._isStarted;
  47426. },
  47427. enumerable: true,
  47428. configurable: true
  47429. });
  47430. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47431. /**
  47432. * Gets or sets the speed ratio to use for all animations
  47433. */
  47434. get: function () {
  47435. return this._speedRatio;
  47436. },
  47437. /**
  47438. * Gets or sets the speed ratio to use for all animations
  47439. */
  47440. set: function (value) {
  47441. if (this._speedRatio === value) {
  47442. return;
  47443. }
  47444. this._speedRatio = value;
  47445. for (var index = 0; index < this._animatables.length; index++) {
  47446. var animatable = this._animatables[index];
  47447. animatable.speedRatio = this._speedRatio;
  47448. }
  47449. },
  47450. enumerable: true,
  47451. configurable: true
  47452. });
  47453. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47454. /**
  47455. * Gets the targeted animations for this animation group
  47456. */
  47457. get: function () {
  47458. return this._targetedAnimations;
  47459. },
  47460. enumerable: true,
  47461. configurable: true
  47462. });
  47463. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47464. /**
  47465. * returning the list of animatables controlled by this animation group.
  47466. */
  47467. get: function () {
  47468. return this._animatables;
  47469. },
  47470. enumerable: true,
  47471. configurable: true
  47472. });
  47473. /**
  47474. * Add an animation (with its target) in the group
  47475. * @param animation defines the animation we want to add
  47476. * @param target defines the target of the animation
  47477. * @returns the {BABYLON.TargetedAnimation} object
  47478. */
  47479. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47480. var targetedAnimation = {
  47481. animation: animation,
  47482. target: target
  47483. };
  47484. var keys = animation.getKeys();
  47485. if (this._from > keys[0].frame) {
  47486. this._from = keys[0].frame;
  47487. }
  47488. if (this._to < keys[keys.length - 1].frame) {
  47489. this._to = keys[keys.length - 1].frame;
  47490. }
  47491. this._targetedAnimations.push(targetedAnimation);
  47492. return targetedAnimation;
  47493. };
  47494. /**
  47495. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47496. * It can add constant keys at begin or end
  47497. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47498. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47499. */
  47500. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47501. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47502. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47503. beginFrame = Math.max(beginFrame, this._from);
  47504. endFrame = Math.min(endFrame, this._to);
  47505. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47506. var targetedAnimation = this._targetedAnimations[index];
  47507. var keys = targetedAnimation.animation.getKeys();
  47508. var startKey = keys[0];
  47509. var endKey = keys[keys.length - 1];
  47510. if (startKey.frame > beginFrame) {
  47511. var newKey = {
  47512. frame: beginFrame,
  47513. value: startKey.value,
  47514. inTangent: startKey.inTangent,
  47515. outTangent: startKey.outTangent,
  47516. interpolation: startKey.interpolation
  47517. };
  47518. keys.splice(0, 0, newKey);
  47519. }
  47520. if (endKey.frame < endFrame) {
  47521. var newKey = {
  47522. frame: endFrame,
  47523. value: endKey.value,
  47524. inTangent: endKey.outTangent,
  47525. outTangent: endKey.outTangent,
  47526. interpolation: endKey.interpolation
  47527. };
  47528. keys.push(newKey);
  47529. }
  47530. }
  47531. return this;
  47532. };
  47533. /**
  47534. * Start all animations on given targets
  47535. * @param loop defines if animations must loop
  47536. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47537. */
  47538. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47539. var _this = this;
  47540. if (loop === void 0) { loop = false; }
  47541. if (speedRatio === void 0) { speedRatio = 1; }
  47542. if (this._isStarted || this._targetedAnimations.length === 0) {
  47543. return this;
  47544. }
  47545. var _loop_1 = function () {
  47546. var targetedAnimation = this_1._targetedAnimations[index];
  47547. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47548. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47549. }));
  47550. };
  47551. var this_1 = this;
  47552. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47553. _loop_1();
  47554. }
  47555. this._speedRatio = speedRatio;
  47556. this._isStarted = true;
  47557. return this;
  47558. };
  47559. /**
  47560. * Pause all animations
  47561. */
  47562. AnimationGroup.prototype.pause = function () {
  47563. if (!this._isStarted) {
  47564. return this;
  47565. }
  47566. for (var index = 0; index < this._animatables.length; index++) {
  47567. var animatable = this._animatables[index];
  47568. animatable.pause();
  47569. }
  47570. return this;
  47571. };
  47572. /**
  47573. * Play all animations to initial state
  47574. * This function will start() the animations if they were not started or will restart() them if they were paused
  47575. * @param loop defines if animations must loop
  47576. */
  47577. AnimationGroup.prototype.play = function (loop) {
  47578. if (this.isStarted) {
  47579. if (loop !== undefined) {
  47580. for (var index = 0; index < this._animatables.length; index++) {
  47581. var animatable = this._animatables[index];
  47582. animatable.loopAnimation = loop;
  47583. }
  47584. }
  47585. this.restart();
  47586. }
  47587. else {
  47588. this.start(loop, this._speedRatio);
  47589. }
  47590. return this;
  47591. };
  47592. /**
  47593. * Reset all animations to initial state
  47594. */
  47595. AnimationGroup.prototype.reset = function () {
  47596. if (!this._isStarted) {
  47597. return this;
  47598. }
  47599. for (var index = 0; index < this._animatables.length; index++) {
  47600. var animatable = this._animatables[index];
  47601. animatable.reset();
  47602. }
  47603. return this;
  47604. };
  47605. /**
  47606. * Restart animations from key 0
  47607. */
  47608. AnimationGroup.prototype.restart = function () {
  47609. if (!this._isStarted) {
  47610. return this;
  47611. }
  47612. for (var index = 0; index < this._animatables.length; index++) {
  47613. var animatable = this._animatables[index];
  47614. animatable.restart();
  47615. }
  47616. return this;
  47617. };
  47618. /**
  47619. * Stop all animations
  47620. */
  47621. AnimationGroup.prototype.stop = function () {
  47622. if (!this._isStarted) {
  47623. return this;
  47624. }
  47625. for (var index = 0; index < this._animatables.length; index++) {
  47626. var animatable = this._animatables[index];
  47627. animatable.stop();
  47628. }
  47629. this._isStarted = false;
  47630. return this;
  47631. };
  47632. /**
  47633. * Goes to a specific frame in this animation group
  47634. *
  47635. * @param frame the frame number to go to
  47636. * @return the animationGroup
  47637. */
  47638. AnimationGroup.prototype.goToFrame = function (frame) {
  47639. if (!this._isStarted) {
  47640. return this;
  47641. }
  47642. for (var index = 0; index < this._animatables.length; index++) {
  47643. var animatable = this._animatables[index];
  47644. animatable.goToFrame(frame);
  47645. }
  47646. return this;
  47647. };
  47648. /**
  47649. * Dispose all associated resources
  47650. */
  47651. AnimationGroup.prototype.dispose = function () {
  47652. this._targetedAnimations = [];
  47653. this._animatables = [];
  47654. var index = this._scene.animationGroups.indexOf(this);
  47655. if (index > -1) {
  47656. this._scene.animationGroups.splice(index, 1);
  47657. }
  47658. };
  47659. return AnimationGroup;
  47660. }());
  47661. BABYLON.AnimationGroup = AnimationGroup;
  47662. })(BABYLON || (BABYLON = {}));
  47663. //# sourceMappingURL=babylon.animationGroup.js.map
  47664. "use strict";
  47665. var BABYLON;
  47666. (function (BABYLON) {
  47667. var RuntimeAnimation = /** @class */ (function () {
  47668. /**
  47669. * Create a new RuntimeAnimation object
  47670. * @param target defines the target of the animation
  47671. * @param animation defines the source {BABYLON.Animation} object
  47672. * @param scene defines the hosting scene
  47673. */
  47674. function RuntimeAnimation(target, animation, scene) {
  47675. this.currentFrame = 0;
  47676. this._offsetsCache = {};
  47677. this._highLimitsCache = {};
  47678. this._stopped = false;
  47679. this._blendingFactor = 0;
  47680. this._targetPath = "";
  47681. this._weight = 1.0;
  47682. this._ratioOffset = 0;
  47683. this._previousDelay = 0;
  47684. this._previousRatio = 0;
  47685. this._animation = animation;
  47686. this._target = target;
  47687. this._scene = scene;
  47688. animation._runtimeAnimations.push(this);
  47689. }
  47690. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47691. /**
  47692. * Gets the weight of the runtime animation
  47693. */
  47694. get: function () {
  47695. return this._weight;
  47696. },
  47697. enumerable: true,
  47698. configurable: true
  47699. });
  47700. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47701. /**
  47702. * Gets the original value of the runtime animation
  47703. */
  47704. get: function () {
  47705. return this._originalValue;
  47706. },
  47707. enumerable: true,
  47708. configurable: true
  47709. });
  47710. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47711. /**
  47712. * Gets the current value of the runtime animation
  47713. */
  47714. get: function () {
  47715. return this._currentValue;
  47716. },
  47717. enumerable: true,
  47718. configurable: true
  47719. });
  47720. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47721. /**
  47722. * Gets the path where to store the animated value in the target
  47723. */
  47724. get: function () {
  47725. return this._targetPath;
  47726. },
  47727. enumerable: true,
  47728. configurable: true
  47729. });
  47730. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47731. /**
  47732. * Gets the actual target of the runtime animation
  47733. */
  47734. get: function () {
  47735. return this._activeTarget;
  47736. },
  47737. enumerable: true,
  47738. configurable: true
  47739. });
  47740. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47741. get: function () {
  47742. return this._animation;
  47743. },
  47744. enumerable: true,
  47745. configurable: true
  47746. });
  47747. RuntimeAnimation.prototype.reset = function () {
  47748. this._offsetsCache = {};
  47749. this._highLimitsCache = {};
  47750. this.currentFrame = 0;
  47751. this._blendingFactor = 0;
  47752. this._originalValue = null;
  47753. };
  47754. RuntimeAnimation.prototype.isStopped = function () {
  47755. return this._stopped;
  47756. };
  47757. RuntimeAnimation.prototype.dispose = function () {
  47758. var index = this._animation.runtimeAnimations.indexOf(this);
  47759. if (index > -1) {
  47760. this._animation.runtimeAnimations.splice(index, 1);
  47761. }
  47762. };
  47763. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47764. if (typeof value === "function") {
  47765. return value();
  47766. }
  47767. return value;
  47768. };
  47769. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47770. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47771. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47772. }
  47773. this.currentFrame = currentFrame;
  47774. var keys = this._animation.getKeys();
  47775. // Try to get a hash to find the right key
  47776. 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));
  47777. if (keys[startKeyIndex].frame >= currentFrame) {
  47778. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47779. startKeyIndex--;
  47780. }
  47781. }
  47782. for (var key = startKeyIndex; key < keys.length; key++) {
  47783. var endKey = keys[key + 1];
  47784. if (endKey.frame >= currentFrame) {
  47785. var startKey = keys[key];
  47786. var startValue = this._getKeyValue(startKey.value);
  47787. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47788. return startValue;
  47789. }
  47790. var endValue = this._getKeyValue(endKey.value);
  47791. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47792. var frameDelta = endKey.frame - startKey.frame;
  47793. // gradient : percent of currentFrame between the frame inf and the frame sup
  47794. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47795. // check for easingFunction and correction of gradient
  47796. var easingFunction = this._animation.getEasingFunction();
  47797. if (easingFunction != null) {
  47798. gradient = easingFunction.ease(gradient);
  47799. }
  47800. switch (this._animation.dataType) {
  47801. // Float
  47802. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47803. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47804. switch (loopMode) {
  47805. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47806. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47807. return floatValue;
  47808. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47809. return offsetValue * repeatCount + floatValue;
  47810. }
  47811. break;
  47812. // Quaternion
  47813. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47814. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47815. switch (loopMode) {
  47816. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47817. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47818. return quatValue;
  47819. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47820. return quatValue.add(offsetValue.scale(repeatCount));
  47821. }
  47822. return quatValue;
  47823. // Vector3
  47824. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47825. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47826. switch (loopMode) {
  47827. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47828. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47829. return vec3Value;
  47830. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47831. return vec3Value.add(offsetValue.scale(repeatCount));
  47832. }
  47833. // Vector2
  47834. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47835. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47836. switch (loopMode) {
  47837. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47838. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47839. return vec2Value;
  47840. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47841. return vec2Value.add(offsetValue.scale(repeatCount));
  47842. }
  47843. // Size
  47844. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47845. switch (loopMode) {
  47846. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47847. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47848. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47849. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47850. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47851. }
  47852. // Color3
  47853. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47854. switch (loopMode) {
  47855. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47856. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47857. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47858. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47859. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47860. }
  47861. // Matrix
  47862. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47863. switch (loopMode) {
  47864. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47865. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47866. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47867. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47868. }
  47869. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47870. return startValue;
  47871. }
  47872. default:
  47873. break;
  47874. }
  47875. break;
  47876. }
  47877. }
  47878. return this._getKeyValue(keys[keys.length - 1].value);
  47879. };
  47880. /**
  47881. * Affect the interpolated value to the target
  47882. * @param currentValue defines the value computed by the animation
  47883. * @param weight defines the weight to apply to this value
  47884. */
  47885. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  47886. if (weight === void 0) { weight = 1.0; }
  47887. // Set value
  47888. var path;
  47889. var destination;
  47890. var targetPropertyPath = this._animation.targetPropertyPath;
  47891. if (targetPropertyPath.length > 1) {
  47892. var property = this._target[targetPropertyPath[0]];
  47893. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47894. property = property[targetPropertyPath[index]];
  47895. }
  47896. path = targetPropertyPath[targetPropertyPath.length - 1];
  47897. destination = property;
  47898. }
  47899. else {
  47900. path = targetPropertyPath[0];
  47901. destination = this._target;
  47902. }
  47903. this._targetPath = path;
  47904. this._activeTarget = destination;
  47905. this._weight = weight;
  47906. // Blending
  47907. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47908. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47909. if (enableBlending && this._blendingFactor <= 1.0) {
  47910. if (!this._originalBlendValue) {
  47911. var originalValue = destination[path];
  47912. if (originalValue.clone) {
  47913. this._originalBlendValue = originalValue.clone();
  47914. }
  47915. else {
  47916. this._originalBlendValue = originalValue;
  47917. }
  47918. }
  47919. }
  47920. if (weight !== -1.0) {
  47921. if (!this._originalValue) {
  47922. var originalValue = void 0;
  47923. if (destination.getRestPose) {
  47924. originalValue = destination.getRestPose();
  47925. }
  47926. else {
  47927. originalValue = destination[path];
  47928. }
  47929. if (originalValue.clone) {
  47930. this._originalValue = originalValue.clone();
  47931. }
  47932. else {
  47933. this._originalValue = originalValue;
  47934. }
  47935. }
  47936. }
  47937. if (enableBlending && this._blendingFactor <= 1.0) {
  47938. if (this._originalBlendValue.prototype) {
  47939. if (this._originalBlendValue.prototype.Lerp) {
  47940. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47941. }
  47942. else {
  47943. this._currentValue = currentValue;
  47944. }
  47945. }
  47946. else if (this._originalBlendValue.m) {
  47947. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47948. }
  47949. else {
  47950. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47951. }
  47952. this._blendingFactor += blendingSpeed;
  47953. }
  47954. else {
  47955. this._currentValue = currentValue;
  47956. }
  47957. if (weight !== -1.0) {
  47958. this._scene._registerTargetForLateAnimationBinding(this);
  47959. }
  47960. else {
  47961. destination[path] = this._currentValue;
  47962. }
  47963. if (this._target.markAsDirty) {
  47964. this._target.markAsDirty(this._animation.targetProperty);
  47965. }
  47966. };
  47967. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47968. if (this._target && this._target.animationPropertiesOverride) {
  47969. return this._target.animationPropertiesOverride.loopMode;
  47970. }
  47971. return this._animation.loopMode;
  47972. };
  47973. /**
  47974. * Move the current animation to a given frame
  47975. * @param frame defines the frame to move to
  47976. */
  47977. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47978. var keys = this._animation.getKeys();
  47979. if (frame < keys[0].frame) {
  47980. frame = keys[0].frame;
  47981. }
  47982. else if (frame > keys[keys.length - 1].frame) {
  47983. frame = keys[keys.length - 1].frame;
  47984. }
  47985. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47986. this.setValue(currentValue, -1);
  47987. };
  47988. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47989. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47990. this._ratioOffset = this._previousRatio - newRatio;
  47991. };
  47992. /**
  47993. * Execute the current animation
  47994. * @param delay defines the delay to add to the current frame
  47995. * @param from defines the lower bound of the animation range
  47996. * @param to defines the upper bound of the animation range
  47997. * @param loop defines if the current animation must loop
  47998. * @param speedRatio defines the current speed ratio
  47999. * @param weight defines the weight of the animation (default is -1 so no weight)
  48000. * @returns a boolean indicating if the animation has ended
  48001. */
  48002. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  48003. if (weight === void 0) { weight = -1.0; }
  48004. var targetPropertyPath = this._animation.targetPropertyPath;
  48005. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  48006. this._stopped = true;
  48007. return false;
  48008. }
  48009. var returnValue = true;
  48010. var keys = this._animation.getKeys();
  48011. // Adding a start key at frame 0 if missing
  48012. if (keys[0].frame !== 0) {
  48013. var newKey = { frame: 0, value: keys[0].value };
  48014. keys.splice(0, 0, newKey);
  48015. }
  48016. // Check limits
  48017. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  48018. from = keys[0].frame;
  48019. }
  48020. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  48021. to = keys[keys.length - 1].frame;
  48022. }
  48023. //to and from cannot be the same key
  48024. if (from === to) {
  48025. if (from > keys[0].frame) {
  48026. from--;
  48027. }
  48028. else if (to < keys[keys.length - 1].frame) {
  48029. to++;
  48030. }
  48031. }
  48032. // Compute ratio
  48033. var range = to - from;
  48034. var offsetValue;
  48035. // ratio represents the frame delta between from and to
  48036. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  48037. var highLimitValue = 0;
  48038. this._previousDelay = delay;
  48039. this._previousRatio = ratio;
  48040. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  48041. returnValue = false;
  48042. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  48043. }
  48044. else {
  48045. // Get max value if required
  48046. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  48047. var keyOffset = to.toString() + from.toString();
  48048. if (!this._offsetsCache[keyOffset]) {
  48049. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48050. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48051. switch (this._animation.dataType) {
  48052. // Float
  48053. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48054. this._offsetsCache[keyOffset] = toValue - fromValue;
  48055. break;
  48056. // Quaternion
  48057. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48058. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48059. break;
  48060. // Vector3
  48061. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48062. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48063. // Vector2
  48064. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48065. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48066. // Size
  48067. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48068. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48069. // Color3
  48070. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48071. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48072. default:
  48073. break;
  48074. }
  48075. this._highLimitsCache[keyOffset] = toValue;
  48076. }
  48077. highLimitValue = this._highLimitsCache[keyOffset];
  48078. offsetValue = this._offsetsCache[keyOffset];
  48079. }
  48080. }
  48081. if (offsetValue === undefined) {
  48082. switch (this._animation.dataType) {
  48083. // Float
  48084. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48085. offsetValue = 0;
  48086. break;
  48087. // Quaternion
  48088. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48089. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  48090. break;
  48091. // Vector3
  48092. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48093. offsetValue = BABYLON.Vector3.Zero();
  48094. break;
  48095. // Vector2
  48096. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48097. offsetValue = BABYLON.Vector2.Zero();
  48098. break;
  48099. // Size
  48100. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48101. offsetValue = BABYLON.Size.Zero();
  48102. break;
  48103. // Color3
  48104. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48105. offsetValue = BABYLON.Color3.Black();
  48106. }
  48107. }
  48108. // Compute value
  48109. var repeatCount = (ratio / range) >> 0;
  48110. var currentFrame = returnValue ? from + ratio % range : to;
  48111. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48112. // Set value
  48113. this.setValue(currentValue, weight);
  48114. // Check events
  48115. var events = this._animation.getEvents();
  48116. for (var index = 0; index < events.length; index++) {
  48117. // Make sure current frame has passed event frame and that event frame is within the current range
  48118. // Also, handle both forward and reverse animations
  48119. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48120. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48121. var event = events[index];
  48122. if (!event.isDone) {
  48123. // If event should be done only once, remove it.
  48124. if (event.onlyOnce) {
  48125. events.splice(index, 1);
  48126. index--;
  48127. }
  48128. event.isDone = true;
  48129. event.action();
  48130. } // Don't do anything if the event has already be done.
  48131. }
  48132. else if (events[index].isDone && !events[index].onlyOnce) {
  48133. // reset event, the animation is looping
  48134. events[index].isDone = false;
  48135. }
  48136. }
  48137. if (!returnValue) {
  48138. this._stopped = true;
  48139. }
  48140. return returnValue;
  48141. };
  48142. return RuntimeAnimation;
  48143. }());
  48144. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48145. })(BABYLON || (BABYLON = {}));
  48146. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48147. "use strict";
  48148. var BABYLON;
  48149. (function (BABYLON) {
  48150. var Animatable = /** @class */ (function () {
  48151. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48152. if (fromFrame === void 0) { fromFrame = 0; }
  48153. if (toFrame === void 0) { toFrame = 100; }
  48154. if (loopAnimation === void 0) { loopAnimation = false; }
  48155. if (speedRatio === void 0) { speedRatio = 1.0; }
  48156. this.target = target;
  48157. this.fromFrame = fromFrame;
  48158. this.toFrame = toFrame;
  48159. this.loopAnimation = loopAnimation;
  48160. this.onAnimationEnd = onAnimationEnd;
  48161. this._localDelayOffset = null;
  48162. this._pausedDelay = null;
  48163. this._runtimeAnimations = new Array();
  48164. this._paused = false;
  48165. this._speedRatio = 1;
  48166. this._weight = -1.0;
  48167. this.animationStarted = false;
  48168. if (animations) {
  48169. this.appendAnimations(target, animations);
  48170. }
  48171. this._speedRatio = speedRatio;
  48172. this._scene = scene;
  48173. scene._activeAnimatables.push(this);
  48174. }
  48175. Object.defineProperty(Animatable.prototype, "weight", {
  48176. /**
  48177. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48178. */
  48179. get: function () {
  48180. return this._weight;
  48181. },
  48182. set: function (value) {
  48183. if (value === -1) {
  48184. this._weight = -1;
  48185. return;
  48186. }
  48187. // Else weight must be in [0, 1] range
  48188. this._weight = Math.min(Math.max(value, 0), 1.0);
  48189. },
  48190. enumerable: true,
  48191. configurable: true
  48192. });
  48193. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48194. /**
  48195. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48196. */
  48197. get: function () {
  48198. return this._speedRatio;
  48199. },
  48200. set: function (value) {
  48201. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48202. var animation = this._runtimeAnimations[index];
  48203. animation._prepareForSpeedRatioChange(value);
  48204. }
  48205. this._speedRatio = value;
  48206. },
  48207. enumerable: true,
  48208. configurable: true
  48209. });
  48210. // Methods
  48211. Animatable.prototype.getAnimations = function () {
  48212. return this._runtimeAnimations;
  48213. };
  48214. Animatable.prototype.appendAnimations = function (target, animations) {
  48215. for (var index = 0; index < animations.length; index++) {
  48216. var animation = animations[index];
  48217. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene));
  48218. }
  48219. };
  48220. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48221. var runtimeAnimations = this._runtimeAnimations;
  48222. for (var index = 0; index < runtimeAnimations.length; index++) {
  48223. if (runtimeAnimations[index].animation.targetProperty === property) {
  48224. return runtimeAnimations[index].animation;
  48225. }
  48226. }
  48227. return null;
  48228. };
  48229. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48230. var runtimeAnimations = this._runtimeAnimations;
  48231. for (var index = 0; index < runtimeAnimations.length; index++) {
  48232. if (runtimeAnimations[index].animation.targetProperty === property) {
  48233. return runtimeAnimations[index];
  48234. }
  48235. }
  48236. return null;
  48237. };
  48238. Animatable.prototype.reset = function () {
  48239. var runtimeAnimations = this._runtimeAnimations;
  48240. for (var index = 0; index < runtimeAnimations.length; index++) {
  48241. runtimeAnimations[index].reset();
  48242. }
  48243. // Reset to original value
  48244. for (index = 0; index < runtimeAnimations.length; index++) {
  48245. var animation = runtimeAnimations[index];
  48246. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48247. }
  48248. this._localDelayOffset = null;
  48249. this._pausedDelay = null;
  48250. };
  48251. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48252. var runtimeAnimations = this._runtimeAnimations;
  48253. for (var index = 0; index < runtimeAnimations.length; index++) {
  48254. runtimeAnimations[index].animation.enableBlending = true;
  48255. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48256. }
  48257. };
  48258. Animatable.prototype.disableBlending = function () {
  48259. var runtimeAnimations = this._runtimeAnimations;
  48260. for (var index = 0; index < runtimeAnimations.length; index++) {
  48261. runtimeAnimations[index].animation.enableBlending = false;
  48262. }
  48263. };
  48264. Animatable.prototype.goToFrame = function (frame) {
  48265. var runtimeAnimations = this._runtimeAnimations;
  48266. if (runtimeAnimations[0]) {
  48267. var fps = runtimeAnimations[0].animation.framePerSecond;
  48268. var currentFrame = runtimeAnimations[0].currentFrame;
  48269. var adjustTime = frame - currentFrame;
  48270. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48271. if (this._localDelayOffset === null) {
  48272. this._localDelayOffset = 0;
  48273. }
  48274. this._localDelayOffset -= delay;
  48275. }
  48276. for (var index = 0; index < runtimeAnimations.length; index++) {
  48277. runtimeAnimations[index].goToFrame(frame);
  48278. }
  48279. };
  48280. Animatable.prototype.pause = function () {
  48281. if (this._paused) {
  48282. return;
  48283. }
  48284. this._paused = true;
  48285. };
  48286. Animatable.prototype.restart = function () {
  48287. this._paused = false;
  48288. };
  48289. Animatable.prototype.stop = function (animationName) {
  48290. if (animationName) {
  48291. var idx = this._scene._activeAnimatables.indexOf(this);
  48292. if (idx > -1) {
  48293. var runtimeAnimations = this._runtimeAnimations;
  48294. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48295. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48296. continue;
  48297. }
  48298. runtimeAnimations[index].dispose();
  48299. runtimeAnimations.splice(index, 1);
  48300. }
  48301. if (runtimeAnimations.length == 0) {
  48302. this._scene._activeAnimatables.splice(idx, 1);
  48303. if (this.onAnimationEnd) {
  48304. this.onAnimationEnd();
  48305. }
  48306. }
  48307. }
  48308. }
  48309. else {
  48310. var index = this._scene._activeAnimatables.indexOf(this);
  48311. if (index > -1) {
  48312. this._scene._activeAnimatables.splice(index, 1);
  48313. var runtimeAnimations = this._runtimeAnimations;
  48314. for (var index = 0; index < runtimeAnimations.length; index++) {
  48315. runtimeAnimations[index].dispose();
  48316. }
  48317. if (this.onAnimationEnd) {
  48318. this.onAnimationEnd();
  48319. }
  48320. }
  48321. }
  48322. };
  48323. Animatable.prototype._animate = function (delay) {
  48324. if (this._paused) {
  48325. this.animationStarted = false;
  48326. if (this._pausedDelay === null) {
  48327. this._pausedDelay = delay;
  48328. }
  48329. return true;
  48330. }
  48331. if (this._localDelayOffset === null) {
  48332. this._localDelayOffset = delay;
  48333. this._pausedDelay = null;
  48334. }
  48335. else if (this._pausedDelay !== null) {
  48336. this._localDelayOffset += delay - this._pausedDelay;
  48337. this._pausedDelay = null;
  48338. }
  48339. if (this._weight === 0) {
  48340. return true;
  48341. }
  48342. // Animating
  48343. var running = false;
  48344. var runtimeAnimations = this._runtimeAnimations;
  48345. var index;
  48346. for (index = 0; index < runtimeAnimations.length; index++) {
  48347. var animation = runtimeAnimations[index];
  48348. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48349. running = running || isRunning;
  48350. }
  48351. this.animationStarted = running;
  48352. if (!running) {
  48353. // Remove from active animatables
  48354. index = this._scene._activeAnimatables.indexOf(this);
  48355. this._scene._activeAnimatables.splice(index, 1);
  48356. // Dispose all runtime animations
  48357. for (index = 0; index < runtimeAnimations.length; index++) {
  48358. runtimeAnimations[index].dispose();
  48359. }
  48360. }
  48361. if (!running && this.onAnimationEnd) {
  48362. this.onAnimationEnd();
  48363. this.onAnimationEnd = null;
  48364. }
  48365. return running;
  48366. };
  48367. return Animatable;
  48368. }());
  48369. BABYLON.Animatable = Animatable;
  48370. })(BABYLON || (BABYLON = {}));
  48371. //# sourceMappingURL=babylon.animatable.js.map
  48372. "use strict";
  48373. var BABYLON;
  48374. (function (BABYLON) {
  48375. var EasingFunction = /** @class */ (function () {
  48376. function EasingFunction() {
  48377. // Properties
  48378. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48379. }
  48380. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48381. get: function () {
  48382. return EasingFunction._EASINGMODE_EASEIN;
  48383. },
  48384. enumerable: true,
  48385. configurable: true
  48386. });
  48387. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48388. get: function () {
  48389. return EasingFunction._EASINGMODE_EASEOUT;
  48390. },
  48391. enumerable: true,
  48392. configurable: true
  48393. });
  48394. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48395. get: function () {
  48396. return EasingFunction._EASINGMODE_EASEINOUT;
  48397. },
  48398. enumerable: true,
  48399. configurable: true
  48400. });
  48401. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48402. var n = Math.min(Math.max(easingMode, 0), 2);
  48403. this._easingMode = n;
  48404. };
  48405. EasingFunction.prototype.getEasingMode = function () {
  48406. return this._easingMode;
  48407. };
  48408. EasingFunction.prototype.easeInCore = function (gradient) {
  48409. throw new Error('You must implement this method');
  48410. };
  48411. EasingFunction.prototype.ease = function (gradient) {
  48412. switch (this._easingMode) {
  48413. case EasingFunction.EASINGMODE_EASEIN:
  48414. return this.easeInCore(gradient);
  48415. case EasingFunction.EASINGMODE_EASEOUT:
  48416. return (1 - this.easeInCore(1 - gradient));
  48417. }
  48418. if (gradient >= 0.5) {
  48419. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48420. }
  48421. return (this.easeInCore(gradient * 2) * 0.5);
  48422. };
  48423. //Statics
  48424. EasingFunction._EASINGMODE_EASEIN = 0;
  48425. EasingFunction._EASINGMODE_EASEOUT = 1;
  48426. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48427. return EasingFunction;
  48428. }());
  48429. BABYLON.EasingFunction = EasingFunction;
  48430. var CircleEase = /** @class */ (function (_super) {
  48431. __extends(CircleEase, _super);
  48432. function CircleEase() {
  48433. return _super !== null && _super.apply(this, arguments) || this;
  48434. }
  48435. CircleEase.prototype.easeInCore = function (gradient) {
  48436. gradient = Math.max(0, Math.min(1, gradient));
  48437. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48438. };
  48439. return CircleEase;
  48440. }(EasingFunction));
  48441. BABYLON.CircleEase = CircleEase;
  48442. var BackEase = /** @class */ (function (_super) {
  48443. __extends(BackEase, _super);
  48444. function BackEase(amplitude) {
  48445. if (amplitude === void 0) { amplitude = 1; }
  48446. var _this = _super.call(this) || this;
  48447. _this.amplitude = amplitude;
  48448. return _this;
  48449. }
  48450. BackEase.prototype.easeInCore = function (gradient) {
  48451. var num = Math.max(0, this.amplitude);
  48452. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48453. };
  48454. return BackEase;
  48455. }(EasingFunction));
  48456. BABYLON.BackEase = BackEase;
  48457. var BounceEase = /** @class */ (function (_super) {
  48458. __extends(BounceEase, _super);
  48459. function BounceEase(bounces, bounciness) {
  48460. if (bounces === void 0) { bounces = 3; }
  48461. if (bounciness === void 0) { bounciness = 2; }
  48462. var _this = _super.call(this) || this;
  48463. _this.bounces = bounces;
  48464. _this.bounciness = bounciness;
  48465. return _this;
  48466. }
  48467. BounceEase.prototype.easeInCore = function (gradient) {
  48468. var y = Math.max(0.0, this.bounces);
  48469. var bounciness = this.bounciness;
  48470. if (bounciness <= 1.0) {
  48471. bounciness = 1.001;
  48472. }
  48473. var num9 = Math.pow(bounciness, y);
  48474. var num5 = 1.0 - bounciness;
  48475. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48476. var num15 = gradient * num4;
  48477. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48478. var num3 = Math.floor(num65);
  48479. var num13 = num3 + 1.0;
  48480. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48481. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48482. var num7 = (num8 + num12) * 0.5;
  48483. var num6 = gradient - num7;
  48484. var num2 = num7 - num8;
  48485. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48486. };
  48487. return BounceEase;
  48488. }(EasingFunction));
  48489. BABYLON.BounceEase = BounceEase;
  48490. var CubicEase = /** @class */ (function (_super) {
  48491. __extends(CubicEase, _super);
  48492. function CubicEase() {
  48493. return _super !== null && _super.apply(this, arguments) || this;
  48494. }
  48495. CubicEase.prototype.easeInCore = function (gradient) {
  48496. return (gradient * gradient * gradient);
  48497. };
  48498. return CubicEase;
  48499. }(EasingFunction));
  48500. BABYLON.CubicEase = CubicEase;
  48501. var ElasticEase = /** @class */ (function (_super) {
  48502. __extends(ElasticEase, _super);
  48503. function ElasticEase(oscillations, springiness) {
  48504. if (oscillations === void 0) { oscillations = 3; }
  48505. if (springiness === void 0) { springiness = 3; }
  48506. var _this = _super.call(this) || this;
  48507. _this.oscillations = oscillations;
  48508. _this.springiness = springiness;
  48509. return _this;
  48510. }
  48511. ElasticEase.prototype.easeInCore = function (gradient) {
  48512. var num2;
  48513. var num3 = Math.max(0.0, this.oscillations);
  48514. var num = Math.max(0.0, this.springiness);
  48515. if (num == 0) {
  48516. num2 = gradient;
  48517. }
  48518. else {
  48519. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48520. }
  48521. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48522. };
  48523. return ElasticEase;
  48524. }(EasingFunction));
  48525. BABYLON.ElasticEase = ElasticEase;
  48526. var ExponentialEase = /** @class */ (function (_super) {
  48527. __extends(ExponentialEase, _super);
  48528. function ExponentialEase(exponent) {
  48529. if (exponent === void 0) { exponent = 2; }
  48530. var _this = _super.call(this) || this;
  48531. _this.exponent = exponent;
  48532. return _this;
  48533. }
  48534. ExponentialEase.prototype.easeInCore = function (gradient) {
  48535. if (this.exponent <= 0) {
  48536. return gradient;
  48537. }
  48538. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48539. };
  48540. return ExponentialEase;
  48541. }(EasingFunction));
  48542. BABYLON.ExponentialEase = ExponentialEase;
  48543. var PowerEase = /** @class */ (function (_super) {
  48544. __extends(PowerEase, _super);
  48545. function PowerEase(power) {
  48546. if (power === void 0) { power = 2; }
  48547. var _this = _super.call(this) || this;
  48548. _this.power = power;
  48549. return _this;
  48550. }
  48551. PowerEase.prototype.easeInCore = function (gradient) {
  48552. var y = Math.max(0.0, this.power);
  48553. return Math.pow(gradient, y);
  48554. };
  48555. return PowerEase;
  48556. }(EasingFunction));
  48557. BABYLON.PowerEase = PowerEase;
  48558. var QuadraticEase = /** @class */ (function (_super) {
  48559. __extends(QuadraticEase, _super);
  48560. function QuadraticEase() {
  48561. return _super !== null && _super.apply(this, arguments) || this;
  48562. }
  48563. QuadraticEase.prototype.easeInCore = function (gradient) {
  48564. return (gradient * gradient);
  48565. };
  48566. return QuadraticEase;
  48567. }(EasingFunction));
  48568. BABYLON.QuadraticEase = QuadraticEase;
  48569. var QuarticEase = /** @class */ (function (_super) {
  48570. __extends(QuarticEase, _super);
  48571. function QuarticEase() {
  48572. return _super !== null && _super.apply(this, arguments) || this;
  48573. }
  48574. QuarticEase.prototype.easeInCore = function (gradient) {
  48575. return (gradient * gradient * gradient * gradient);
  48576. };
  48577. return QuarticEase;
  48578. }(EasingFunction));
  48579. BABYLON.QuarticEase = QuarticEase;
  48580. var QuinticEase = /** @class */ (function (_super) {
  48581. __extends(QuinticEase, _super);
  48582. function QuinticEase() {
  48583. return _super !== null && _super.apply(this, arguments) || this;
  48584. }
  48585. QuinticEase.prototype.easeInCore = function (gradient) {
  48586. return (gradient * gradient * gradient * gradient * gradient);
  48587. };
  48588. return QuinticEase;
  48589. }(EasingFunction));
  48590. BABYLON.QuinticEase = QuinticEase;
  48591. var SineEase = /** @class */ (function (_super) {
  48592. __extends(SineEase, _super);
  48593. function SineEase() {
  48594. return _super !== null && _super.apply(this, arguments) || this;
  48595. }
  48596. SineEase.prototype.easeInCore = function (gradient) {
  48597. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48598. };
  48599. return SineEase;
  48600. }(EasingFunction));
  48601. BABYLON.SineEase = SineEase;
  48602. var BezierCurveEase = /** @class */ (function (_super) {
  48603. __extends(BezierCurveEase, _super);
  48604. function BezierCurveEase(x1, y1, x2, y2) {
  48605. if (x1 === void 0) { x1 = 0; }
  48606. if (y1 === void 0) { y1 = 0; }
  48607. if (x2 === void 0) { x2 = 1; }
  48608. if (y2 === void 0) { y2 = 1; }
  48609. var _this = _super.call(this) || this;
  48610. _this.x1 = x1;
  48611. _this.y1 = y1;
  48612. _this.x2 = x2;
  48613. _this.y2 = y2;
  48614. return _this;
  48615. }
  48616. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48617. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48618. };
  48619. return BezierCurveEase;
  48620. }(EasingFunction));
  48621. BABYLON.BezierCurveEase = BezierCurveEase;
  48622. })(BABYLON || (BABYLON = {}));
  48623. //# sourceMappingURL=babylon.easing.js.map
  48624. "use strict";
  48625. var BABYLON;
  48626. (function (BABYLON) {
  48627. var Condition = /** @class */ (function () {
  48628. function Condition(actionManager) {
  48629. this._actionManager = actionManager;
  48630. }
  48631. Condition.prototype.isValid = function () {
  48632. return true;
  48633. };
  48634. Condition.prototype._getProperty = function (propertyPath) {
  48635. return this._actionManager._getProperty(propertyPath);
  48636. };
  48637. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48638. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48639. };
  48640. Condition.prototype.serialize = function () {
  48641. };
  48642. Condition.prototype._serialize = function (serializedCondition) {
  48643. return {
  48644. type: 2,
  48645. children: [],
  48646. name: serializedCondition.name,
  48647. properties: serializedCondition.properties
  48648. };
  48649. };
  48650. return Condition;
  48651. }());
  48652. BABYLON.Condition = Condition;
  48653. var ValueCondition = /** @class */ (function (_super) {
  48654. __extends(ValueCondition, _super);
  48655. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48656. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48657. var _this = _super.call(this, actionManager) || this;
  48658. _this.propertyPath = propertyPath;
  48659. _this.value = value;
  48660. _this.operator = operator;
  48661. _this._target = target;
  48662. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48663. _this._property = _this._getProperty(_this.propertyPath);
  48664. return _this;
  48665. }
  48666. Object.defineProperty(ValueCondition, "IsEqual", {
  48667. get: function () {
  48668. return ValueCondition._IsEqual;
  48669. },
  48670. enumerable: true,
  48671. configurable: true
  48672. });
  48673. Object.defineProperty(ValueCondition, "IsDifferent", {
  48674. get: function () {
  48675. return ValueCondition._IsDifferent;
  48676. },
  48677. enumerable: true,
  48678. configurable: true
  48679. });
  48680. Object.defineProperty(ValueCondition, "IsGreater", {
  48681. get: function () {
  48682. return ValueCondition._IsGreater;
  48683. },
  48684. enumerable: true,
  48685. configurable: true
  48686. });
  48687. Object.defineProperty(ValueCondition, "IsLesser", {
  48688. get: function () {
  48689. return ValueCondition._IsLesser;
  48690. },
  48691. enumerable: true,
  48692. configurable: true
  48693. });
  48694. // Methods
  48695. ValueCondition.prototype.isValid = function () {
  48696. switch (this.operator) {
  48697. case ValueCondition.IsGreater:
  48698. return this._effectiveTarget[this._property] > this.value;
  48699. case ValueCondition.IsLesser:
  48700. return this._effectiveTarget[this._property] < this.value;
  48701. case ValueCondition.IsEqual:
  48702. case ValueCondition.IsDifferent:
  48703. var check;
  48704. if (this.value.equals) {
  48705. check = this.value.equals(this._effectiveTarget[this._property]);
  48706. }
  48707. else {
  48708. check = this.value === this._effectiveTarget[this._property];
  48709. }
  48710. return this.operator === ValueCondition.IsEqual ? check : !check;
  48711. }
  48712. return false;
  48713. };
  48714. ValueCondition.prototype.serialize = function () {
  48715. return this._serialize({
  48716. name: "ValueCondition",
  48717. properties: [
  48718. BABYLON.Action._GetTargetProperty(this._target),
  48719. { name: "propertyPath", value: this.propertyPath },
  48720. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48721. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48722. ]
  48723. });
  48724. };
  48725. ValueCondition.GetOperatorName = function (operator) {
  48726. switch (operator) {
  48727. case ValueCondition._IsEqual: return "IsEqual";
  48728. case ValueCondition._IsDifferent: return "IsDifferent";
  48729. case ValueCondition._IsGreater: return "IsGreater";
  48730. case ValueCondition._IsLesser: return "IsLesser";
  48731. default: return "";
  48732. }
  48733. };
  48734. // Statics
  48735. ValueCondition._IsEqual = 0;
  48736. ValueCondition._IsDifferent = 1;
  48737. ValueCondition._IsGreater = 2;
  48738. ValueCondition._IsLesser = 3;
  48739. return ValueCondition;
  48740. }(Condition));
  48741. BABYLON.ValueCondition = ValueCondition;
  48742. var PredicateCondition = /** @class */ (function (_super) {
  48743. __extends(PredicateCondition, _super);
  48744. function PredicateCondition(actionManager, predicate) {
  48745. var _this = _super.call(this, actionManager) || this;
  48746. _this.predicate = predicate;
  48747. return _this;
  48748. }
  48749. PredicateCondition.prototype.isValid = function () {
  48750. return this.predicate();
  48751. };
  48752. return PredicateCondition;
  48753. }(Condition));
  48754. BABYLON.PredicateCondition = PredicateCondition;
  48755. var StateCondition = /** @class */ (function (_super) {
  48756. __extends(StateCondition, _super);
  48757. function StateCondition(actionManager, target, value) {
  48758. var _this = _super.call(this, actionManager) || this;
  48759. _this.value = value;
  48760. _this._target = target;
  48761. return _this;
  48762. }
  48763. // Methods
  48764. StateCondition.prototype.isValid = function () {
  48765. return this._target.state === this.value;
  48766. };
  48767. StateCondition.prototype.serialize = function () {
  48768. return this._serialize({
  48769. name: "StateCondition",
  48770. properties: [
  48771. BABYLON.Action._GetTargetProperty(this._target),
  48772. { name: "value", value: this.value }
  48773. ]
  48774. });
  48775. };
  48776. return StateCondition;
  48777. }(Condition));
  48778. BABYLON.StateCondition = StateCondition;
  48779. })(BABYLON || (BABYLON = {}));
  48780. //# sourceMappingURL=babylon.condition.js.map
  48781. "use strict";
  48782. var BABYLON;
  48783. (function (BABYLON) {
  48784. var Action = /** @class */ (function () {
  48785. function Action(triggerOptions, condition) {
  48786. this.triggerOptions = triggerOptions;
  48787. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48788. if (triggerOptions.parameter) {
  48789. this.trigger = triggerOptions.trigger;
  48790. this._triggerParameter = triggerOptions.parameter;
  48791. }
  48792. else {
  48793. this.trigger = triggerOptions;
  48794. }
  48795. this._nextActiveAction = this;
  48796. this._condition = condition;
  48797. }
  48798. // Methods
  48799. Action.prototype._prepare = function () {
  48800. };
  48801. Action.prototype.getTriggerParameter = function () {
  48802. return this._triggerParameter;
  48803. };
  48804. Action.prototype._executeCurrent = function (evt) {
  48805. if (this._nextActiveAction._condition) {
  48806. var condition = this._nextActiveAction._condition;
  48807. var currentRenderId = this._actionManager.getScene().getRenderId();
  48808. // We cache the current evaluation for the current frame
  48809. if (condition._evaluationId === currentRenderId) {
  48810. if (!condition._currentResult) {
  48811. return;
  48812. }
  48813. }
  48814. else {
  48815. condition._evaluationId = currentRenderId;
  48816. if (!condition.isValid()) {
  48817. condition._currentResult = false;
  48818. return;
  48819. }
  48820. condition._currentResult = true;
  48821. }
  48822. }
  48823. this.onBeforeExecuteObservable.notifyObservers(this);
  48824. this._nextActiveAction.execute(evt);
  48825. this.skipToNextActiveAction();
  48826. };
  48827. Action.prototype.execute = function (evt) {
  48828. };
  48829. Action.prototype.skipToNextActiveAction = function () {
  48830. if (this._nextActiveAction._child) {
  48831. if (!this._nextActiveAction._child._actionManager) {
  48832. this._nextActiveAction._child._actionManager = this._actionManager;
  48833. }
  48834. this._nextActiveAction = this._nextActiveAction._child;
  48835. }
  48836. else {
  48837. this._nextActiveAction = this;
  48838. }
  48839. };
  48840. Action.prototype.then = function (action) {
  48841. this._child = action;
  48842. action._actionManager = this._actionManager;
  48843. action._prepare();
  48844. return action;
  48845. };
  48846. Action.prototype._getProperty = function (propertyPath) {
  48847. return this._actionManager._getProperty(propertyPath);
  48848. };
  48849. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48850. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48851. };
  48852. Action.prototype.serialize = function (parent) {
  48853. };
  48854. // Called by BABYLON.Action objects in serialize(...). Internal use
  48855. Action.prototype._serialize = function (serializedAction, parent) {
  48856. var serializationObject = {
  48857. type: 1,
  48858. children: [],
  48859. name: serializedAction.name,
  48860. properties: serializedAction.properties || []
  48861. };
  48862. // Serialize child
  48863. if (this._child) {
  48864. this._child.serialize(serializationObject);
  48865. }
  48866. // Check if "this" has a condition
  48867. if (this._condition) {
  48868. var serializedCondition = this._condition.serialize();
  48869. serializedCondition.children.push(serializationObject);
  48870. if (parent) {
  48871. parent.children.push(serializedCondition);
  48872. }
  48873. return serializedCondition;
  48874. }
  48875. if (parent) {
  48876. parent.children.push(serializationObject);
  48877. }
  48878. return serializationObject;
  48879. };
  48880. Action._SerializeValueAsString = function (value) {
  48881. if (typeof value === "number") {
  48882. return value.toString();
  48883. }
  48884. if (typeof value === "boolean") {
  48885. return value ? "true" : "false";
  48886. }
  48887. if (value instanceof BABYLON.Vector2) {
  48888. return value.x + ", " + value.y;
  48889. }
  48890. if (value instanceof BABYLON.Vector3) {
  48891. return value.x + ", " + value.y + ", " + value.z;
  48892. }
  48893. if (value instanceof BABYLON.Color3) {
  48894. return value.r + ", " + value.g + ", " + value.b;
  48895. }
  48896. if (value instanceof BABYLON.Color4) {
  48897. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48898. }
  48899. return value; // string
  48900. };
  48901. Action._GetTargetProperty = function (target) {
  48902. return {
  48903. name: "target",
  48904. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48905. : target instanceof BABYLON.Light ? "LightProperties"
  48906. : target instanceof BABYLON.Camera ? "CameraProperties"
  48907. : "SceneProperties",
  48908. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48909. };
  48910. };
  48911. return Action;
  48912. }());
  48913. BABYLON.Action = Action;
  48914. })(BABYLON || (BABYLON = {}));
  48915. //# sourceMappingURL=babylon.action.js.map
  48916. "use strict";
  48917. var BABYLON;
  48918. (function (BABYLON) {
  48919. /**
  48920. * ActionEvent is the event beint sent when an action is triggered.
  48921. */
  48922. var ActionEvent = /** @class */ (function () {
  48923. /**
  48924. * @param source The mesh or sprite that triggered the action.
  48925. * @param pointerX The X mouse cursor position at the time of the event
  48926. * @param pointerY The Y mouse cursor position at the time of the event
  48927. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48928. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48929. */
  48930. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48931. this.source = source;
  48932. this.pointerX = pointerX;
  48933. this.pointerY = pointerY;
  48934. this.meshUnderPointer = meshUnderPointer;
  48935. this.sourceEvent = sourceEvent;
  48936. this.additionalData = additionalData;
  48937. }
  48938. /**
  48939. * Helper function to auto-create an ActionEvent from a source mesh.
  48940. * @param source The source mesh that triggered the event
  48941. * @param evt {Event} The original (browser) event
  48942. */
  48943. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48944. var scene = source.getScene();
  48945. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48946. };
  48947. /**
  48948. * Helper function to auto-create an ActionEvent from a source mesh.
  48949. * @param source The source sprite that triggered the event
  48950. * @param scene Scene associated with the sprite
  48951. * @param evt {Event} The original (browser) event
  48952. */
  48953. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48954. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48955. };
  48956. /**
  48957. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48958. * @param scene the scene where the event occurred
  48959. * @param evt {Event} The original (browser) event
  48960. */
  48961. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48962. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48963. };
  48964. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48965. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48966. };
  48967. return ActionEvent;
  48968. }());
  48969. BABYLON.ActionEvent = ActionEvent;
  48970. /**
  48971. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48972. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48973. */
  48974. var ActionManager = /** @class */ (function () {
  48975. function ActionManager(scene) {
  48976. // Members
  48977. this.actions = new Array();
  48978. this.hoverCursor = '';
  48979. this._scene = scene;
  48980. scene._actionManagers.push(this);
  48981. }
  48982. Object.defineProperty(ActionManager, "NothingTrigger", {
  48983. get: function () {
  48984. return ActionManager._NothingTrigger;
  48985. },
  48986. enumerable: true,
  48987. configurable: true
  48988. });
  48989. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48990. get: function () {
  48991. return ActionManager._OnPickTrigger;
  48992. },
  48993. enumerable: true,
  48994. configurable: true
  48995. });
  48996. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48997. get: function () {
  48998. return ActionManager._OnLeftPickTrigger;
  48999. },
  49000. enumerable: true,
  49001. configurable: true
  49002. });
  49003. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  49004. get: function () {
  49005. return ActionManager._OnRightPickTrigger;
  49006. },
  49007. enumerable: true,
  49008. configurable: true
  49009. });
  49010. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  49011. get: function () {
  49012. return ActionManager._OnCenterPickTrigger;
  49013. },
  49014. enumerable: true,
  49015. configurable: true
  49016. });
  49017. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  49018. get: function () {
  49019. return ActionManager._OnPickDownTrigger;
  49020. },
  49021. enumerable: true,
  49022. configurable: true
  49023. });
  49024. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  49025. get: function () {
  49026. return ActionManager._OnDoublePickTrigger;
  49027. },
  49028. enumerable: true,
  49029. configurable: true
  49030. });
  49031. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  49032. get: function () {
  49033. return ActionManager._OnPickUpTrigger;
  49034. },
  49035. enumerable: true,
  49036. configurable: true
  49037. });
  49038. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  49039. /// This trigger will only be raised if you also declared a OnPickDown
  49040. get: function () {
  49041. return ActionManager._OnPickOutTrigger;
  49042. },
  49043. enumerable: true,
  49044. configurable: true
  49045. });
  49046. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  49047. get: function () {
  49048. return ActionManager._OnLongPressTrigger;
  49049. },
  49050. enumerable: true,
  49051. configurable: true
  49052. });
  49053. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  49054. get: function () {
  49055. return ActionManager._OnPointerOverTrigger;
  49056. },
  49057. enumerable: true,
  49058. configurable: true
  49059. });
  49060. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  49061. get: function () {
  49062. return ActionManager._OnPointerOutTrigger;
  49063. },
  49064. enumerable: true,
  49065. configurable: true
  49066. });
  49067. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  49068. get: function () {
  49069. return ActionManager._OnEveryFrameTrigger;
  49070. },
  49071. enumerable: true,
  49072. configurable: true
  49073. });
  49074. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  49075. get: function () {
  49076. return ActionManager._OnIntersectionEnterTrigger;
  49077. },
  49078. enumerable: true,
  49079. configurable: true
  49080. });
  49081. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  49082. get: function () {
  49083. return ActionManager._OnIntersectionExitTrigger;
  49084. },
  49085. enumerable: true,
  49086. configurable: true
  49087. });
  49088. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  49089. get: function () {
  49090. return ActionManager._OnKeyDownTrigger;
  49091. },
  49092. enumerable: true,
  49093. configurable: true
  49094. });
  49095. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  49096. get: function () {
  49097. return ActionManager._OnKeyUpTrigger;
  49098. },
  49099. enumerable: true,
  49100. configurable: true
  49101. });
  49102. // Methods
  49103. ActionManager.prototype.dispose = function () {
  49104. var index = this._scene._actionManagers.indexOf(this);
  49105. for (var i = 0; i < this.actions.length; i++) {
  49106. var action = this.actions[i];
  49107. ActionManager.Triggers[action.trigger]--;
  49108. if (ActionManager.Triggers[action.trigger] === 0) {
  49109. delete ActionManager.Triggers[action.trigger];
  49110. }
  49111. }
  49112. if (index > -1) {
  49113. this._scene._actionManagers.splice(index, 1);
  49114. }
  49115. };
  49116. ActionManager.prototype.getScene = function () {
  49117. return this._scene;
  49118. };
  49119. /**
  49120. * Does this action manager handles actions of any of the given triggers
  49121. * @param {number[]} triggers - the triggers to be tested
  49122. * @return {boolean} whether one (or more) of the triggers is handeled
  49123. */
  49124. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  49125. for (var index = 0; index < this.actions.length; index++) {
  49126. var action = this.actions[index];
  49127. if (triggers.indexOf(action.trigger) > -1) {
  49128. return true;
  49129. }
  49130. }
  49131. return false;
  49132. };
  49133. /**
  49134. * Does this action manager handles actions of a given trigger
  49135. * @param {number} trigger - the trigger to be tested
  49136. * @return {boolean} whether the trigger is handeled
  49137. */
  49138. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  49139. for (var index = 0; index < this.actions.length; index++) {
  49140. var action = this.actions[index];
  49141. if (action.trigger === trigger) {
  49142. return true;
  49143. }
  49144. }
  49145. return false;
  49146. };
  49147. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  49148. /**
  49149. * Does this action manager has pointer triggers
  49150. * @return {boolean} whether or not it has pointer triggers
  49151. */
  49152. get: function () {
  49153. for (var index = 0; index < this.actions.length; index++) {
  49154. var action = this.actions[index];
  49155. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  49156. return true;
  49157. }
  49158. }
  49159. return false;
  49160. },
  49161. enumerable: true,
  49162. configurable: true
  49163. });
  49164. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  49165. /**
  49166. * Does this action manager has pick triggers
  49167. * @return {boolean} whether or not it has pick triggers
  49168. */
  49169. get: function () {
  49170. for (var index = 0; index < this.actions.length; index++) {
  49171. var action = this.actions[index];
  49172. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  49173. return true;
  49174. }
  49175. }
  49176. return false;
  49177. },
  49178. enumerable: true,
  49179. configurable: true
  49180. });
  49181. Object.defineProperty(ActionManager, "HasTriggers", {
  49182. /**
  49183. * Does exist one action manager with at least one trigger
  49184. * @return {boolean} whether or not it exists one action manager with one trigger
  49185. **/
  49186. get: function () {
  49187. for (var t in ActionManager.Triggers) {
  49188. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49189. return true;
  49190. }
  49191. }
  49192. return false;
  49193. },
  49194. enumerable: true,
  49195. configurable: true
  49196. });
  49197. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49198. /**
  49199. * Does exist one action manager with at least one pick trigger
  49200. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49201. **/
  49202. get: function () {
  49203. for (var t in ActionManager.Triggers) {
  49204. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49205. var t_int = parseInt(t);
  49206. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49207. return true;
  49208. }
  49209. }
  49210. }
  49211. return false;
  49212. },
  49213. enumerable: true,
  49214. configurable: true
  49215. });
  49216. /**
  49217. * Does exist one action manager that handles actions of a given trigger
  49218. * @param {number} trigger - the trigger to be tested
  49219. * @return {boolean} whether the trigger is handeled by at least one action manager
  49220. **/
  49221. ActionManager.HasSpecificTrigger = function (trigger) {
  49222. for (var t in ActionManager.Triggers) {
  49223. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49224. var t_int = parseInt(t);
  49225. if (t_int === trigger) {
  49226. return true;
  49227. }
  49228. }
  49229. }
  49230. return false;
  49231. };
  49232. /**
  49233. * Registers an action to this action manager
  49234. * @param {BABYLON.Action} action - the action to be registered
  49235. * @return {BABYLON.Action} the action amended (prepared) after registration
  49236. */
  49237. ActionManager.prototype.registerAction = function (action) {
  49238. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49239. if (this.getScene().actionManager !== this) {
  49240. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49241. return null;
  49242. }
  49243. }
  49244. this.actions.push(action);
  49245. if (ActionManager.Triggers[action.trigger]) {
  49246. ActionManager.Triggers[action.trigger]++;
  49247. }
  49248. else {
  49249. ActionManager.Triggers[action.trigger] = 1;
  49250. }
  49251. action._actionManager = this;
  49252. action._prepare();
  49253. return action;
  49254. };
  49255. /**
  49256. * Unregisters an action to this action manager
  49257. * @param action The action to be unregistered
  49258. * @return whether the action has been unregistered
  49259. */
  49260. ActionManager.prototype.unregisterAction = function (action) {
  49261. var index = this.actions.indexOf(action);
  49262. if (index !== -1) {
  49263. this.actions.splice(index, 1);
  49264. ActionManager.Triggers[action.trigger] -= 1;
  49265. if (ActionManager.Triggers[action.trigger] === 0) {
  49266. delete ActionManager.Triggers[action.trigger];
  49267. }
  49268. delete action._actionManager;
  49269. return true;
  49270. }
  49271. return false;
  49272. };
  49273. /**
  49274. * Process a specific trigger
  49275. * @param {number} trigger - the trigger to process
  49276. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49277. */
  49278. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49279. for (var index = 0; index < this.actions.length; index++) {
  49280. var action = this.actions[index];
  49281. if (action.trigger === trigger) {
  49282. if (evt) {
  49283. if (trigger === ActionManager.OnKeyUpTrigger
  49284. || trigger === ActionManager.OnKeyDownTrigger) {
  49285. var parameter = action.getTriggerParameter();
  49286. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49287. if (!parameter.toLowerCase) {
  49288. continue;
  49289. }
  49290. var lowerCase = parameter.toLowerCase();
  49291. if (lowerCase !== evt.sourceEvent.key) {
  49292. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49293. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49294. if (actualkey !== lowerCase) {
  49295. continue;
  49296. }
  49297. }
  49298. }
  49299. }
  49300. }
  49301. action._executeCurrent(evt);
  49302. }
  49303. }
  49304. };
  49305. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49306. var properties = propertyPath.split(".");
  49307. for (var index = 0; index < properties.length - 1; index++) {
  49308. target = target[properties[index]];
  49309. }
  49310. return target;
  49311. };
  49312. ActionManager.prototype._getProperty = function (propertyPath) {
  49313. var properties = propertyPath.split(".");
  49314. return properties[properties.length - 1];
  49315. };
  49316. ActionManager.prototype.serialize = function (name) {
  49317. var root = {
  49318. children: new Array(),
  49319. name: name,
  49320. type: 3,
  49321. properties: new Array() // Empty for root but required
  49322. };
  49323. for (var i = 0; i < this.actions.length; i++) {
  49324. var triggerObject = {
  49325. type: 0,
  49326. children: new Array(),
  49327. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49328. properties: new Array()
  49329. };
  49330. var triggerOptions = this.actions[i].triggerOptions;
  49331. if (triggerOptions && typeof triggerOptions !== "number") {
  49332. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49333. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49334. }
  49335. else {
  49336. var parameter = {};
  49337. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49338. if (triggerOptions.parameter.mesh) {
  49339. parameter._meshId = triggerOptions.parameter.mesh.id;
  49340. }
  49341. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49342. }
  49343. }
  49344. // Serialize child action, recursively
  49345. this.actions[i].serialize(triggerObject);
  49346. // Add serialized trigger
  49347. root.children.push(triggerObject);
  49348. }
  49349. return root;
  49350. };
  49351. ActionManager.Parse = function (parsedActions, object, scene) {
  49352. var actionManager = new ActionManager(scene);
  49353. if (object === null)
  49354. scene.actionManager = actionManager;
  49355. else
  49356. object.actionManager = actionManager;
  49357. // instanciate a new object
  49358. var instanciate = function (name, params) {
  49359. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49360. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49361. newInstance.constructor.apply(newInstance, params);
  49362. return newInstance;
  49363. };
  49364. var parseParameter = function (name, value, target, propertyPath) {
  49365. if (propertyPath === null) {
  49366. // String, boolean or float
  49367. var floatValue = parseFloat(value);
  49368. if (value === "true" || value === "false")
  49369. return value === "true";
  49370. else
  49371. return isNaN(floatValue) ? value : floatValue;
  49372. }
  49373. var effectiveTarget = propertyPath.split(".");
  49374. var values = value.split(",");
  49375. // Get effective Target
  49376. for (var i = 0; i < effectiveTarget.length; i++) {
  49377. target = target[effectiveTarget[i]];
  49378. }
  49379. // Return appropriate value with its type
  49380. if (typeof (target) === "boolean")
  49381. return values[0] === "true";
  49382. if (typeof (target) === "string")
  49383. return values[0];
  49384. // Parameters with multiple values such as Vector3 etc.
  49385. var split = new Array();
  49386. for (var i = 0; i < values.length; i++)
  49387. split.push(parseFloat(values[i]));
  49388. if (target instanceof BABYLON.Vector3)
  49389. return BABYLON.Vector3.FromArray(split);
  49390. if (target instanceof BABYLON.Vector4)
  49391. return BABYLON.Vector4.FromArray(split);
  49392. if (target instanceof BABYLON.Color3)
  49393. return BABYLON.Color3.FromArray(split);
  49394. if (target instanceof BABYLON.Color4)
  49395. return BABYLON.Color4.FromArray(split);
  49396. return parseFloat(values[0]);
  49397. };
  49398. // traverse graph per trigger
  49399. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49400. if (combineArray === void 0) { combineArray = null; }
  49401. if (parsedAction.detached)
  49402. return;
  49403. var parameters = new Array();
  49404. var target = null;
  49405. var propertyPath = null;
  49406. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49407. // Parameters
  49408. if (parsedAction.type === 2)
  49409. parameters.push(actionManager);
  49410. else
  49411. parameters.push(trigger);
  49412. if (combine) {
  49413. var actions = new Array();
  49414. for (var j = 0; j < parsedAction.combine.length; j++) {
  49415. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49416. }
  49417. parameters.push(actions);
  49418. }
  49419. else {
  49420. for (var i = 0; i < parsedAction.properties.length; i++) {
  49421. var value = parsedAction.properties[i].value;
  49422. var name = parsedAction.properties[i].name;
  49423. var targetType = parsedAction.properties[i].targetType;
  49424. if (name === "target")
  49425. if (targetType !== null && targetType === "SceneProperties")
  49426. value = target = scene;
  49427. else
  49428. value = target = scene.getNodeByName(value);
  49429. else if (name === "parent")
  49430. value = scene.getNodeByName(value);
  49431. else if (name === "sound")
  49432. value = scene.getSoundByName(value);
  49433. else if (name !== "propertyPath") {
  49434. if (parsedAction.type === 2 && name === "operator")
  49435. value = BABYLON.ValueCondition[value];
  49436. else
  49437. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49438. }
  49439. else {
  49440. propertyPath = value;
  49441. }
  49442. parameters.push(value);
  49443. }
  49444. }
  49445. if (combineArray === null) {
  49446. parameters.push(condition);
  49447. }
  49448. else {
  49449. parameters.push(null);
  49450. }
  49451. // If interpolate value action
  49452. if (parsedAction.name === "InterpolateValueAction") {
  49453. var param = parameters[parameters.length - 2];
  49454. parameters[parameters.length - 1] = param;
  49455. parameters[parameters.length - 2] = condition;
  49456. }
  49457. // Action or condition(s) and not CombineAction
  49458. var newAction = instanciate(parsedAction.name, parameters);
  49459. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49460. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49461. if (action)
  49462. action.then(nothing);
  49463. else
  49464. actionManager.registerAction(nothing);
  49465. action = nothing;
  49466. }
  49467. if (combineArray === null) {
  49468. if (newAction instanceof BABYLON.Condition) {
  49469. condition = newAction;
  49470. newAction = action;
  49471. }
  49472. else {
  49473. condition = null;
  49474. if (action)
  49475. action.then(newAction);
  49476. else
  49477. actionManager.registerAction(newAction);
  49478. }
  49479. }
  49480. else {
  49481. combineArray.push(newAction);
  49482. }
  49483. for (var i = 0; i < parsedAction.children.length; i++)
  49484. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49485. };
  49486. // triggers
  49487. for (var i = 0; i < parsedActions.children.length; i++) {
  49488. var triggerParams;
  49489. var trigger = parsedActions.children[i];
  49490. if (trigger.properties.length > 0) {
  49491. var param = trigger.properties[0].value;
  49492. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49493. if (value._meshId) {
  49494. value.mesh = scene.getMeshByID(value._meshId);
  49495. }
  49496. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49497. }
  49498. else
  49499. triggerParams = ActionManager[trigger.name];
  49500. for (var j = 0; j < trigger.children.length; j++) {
  49501. if (!trigger.detached)
  49502. traverse(trigger.children[j], triggerParams, null, null);
  49503. }
  49504. }
  49505. };
  49506. ActionManager.GetTriggerName = function (trigger) {
  49507. switch (trigger) {
  49508. case 0: return "NothingTrigger";
  49509. case 1: return "OnPickTrigger";
  49510. case 2: return "OnLeftPickTrigger";
  49511. case 3: return "OnRightPickTrigger";
  49512. case 4: return "OnCenterPickTrigger";
  49513. case 5: return "OnPickDownTrigger";
  49514. case 6: return "OnPickUpTrigger";
  49515. case 7: return "OnLongPressTrigger";
  49516. case 8: return "OnPointerOverTrigger";
  49517. case 9: return "OnPointerOutTrigger";
  49518. case 10: return "OnEveryFrameTrigger";
  49519. case 11: return "OnIntersectionEnterTrigger";
  49520. case 12: return "OnIntersectionExitTrigger";
  49521. case 13: return "OnKeyDownTrigger";
  49522. case 14: return "OnKeyUpTrigger";
  49523. case 15: return "OnPickOutTrigger";
  49524. default: return "";
  49525. }
  49526. };
  49527. // Statics
  49528. ActionManager._NothingTrigger = 0;
  49529. ActionManager._OnPickTrigger = 1;
  49530. ActionManager._OnLeftPickTrigger = 2;
  49531. ActionManager._OnRightPickTrigger = 3;
  49532. ActionManager._OnCenterPickTrigger = 4;
  49533. ActionManager._OnPickDownTrigger = 5;
  49534. ActionManager._OnDoublePickTrigger = 6;
  49535. ActionManager._OnPickUpTrigger = 7;
  49536. ActionManager._OnLongPressTrigger = 8;
  49537. ActionManager._OnPointerOverTrigger = 9;
  49538. ActionManager._OnPointerOutTrigger = 10;
  49539. ActionManager._OnEveryFrameTrigger = 11;
  49540. ActionManager._OnIntersectionEnterTrigger = 12;
  49541. ActionManager._OnIntersectionExitTrigger = 13;
  49542. ActionManager._OnKeyDownTrigger = 14;
  49543. ActionManager._OnKeyUpTrigger = 15;
  49544. ActionManager._OnPickOutTrigger = 16;
  49545. ActionManager.Triggers = {};
  49546. return ActionManager;
  49547. }());
  49548. BABYLON.ActionManager = ActionManager;
  49549. })(BABYLON || (BABYLON = {}));
  49550. //# sourceMappingURL=babylon.actionManager.js.map
  49551. "use strict";
  49552. var BABYLON;
  49553. (function (BABYLON) {
  49554. var InterpolateValueAction = /** @class */ (function (_super) {
  49555. __extends(InterpolateValueAction, _super);
  49556. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49557. if (duration === void 0) { duration = 1000; }
  49558. var _this = _super.call(this, triggerOptions, condition) || this;
  49559. _this.propertyPath = propertyPath;
  49560. _this.value = value;
  49561. _this.duration = duration;
  49562. _this.stopOtherAnimations = stopOtherAnimations;
  49563. _this.onInterpolationDone = onInterpolationDone;
  49564. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49565. _this._target = _this._effectiveTarget = target;
  49566. return _this;
  49567. }
  49568. InterpolateValueAction.prototype._prepare = function () {
  49569. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49570. this._property = this._getProperty(this.propertyPath);
  49571. };
  49572. InterpolateValueAction.prototype.execute = function () {
  49573. var _this = this;
  49574. var scene = this._actionManager.getScene();
  49575. var keys = [
  49576. {
  49577. frame: 0,
  49578. value: this._effectiveTarget[this._property]
  49579. }, {
  49580. frame: 100,
  49581. value: this.value
  49582. }
  49583. ];
  49584. var dataType;
  49585. if (typeof this.value === "number") {
  49586. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49587. }
  49588. else if (this.value instanceof BABYLON.Color3) {
  49589. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49590. }
  49591. else if (this.value instanceof BABYLON.Vector3) {
  49592. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49593. }
  49594. else if (this.value instanceof BABYLON.Matrix) {
  49595. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49596. }
  49597. else if (this.value instanceof BABYLON.Quaternion) {
  49598. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49599. }
  49600. else {
  49601. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49602. return;
  49603. }
  49604. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49605. animation.setKeys(keys);
  49606. if (this.stopOtherAnimations) {
  49607. scene.stopAnimation(this._effectiveTarget);
  49608. }
  49609. var wrapper = function () {
  49610. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49611. if (_this.onInterpolationDone) {
  49612. _this.onInterpolationDone();
  49613. }
  49614. };
  49615. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49616. };
  49617. InterpolateValueAction.prototype.serialize = function (parent) {
  49618. return _super.prototype._serialize.call(this, {
  49619. name: "InterpolateValueAction",
  49620. properties: [
  49621. BABYLON.Action._GetTargetProperty(this._target),
  49622. { name: "propertyPath", value: this.propertyPath },
  49623. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49624. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49625. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49626. ]
  49627. }, parent);
  49628. };
  49629. return InterpolateValueAction;
  49630. }(BABYLON.Action));
  49631. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49632. })(BABYLON || (BABYLON = {}));
  49633. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49634. "use strict";
  49635. var BABYLON;
  49636. (function (BABYLON) {
  49637. var SwitchBooleanAction = /** @class */ (function (_super) {
  49638. __extends(SwitchBooleanAction, _super);
  49639. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49640. var _this = _super.call(this, triggerOptions, condition) || this;
  49641. _this.propertyPath = propertyPath;
  49642. _this._target = _this._effectiveTarget = target;
  49643. return _this;
  49644. }
  49645. SwitchBooleanAction.prototype._prepare = function () {
  49646. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49647. this._property = this._getProperty(this.propertyPath);
  49648. };
  49649. SwitchBooleanAction.prototype.execute = function () {
  49650. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49651. };
  49652. SwitchBooleanAction.prototype.serialize = function (parent) {
  49653. return _super.prototype._serialize.call(this, {
  49654. name: "SwitchBooleanAction",
  49655. properties: [
  49656. BABYLON.Action._GetTargetProperty(this._target),
  49657. { name: "propertyPath", value: this.propertyPath }
  49658. ]
  49659. }, parent);
  49660. };
  49661. return SwitchBooleanAction;
  49662. }(BABYLON.Action));
  49663. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49664. var SetStateAction = /** @class */ (function (_super) {
  49665. __extends(SetStateAction, _super);
  49666. function SetStateAction(triggerOptions, target, value, condition) {
  49667. var _this = _super.call(this, triggerOptions, condition) || this;
  49668. _this.value = value;
  49669. _this._target = target;
  49670. return _this;
  49671. }
  49672. SetStateAction.prototype.execute = function () {
  49673. this._target.state = this.value;
  49674. };
  49675. SetStateAction.prototype.serialize = function (parent) {
  49676. return _super.prototype._serialize.call(this, {
  49677. name: "SetStateAction",
  49678. properties: [
  49679. BABYLON.Action._GetTargetProperty(this._target),
  49680. { name: "value", value: this.value }
  49681. ]
  49682. }, parent);
  49683. };
  49684. return SetStateAction;
  49685. }(BABYLON.Action));
  49686. BABYLON.SetStateAction = SetStateAction;
  49687. var SetValueAction = /** @class */ (function (_super) {
  49688. __extends(SetValueAction, _super);
  49689. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49690. var _this = _super.call(this, triggerOptions, condition) || this;
  49691. _this.propertyPath = propertyPath;
  49692. _this.value = value;
  49693. _this._target = _this._effectiveTarget = target;
  49694. return _this;
  49695. }
  49696. SetValueAction.prototype._prepare = function () {
  49697. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49698. this._property = this._getProperty(this.propertyPath);
  49699. };
  49700. SetValueAction.prototype.execute = function () {
  49701. this._effectiveTarget[this._property] = this.value;
  49702. if (this._target.markAsDirty) {
  49703. this._target.markAsDirty(this._property);
  49704. }
  49705. };
  49706. SetValueAction.prototype.serialize = function (parent) {
  49707. return _super.prototype._serialize.call(this, {
  49708. name: "SetValueAction",
  49709. properties: [
  49710. BABYLON.Action._GetTargetProperty(this._target),
  49711. { name: "propertyPath", value: this.propertyPath },
  49712. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49713. ]
  49714. }, parent);
  49715. };
  49716. return SetValueAction;
  49717. }(BABYLON.Action));
  49718. BABYLON.SetValueAction = SetValueAction;
  49719. var IncrementValueAction = /** @class */ (function (_super) {
  49720. __extends(IncrementValueAction, _super);
  49721. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49722. var _this = _super.call(this, triggerOptions, condition) || this;
  49723. _this.propertyPath = propertyPath;
  49724. _this.value = value;
  49725. _this._target = _this._effectiveTarget = target;
  49726. return _this;
  49727. }
  49728. IncrementValueAction.prototype._prepare = function () {
  49729. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49730. this._property = this._getProperty(this.propertyPath);
  49731. if (typeof this._effectiveTarget[this._property] !== "number") {
  49732. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49733. }
  49734. };
  49735. IncrementValueAction.prototype.execute = function () {
  49736. this._effectiveTarget[this._property] += this.value;
  49737. if (this._target.markAsDirty) {
  49738. this._target.markAsDirty(this._property);
  49739. }
  49740. };
  49741. IncrementValueAction.prototype.serialize = function (parent) {
  49742. return _super.prototype._serialize.call(this, {
  49743. name: "IncrementValueAction",
  49744. properties: [
  49745. BABYLON.Action._GetTargetProperty(this._target),
  49746. { name: "propertyPath", value: this.propertyPath },
  49747. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49748. ]
  49749. }, parent);
  49750. };
  49751. return IncrementValueAction;
  49752. }(BABYLON.Action));
  49753. BABYLON.IncrementValueAction = IncrementValueAction;
  49754. var PlayAnimationAction = /** @class */ (function (_super) {
  49755. __extends(PlayAnimationAction, _super);
  49756. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49757. var _this = _super.call(this, triggerOptions, condition) || this;
  49758. _this.from = from;
  49759. _this.to = to;
  49760. _this.loop = loop;
  49761. _this._target = target;
  49762. return _this;
  49763. }
  49764. PlayAnimationAction.prototype._prepare = function () {
  49765. };
  49766. PlayAnimationAction.prototype.execute = function () {
  49767. var scene = this._actionManager.getScene();
  49768. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49769. };
  49770. PlayAnimationAction.prototype.serialize = function (parent) {
  49771. return _super.prototype._serialize.call(this, {
  49772. name: "PlayAnimationAction",
  49773. properties: [
  49774. BABYLON.Action._GetTargetProperty(this._target),
  49775. { name: "from", value: String(this.from) },
  49776. { name: "to", value: String(this.to) },
  49777. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49778. ]
  49779. }, parent);
  49780. };
  49781. return PlayAnimationAction;
  49782. }(BABYLON.Action));
  49783. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49784. var StopAnimationAction = /** @class */ (function (_super) {
  49785. __extends(StopAnimationAction, _super);
  49786. function StopAnimationAction(triggerOptions, target, condition) {
  49787. var _this = _super.call(this, triggerOptions, condition) || this;
  49788. _this._target = target;
  49789. return _this;
  49790. }
  49791. StopAnimationAction.prototype._prepare = function () {
  49792. };
  49793. StopAnimationAction.prototype.execute = function () {
  49794. var scene = this._actionManager.getScene();
  49795. scene.stopAnimation(this._target);
  49796. };
  49797. StopAnimationAction.prototype.serialize = function (parent) {
  49798. return _super.prototype._serialize.call(this, {
  49799. name: "StopAnimationAction",
  49800. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49801. }, parent);
  49802. };
  49803. return StopAnimationAction;
  49804. }(BABYLON.Action));
  49805. BABYLON.StopAnimationAction = StopAnimationAction;
  49806. var DoNothingAction = /** @class */ (function (_super) {
  49807. __extends(DoNothingAction, _super);
  49808. function DoNothingAction(triggerOptions, condition) {
  49809. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49810. return _super.call(this, triggerOptions, condition) || this;
  49811. }
  49812. DoNothingAction.prototype.execute = function () {
  49813. };
  49814. DoNothingAction.prototype.serialize = function (parent) {
  49815. return _super.prototype._serialize.call(this, {
  49816. name: "DoNothingAction",
  49817. properties: []
  49818. }, parent);
  49819. };
  49820. return DoNothingAction;
  49821. }(BABYLON.Action));
  49822. BABYLON.DoNothingAction = DoNothingAction;
  49823. var CombineAction = /** @class */ (function (_super) {
  49824. __extends(CombineAction, _super);
  49825. function CombineAction(triggerOptions, children, condition) {
  49826. var _this = _super.call(this, triggerOptions, condition) || this;
  49827. _this.children = children;
  49828. return _this;
  49829. }
  49830. CombineAction.prototype._prepare = function () {
  49831. for (var index = 0; index < this.children.length; index++) {
  49832. this.children[index]._actionManager = this._actionManager;
  49833. this.children[index]._prepare();
  49834. }
  49835. };
  49836. CombineAction.prototype.execute = function (evt) {
  49837. for (var index = 0; index < this.children.length; index++) {
  49838. this.children[index].execute(evt);
  49839. }
  49840. };
  49841. CombineAction.prototype.serialize = function (parent) {
  49842. var serializationObject = _super.prototype._serialize.call(this, {
  49843. name: "CombineAction",
  49844. properties: [],
  49845. combine: []
  49846. }, parent);
  49847. for (var i = 0; i < this.children.length; i++) {
  49848. serializationObject.combine.push(this.children[i].serialize(null));
  49849. }
  49850. return serializationObject;
  49851. };
  49852. return CombineAction;
  49853. }(BABYLON.Action));
  49854. BABYLON.CombineAction = CombineAction;
  49855. var ExecuteCodeAction = /** @class */ (function (_super) {
  49856. __extends(ExecuteCodeAction, _super);
  49857. function ExecuteCodeAction(triggerOptions, func, condition) {
  49858. var _this = _super.call(this, triggerOptions, condition) || this;
  49859. _this.func = func;
  49860. return _this;
  49861. }
  49862. ExecuteCodeAction.prototype.execute = function (evt) {
  49863. this.func(evt);
  49864. };
  49865. return ExecuteCodeAction;
  49866. }(BABYLON.Action));
  49867. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49868. var SetParentAction = /** @class */ (function (_super) {
  49869. __extends(SetParentAction, _super);
  49870. function SetParentAction(triggerOptions, target, parent, condition) {
  49871. var _this = _super.call(this, triggerOptions, condition) || this;
  49872. _this._target = target;
  49873. _this._parent = parent;
  49874. return _this;
  49875. }
  49876. SetParentAction.prototype._prepare = function () {
  49877. };
  49878. SetParentAction.prototype.execute = function () {
  49879. if (this._target.parent === this._parent) {
  49880. return;
  49881. }
  49882. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49883. invertParentWorldMatrix.invert();
  49884. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49885. this._target.parent = this._parent;
  49886. };
  49887. SetParentAction.prototype.serialize = function (parent) {
  49888. return _super.prototype._serialize.call(this, {
  49889. name: "SetParentAction",
  49890. properties: [
  49891. BABYLON.Action._GetTargetProperty(this._target),
  49892. BABYLON.Action._GetTargetProperty(this._parent),
  49893. ]
  49894. }, parent);
  49895. };
  49896. return SetParentAction;
  49897. }(BABYLON.Action));
  49898. BABYLON.SetParentAction = SetParentAction;
  49899. var PlaySoundAction = /** @class */ (function (_super) {
  49900. __extends(PlaySoundAction, _super);
  49901. function PlaySoundAction(triggerOptions, sound, condition) {
  49902. var _this = _super.call(this, triggerOptions, condition) || this;
  49903. _this._sound = sound;
  49904. return _this;
  49905. }
  49906. PlaySoundAction.prototype._prepare = function () {
  49907. };
  49908. PlaySoundAction.prototype.execute = function () {
  49909. if (this._sound !== undefined)
  49910. this._sound.play();
  49911. };
  49912. PlaySoundAction.prototype.serialize = function (parent) {
  49913. return _super.prototype._serialize.call(this, {
  49914. name: "PlaySoundAction",
  49915. properties: [{ name: "sound", value: this._sound.name }]
  49916. }, parent);
  49917. };
  49918. return PlaySoundAction;
  49919. }(BABYLON.Action));
  49920. BABYLON.PlaySoundAction = PlaySoundAction;
  49921. var StopSoundAction = /** @class */ (function (_super) {
  49922. __extends(StopSoundAction, _super);
  49923. function StopSoundAction(triggerOptions, sound, condition) {
  49924. var _this = _super.call(this, triggerOptions, condition) || this;
  49925. _this._sound = sound;
  49926. return _this;
  49927. }
  49928. StopSoundAction.prototype._prepare = function () {
  49929. };
  49930. StopSoundAction.prototype.execute = function () {
  49931. if (this._sound !== undefined)
  49932. this._sound.stop();
  49933. };
  49934. StopSoundAction.prototype.serialize = function (parent) {
  49935. return _super.prototype._serialize.call(this, {
  49936. name: "StopSoundAction",
  49937. properties: [{ name: "sound", value: this._sound.name }]
  49938. }, parent);
  49939. };
  49940. return StopSoundAction;
  49941. }(BABYLON.Action));
  49942. BABYLON.StopSoundAction = StopSoundAction;
  49943. })(BABYLON || (BABYLON = {}));
  49944. //# sourceMappingURL=babylon.directActions.js.map
  49945. "use strict";
  49946. var BABYLON;
  49947. (function (BABYLON) {
  49948. var SpriteManager = /** @class */ (function () {
  49949. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49950. if (epsilon === void 0) { epsilon = 0.01; }
  49951. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49952. this.name = name;
  49953. this.sprites = new Array();
  49954. this.renderingGroupId = 0;
  49955. this.layerMask = 0x0FFFFFFF;
  49956. this.fogEnabled = true;
  49957. this.isPickable = false;
  49958. /**
  49959. * An event triggered when the manager is disposed.
  49960. * @type {BABYLON.Observable}
  49961. */
  49962. this.onDisposeObservable = new BABYLON.Observable();
  49963. this._vertexBuffers = {};
  49964. this._capacity = capacity;
  49965. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49966. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49967. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49968. if (cellSize.width && cellSize.height) {
  49969. this.cellWidth = cellSize.width;
  49970. this.cellHeight = cellSize.height;
  49971. }
  49972. else if (cellSize !== undefined) {
  49973. this.cellWidth = cellSize;
  49974. this.cellHeight = cellSize;
  49975. }
  49976. else {
  49977. return;
  49978. }
  49979. this._epsilon = epsilon;
  49980. this._scene = scene;
  49981. this._scene.spriteManagers.push(this);
  49982. var indices = [];
  49983. var index = 0;
  49984. for (var count = 0; count < capacity; count++) {
  49985. indices.push(index);
  49986. indices.push(index + 1);
  49987. indices.push(index + 2);
  49988. indices.push(index);
  49989. indices.push(index + 2);
  49990. indices.push(index + 3);
  49991. index += 4;
  49992. }
  49993. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49994. // VBO
  49995. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49996. this._vertexData = new Float32Array(capacity * 16 * 4);
  49997. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49998. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49999. var options = this._buffer.createVertexBuffer("options", 4, 4);
  50000. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  50001. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  50002. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50003. this._vertexBuffers["options"] = options;
  50004. this._vertexBuffers["cellInfo"] = cellInfo;
  50005. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50006. // Effects
  50007. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  50008. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  50009. }
  50010. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  50011. set: function (callback) {
  50012. if (this._onDisposeObserver) {
  50013. this.onDisposeObservable.remove(this._onDisposeObserver);
  50014. }
  50015. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50016. },
  50017. enumerable: true,
  50018. configurable: true
  50019. });
  50020. Object.defineProperty(SpriteManager.prototype, "texture", {
  50021. get: function () {
  50022. return this._spriteTexture;
  50023. },
  50024. set: function (value) {
  50025. this._spriteTexture = value;
  50026. },
  50027. enumerable: true,
  50028. configurable: true
  50029. });
  50030. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  50031. var arrayOffset = index * 16;
  50032. if (offsetX === 0)
  50033. offsetX = this._epsilon;
  50034. else if (offsetX === 1)
  50035. offsetX = 1 - this._epsilon;
  50036. if (offsetY === 0)
  50037. offsetY = this._epsilon;
  50038. else if (offsetY === 1)
  50039. offsetY = 1 - this._epsilon;
  50040. this._vertexData[arrayOffset] = sprite.position.x;
  50041. this._vertexData[arrayOffset + 1] = sprite.position.y;
  50042. this._vertexData[arrayOffset + 2] = sprite.position.z;
  50043. this._vertexData[arrayOffset + 3] = sprite.angle;
  50044. this._vertexData[arrayOffset + 4] = sprite.width;
  50045. this._vertexData[arrayOffset + 5] = sprite.height;
  50046. this._vertexData[arrayOffset + 6] = offsetX;
  50047. this._vertexData[arrayOffset + 7] = offsetY;
  50048. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  50049. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  50050. var offset = (sprite.cellIndex / rowSize) >> 0;
  50051. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  50052. this._vertexData[arrayOffset + 11] = offset;
  50053. // Color
  50054. this._vertexData[arrayOffset + 12] = sprite.color.r;
  50055. this._vertexData[arrayOffset + 13] = sprite.color.g;
  50056. this._vertexData[arrayOffset + 14] = sprite.color.b;
  50057. this._vertexData[arrayOffset + 15] = sprite.color.a;
  50058. };
  50059. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  50060. var count = Math.min(this._capacity, this.sprites.length);
  50061. var min = BABYLON.Vector3.Zero();
  50062. var max = BABYLON.Vector3.Zero();
  50063. var distance = Number.MAX_VALUE;
  50064. var currentSprite = null;
  50065. var cameraSpacePosition = BABYLON.Vector3.Zero();
  50066. var cameraView = camera.getViewMatrix();
  50067. for (var index = 0; index < count; index++) {
  50068. var sprite = this.sprites[index];
  50069. if (!sprite) {
  50070. continue;
  50071. }
  50072. if (predicate) {
  50073. if (!predicate(sprite)) {
  50074. continue;
  50075. }
  50076. }
  50077. else if (!sprite.isPickable) {
  50078. continue;
  50079. }
  50080. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  50081. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  50082. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  50083. if (ray.intersectsBoxMinMax(min, max)) {
  50084. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  50085. if (distance > currentDistance) {
  50086. distance = currentDistance;
  50087. currentSprite = sprite;
  50088. if (fastCheck) {
  50089. break;
  50090. }
  50091. }
  50092. }
  50093. }
  50094. if (currentSprite) {
  50095. var result = new BABYLON.PickingInfo();
  50096. result.hit = true;
  50097. result.pickedSprite = currentSprite;
  50098. result.distance = distance;
  50099. return result;
  50100. }
  50101. return null;
  50102. };
  50103. SpriteManager.prototype.render = function () {
  50104. // Check
  50105. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  50106. return;
  50107. var engine = this._scene.getEngine();
  50108. var baseSize = this._spriteTexture.getBaseSize();
  50109. // Sprites
  50110. var deltaTime = engine.getDeltaTime();
  50111. var max = Math.min(this._capacity, this.sprites.length);
  50112. var rowSize = baseSize.width / this.cellWidth;
  50113. var offset = 0;
  50114. for (var index = 0; index < max; index++) {
  50115. var sprite = this.sprites[index];
  50116. if (!sprite) {
  50117. continue;
  50118. }
  50119. sprite._animate(deltaTime);
  50120. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  50121. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  50122. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  50123. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  50124. }
  50125. this._buffer.update(this._vertexData);
  50126. // Render
  50127. var effect = this._effectBase;
  50128. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50129. effect = this._effectFog;
  50130. }
  50131. engine.enableEffect(effect);
  50132. var viewMatrix = this._scene.getViewMatrix();
  50133. effect.setTexture("diffuseSampler", this._spriteTexture);
  50134. effect.setMatrix("view", viewMatrix);
  50135. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50136. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  50137. // Fog
  50138. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50139. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  50140. effect.setColor3("vFogColor", this._scene.fogColor);
  50141. }
  50142. // VBOs
  50143. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50144. // Draw order
  50145. engine.setDepthFunctionToLessOrEqual();
  50146. effect.setBool("alphaTest", true);
  50147. engine.setColorWrite(false);
  50148. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50149. engine.setColorWrite(true);
  50150. effect.setBool("alphaTest", false);
  50151. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50152. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50153. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50154. };
  50155. SpriteManager.prototype.dispose = function () {
  50156. if (this._buffer) {
  50157. this._buffer.dispose();
  50158. this._buffer = null;
  50159. }
  50160. if (this._indexBuffer) {
  50161. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50162. this._indexBuffer = null;
  50163. }
  50164. if (this._spriteTexture) {
  50165. this._spriteTexture.dispose();
  50166. this._spriteTexture = null;
  50167. }
  50168. // Remove from scene
  50169. var index = this._scene.spriteManagers.indexOf(this);
  50170. this._scene.spriteManagers.splice(index, 1);
  50171. // Callback
  50172. this.onDisposeObservable.notifyObservers(this);
  50173. this.onDisposeObservable.clear();
  50174. };
  50175. return SpriteManager;
  50176. }());
  50177. BABYLON.SpriteManager = SpriteManager;
  50178. })(BABYLON || (BABYLON = {}));
  50179. //# sourceMappingURL=babylon.spriteManager.js.map
  50180. "use strict";
  50181. var BABYLON;
  50182. (function (BABYLON) {
  50183. var Sprite = /** @class */ (function () {
  50184. function Sprite(name, manager) {
  50185. this.name = name;
  50186. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50187. this.width = 1.0;
  50188. this.height = 1.0;
  50189. this.angle = 0;
  50190. this.cellIndex = 0;
  50191. this.invertU = 0;
  50192. this.invertV = 0;
  50193. this.animations = new Array();
  50194. this.isPickable = false;
  50195. this._animationStarted = false;
  50196. this._loopAnimation = false;
  50197. this._fromIndex = 0;
  50198. this._toIndex = 0;
  50199. this._delay = 0;
  50200. this._direction = 1;
  50201. this._time = 0;
  50202. this._manager = manager;
  50203. this._manager.sprites.push(this);
  50204. this.position = BABYLON.Vector3.Zero();
  50205. }
  50206. Object.defineProperty(Sprite.prototype, "size", {
  50207. get: function () {
  50208. return this.width;
  50209. },
  50210. set: function (value) {
  50211. this.width = value;
  50212. this.height = value;
  50213. },
  50214. enumerable: true,
  50215. configurable: true
  50216. });
  50217. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50218. this._fromIndex = from;
  50219. this._toIndex = to;
  50220. this._loopAnimation = loop;
  50221. this._delay = delay;
  50222. this._animationStarted = true;
  50223. this._direction = from < to ? 1 : -1;
  50224. this.cellIndex = from;
  50225. this._time = 0;
  50226. this._onAnimationEnd = onAnimationEnd;
  50227. };
  50228. Sprite.prototype.stopAnimation = function () {
  50229. this._animationStarted = false;
  50230. };
  50231. Sprite.prototype._animate = function (deltaTime) {
  50232. if (!this._animationStarted)
  50233. return;
  50234. this._time += deltaTime;
  50235. if (this._time > this._delay) {
  50236. this._time = this._time % this._delay;
  50237. this.cellIndex += this._direction;
  50238. if (this.cellIndex > this._toIndex) {
  50239. if (this._loopAnimation) {
  50240. this.cellIndex = this._fromIndex;
  50241. }
  50242. else {
  50243. this.cellIndex = this._toIndex;
  50244. this._animationStarted = false;
  50245. if (this._onAnimationEnd) {
  50246. this._onAnimationEnd();
  50247. }
  50248. if (this.disposeWhenFinishedAnimating) {
  50249. this.dispose();
  50250. }
  50251. }
  50252. }
  50253. }
  50254. };
  50255. Sprite.prototype.dispose = function () {
  50256. for (var i = 0; i < this._manager.sprites.length; i++) {
  50257. if (this._manager.sprites[i] == this) {
  50258. this._manager.sprites.splice(i, 1);
  50259. }
  50260. }
  50261. };
  50262. return Sprite;
  50263. }());
  50264. BABYLON.Sprite = Sprite;
  50265. })(BABYLON || (BABYLON = {}));
  50266. //# sourceMappingURL=babylon.sprite.js.map
  50267. "use strict";
  50268. var BABYLON;
  50269. (function (BABYLON) {
  50270. var IntersectionInfo = /** @class */ (function () {
  50271. function IntersectionInfo(bu, bv, distance) {
  50272. this.bu = bu;
  50273. this.bv = bv;
  50274. this.distance = distance;
  50275. this.faceId = 0;
  50276. this.subMeshId = 0;
  50277. }
  50278. return IntersectionInfo;
  50279. }());
  50280. BABYLON.IntersectionInfo = IntersectionInfo;
  50281. var PickingInfo = /** @class */ (function () {
  50282. function PickingInfo() {
  50283. this.hit = false;
  50284. this.distance = 0;
  50285. this.pickedPoint = null;
  50286. this.pickedMesh = null;
  50287. this.bu = 0;
  50288. this.bv = 0;
  50289. this.faceId = -1;
  50290. this.subMeshId = 0;
  50291. this.pickedSprite = null;
  50292. }
  50293. // Methods
  50294. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50295. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50296. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50297. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50298. return null;
  50299. }
  50300. var indices = this.pickedMesh.getIndices();
  50301. if (!indices) {
  50302. return null;
  50303. }
  50304. var result;
  50305. if (useVerticesNormals) {
  50306. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50307. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50308. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50309. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50310. normal0 = normal0.scale(this.bu);
  50311. normal1 = normal1.scale(this.bv);
  50312. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50313. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50314. }
  50315. else {
  50316. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50317. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50318. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50319. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50320. var p1p2 = vertex1.subtract(vertex2);
  50321. var p3p2 = vertex3.subtract(vertex2);
  50322. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50323. }
  50324. if (useWorldCoordinates) {
  50325. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50326. }
  50327. return BABYLON.Vector3.Normalize(result);
  50328. };
  50329. PickingInfo.prototype.getTextureCoordinates = function () {
  50330. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50331. return null;
  50332. }
  50333. var indices = this.pickedMesh.getIndices();
  50334. if (!indices) {
  50335. return null;
  50336. }
  50337. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50338. if (!uvs) {
  50339. return null;
  50340. }
  50341. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50342. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50343. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50344. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50345. uv1 = uv1.scale(this.bu);
  50346. uv2 = uv2.scale(this.bv);
  50347. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50348. };
  50349. return PickingInfo;
  50350. }());
  50351. BABYLON.PickingInfo = PickingInfo;
  50352. })(BABYLON || (BABYLON = {}));
  50353. //# sourceMappingURL=babylon.pickingInfo.js.map
  50354. "use strict";
  50355. var BABYLON;
  50356. (function (BABYLON) {
  50357. var Ray = /** @class */ (function () {
  50358. function Ray(origin, direction, length) {
  50359. if (length === void 0) { length = Number.MAX_VALUE; }
  50360. this.origin = origin;
  50361. this.direction = direction;
  50362. this.length = length;
  50363. }
  50364. // Methods
  50365. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50366. var d = 0.0;
  50367. var maxValue = Number.MAX_VALUE;
  50368. var inv;
  50369. var min;
  50370. var max;
  50371. var temp;
  50372. if (Math.abs(this.direction.x) < 0.0000001) {
  50373. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50374. return false;
  50375. }
  50376. }
  50377. else {
  50378. inv = 1.0 / this.direction.x;
  50379. min = (minimum.x - this.origin.x) * inv;
  50380. max = (maximum.x - this.origin.x) * inv;
  50381. if (max === -Infinity) {
  50382. max = Infinity;
  50383. }
  50384. if (min > max) {
  50385. temp = min;
  50386. min = max;
  50387. max = temp;
  50388. }
  50389. d = Math.max(min, d);
  50390. maxValue = Math.min(max, maxValue);
  50391. if (d > maxValue) {
  50392. return false;
  50393. }
  50394. }
  50395. if (Math.abs(this.direction.y) < 0.0000001) {
  50396. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50397. return false;
  50398. }
  50399. }
  50400. else {
  50401. inv = 1.0 / this.direction.y;
  50402. min = (minimum.y - this.origin.y) * inv;
  50403. max = (maximum.y - this.origin.y) * inv;
  50404. if (max === -Infinity) {
  50405. max = Infinity;
  50406. }
  50407. if (min > max) {
  50408. temp = min;
  50409. min = max;
  50410. max = temp;
  50411. }
  50412. d = Math.max(min, d);
  50413. maxValue = Math.min(max, maxValue);
  50414. if (d > maxValue) {
  50415. return false;
  50416. }
  50417. }
  50418. if (Math.abs(this.direction.z) < 0.0000001) {
  50419. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50420. return false;
  50421. }
  50422. }
  50423. else {
  50424. inv = 1.0 / this.direction.z;
  50425. min = (minimum.z - this.origin.z) * inv;
  50426. max = (maximum.z - this.origin.z) * inv;
  50427. if (max === -Infinity) {
  50428. max = Infinity;
  50429. }
  50430. if (min > max) {
  50431. temp = min;
  50432. min = max;
  50433. max = temp;
  50434. }
  50435. d = Math.max(min, d);
  50436. maxValue = Math.min(max, maxValue);
  50437. if (d > maxValue) {
  50438. return false;
  50439. }
  50440. }
  50441. return true;
  50442. };
  50443. Ray.prototype.intersectsBox = function (box) {
  50444. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50445. };
  50446. Ray.prototype.intersectsSphere = function (sphere) {
  50447. var x = sphere.center.x - this.origin.x;
  50448. var y = sphere.center.y - this.origin.y;
  50449. var z = sphere.center.z - this.origin.z;
  50450. var pyth = (x * x) + (y * y) + (z * z);
  50451. var rr = sphere.radius * sphere.radius;
  50452. if (pyth <= rr) {
  50453. return true;
  50454. }
  50455. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50456. if (dot < 0.0) {
  50457. return false;
  50458. }
  50459. var temp = pyth - (dot * dot);
  50460. return temp <= rr;
  50461. };
  50462. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50463. if (!this._edge1) {
  50464. this._edge1 = BABYLON.Vector3.Zero();
  50465. this._edge2 = BABYLON.Vector3.Zero();
  50466. this._pvec = BABYLON.Vector3.Zero();
  50467. this._tvec = BABYLON.Vector3.Zero();
  50468. this._qvec = BABYLON.Vector3.Zero();
  50469. }
  50470. vertex1.subtractToRef(vertex0, this._edge1);
  50471. vertex2.subtractToRef(vertex0, this._edge2);
  50472. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50473. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50474. if (det === 0) {
  50475. return null;
  50476. }
  50477. var invdet = 1 / det;
  50478. this.origin.subtractToRef(vertex0, this._tvec);
  50479. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50480. if (bu < 0 || bu > 1.0) {
  50481. return null;
  50482. }
  50483. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50484. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50485. if (bv < 0 || bu + bv > 1.0) {
  50486. return null;
  50487. }
  50488. //check if the distance is longer than the predefined length.
  50489. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50490. if (distance > this.length) {
  50491. return null;
  50492. }
  50493. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50494. };
  50495. Ray.prototype.intersectsPlane = function (plane) {
  50496. var distance;
  50497. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50498. if (Math.abs(result1) < 9.99999997475243E-07) {
  50499. return null;
  50500. }
  50501. else {
  50502. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50503. distance = (-plane.d - result2) / result1;
  50504. if (distance < 0.0) {
  50505. if (distance < -9.99999997475243E-07) {
  50506. return null;
  50507. }
  50508. else {
  50509. return 0;
  50510. }
  50511. }
  50512. return distance;
  50513. }
  50514. };
  50515. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50516. var tm = BABYLON.Tmp.Matrix[0];
  50517. mesh.getWorldMatrix().invertToRef(tm);
  50518. if (this._tmpRay) {
  50519. Ray.TransformToRef(this, tm, this._tmpRay);
  50520. }
  50521. else {
  50522. this._tmpRay = Ray.Transform(this, tm);
  50523. }
  50524. return mesh.intersects(this._tmpRay, fastCheck);
  50525. };
  50526. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50527. if (results) {
  50528. results.length = 0;
  50529. }
  50530. else {
  50531. results = [];
  50532. }
  50533. for (var i = 0; i < meshes.length; i++) {
  50534. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50535. if (pickInfo.hit) {
  50536. results.push(pickInfo);
  50537. }
  50538. }
  50539. results.sort(this._comparePickingInfo);
  50540. return results;
  50541. };
  50542. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50543. if (pickingInfoA.distance < pickingInfoB.distance) {
  50544. return -1;
  50545. }
  50546. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50547. return 1;
  50548. }
  50549. else {
  50550. return 0;
  50551. }
  50552. };
  50553. /**
  50554. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50555. * @param sega the first point of the segment to test the intersection against
  50556. * @param segb the second point of the segment to test the intersection against
  50557. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50558. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50559. */
  50560. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50561. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50562. var u = segb.subtract(sega);
  50563. var v = rsegb.subtract(this.origin);
  50564. var w = sega.subtract(this.origin);
  50565. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50566. var b = BABYLON.Vector3.Dot(u, v);
  50567. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50568. var d = BABYLON.Vector3.Dot(u, w);
  50569. var e = BABYLON.Vector3.Dot(v, w);
  50570. var D = a * c - b * b; // always >= 0
  50571. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50572. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50573. // compute the line parameters of the two closest points
  50574. if (D < Ray.smallnum) {
  50575. sN = 0.0; // force using point P0 on segment S1
  50576. sD = 1.0; // to prevent possible division by 0.0 later
  50577. tN = e;
  50578. tD = c;
  50579. }
  50580. else {
  50581. sN = (b * e - c * d);
  50582. tN = (a * e - b * d);
  50583. if (sN < 0.0) {
  50584. sN = 0.0;
  50585. tN = e;
  50586. tD = c;
  50587. }
  50588. else if (sN > sD) {
  50589. sN = sD;
  50590. tN = e + b;
  50591. tD = c;
  50592. }
  50593. }
  50594. if (tN < 0.0) {
  50595. tN = 0.0;
  50596. // recompute sc for this edge
  50597. if (-d < 0.0) {
  50598. sN = 0.0;
  50599. }
  50600. else if (-d > a)
  50601. sN = sD;
  50602. else {
  50603. sN = -d;
  50604. sD = a;
  50605. }
  50606. }
  50607. else if (tN > tD) {
  50608. tN = tD;
  50609. // recompute sc for this edge
  50610. if ((-d + b) < 0.0) {
  50611. sN = 0;
  50612. }
  50613. else if ((-d + b) > a) {
  50614. sN = sD;
  50615. }
  50616. else {
  50617. sN = (-d + b);
  50618. sD = a;
  50619. }
  50620. }
  50621. // finally do the division to get sc and tc
  50622. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50623. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50624. // get the difference of the two closest points
  50625. var qtc = v.multiplyByFloats(tc, tc, tc);
  50626. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50627. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50628. if (isIntersected) {
  50629. return qtc.length();
  50630. }
  50631. return -1;
  50632. };
  50633. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50634. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50635. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50636. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50637. this.direction.normalize();
  50638. return this;
  50639. };
  50640. // Statics
  50641. Ray.Zero = function () {
  50642. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50643. };
  50644. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50645. var result = Ray.Zero();
  50646. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50647. };
  50648. /**
  50649. * 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
  50650. * transformed to the given world matrix.
  50651. * @param origin The origin point
  50652. * @param end The end point
  50653. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50654. */
  50655. Ray.CreateNewFromTo = function (origin, end, world) {
  50656. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50657. var direction = end.subtract(origin);
  50658. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50659. direction.normalize();
  50660. return Ray.Transform(new Ray(origin, direction, length), world);
  50661. };
  50662. Ray.Transform = function (ray, matrix) {
  50663. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50664. Ray.TransformToRef(ray, matrix, result);
  50665. return result;
  50666. };
  50667. Ray.TransformToRef = function (ray, matrix, result) {
  50668. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50669. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50670. result.length = ray.length;
  50671. var dir = result.direction;
  50672. var len = dir.length();
  50673. if (!(len === 0 || len === 1)) {
  50674. var num = 1.0 / len;
  50675. dir.x *= num;
  50676. dir.y *= num;
  50677. dir.z *= num;
  50678. result.length *= len;
  50679. }
  50680. };
  50681. Ray.smallnum = 0.00000001;
  50682. Ray.rayl = 10e8;
  50683. return Ray;
  50684. }());
  50685. BABYLON.Ray = Ray;
  50686. })(BABYLON || (BABYLON = {}));
  50687. //# sourceMappingURL=babylon.ray.js.map
  50688. "use strict";
  50689. var BABYLON;
  50690. (function (BABYLON) {
  50691. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50692. if (boxMin.x > sphereCenter.x + sphereRadius)
  50693. return false;
  50694. if (sphereCenter.x - sphereRadius > boxMax.x)
  50695. return false;
  50696. if (boxMin.y > sphereCenter.y + sphereRadius)
  50697. return false;
  50698. if (sphereCenter.y - sphereRadius > boxMax.y)
  50699. return false;
  50700. if (boxMin.z > sphereCenter.z + sphereRadius)
  50701. return false;
  50702. if (sphereCenter.z - sphereRadius > boxMax.z)
  50703. return false;
  50704. return true;
  50705. };
  50706. var getLowestRoot = (function () {
  50707. var result = { root: 0, found: false };
  50708. return function (a, b, c, maxR) {
  50709. result.root = 0;
  50710. result.found = false;
  50711. var determinant = b * b - 4.0 * a * c;
  50712. if (determinant < 0)
  50713. return result;
  50714. var sqrtD = Math.sqrt(determinant);
  50715. var r1 = (-b - sqrtD) / (2.0 * a);
  50716. var r2 = (-b + sqrtD) / (2.0 * a);
  50717. if (r1 > r2) {
  50718. var temp = r2;
  50719. r2 = r1;
  50720. r1 = temp;
  50721. }
  50722. if (r1 > 0 && r1 < maxR) {
  50723. result.root = r1;
  50724. result.found = true;
  50725. return result;
  50726. }
  50727. if (r2 > 0 && r2 < maxR) {
  50728. result.root = r2;
  50729. result.found = true;
  50730. return result;
  50731. }
  50732. return result;
  50733. };
  50734. })();
  50735. var Collider = /** @class */ (function () {
  50736. function Collider() {
  50737. this._collisionPoint = BABYLON.Vector3.Zero();
  50738. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50739. this._tempVector = BABYLON.Vector3.Zero();
  50740. this._tempVector2 = BABYLON.Vector3.Zero();
  50741. this._tempVector3 = BABYLON.Vector3.Zero();
  50742. this._tempVector4 = BABYLON.Vector3.Zero();
  50743. this._edge = BABYLON.Vector3.Zero();
  50744. this._baseToVertex = BABYLON.Vector3.Zero();
  50745. this._destinationPoint = BABYLON.Vector3.Zero();
  50746. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50747. this._displacementVector = BABYLON.Vector3.Zero();
  50748. this._radius = BABYLON.Vector3.One();
  50749. this._retry = 0;
  50750. this._basePointWorld = BABYLON.Vector3.Zero();
  50751. this._velocityWorld = BABYLON.Vector3.Zero();
  50752. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50753. this._collisionMask = -1;
  50754. }
  50755. Object.defineProperty(Collider.prototype, "collisionMask", {
  50756. get: function () {
  50757. return this._collisionMask;
  50758. },
  50759. set: function (mask) {
  50760. this._collisionMask = !isNaN(mask) ? mask : -1;
  50761. },
  50762. enumerable: true,
  50763. configurable: true
  50764. });
  50765. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50766. /**
  50767. * Gets the plane normal used to compute the sliding response (in local space)
  50768. */
  50769. get: function () {
  50770. return this._slidePlaneNormal;
  50771. },
  50772. enumerable: true,
  50773. configurable: true
  50774. });
  50775. // Methods
  50776. Collider.prototype._initialize = function (source, dir, e) {
  50777. this._velocity = dir;
  50778. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50779. this._basePoint = source;
  50780. source.multiplyToRef(this._radius, this._basePointWorld);
  50781. dir.multiplyToRef(this._radius, this._velocityWorld);
  50782. this._velocityWorldLength = this._velocityWorld.length();
  50783. this._epsilon = e;
  50784. this.collisionFound = false;
  50785. };
  50786. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50787. pa.subtractToRef(point, this._tempVector);
  50788. pb.subtractToRef(point, this._tempVector2);
  50789. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50790. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50791. if (d < 0)
  50792. return false;
  50793. pc.subtractToRef(point, this._tempVector3);
  50794. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50795. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50796. if (d < 0)
  50797. return false;
  50798. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50799. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50800. return d >= 0;
  50801. };
  50802. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50803. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50804. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50805. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50806. return false;
  50807. }
  50808. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50809. return false;
  50810. return true;
  50811. };
  50812. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50813. var t0;
  50814. var embeddedInPlane = false;
  50815. //defensive programming, actually not needed.
  50816. if (!trianglePlaneArray) {
  50817. trianglePlaneArray = [];
  50818. }
  50819. if (!trianglePlaneArray[faceIndex]) {
  50820. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50821. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50822. }
  50823. var trianglePlane = trianglePlaneArray[faceIndex];
  50824. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50825. return;
  50826. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50827. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50828. if (normalDotVelocity == 0) {
  50829. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50830. return;
  50831. embeddedInPlane = true;
  50832. t0 = 0;
  50833. }
  50834. else {
  50835. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50836. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50837. if (t0 > t1) {
  50838. var temp = t1;
  50839. t1 = t0;
  50840. t0 = temp;
  50841. }
  50842. if (t0 > 1.0 || t1 < 0.0)
  50843. return;
  50844. if (t0 < 0)
  50845. t0 = 0;
  50846. if (t0 > 1.0)
  50847. t0 = 1.0;
  50848. }
  50849. this._collisionPoint.copyFromFloats(0, 0, 0);
  50850. var found = false;
  50851. var t = 1.0;
  50852. if (!embeddedInPlane) {
  50853. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50854. this._velocity.scaleToRef(t0, this._tempVector);
  50855. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50856. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50857. found = true;
  50858. t = t0;
  50859. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50860. }
  50861. }
  50862. if (!found) {
  50863. var velocitySquaredLength = this._velocity.lengthSquared();
  50864. var a = velocitySquaredLength;
  50865. this._basePoint.subtractToRef(p1, this._tempVector);
  50866. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50867. var c = this._tempVector.lengthSquared() - 1.0;
  50868. var lowestRoot = getLowestRoot(a, b, c, t);
  50869. if (lowestRoot.found) {
  50870. t = lowestRoot.root;
  50871. found = true;
  50872. this._collisionPoint.copyFrom(p1);
  50873. }
  50874. this._basePoint.subtractToRef(p2, this._tempVector);
  50875. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50876. c = this._tempVector.lengthSquared() - 1.0;
  50877. lowestRoot = getLowestRoot(a, b, c, t);
  50878. if (lowestRoot.found) {
  50879. t = lowestRoot.root;
  50880. found = true;
  50881. this._collisionPoint.copyFrom(p2);
  50882. }
  50883. this._basePoint.subtractToRef(p3, this._tempVector);
  50884. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50885. c = this._tempVector.lengthSquared() - 1.0;
  50886. lowestRoot = getLowestRoot(a, b, c, t);
  50887. if (lowestRoot.found) {
  50888. t = lowestRoot.root;
  50889. found = true;
  50890. this._collisionPoint.copyFrom(p3);
  50891. }
  50892. p2.subtractToRef(p1, this._edge);
  50893. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50894. var edgeSquaredLength = this._edge.lengthSquared();
  50895. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50896. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50897. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50898. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50899. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50900. lowestRoot = getLowestRoot(a, b, c, t);
  50901. if (lowestRoot.found) {
  50902. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50903. if (f >= 0.0 && f <= 1.0) {
  50904. t = lowestRoot.root;
  50905. found = true;
  50906. this._edge.scaleInPlace(f);
  50907. p1.addToRef(this._edge, this._collisionPoint);
  50908. }
  50909. }
  50910. p3.subtractToRef(p2, this._edge);
  50911. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50912. edgeSquaredLength = this._edge.lengthSquared();
  50913. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50914. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50915. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50916. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50917. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50918. lowestRoot = getLowestRoot(a, b, c, t);
  50919. if (lowestRoot.found) {
  50920. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50921. if (f >= 0.0 && f <= 1.0) {
  50922. t = lowestRoot.root;
  50923. found = true;
  50924. this._edge.scaleInPlace(f);
  50925. p2.addToRef(this._edge, this._collisionPoint);
  50926. }
  50927. }
  50928. p1.subtractToRef(p3, this._edge);
  50929. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50930. edgeSquaredLength = this._edge.lengthSquared();
  50931. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50932. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50933. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50934. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50935. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50936. lowestRoot = getLowestRoot(a, b, c, t);
  50937. if (lowestRoot.found) {
  50938. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50939. if (f >= 0.0 && f <= 1.0) {
  50940. t = lowestRoot.root;
  50941. found = true;
  50942. this._edge.scaleInPlace(f);
  50943. p3.addToRef(this._edge, this._collisionPoint);
  50944. }
  50945. }
  50946. }
  50947. if (found) {
  50948. var distToCollision = t * this._velocity.length();
  50949. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50950. if (!this.intersectionPoint) {
  50951. this.intersectionPoint = this._collisionPoint.clone();
  50952. }
  50953. else {
  50954. this.intersectionPoint.copyFrom(this._collisionPoint);
  50955. }
  50956. this._nearestDistance = distToCollision;
  50957. this.collisionFound = true;
  50958. }
  50959. }
  50960. };
  50961. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50962. for (var i = indexStart; i < indexEnd; i += 3) {
  50963. var p1 = pts[indices[i] - decal];
  50964. var p2 = pts[indices[i + 1] - decal];
  50965. var p3 = pts[indices[i + 2] - decal];
  50966. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50967. }
  50968. };
  50969. Collider.prototype._getResponse = function (pos, vel) {
  50970. pos.addToRef(vel, this._destinationPoint);
  50971. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50972. this._basePoint.addToRef(vel, pos);
  50973. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50974. this._slidePlaneNormal.normalize();
  50975. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50976. pos.addInPlace(this._displacementVector);
  50977. this.intersectionPoint.addInPlace(this._displacementVector);
  50978. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50979. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50980. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50981. };
  50982. return Collider;
  50983. }());
  50984. BABYLON.Collider = Collider;
  50985. })(BABYLON || (BABYLON = {}));
  50986. //# sourceMappingURL=babylon.collider.js.map
  50987. "use strict";
  50988. var BABYLON;
  50989. (function (BABYLON) {
  50990. //WebWorker code will be inserted to this variable.
  50991. BABYLON.CollisionWorker = "";
  50992. var WorkerTaskType;
  50993. (function (WorkerTaskType) {
  50994. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50995. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50996. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50997. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50998. var WorkerReplyType;
  50999. (function (WorkerReplyType) {
  51000. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  51001. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  51002. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  51003. var CollisionCoordinatorWorker = /** @class */ (function () {
  51004. function CollisionCoordinatorWorker() {
  51005. var _this = this;
  51006. this._scaledPosition = BABYLON.Vector3.Zero();
  51007. this._scaledVelocity = BABYLON.Vector3.Zero();
  51008. this.onMeshUpdated = function (transformNode) {
  51009. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  51010. };
  51011. this.onGeometryUpdated = function (geometry) {
  51012. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  51013. };
  51014. this._afterRender = function () {
  51015. if (!_this._init)
  51016. return;
  51017. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  51018. return;
  51019. }
  51020. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  51021. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  51022. if (_this._runningUpdated > 4) {
  51023. return;
  51024. }
  51025. ++_this._runningUpdated;
  51026. var payload = {
  51027. updatedMeshes: _this._addUpdateMeshesList,
  51028. updatedGeometries: _this._addUpdateGeometriesList,
  51029. removedGeometries: _this._toRemoveGeometryArray,
  51030. removedMeshes: _this._toRemoveMeshesArray
  51031. };
  51032. var message = {
  51033. payload: payload,
  51034. taskType: WorkerTaskType.UPDATE
  51035. };
  51036. var serializable = [];
  51037. for (var id in payload.updatedGeometries) {
  51038. if (payload.updatedGeometries.hasOwnProperty(id)) {
  51039. //prepare transferables
  51040. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  51041. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  51042. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  51043. }
  51044. }
  51045. _this._worker.postMessage(message, serializable);
  51046. _this._addUpdateMeshesList = {};
  51047. _this._addUpdateGeometriesList = {};
  51048. _this._toRemoveGeometryArray = [];
  51049. _this._toRemoveMeshesArray = [];
  51050. };
  51051. this._onMessageFromWorker = function (e) {
  51052. var returnData = e.data;
  51053. if (returnData.error != WorkerReplyType.SUCCESS) {
  51054. //TODO what errors can be returned from the worker?
  51055. BABYLON.Tools.Warn("error returned from worker!");
  51056. return;
  51057. }
  51058. switch (returnData.taskType) {
  51059. case WorkerTaskType.INIT:
  51060. _this._init = true;
  51061. //Update the worked with ALL of the scene's current state
  51062. _this._scene.meshes.forEach(function (mesh) {
  51063. _this.onMeshAdded(mesh);
  51064. });
  51065. _this._scene.getGeometries().forEach(function (geometry) {
  51066. _this.onGeometryAdded(geometry);
  51067. });
  51068. break;
  51069. case WorkerTaskType.UPDATE:
  51070. _this._runningUpdated--;
  51071. break;
  51072. case WorkerTaskType.COLLIDE:
  51073. var returnPayload = returnData.payload;
  51074. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  51075. return;
  51076. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  51077. if (callback) {
  51078. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  51079. if (mesh) {
  51080. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  51081. }
  51082. }
  51083. //cleanup
  51084. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  51085. break;
  51086. }
  51087. };
  51088. this._collisionsCallbackArray = [];
  51089. this._init = false;
  51090. this._runningUpdated = 0;
  51091. this._addUpdateMeshesList = {};
  51092. this._addUpdateGeometriesList = {};
  51093. this._toRemoveGeometryArray = [];
  51094. this._toRemoveMeshesArray = [];
  51095. }
  51096. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51097. if (!this._init)
  51098. return;
  51099. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  51100. return;
  51101. position.divideToRef(collider._radius, this._scaledPosition);
  51102. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51103. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  51104. var payload = {
  51105. collider: {
  51106. position: this._scaledPosition.asArray(),
  51107. velocity: this._scaledVelocity.asArray(),
  51108. radius: collider._radius.asArray()
  51109. },
  51110. collisionId: collisionIndex,
  51111. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  51112. maximumRetry: maximumRetry
  51113. };
  51114. var message = {
  51115. payload: payload,
  51116. taskType: WorkerTaskType.COLLIDE
  51117. };
  51118. this._worker.postMessage(message);
  51119. };
  51120. CollisionCoordinatorWorker.prototype.init = function (scene) {
  51121. this._scene = scene;
  51122. this._scene.registerAfterRender(this._afterRender);
  51123. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  51124. this._worker = new Worker(workerUrl);
  51125. this._worker.onmessage = this._onMessageFromWorker;
  51126. var message = {
  51127. payload: {},
  51128. taskType: WorkerTaskType.INIT
  51129. };
  51130. this._worker.postMessage(message);
  51131. };
  51132. CollisionCoordinatorWorker.prototype.destroy = function () {
  51133. this._scene.unregisterAfterRender(this._afterRender);
  51134. this._worker.terminate();
  51135. };
  51136. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  51137. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  51138. this.onMeshUpdated(mesh);
  51139. };
  51140. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  51141. this._toRemoveMeshesArray.push(mesh.uniqueId);
  51142. };
  51143. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  51144. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  51145. geometry.onGeometryUpdated = this.onGeometryUpdated;
  51146. this.onGeometryUpdated(geometry);
  51147. };
  51148. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  51149. this._toRemoveGeometryArray.push(geometry.id);
  51150. };
  51151. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  51152. var submeshes = [];
  51153. if (mesh.subMeshes) {
  51154. submeshes = mesh.subMeshes.map(function (sm, idx) {
  51155. var boundingInfo = sm.getBoundingInfo();
  51156. return {
  51157. position: idx,
  51158. verticesStart: sm.verticesStart,
  51159. verticesCount: sm.verticesCount,
  51160. indexStart: sm.indexStart,
  51161. indexCount: sm.indexCount,
  51162. hasMaterial: !!sm.getMaterial(),
  51163. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51164. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51165. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51166. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  51167. };
  51168. });
  51169. }
  51170. var geometryId = null;
  51171. if (mesh instanceof BABYLON.Mesh) {
  51172. var geometry = mesh.geometry;
  51173. geometryId = geometry ? geometry.id : null;
  51174. }
  51175. else if (mesh instanceof BABYLON.InstancedMesh) {
  51176. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  51177. geometryId = geometry ? geometry.id : null;
  51178. }
  51179. var boundingInfo = mesh.getBoundingInfo();
  51180. return {
  51181. uniqueId: mesh.uniqueId,
  51182. id: mesh.id,
  51183. name: mesh.name,
  51184. geometryId: geometryId,
  51185. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51186. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51187. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51188. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  51189. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  51190. subMeshes: submeshes,
  51191. checkCollisions: mesh.checkCollisions
  51192. };
  51193. };
  51194. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  51195. return {
  51196. id: geometry.id,
  51197. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51198. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51199. indices: new Uint32Array(geometry.getIndices() || []),
  51200. };
  51201. };
  51202. return CollisionCoordinatorWorker;
  51203. }());
  51204. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51205. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51206. function CollisionCoordinatorLegacy() {
  51207. this._scaledPosition = BABYLON.Vector3.Zero();
  51208. this._scaledVelocity = BABYLON.Vector3.Zero();
  51209. this._finalPosition = BABYLON.Vector3.Zero();
  51210. }
  51211. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51212. position.divideToRef(collider._radius, this._scaledPosition);
  51213. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51214. collider.collidedMesh = null;
  51215. collider._retry = 0;
  51216. collider._initialVelocity = this._scaledVelocity;
  51217. collider._initialPosition = this._scaledPosition;
  51218. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51219. this._finalPosition.multiplyInPlace(collider._radius);
  51220. //run the callback
  51221. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51222. };
  51223. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51224. this._scene = scene;
  51225. };
  51226. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51227. //Legacy need no destruction method.
  51228. };
  51229. //No update in legacy mode
  51230. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51231. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51232. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51233. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51234. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51235. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51236. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51237. if (excludedMesh === void 0) { excludedMesh = null; }
  51238. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51239. if (collider._retry >= maximumRetry) {
  51240. finalPosition.copyFrom(position);
  51241. return;
  51242. }
  51243. // Check if this is a mesh else camera or -1
  51244. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51245. collider._initialize(position, velocity, closeDistance);
  51246. // Check all meshes
  51247. for (var index = 0; index < this._scene.meshes.length; index++) {
  51248. var mesh = this._scene.meshes[index];
  51249. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51250. mesh._checkCollision(collider);
  51251. }
  51252. }
  51253. if (!collider.collisionFound) {
  51254. position.addToRef(velocity, finalPosition);
  51255. return;
  51256. }
  51257. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51258. collider._getResponse(position, velocity);
  51259. }
  51260. if (velocity.length() <= closeDistance) {
  51261. finalPosition.copyFrom(position);
  51262. return;
  51263. }
  51264. collider._retry++;
  51265. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51266. };
  51267. return CollisionCoordinatorLegacy;
  51268. }());
  51269. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51270. })(BABYLON || (BABYLON = {}));
  51271. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51272. "use strict";
  51273. var BABYLON;
  51274. (function (BABYLON) {
  51275. /**
  51276. * A particle represents one of the element emitted by a particle system.
  51277. * This is mainly define by its coordinates, direction, velocity and age.
  51278. */
  51279. var Particle = /** @class */ (function () {
  51280. /**
  51281. * Creates a new instance of @see Particle
  51282. * @param particleSystem the particle system the particle belongs to
  51283. */
  51284. function Particle(
  51285. /**
  51286. * particleSystem the particle system the particle belongs to.
  51287. */
  51288. particleSystem) {
  51289. this.particleSystem = particleSystem;
  51290. /**
  51291. * The world position of the particle in the scene.
  51292. */
  51293. this.position = BABYLON.Vector3.Zero();
  51294. /**
  51295. * The world direction of the particle in the scene.
  51296. */
  51297. this.direction = BABYLON.Vector3.Zero();
  51298. /**
  51299. * The color of the particle.
  51300. */
  51301. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51302. /**
  51303. * The color change of the particle per step.
  51304. */
  51305. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51306. /**
  51307. * Defines how long will the life of the particle be.
  51308. */
  51309. this.lifeTime = 1.0;
  51310. /**
  51311. * The current age of the particle.
  51312. */
  51313. this.age = 0;
  51314. /**
  51315. * The current size of the particle.
  51316. */
  51317. this.size = 0;
  51318. /**
  51319. * The current angle of the particle.
  51320. */
  51321. this.angle = 0;
  51322. /**
  51323. * Defines how fast is the angle changing.
  51324. */
  51325. this.angularSpeed = 0;
  51326. /**
  51327. * Defines the cell index used by the particle to be rendered from a sprite.
  51328. */
  51329. this.cellIndex = 0;
  51330. this._currentFrameCounter = 0;
  51331. if (!this.particleSystem.isAnimationSheetEnabled) {
  51332. return;
  51333. }
  51334. this.updateCellInfoFromSystem();
  51335. }
  51336. Particle.prototype.updateCellInfoFromSystem = function () {
  51337. this.cellIndex = this.particleSystem.startSpriteCellID;
  51338. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51339. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51340. }
  51341. else {
  51342. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51343. }
  51344. };
  51345. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51346. // (ageOffset / scaledUpdateSpeed) / available cells
  51347. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51348. this._currentFrameCounter += scaledUpdateSpeed;
  51349. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51350. this._currentFrameCounter = 0;
  51351. this.cellIndex++;
  51352. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51353. this.cellIndex = this.particleSystem.endSpriteCellID;
  51354. }
  51355. }
  51356. };
  51357. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51358. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51359. this.cellIndex++;
  51360. this._currentFrameCounter = 0;
  51361. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51362. if (this.particleSystem.spriteCellLoop) {
  51363. this.cellIndex = this.particleSystem.startSpriteCellID;
  51364. }
  51365. else {
  51366. this.cellIndex = this.particleSystem.endSpriteCellID;
  51367. }
  51368. }
  51369. }
  51370. else {
  51371. this._currentFrameCounter++;
  51372. }
  51373. };
  51374. /**
  51375. * Copy the properties of particle to another one.
  51376. * @param other the particle to copy the information to.
  51377. */
  51378. Particle.prototype.copyTo = function (other) {
  51379. other.position.copyFrom(this.position);
  51380. other.direction.copyFrom(this.direction);
  51381. other.color.copyFrom(this.color);
  51382. other.colorStep.copyFrom(this.colorStep);
  51383. other.lifeTime = this.lifeTime;
  51384. other.age = this.age;
  51385. other.size = this.size;
  51386. other.angle = this.angle;
  51387. other.angularSpeed = this.angularSpeed;
  51388. other.particleSystem = this.particleSystem;
  51389. other.cellIndex = this.cellIndex;
  51390. };
  51391. return Particle;
  51392. }());
  51393. BABYLON.Particle = Particle;
  51394. })(BABYLON || (BABYLON = {}));
  51395. //# sourceMappingURL=babylon.particle.js.map
  51396. "use strict";
  51397. var BABYLON;
  51398. (function (BABYLON) {
  51399. /**
  51400. * This represents a particle system in Babylon.
  51401. * 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.
  51402. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51403. * @example https://doc.babylonjs.com/babylon101/particles
  51404. */
  51405. var ParticleSystem = /** @class */ (function () {
  51406. /**
  51407. * Instantiates a particle system.
  51408. * 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.
  51409. * @param name The name of the particle system
  51410. * @param capacity The max number of particles alive at the same time
  51411. * @param scene The scene the particle system belongs to
  51412. * @param customEffect a custom effect used to change the way particles are rendered by default
  51413. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51414. * @param epsilon Offset used to render the particles
  51415. */
  51416. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51417. if (customEffect === void 0) { customEffect = null; }
  51418. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51419. if (epsilon === void 0) { epsilon = 0.01; }
  51420. var _this = this;
  51421. /**
  51422. * List of animations used by the particle system.
  51423. */
  51424. this.animations = [];
  51425. /**
  51426. * The rendering group used by the Particle system to chose when to render.
  51427. */
  51428. this.renderingGroupId = 0;
  51429. /**
  51430. * The emitter represents the Mesh or position we are attaching the particle system to.
  51431. */
  51432. this.emitter = null;
  51433. /**
  51434. * The maximum number of particles to emit per frame
  51435. */
  51436. this.emitRate = 10;
  51437. /**
  51438. * If you want to launch only a few particles at once, that can be done, as well.
  51439. */
  51440. this.manualEmitCount = -1;
  51441. /**
  51442. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51443. */
  51444. this.updateSpeed = 0.01;
  51445. /**
  51446. * The amount of time the particle system is running (depends of the overall update speed).
  51447. */
  51448. this.targetStopDuration = 0;
  51449. /**
  51450. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51451. */
  51452. this.disposeOnStop = false;
  51453. /**
  51454. * Minimum power of emitting particles.
  51455. */
  51456. this.minEmitPower = 1;
  51457. /**
  51458. * Maximum power of emitting particles.
  51459. */
  51460. this.maxEmitPower = 1;
  51461. /**
  51462. * Minimum life time of emitting particles.
  51463. */
  51464. this.minLifeTime = 1;
  51465. /**
  51466. * Maximum life time of emitting particles.
  51467. */
  51468. this.maxLifeTime = 1;
  51469. /**
  51470. * Minimum Size of emitting particles.
  51471. */
  51472. this.minSize = 1;
  51473. /**
  51474. * Maximum Size of emitting particles.
  51475. */
  51476. this.maxSize = 1;
  51477. /**
  51478. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51479. */
  51480. this.minAngularSpeed = 0;
  51481. /**
  51482. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51483. */
  51484. this.maxAngularSpeed = 0;
  51485. /**
  51486. * The layer mask we are rendering the particles through.
  51487. */
  51488. this.layerMask = 0x0FFFFFFF;
  51489. /**
  51490. * This can help using your own shader to render the particle system.
  51491. * The according effect will be created
  51492. */
  51493. this.customShader = null;
  51494. /**
  51495. * By default particle system starts as soon as they are created. This prevents the
  51496. * automatic start to happen and let you decide when to start emitting particles.
  51497. */
  51498. this.preventAutoStart = false;
  51499. /**
  51500. * Callback triggered when the particle animation is ending.
  51501. */
  51502. this.onAnimationEnd = null;
  51503. /**
  51504. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51505. */
  51506. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51507. /**
  51508. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51509. * to override the particles.
  51510. */
  51511. this.forceDepthWrite = false;
  51512. /**
  51513. * You can use gravity if you want to give an orientation to your particles.
  51514. */
  51515. this.gravity = BABYLON.Vector3.Zero();
  51516. /**
  51517. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51518. */
  51519. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51520. /**
  51521. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51522. */
  51523. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51524. /**
  51525. * Color the particle will have at the end of its lifetime.
  51526. */
  51527. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51528. /**
  51529. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51530. */
  51531. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51532. /**
  51533. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51534. */
  51535. this.spriteCellLoop = true;
  51536. /**
  51537. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51538. */
  51539. this.spriteCellChangeSpeed = 0;
  51540. /**
  51541. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51542. */
  51543. this.startSpriteCellID = 0;
  51544. /**
  51545. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51546. */
  51547. this.endSpriteCellID = 0;
  51548. /**
  51549. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51550. */
  51551. this.spriteCellWidth = 0;
  51552. /**
  51553. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51554. */
  51555. this.spriteCellHeight = 0;
  51556. /**
  51557. * An event triggered when the system is disposed.
  51558. */
  51559. this.onDisposeObservable = new BABYLON.Observable();
  51560. this._particles = new Array();
  51561. this._stockParticles = new Array();
  51562. this._newPartsExcess = 0;
  51563. this._vertexBuffers = {};
  51564. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51565. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51566. this._scaledDirection = BABYLON.Vector3.Zero();
  51567. this._scaledGravity = BABYLON.Vector3.Zero();
  51568. this._currentRenderId = -1;
  51569. this._started = false;
  51570. this._stopped = false;
  51571. this._actualFrame = 0;
  51572. this._vertexBufferSize = 11;
  51573. // start of sub system methods
  51574. /**
  51575. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51576. * Its lifetime will start back at 0.
  51577. */
  51578. this.recycleParticle = function (particle) {
  51579. var lastParticle = _this._particles.pop();
  51580. if (lastParticle !== particle) {
  51581. lastParticle.copyTo(particle);
  51582. }
  51583. _this._stockParticles.push(lastParticle);
  51584. };
  51585. this._createParticle = function () {
  51586. var particle;
  51587. if (_this._stockParticles.length !== 0) {
  51588. particle = _this._stockParticles.pop();
  51589. particle.age = 0;
  51590. particle.cellIndex = _this.startSpriteCellID;
  51591. }
  51592. else {
  51593. particle = new BABYLON.Particle(_this);
  51594. }
  51595. return particle;
  51596. };
  51597. this._emitFromParticle = function (particle) {
  51598. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51599. return;
  51600. }
  51601. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51602. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51603. subSystem._rootParticleSystem = _this;
  51604. _this.activeSubSystems.push(subSystem);
  51605. subSystem.start();
  51606. };
  51607. this._appendParticleVertexes = null;
  51608. this.id = name;
  51609. this.name = name;
  51610. this._capacity = capacity;
  51611. this._epsilon = epsilon;
  51612. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51613. if (isAnimationSheetEnabled) {
  51614. this._vertexBufferSize = 12;
  51615. }
  51616. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51617. this._customEffect = customEffect;
  51618. scene.particleSystems.push(this);
  51619. this._createIndexBuffer();
  51620. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51621. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51622. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51623. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51624. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51625. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51626. if (this._isAnimationSheetEnabled) {
  51627. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51628. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51629. }
  51630. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51631. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51632. this._vertexBuffers["options"] = options;
  51633. // Default emitter type
  51634. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51635. this.updateFunction = function (particles) {
  51636. for (var index = 0; index < particles.length; index++) {
  51637. var particle = particles[index];
  51638. particle.age += _this._scaledUpdateSpeed;
  51639. if (particle.age >= particle.lifeTime) {
  51640. _this._emitFromParticle(particle);
  51641. _this.recycleParticle(particle);
  51642. index--;
  51643. continue;
  51644. }
  51645. else {
  51646. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51647. particle.color.addInPlace(_this._scaledColorStep);
  51648. if (particle.color.a < 0)
  51649. particle.color.a = 0;
  51650. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51651. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51652. particle.position.addInPlace(_this._scaledDirection);
  51653. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51654. particle.direction.addInPlace(_this._scaledGravity);
  51655. if (_this._isAnimationSheetEnabled) {
  51656. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51657. }
  51658. }
  51659. }
  51660. };
  51661. }
  51662. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51663. /**
  51664. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51665. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51666. */
  51667. get: function () {
  51668. if (this.particleEmitterType.direction1) {
  51669. return this.particleEmitterType.direction1;
  51670. }
  51671. return BABYLON.Vector3.Zero();
  51672. },
  51673. set: function (value) {
  51674. if (this.particleEmitterType.direction1) {
  51675. this.particleEmitterType.direction1 = value;
  51676. }
  51677. },
  51678. enumerable: true,
  51679. configurable: true
  51680. });
  51681. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51682. /**
  51683. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51684. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51685. */
  51686. get: function () {
  51687. if (this.particleEmitterType.direction2) {
  51688. return this.particleEmitterType.direction2;
  51689. }
  51690. return BABYLON.Vector3.Zero();
  51691. },
  51692. set: function (value) {
  51693. if (this.particleEmitterType.direction2) {
  51694. this.particleEmitterType.direction2 = value;
  51695. }
  51696. },
  51697. enumerable: true,
  51698. configurable: true
  51699. });
  51700. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51701. /**
  51702. * 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.
  51703. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51704. */
  51705. get: function () {
  51706. if (this.particleEmitterType.minEmitBox) {
  51707. return this.particleEmitterType.minEmitBox;
  51708. }
  51709. return BABYLON.Vector3.Zero();
  51710. },
  51711. set: function (value) {
  51712. if (this.particleEmitterType.minEmitBox) {
  51713. this.particleEmitterType.minEmitBox = value;
  51714. }
  51715. },
  51716. enumerable: true,
  51717. configurable: true
  51718. });
  51719. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51720. /**
  51721. * 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.
  51722. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51723. */
  51724. get: function () {
  51725. if (this.particleEmitterType.maxEmitBox) {
  51726. return this.particleEmitterType.maxEmitBox;
  51727. }
  51728. return BABYLON.Vector3.Zero();
  51729. },
  51730. set: function (value) {
  51731. if (this.particleEmitterType.maxEmitBox) {
  51732. this.particleEmitterType.maxEmitBox = value;
  51733. }
  51734. },
  51735. enumerable: true,
  51736. configurable: true
  51737. });
  51738. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51739. /**
  51740. * Sets a callback that will be triggered when the system is disposed.
  51741. */
  51742. set: function (callback) {
  51743. if (this._onDisposeObserver) {
  51744. this.onDisposeObservable.remove(this._onDisposeObserver);
  51745. }
  51746. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51747. },
  51748. enumerable: true,
  51749. configurable: true
  51750. });
  51751. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51752. /**
  51753. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51754. */
  51755. get: function () {
  51756. return this._isAnimationSheetEnabled;
  51757. },
  51758. enumerable: true,
  51759. configurable: true
  51760. });
  51761. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51762. //end of Sub-emitter
  51763. /**
  51764. * Gets the current list of active particles
  51765. */
  51766. get: function () {
  51767. return this._particles;
  51768. },
  51769. enumerable: true,
  51770. configurable: true
  51771. });
  51772. /**
  51773. * Returns the string "ParticleSystem"
  51774. * @returns a string containing the class name
  51775. */
  51776. ParticleSystem.prototype.getClassName = function () {
  51777. return "ParticleSystem";
  51778. };
  51779. ParticleSystem.prototype._createIndexBuffer = function () {
  51780. var indices = [];
  51781. var index = 0;
  51782. for (var count = 0; count < this._capacity; count++) {
  51783. indices.push(index);
  51784. indices.push(index + 1);
  51785. indices.push(index + 2);
  51786. indices.push(index);
  51787. indices.push(index + 2);
  51788. indices.push(index + 3);
  51789. index += 4;
  51790. }
  51791. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51792. };
  51793. /**
  51794. * Gets the maximum number of particles active at the same time.
  51795. * @returns The max number of active particles.
  51796. */
  51797. ParticleSystem.prototype.getCapacity = function () {
  51798. return this._capacity;
  51799. };
  51800. /**
  51801. * Gets Wether there are still active particles in the system.
  51802. * @returns True if it is alive, otherwise false.
  51803. */
  51804. ParticleSystem.prototype.isAlive = function () {
  51805. return this._alive;
  51806. };
  51807. /**
  51808. * Gets Wether the system has been started.
  51809. * @returns True if it has been started, otherwise false.
  51810. */
  51811. ParticleSystem.prototype.isStarted = function () {
  51812. return this._started;
  51813. };
  51814. /**
  51815. * Starts the particle system and begins to emit.
  51816. */
  51817. ParticleSystem.prototype.start = function () {
  51818. this._started = true;
  51819. this._stopped = false;
  51820. this._actualFrame = 0;
  51821. if (this.subEmitters && this.subEmitters.length != 0) {
  51822. this.activeSubSystems = new Array();
  51823. }
  51824. };
  51825. /**
  51826. * Stops the particle system.
  51827. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  51828. */
  51829. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51830. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51831. this._stopped = true;
  51832. if (stopSubEmitters) {
  51833. this._stopSubEmitters();
  51834. }
  51835. };
  51836. // animation sheet
  51837. /**
  51838. * Remove all active particles
  51839. */
  51840. ParticleSystem.prototype.reset = function () {
  51841. this._stockParticles = [];
  51842. this._particles = [];
  51843. };
  51844. /**
  51845. * @ignore (for internal use only)
  51846. */
  51847. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51848. var offset = index * this._vertexBufferSize;
  51849. this._vertexData[offset] = particle.position.x;
  51850. this._vertexData[offset + 1] = particle.position.y;
  51851. this._vertexData[offset + 2] = particle.position.z;
  51852. this._vertexData[offset + 3] = particle.color.r;
  51853. this._vertexData[offset + 4] = particle.color.g;
  51854. this._vertexData[offset + 5] = particle.color.b;
  51855. this._vertexData[offset + 6] = particle.color.a;
  51856. this._vertexData[offset + 7] = particle.angle;
  51857. this._vertexData[offset + 8] = particle.size;
  51858. this._vertexData[offset + 9] = offsetX;
  51859. this._vertexData[offset + 10] = offsetY;
  51860. };
  51861. /**
  51862. * @ignore (for internal use only)
  51863. */
  51864. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51865. if (offsetX === 0)
  51866. offsetX = this._epsilon;
  51867. else if (offsetX === 1)
  51868. offsetX = 1 - this._epsilon;
  51869. if (offsetY === 0)
  51870. offsetY = this._epsilon;
  51871. else if (offsetY === 1)
  51872. offsetY = 1 - this._epsilon;
  51873. var offset = index * this._vertexBufferSize;
  51874. this._vertexData[offset] = particle.position.x;
  51875. this._vertexData[offset + 1] = particle.position.y;
  51876. this._vertexData[offset + 2] = particle.position.z;
  51877. this._vertexData[offset + 3] = particle.color.r;
  51878. this._vertexData[offset + 4] = particle.color.g;
  51879. this._vertexData[offset + 5] = particle.color.b;
  51880. this._vertexData[offset + 6] = particle.color.a;
  51881. this._vertexData[offset + 7] = particle.angle;
  51882. this._vertexData[offset + 8] = particle.size;
  51883. this._vertexData[offset + 9] = offsetX;
  51884. this._vertexData[offset + 10] = offsetY;
  51885. this._vertexData[offset + 11] = particle.cellIndex;
  51886. };
  51887. ParticleSystem.prototype._stopSubEmitters = function () {
  51888. if (!this.activeSubSystems) {
  51889. return;
  51890. }
  51891. this.activeSubSystems.forEach(function (subSystem) {
  51892. subSystem.stop(true);
  51893. });
  51894. this.activeSubSystems = new Array();
  51895. };
  51896. ParticleSystem.prototype._removeFromRoot = function () {
  51897. if (!this._rootParticleSystem) {
  51898. return;
  51899. }
  51900. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51901. if (index !== -1) {
  51902. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51903. }
  51904. };
  51905. // end of sub system methods
  51906. ParticleSystem.prototype._update = function (newParticles) {
  51907. // Update current
  51908. this._alive = this._particles.length > 0;
  51909. this.updateFunction(this._particles);
  51910. // Add new ones
  51911. var worldMatrix;
  51912. if (this.emitter.position) {
  51913. var emitterMesh = this.emitter;
  51914. worldMatrix = emitterMesh.getWorldMatrix();
  51915. }
  51916. else {
  51917. var emitterPosition = this.emitter;
  51918. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51919. }
  51920. var particle;
  51921. for (var index = 0; index < newParticles; index++) {
  51922. if (this._particles.length === this._capacity) {
  51923. break;
  51924. }
  51925. particle = this._createParticle();
  51926. this._particles.push(particle);
  51927. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51928. if (this.startPositionFunction) {
  51929. this.startPositionFunction(worldMatrix, particle.position, particle);
  51930. }
  51931. else {
  51932. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51933. }
  51934. if (this.startDirectionFunction) {
  51935. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51936. }
  51937. else {
  51938. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51939. }
  51940. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51941. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51942. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51943. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51944. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51945. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51946. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51947. }
  51948. };
  51949. ParticleSystem.prototype._getEffect = function () {
  51950. if (this._customEffect) {
  51951. return this._customEffect;
  51952. }
  51953. ;
  51954. var defines = [];
  51955. if (this._scene.clipPlane) {
  51956. defines.push("#define CLIPPLANE");
  51957. }
  51958. if (this._isAnimationSheetEnabled) {
  51959. defines.push("#define ANIMATESHEET");
  51960. }
  51961. // Effect
  51962. var join = defines.join("\n");
  51963. if (this._cachedDefines !== join) {
  51964. this._cachedDefines = join;
  51965. var attributesNamesOrOptions;
  51966. var effectCreationOption;
  51967. if (this._isAnimationSheetEnabled) {
  51968. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51969. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51970. }
  51971. else {
  51972. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51973. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51974. }
  51975. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51976. }
  51977. return this._effect;
  51978. };
  51979. /**
  51980. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51981. */
  51982. ParticleSystem.prototype.animate = function () {
  51983. if (!this._started)
  51984. return;
  51985. var effect = this._getEffect();
  51986. // Check
  51987. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51988. return;
  51989. if (this._currentRenderId === this._scene.getRenderId()) {
  51990. return;
  51991. }
  51992. this._currentRenderId = this._scene.getRenderId();
  51993. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51994. // determine the number of particles we need to create
  51995. var newParticles;
  51996. if (this.manualEmitCount > -1) {
  51997. newParticles = this.manualEmitCount;
  51998. this._newPartsExcess = 0;
  51999. this.manualEmitCount = 0;
  52000. }
  52001. else {
  52002. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  52003. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  52004. }
  52005. if (this._newPartsExcess > 1.0) {
  52006. newParticles += this._newPartsExcess >> 0;
  52007. this._newPartsExcess -= this._newPartsExcess >> 0;
  52008. }
  52009. this._alive = false;
  52010. if (!this._stopped) {
  52011. this._actualFrame += this._scaledUpdateSpeed;
  52012. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52013. this.stop();
  52014. }
  52015. else {
  52016. newParticles = 0;
  52017. }
  52018. this._update(newParticles);
  52019. // Stopped?
  52020. if (this._stopped) {
  52021. if (!this._alive) {
  52022. this._started = false;
  52023. if (this.onAnimationEnd) {
  52024. this.onAnimationEnd();
  52025. }
  52026. if (this.disposeOnStop) {
  52027. this._scene._toBeDisposed.push(this);
  52028. }
  52029. }
  52030. }
  52031. // Animation sheet
  52032. if (this._isAnimationSheetEnabled) {
  52033. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  52034. }
  52035. else {
  52036. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  52037. }
  52038. // Update VBO
  52039. var offset = 0;
  52040. for (var index = 0; index < this._particles.length; index++) {
  52041. var particle = this._particles[index];
  52042. this._appendParticleVertexes(offset, particle);
  52043. offset += 4;
  52044. }
  52045. if (this._vertexBuffer) {
  52046. this._vertexBuffer.update(this._vertexData);
  52047. }
  52048. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  52049. this.stop();
  52050. }
  52051. };
  52052. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  52053. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  52054. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  52055. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  52056. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  52057. };
  52058. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  52059. this._appendParticleVertex(offset++, particle, 0, 0);
  52060. this._appendParticleVertex(offset++, particle, 1, 0);
  52061. this._appendParticleVertex(offset++, particle, 1, 1);
  52062. this._appendParticleVertex(offset++, particle, 0, 1);
  52063. };
  52064. /**
  52065. * Rebuilds the particle system.
  52066. */
  52067. ParticleSystem.prototype.rebuild = function () {
  52068. this._createIndexBuffer();
  52069. if (this._vertexBuffer) {
  52070. this._vertexBuffer._rebuild();
  52071. }
  52072. };
  52073. /**
  52074. * Is this system ready to be used/rendered
  52075. * @return true if the system is ready
  52076. */
  52077. ParticleSystem.prototype.isReady = function () {
  52078. var effect = this._getEffect();
  52079. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52080. return false;
  52081. }
  52082. return true;
  52083. };
  52084. /**
  52085. * Renders the particle system in its current state.
  52086. * @returns the current number of particles
  52087. */
  52088. ParticleSystem.prototype.render = function () {
  52089. var effect = this._getEffect();
  52090. // Check
  52091. if (!this.isReady() || !this._particles.length) {
  52092. return 0;
  52093. }
  52094. var engine = this._scene.getEngine();
  52095. // Render
  52096. engine.enableEffect(effect);
  52097. engine.setState(false);
  52098. var viewMatrix = this._scene.getViewMatrix();
  52099. effect.setTexture("diffuseSampler", this.particleTexture);
  52100. effect.setMatrix("view", viewMatrix);
  52101. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52102. if (this._isAnimationSheetEnabled && this.particleTexture) {
  52103. var baseSize = this.particleTexture.getBaseSize();
  52104. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  52105. }
  52106. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  52107. if (this._scene.clipPlane) {
  52108. var clipPlane = this._scene.clipPlane;
  52109. var invView = viewMatrix.clone();
  52110. invView.invert();
  52111. effect.setMatrix("invView", invView);
  52112. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52113. }
  52114. // VBOs
  52115. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52116. // Draw order
  52117. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  52118. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52119. }
  52120. else {
  52121. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52122. }
  52123. if (this.forceDepthWrite) {
  52124. engine.setDepthWrite(true);
  52125. }
  52126. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  52127. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52128. return this._particles.length;
  52129. };
  52130. /**
  52131. * Disposes the particle system and free the associated resources
  52132. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52133. */
  52134. ParticleSystem.prototype.dispose = function (disposeTexture) {
  52135. if (disposeTexture === void 0) { disposeTexture = true; }
  52136. if (this._vertexBuffer) {
  52137. this._vertexBuffer.dispose();
  52138. this._vertexBuffer = null;
  52139. }
  52140. if (this._indexBuffer) {
  52141. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52142. this._indexBuffer = null;
  52143. }
  52144. if (disposeTexture && this.particleTexture) {
  52145. this.particleTexture.dispose();
  52146. this.particleTexture = null;
  52147. }
  52148. this._removeFromRoot();
  52149. // Remove from scene
  52150. var index = this._scene.particleSystems.indexOf(this);
  52151. if (index > -1) {
  52152. this._scene.particleSystems.splice(index, 1);
  52153. }
  52154. // Callback
  52155. this.onDisposeObservable.notifyObservers(this);
  52156. this.onDisposeObservable.clear();
  52157. };
  52158. /**
  52159. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  52160. * @param radius The radius of the sphere to emit from
  52161. * @returns the emitter
  52162. */
  52163. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  52164. if (radius === void 0) { radius = 1; }
  52165. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  52166. this.particleEmitterType = particleEmitter;
  52167. return particleEmitter;
  52168. };
  52169. /**
  52170. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  52171. * @param radius The radius of the sphere to emit from
  52172. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  52173. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  52174. * @returns the emitter
  52175. */
  52176. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  52177. if (radius === void 0) { radius = 1; }
  52178. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  52179. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  52180. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  52181. this.particleEmitterType = particleEmitter;
  52182. return particleEmitter;
  52183. };
  52184. /**
  52185. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  52186. * @param radius The radius of the cone to emit from
  52187. * @param angle The base angle of the cone
  52188. * @returns the emitter
  52189. */
  52190. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  52191. if (radius === void 0) { radius = 1; }
  52192. if (angle === void 0) { angle = Math.PI / 4; }
  52193. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  52194. this.particleEmitterType = particleEmitter;
  52195. return particleEmitter;
  52196. };
  52197. // 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.
  52198. /**
  52199. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52200. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52201. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52202. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52203. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52204. * @returns the emitter
  52205. */
  52206. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52207. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52208. this.direction1 = direction1;
  52209. this.direction2 = direction2;
  52210. this.minEmitBox = minEmitBox;
  52211. this.maxEmitBox = maxEmitBox;
  52212. this.particleEmitterType = particleEmitter;
  52213. return particleEmitter;
  52214. };
  52215. // Clone
  52216. /**
  52217. * Clones the particle system.
  52218. * @param name The name of the cloned object
  52219. * @param newEmitter The new emitter to use
  52220. * @returns the cloned particle system
  52221. */
  52222. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52223. var custom = null;
  52224. var program = null;
  52225. if (this.customShader != null) {
  52226. program = this.customShader;
  52227. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52228. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52229. }
  52230. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52231. result.customShader = program;
  52232. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52233. if (newEmitter === undefined) {
  52234. newEmitter = this.emitter;
  52235. }
  52236. result.emitter = newEmitter;
  52237. if (this.particleTexture) {
  52238. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52239. }
  52240. if (!this.preventAutoStart) {
  52241. result.start();
  52242. }
  52243. return result;
  52244. };
  52245. /**
  52246. * Serializes the particle system to a JSON object.
  52247. * @returns the JSON object
  52248. */
  52249. ParticleSystem.prototype.serialize = function () {
  52250. var serializationObject = {};
  52251. serializationObject.name = this.name;
  52252. serializationObject.id = this.id;
  52253. // Emitter
  52254. if (this.emitter.position) {
  52255. var emitterMesh = this.emitter;
  52256. serializationObject.emitterId = emitterMesh.id;
  52257. }
  52258. else {
  52259. var emitterPosition = this.emitter;
  52260. serializationObject.emitter = emitterPosition.asArray();
  52261. }
  52262. serializationObject.capacity = this.getCapacity();
  52263. if (this.particleTexture) {
  52264. serializationObject.textureName = this.particleTexture.name;
  52265. }
  52266. // Animations
  52267. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52268. // Particle system
  52269. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52270. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52271. serializationObject.minSize = this.minSize;
  52272. serializationObject.maxSize = this.maxSize;
  52273. serializationObject.minEmitPower = this.minEmitPower;
  52274. serializationObject.maxEmitPower = this.maxEmitPower;
  52275. serializationObject.minLifeTime = this.minLifeTime;
  52276. serializationObject.maxLifeTime = this.maxLifeTime;
  52277. serializationObject.emitRate = this.emitRate;
  52278. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52279. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52280. serializationObject.gravity = this.gravity.asArray();
  52281. serializationObject.direction1 = this.direction1.asArray();
  52282. serializationObject.direction2 = this.direction2.asArray();
  52283. serializationObject.color1 = this.color1.asArray();
  52284. serializationObject.color2 = this.color2.asArray();
  52285. serializationObject.colorDead = this.colorDead.asArray();
  52286. serializationObject.updateSpeed = this.updateSpeed;
  52287. serializationObject.targetStopDuration = this.targetStopDuration;
  52288. serializationObject.textureMask = this.textureMask.asArray();
  52289. serializationObject.blendMode = this.blendMode;
  52290. serializationObject.customShader = this.customShader;
  52291. serializationObject.preventAutoStart = this.preventAutoStart;
  52292. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52293. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52294. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52295. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52296. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52297. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52298. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52299. // Emitter
  52300. if (this.particleEmitterType) {
  52301. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52302. }
  52303. return serializationObject;
  52304. };
  52305. /**
  52306. * Parses a JSON object to create a particle system.
  52307. * @param parsedParticleSystem The JSON object to parse
  52308. * @param scene The scene to create the particle system in
  52309. * @param rootUrl The root url to use to load external dependencies like texture
  52310. * @returns the Parsed particle system
  52311. */
  52312. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52313. var name = parsedParticleSystem.name;
  52314. var custom = null;
  52315. var program = null;
  52316. if (parsedParticleSystem.customShader) {
  52317. program = parsedParticleSystem.customShader;
  52318. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52319. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52320. }
  52321. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52322. particleSystem.customShader = program;
  52323. if (parsedParticleSystem.id) {
  52324. particleSystem.id = parsedParticleSystem.id;
  52325. }
  52326. // Auto start
  52327. if (parsedParticleSystem.preventAutoStart) {
  52328. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52329. }
  52330. // Texture
  52331. if (parsedParticleSystem.textureName) {
  52332. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52333. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52334. }
  52335. // Emitter
  52336. if (parsedParticleSystem.emitterId) {
  52337. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52338. }
  52339. else {
  52340. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52341. }
  52342. // Animations
  52343. if (parsedParticleSystem.animations) {
  52344. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52345. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52346. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52347. }
  52348. }
  52349. if (parsedParticleSystem.autoAnimate) {
  52350. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52351. }
  52352. // Particle system
  52353. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52354. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52355. particleSystem.minSize = parsedParticleSystem.minSize;
  52356. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52357. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52358. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52359. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52360. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52361. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52362. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52363. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52364. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52365. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52366. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52367. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52368. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52369. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52370. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52371. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52372. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52373. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52374. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52375. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52376. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52377. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52378. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52379. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52380. if (!particleSystem.preventAutoStart) {
  52381. particleSystem.start();
  52382. }
  52383. return particleSystem;
  52384. };
  52385. /**
  52386. * Source color is added to the destination color without alpha affecting the result.
  52387. */
  52388. ParticleSystem.BLENDMODE_ONEONE = 0;
  52389. /**
  52390. * Blend current color and particle color using particle’s alpha.
  52391. */
  52392. ParticleSystem.BLENDMODE_STANDARD = 1;
  52393. return ParticleSystem;
  52394. }());
  52395. BABYLON.ParticleSystem = ParticleSystem;
  52396. })(BABYLON || (BABYLON = {}));
  52397. //# sourceMappingURL=babylon.particleSystem.js.map
  52398. "use strict";
  52399. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52400. "use strict";
  52401. var BABYLON;
  52402. (function (BABYLON) {
  52403. /**
  52404. * Particle emitter emitting particles from the inside of a box.
  52405. * It emits the particles randomly between 2 given directions.
  52406. */
  52407. var BoxParticleEmitter = /** @class */ (function () {
  52408. /**
  52409. * Creates a new instance of @see BoxParticleEmitter
  52410. */
  52411. function BoxParticleEmitter() {
  52412. /**
  52413. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52414. */
  52415. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52416. /**
  52417. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52418. */
  52419. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52420. /**
  52421. * 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.
  52422. */
  52423. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52424. /**
  52425. * 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.
  52426. */
  52427. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52428. }
  52429. /**
  52430. * Called by the particle System when the direction is computed for the created particle.
  52431. * @param emitPower is the power of the particle (speed)
  52432. * @param worldMatrix is the world matrix of the particle system
  52433. * @param directionToUpdate is the direction vector to update with the result
  52434. * @param particle is the particle we are computed the direction for
  52435. */
  52436. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52437. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52438. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52439. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52440. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52441. };
  52442. /**
  52443. * Called by the particle System when the position is computed for the created particle.
  52444. * @param worldMatrix is the world matrix of the particle system
  52445. * @param positionToUpdate is the position vector to update with the result
  52446. * @param particle is the particle we are computed the position for
  52447. */
  52448. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52449. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52450. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52451. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52452. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52453. };
  52454. /**
  52455. * Clones the current emitter and returns a copy of it
  52456. * @returns the new emitter
  52457. */
  52458. BoxParticleEmitter.prototype.clone = function () {
  52459. var newOne = new BoxParticleEmitter();
  52460. BABYLON.Tools.DeepCopy(this, newOne);
  52461. return newOne;
  52462. };
  52463. /**
  52464. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52465. * @param effect defines the update shader
  52466. */
  52467. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52468. effect.setVector3("direction1", this.direction1);
  52469. effect.setVector3("direction2", this.direction2);
  52470. effect.setVector3("minEmitBox", this.minEmitBox);
  52471. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52472. };
  52473. /**
  52474. * Returns a string to use to update the GPU particles update shader
  52475. * @returns a string containng the defines string
  52476. */
  52477. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52478. return "#define BOXEMITTER";
  52479. };
  52480. /**
  52481. * Returns the string "BoxEmitter"
  52482. * @returns a string containing the class name
  52483. */
  52484. BoxParticleEmitter.prototype.getClassName = function () {
  52485. return "BoxEmitter";
  52486. };
  52487. /**
  52488. * Serializes the particle system to a JSON object.
  52489. * @returns the JSON object
  52490. */
  52491. BoxParticleEmitter.prototype.serialize = function () {
  52492. var serializationObject = {};
  52493. serializationObject.type = this.getClassName();
  52494. serializationObject.direction1 = this.direction1.asArray();
  52495. ;
  52496. serializationObject.direction2 = this.direction2.asArray();
  52497. ;
  52498. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52499. ;
  52500. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52501. ;
  52502. return serializationObject;
  52503. };
  52504. /**
  52505. * Parse properties from a JSON object
  52506. * @param serializationObject defines the JSON object
  52507. */
  52508. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52509. this.direction1.copyFrom(serializationObject.direction1);
  52510. this.direction2.copyFrom(serializationObject.direction2);
  52511. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52512. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52513. };
  52514. return BoxParticleEmitter;
  52515. }());
  52516. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52517. })(BABYLON || (BABYLON = {}));
  52518. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52519. "use strict";
  52520. var BABYLON;
  52521. (function (BABYLON) {
  52522. /**
  52523. * Particle emitter emitting particles from the inside of a cone.
  52524. * It emits the particles alongside the cone volume from the base to the particle.
  52525. * The emission direction might be randomized.
  52526. */
  52527. var ConeParticleEmitter = /** @class */ (function () {
  52528. /**
  52529. * Creates a new instance of @see ConeParticleEmitter
  52530. * @param radius the radius of the emission cone (1 by default)
  52531. * @param angles the cone base angle (PI by default)
  52532. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52533. */
  52534. function ConeParticleEmitter(radius,
  52535. /**
  52536. * The radius of the emission cone.
  52537. */
  52538. angle,
  52539. /**
  52540. * The cone base angle.
  52541. */
  52542. directionRandomizer) {
  52543. if (radius === void 0) { radius = 1; }
  52544. if (angle === void 0) { angle = Math.PI; }
  52545. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52546. this.angle = angle;
  52547. this.directionRandomizer = directionRandomizer;
  52548. this.radius = radius;
  52549. }
  52550. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52551. /**
  52552. * Gets the radius of the emission cone.
  52553. */
  52554. get: function () {
  52555. return this._radius;
  52556. },
  52557. /**
  52558. * Sets the radius of the emission cone.
  52559. */
  52560. set: function (value) {
  52561. this._radius = value;
  52562. if (this.angle !== 0) {
  52563. this._height = value / Math.tan(this.angle / 2);
  52564. }
  52565. else {
  52566. this._height = 1;
  52567. }
  52568. },
  52569. enumerable: true,
  52570. configurable: true
  52571. });
  52572. /**
  52573. * Called by the particle System when the direction is computed for the created particle.
  52574. * @param emitPower is the power of the particle (speed)
  52575. * @param worldMatrix is the world matrix of the particle system
  52576. * @param directionToUpdate is the direction vector to update with the result
  52577. * @param particle is the particle we are computed the direction for
  52578. */
  52579. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52580. if (this.angle === 0) {
  52581. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52582. }
  52583. else {
  52584. // measure the direction Vector from the emitter to the particle.
  52585. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52586. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52587. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52588. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52589. direction.x += randX;
  52590. direction.y += randY;
  52591. direction.z += randZ;
  52592. direction.normalize();
  52593. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52594. }
  52595. };
  52596. /**
  52597. * Called by the particle System when the position is computed for the created particle.
  52598. * @param worldMatrix is the world matrix of the particle system
  52599. * @param positionToUpdate is the position vector to update with the result
  52600. * @param particle is the particle we are computed the position for
  52601. */
  52602. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52603. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52604. var h = BABYLON.Scalar.RandomRange(0, 1);
  52605. // Better distribution in a cone at normal angles.
  52606. h = 1 - h * h;
  52607. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52608. radius = radius * h / this._height;
  52609. var randX = radius * Math.sin(s);
  52610. var randZ = radius * Math.cos(s);
  52611. var randY = h * this._height;
  52612. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52613. };
  52614. /**
  52615. * Clones the current emitter and returns a copy of it
  52616. * @returns the new emitter
  52617. */
  52618. ConeParticleEmitter.prototype.clone = function () {
  52619. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52620. BABYLON.Tools.DeepCopy(this, newOne);
  52621. return newOne;
  52622. };
  52623. /**
  52624. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52625. * @param effect defines the update shader
  52626. */
  52627. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52628. effect.setFloat("radius", this.radius);
  52629. effect.setFloat("angle", this.angle);
  52630. effect.setFloat("height", this._height);
  52631. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52632. };
  52633. /**
  52634. * Returns a string to use to update the GPU particles update shader
  52635. * @returns a string containng the defines string
  52636. */
  52637. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52638. return "#define CONEEMITTER";
  52639. };
  52640. /**
  52641. * Returns the string "BoxEmitter"
  52642. * @returns a string containing the class name
  52643. */
  52644. ConeParticleEmitter.prototype.getClassName = function () {
  52645. return "ConeEmitter";
  52646. };
  52647. /**
  52648. * Serializes the particle system to a JSON object.
  52649. * @returns the JSON object
  52650. */
  52651. ConeParticleEmitter.prototype.serialize = function () {
  52652. var serializationObject = {};
  52653. serializationObject.type = this.getClassName();
  52654. serializationObject.radius = this.radius;
  52655. serializationObject.angle = this.angle;
  52656. serializationObject.directionRandomizer = this.directionRandomizer;
  52657. return serializationObject;
  52658. };
  52659. /**
  52660. * Parse properties from a JSON object
  52661. * @param serializationObject defines the JSON object
  52662. */
  52663. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52664. this.radius = serializationObject.radius;
  52665. this.angle = serializationObject.angle;
  52666. this.directionRandomizer = serializationObject.directionRandomizer;
  52667. };
  52668. return ConeParticleEmitter;
  52669. }());
  52670. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52671. })(BABYLON || (BABYLON = {}));
  52672. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52673. "use strict";
  52674. var BABYLON;
  52675. (function (BABYLON) {
  52676. /**
  52677. * Particle emitter emitting particles from the inside of a sphere.
  52678. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52679. */
  52680. var SphereParticleEmitter = /** @class */ (function () {
  52681. /**
  52682. * Creates a new instance of @see SphereParticleEmitter
  52683. * @param radius the radius of the emission sphere (1 by default)
  52684. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52685. */
  52686. function SphereParticleEmitter(
  52687. /**
  52688. * The radius of the emission sphere.
  52689. */
  52690. radius,
  52691. /**
  52692. * How much to randomize the particle direction [0-1].
  52693. */
  52694. directionRandomizer) {
  52695. if (radius === void 0) { radius = 1; }
  52696. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52697. this.radius = radius;
  52698. this.directionRandomizer = directionRandomizer;
  52699. }
  52700. /**
  52701. * Called by the particle System when the direction is computed for the created particle.
  52702. * @param emitPower is the power of the particle (speed)
  52703. * @param worldMatrix is the world matrix of the particle system
  52704. * @param directionToUpdate is the direction vector to update with the result
  52705. * @param particle is the particle we are computed the direction for
  52706. */
  52707. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52708. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52709. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52710. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52711. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52712. direction.x += randX;
  52713. direction.y += randY;
  52714. direction.z += randZ;
  52715. direction.normalize();
  52716. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52717. };
  52718. /**
  52719. * Called by the particle System when the position is computed for the created particle.
  52720. * @param worldMatrix is the world matrix of the particle system
  52721. * @param positionToUpdate is the position vector to update with the result
  52722. * @param particle is the particle we are computed the position for
  52723. */
  52724. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52725. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52726. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52727. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52728. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52729. var randY = randRadius * Math.cos(theta);
  52730. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52731. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52732. };
  52733. /**
  52734. * Clones the current emitter and returns a copy of it
  52735. * @returns the new emitter
  52736. */
  52737. SphereParticleEmitter.prototype.clone = function () {
  52738. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52739. BABYLON.Tools.DeepCopy(this, newOne);
  52740. return newOne;
  52741. };
  52742. /**
  52743. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52744. * @param effect defines the update shader
  52745. */
  52746. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52747. effect.setFloat("radius", this.radius);
  52748. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52749. };
  52750. /**
  52751. * Returns a string to use to update the GPU particles update shader
  52752. * @returns a string containng the defines string
  52753. */
  52754. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52755. return "#define SPHEREEMITTER";
  52756. };
  52757. /**
  52758. * Returns the string "SphereParticleEmitter"
  52759. * @returns a string containing the class name
  52760. */
  52761. SphereParticleEmitter.prototype.getClassName = function () {
  52762. return "SphereParticleEmitter";
  52763. };
  52764. /**
  52765. * Serializes the particle system to a JSON object.
  52766. * @returns the JSON object
  52767. */
  52768. SphereParticleEmitter.prototype.serialize = function () {
  52769. var serializationObject = {};
  52770. serializationObject.type = this.getClassName();
  52771. serializationObject.radius = this.radius;
  52772. serializationObject.directionRandomizer = this.directionRandomizer;
  52773. return serializationObject;
  52774. };
  52775. /**
  52776. * Parse properties from a JSON object
  52777. * @param serializationObject defines the JSON object
  52778. */
  52779. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52780. this.radius = serializationObject.radius;
  52781. this.directionRandomizer = serializationObject.directionRandomizer;
  52782. };
  52783. return SphereParticleEmitter;
  52784. }());
  52785. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52786. /**
  52787. * Particle emitter emitting particles from the inside of a sphere.
  52788. * It emits the particles randomly between two vectors.
  52789. */
  52790. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52791. __extends(SphereDirectedParticleEmitter, _super);
  52792. /**
  52793. * Creates a new instance of @see SphereDirectedParticleEmitter
  52794. * @param radius the radius of the emission sphere (1 by default)
  52795. * @param direction1 the min limit of the emission direction (up vector by default)
  52796. * @param direction2 the max limit of the emission direction (up vector by default)
  52797. */
  52798. function SphereDirectedParticleEmitter(radius,
  52799. /**
  52800. * The min limit of the emission direction.
  52801. */
  52802. direction1,
  52803. /**
  52804. * The max limit of the emission direction.
  52805. */
  52806. direction2) {
  52807. if (radius === void 0) { radius = 1; }
  52808. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52809. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52810. var _this = _super.call(this, radius) || this;
  52811. _this.direction1 = direction1;
  52812. _this.direction2 = direction2;
  52813. return _this;
  52814. }
  52815. /**
  52816. * Called by the particle System when the direction is computed for the created particle.
  52817. * @param emitPower is the power of the particle (speed)
  52818. * @param worldMatrix is the world matrix of the particle system
  52819. * @param directionToUpdate is the direction vector to update with the result
  52820. * @param particle is the particle we are computed the direction for
  52821. */
  52822. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52823. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52824. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52825. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52826. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52827. };
  52828. /**
  52829. * Clones the current emitter and returns a copy of it
  52830. * @returns the new emitter
  52831. */
  52832. SphereDirectedParticleEmitter.prototype.clone = function () {
  52833. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52834. BABYLON.Tools.DeepCopy(this, newOne);
  52835. return newOne;
  52836. };
  52837. /**
  52838. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52839. * @param effect defines the update shader
  52840. */
  52841. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52842. effect.setFloat("radius", this.radius);
  52843. effect.setVector3("direction1", this.direction1);
  52844. effect.setVector3("direction2", this.direction2);
  52845. };
  52846. /**
  52847. * Returns a string to use to update the GPU particles update shader
  52848. * @returns a string containng the defines string
  52849. */
  52850. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52851. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52852. };
  52853. /**
  52854. * Returns the string "SphereDirectedParticleEmitter"
  52855. * @returns a string containing the class name
  52856. */
  52857. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52858. return "SphereDirectedParticleEmitter";
  52859. };
  52860. /**
  52861. * Serializes the particle system to a JSON object.
  52862. * @returns the JSON object
  52863. */
  52864. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52865. var serializationObject = _super.prototype.serialize.call(this);
  52866. ;
  52867. serializationObject.direction1 = this.direction1.asArray();
  52868. ;
  52869. serializationObject.direction2 = this.direction2.asArray();
  52870. ;
  52871. return serializationObject;
  52872. };
  52873. /**
  52874. * Parse properties from a JSON object
  52875. * @param serializationObject defines the JSON object
  52876. */
  52877. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52878. _super.prototype.parse.call(this, serializationObject);
  52879. this.direction1.copyFrom(serializationObject.direction1);
  52880. this.direction2.copyFrom(serializationObject.direction2);
  52881. };
  52882. return SphereDirectedParticleEmitter;
  52883. }(SphereParticleEmitter));
  52884. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52885. })(BABYLON || (BABYLON = {}));
  52886. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52887. "use strict";
  52888. var BABYLON;
  52889. (function (BABYLON) {
  52890. /**
  52891. * Represents one particle of a solid particle system.
  52892. * @see SolidParticleSystem
  52893. */
  52894. var SolidParticle = /** @class */ (function () {
  52895. /**
  52896. * Creates a Solid Particle object.
  52897. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52898. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52899. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52900. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52901. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52902. * @param shapeId (integer) is the model shape identifier in the SPS.
  52903. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52904. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52905. */
  52906. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52907. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52908. /**
  52909. * particle global index
  52910. */
  52911. this.idx = 0;
  52912. /**
  52913. * The color of the particle
  52914. */
  52915. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52916. /**
  52917. * The world space position of the particle.
  52918. */
  52919. this.position = BABYLON.Vector3.Zero();
  52920. /**
  52921. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52922. */
  52923. this.rotation = BABYLON.Vector3.Zero();
  52924. /**
  52925. * The scaling of the particle.
  52926. */
  52927. this.scaling = BABYLON.Vector3.One();
  52928. /**
  52929. * The uvs of the particle.
  52930. */
  52931. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52932. /**
  52933. * The current speed of the particle.
  52934. */
  52935. this.velocity = BABYLON.Vector3.Zero();
  52936. /**
  52937. * The pivot point in the particle local space.
  52938. */
  52939. this.pivot = BABYLON.Vector3.Zero();
  52940. /**
  52941. * Must the particle be translated from its pivot point in its local space ?
  52942. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52943. * Default : false
  52944. */
  52945. this.translateFromPivot = false;
  52946. /**
  52947. * Is the particle active or not ?
  52948. */
  52949. this.alive = true;
  52950. /**
  52951. * Is the particle visible or not ?
  52952. */
  52953. this.isVisible = true;
  52954. /**
  52955. * Index of this particle in the global "positions" array (Internal use)
  52956. */
  52957. this._pos = 0;
  52958. /**
  52959. * Index of this particle in the global "indices" array (Internal use)
  52960. */
  52961. this._ind = 0;
  52962. /**
  52963. * ModelShape id of this particle
  52964. */
  52965. this.shapeId = 0;
  52966. /**
  52967. * Index of the particle in its shape id (Internal use)
  52968. */
  52969. this.idxInShape = 0;
  52970. /**
  52971. * Still set as invisible in order to skip useless computations (Internal use)
  52972. */
  52973. this._stillInvisible = false;
  52974. /**
  52975. * Last computed particle rotation matrix
  52976. */
  52977. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52978. /**
  52979. * Parent particle Id, if any.
  52980. * Default null.
  52981. */
  52982. this.parentId = null;
  52983. /**
  52984. * Internal global position in the SPS.
  52985. */
  52986. this._globalPosition = BABYLON.Vector3.Zero();
  52987. this.idx = particleIndex;
  52988. this._pos = positionIndex;
  52989. this._ind = indiceIndex;
  52990. this._model = model;
  52991. this.shapeId = shapeId;
  52992. this.idxInShape = idxInShape;
  52993. this._sps = sps;
  52994. if (modelBoundingInfo) {
  52995. this._modelBoundingInfo = modelBoundingInfo;
  52996. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52997. }
  52998. }
  52999. Object.defineProperty(SolidParticle.prototype, "scale", {
  53000. /**
  53001. * Legacy support, changed scale to scaling
  53002. */
  53003. get: function () {
  53004. return this.scaling;
  53005. },
  53006. /**
  53007. * Legacy support, changed scale to scaling
  53008. */
  53009. set: function (scale) {
  53010. this.scaling = scale;
  53011. },
  53012. enumerable: true,
  53013. configurable: true
  53014. });
  53015. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53016. /**
  53017. * Legacy support, changed quaternion to rotationQuaternion
  53018. */
  53019. get: function () {
  53020. return this.rotationQuaternion;
  53021. },
  53022. /**
  53023. * Legacy support, changed quaternion to rotationQuaternion
  53024. */
  53025. set: function (q) {
  53026. this.rotationQuaternion = q;
  53027. },
  53028. enumerable: true,
  53029. configurable: true
  53030. });
  53031. /**
  53032. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53033. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53034. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53035. * @returns true if it intersects
  53036. */
  53037. SolidParticle.prototype.intersectsMesh = function (target) {
  53038. if (!this._boundingInfo || !target._boundingInfo) {
  53039. return false;
  53040. }
  53041. if (this._sps._bSphereOnly) {
  53042. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53043. }
  53044. return this._boundingInfo.intersects(target._boundingInfo, false);
  53045. };
  53046. return SolidParticle;
  53047. }());
  53048. BABYLON.SolidParticle = SolidParticle;
  53049. /**
  53050. * Represents the shape of the model used by one particle of a solid particle system.
  53051. * SPS internal tool, don't use it manually.
  53052. * @see SolidParticleSystem
  53053. */
  53054. var ModelShape = /** @class */ (function () {
  53055. /**
  53056. * 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.
  53057. * SPS internal tool, don't use it manually.
  53058. * @ignore
  53059. */
  53060. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53061. /**
  53062. * length of the shape in the model indices array (internal use)
  53063. */
  53064. this._indicesLength = 0;
  53065. this.shapeID = id;
  53066. this._shape = shape;
  53067. this._indicesLength = indicesLength;
  53068. this._shapeUV = shapeUV;
  53069. this._positionFunction = posFunction;
  53070. this._vertexFunction = vtxFunction;
  53071. }
  53072. return ModelShape;
  53073. }());
  53074. BABYLON.ModelShape = ModelShape;
  53075. /**
  53076. * Represents a Depth Sorted Particle in the solid particle system.
  53077. * @see SolidParticleSystem
  53078. */
  53079. var DepthSortedParticle = /** @class */ (function () {
  53080. function DepthSortedParticle() {
  53081. /**
  53082. * Index of the particle in the "indices" array
  53083. */
  53084. this.ind = 0;
  53085. /**
  53086. * Length of the particle shape in the "indices" array
  53087. */
  53088. this.indicesLength = 0;
  53089. /**
  53090. * Squared distance from the particle to the camera
  53091. */
  53092. this.sqDistance = 0.0;
  53093. }
  53094. return DepthSortedParticle;
  53095. }());
  53096. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53097. })(BABYLON || (BABYLON = {}));
  53098. //# sourceMappingURL=babylon.solidParticle.js.map
  53099. "use strict";
  53100. var BABYLON;
  53101. (function (BABYLON) {
  53102. /**
  53103. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53104. *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.
  53105. * The SPS is also a particle system. It provides some methods to manage the particles.
  53106. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53107. *
  53108. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53109. */
  53110. var SolidParticleSystem = /** @class */ (function () {
  53111. /**
  53112. * Creates a SPS (Solid Particle System) object.
  53113. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53114. * @param scene (Scene) is the scene in which the SPS is added.
  53115. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53116. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53117. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53118. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53119. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53120. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53121. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53122. */
  53123. function SolidParticleSystem(name, scene, options) {
  53124. /**
  53125. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53126. * Example : var p = SPS.particles[i];
  53127. */
  53128. this.particles = new Array();
  53129. /**
  53130. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53131. */
  53132. this.nbParticles = 0;
  53133. /**
  53134. * If the particles must ever face the camera (default false). Useful for planar particles.
  53135. */
  53136. this.billboard = false;
  53137. /**
  53138. * Recompute normals when adding a shape
  53139. */
  53140. this.recomputeNormals = true;
  53141. /**
  53142. * This a counter ofr your own usage. It's not set by any SPS functions.
  53143. */
  53144. this.counter = 0;
  53145. /**
  53146. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53147. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53148. */
  53149. this.vars = {};
  53150. /**
  53151. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53152. */
  53153. this._bSphereOnly = false;
  53154. /**
  53155. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53156. */
  53157. this._bSphereRadiusFactor = 1.0;
  53158. this._positions = new Array();
  53159. this._indices = new Array();
  53160. this._normals = new Array();
  53161. this._colors = new Array();
  53162. this._uvs = new Array();
  53163. this._index = 0; // indices index
  53164. this._updatable = true;
  53165. this._pickable = false;
  53166. this._isVisibilityBoxLocked = false;
  53167. this._alwaysVisible = false;
  53168. this._depthSort = false;
  53169. this._shapeCounter = 0;
  53170. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53171. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53172. this._computeParticleColor = true;
  53173. this._computeParticleTexture = true;
  53174. this._computeParticleRotation = true;
  53175. this._computeParticleVertex = false;
  53176. this._computeBoundingBox = false;
  53177. this._depthSortParticles = true;
  53178. this._cam_axisZ = BABYLON.Vector3.Zero();
  53179. this._cam_axisY = BABYLON.Vector3.Zero();
  53180. this._cam_axisX = BABYLON.Vector3.Zero();
  53181. this._axisZ = BABYLON.Axis.Z;
  53182. this._camDir = BABYLON.Vector3.Zero();
  53183. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53184. this._rotMatrix = new BABYLON.Matrix();
  53185. this._invertMatrix = new BABYLON.Matrix();
  53186. this._rotated = BABYLON.Vector3.Zero();
  53187. this._quaternion = new BABYLON.Quaternion();
  53188. this._vertex = BABYLON.Vector3.Zero();
  53189. this._normal = BABYLON.Vector3.Zero();
  53190. this._yaw = 0.0;
  53191. this._pitch = 0.0;
  53192. this._roll = 0.0;
  53193. this._halfroll = 0.0;
  53194. this._halfpitch = 0.0;
  53195. this._halfyaw = 0.0;
  53196. this._sinRoll = 0.0;
  53197. this._cosRoll = 0.0;
  53198. this._sinPitch = 0.0;
  53199. this._cosPitch = 0.0;
  53200. this._sinYaw = 0.0;
  53201. this._cosYaw = 0.0;
  53202. this._mustUnrotateFixedNormals = false;
  53203. this._minimum = BABYLON.Vector3.Zero();
  53204. this._maximum = BABYLON.Vector3.Zero();
  53205. this._minBbox = BABYLON.Vector3.Zero();
  53206. this._maxBbox = BABYLON.Vector3.Zero();
  53207. this._particlesIntersect = false;
  53208. this._depthSortFunction = function (p1, p2) {
  53209. return (p2.sqDistance - p1.sqDistance);
  53210. };
  53211. this._needs32Bits = false;
  53212. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53213. this._scaledPivot = BABYLON.Vector3.Zero();
  53214. this._particleHasParent = false;
  53215. this.name = name;
  53216. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53217. this._camera = scene.activeCamera;
  53218. this._pickable = options ? options.isPickable : false;
  53219. this._depthSort = options ? options.enableDepthSort : false;
  53220. this._particlesIntersect = options ? options.particleIntersection : false;
  53221. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53222. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53223. if (options && options.updatable) {
  53224. this._updatable = options.updatable;
  53225. }
  53226. else {
  53227. this._updatable = true;
  53228. }
  53229. if (this._pickable) {
  53230. this.pickedParticles = [];
  53231. }
  53232. if (this._depthSort) {
  53233. this.depthSortedParticles = [];
  53234. }
  53235. }
  53236. /**
  53237. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53238. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53239. * @returns the created mesh
  53240. */
  53241. SolidParticleSystem.prototype.buildMesh = function () {
  53242. if (this.nbParticles === 0) {
  53243. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53244. this.addShape(triangle, 1);
  53245. triangle.dispose();
  53246. }
  53247. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  53248. this._positions32 = new Float32Array(this._positions);
  53249. this._uvs32 = new Float32Array(this._uvs);
  53250. this._colors32 = new Float32Array(this._colors);
  53251. if (this.recomputeNormals) {
  53252. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  53253. }
  53254. this._normals32 = new Float32Array(this._normals);
  53255. this._fixedNormal32 = new Float32Array(this._normals);
  53256. if (this._mustUnrotateFixedNormals) {
  53257. this._unrotateFixedNormals();
  53258. }
  53259. var vertexData = new BABYLON.VertexData();
  53260. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  53261. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  53262. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  53263. if (this._uvs32) {
  53264. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  53265. ;
  53266. }
  53267. if (this._colors32) {
  53268. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  53269. }
  53270. var mesh = new BABYLON.Mesh(this.name, this._scene);
  53271. vertexData.applyToMesh(mesh, this._updatable);
  53272. this.mesh = mesh;
  53273. this.mesh.isPickable = this._pickable;
  53274. // free memory
  53275. if (!this._depthSort) {
  53276. this._indices = null;
  53277. }
  53278. this._positions = null;
  53279. this._normals = null;
  53280. this._uvs = null;
  53281. this._colors = null;
  53282. if (!this._updatable) {
  53283. this.particles.length = 0;
  53284. }
  53285. return mesh;
  53286. };
  53287. /**
  53288. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  53289. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53290. * Thus the particles generated from `digest()` have their property `position` set yet.
  53291. * @param mesh ( Mesh ) is the mesh to be digested
  53292. * @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
  53293. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53294. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53295. * @returns the current SPS
  53296. */
  53297. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53298. var size = (options && options.facetNb) || 1;
  53299. var number = (options && options.number) || 0;
  53300. var delta = (options && options.delta) || 0;
  53301. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53302. var meshInd = mesh.getIndices();
  53303. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53304. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53305. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53306. var f = 0; // facet counter
  53307. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  53308. // compute size from number
  53309. if (number) {
  53310. number = (number > totalFacets) ? totalFacets : number;
  53311. size = Math.round(totalFacets / number);
  53312. delta = 0;
  53313. }
  53314. else {
  53315. size = (size > totalFacets) ? totalFacets : size;
  53316. }
  53317. var facetPos = []; // submesh positions
  53318. var facetInd = []; // submesh indices
  53319. var facetUV = []; // submesh UV
  53320. var facetCol = []; // submesh colors
  53321. var barycenter = BABYLON.Vector3.Zero();
  53322. var sizeO = size;
  53323. while (f < totalFacets) {
  53324. size = sizeO + Math.floor((1 + delta) * Math.random());
  53325. if (f > totalFacets - size) {
  53326. size = totalFacets - f;
  53327. }
  53328. // reset temp arrays
  53329. facetPos.length = 0;
  53330. facetInd.length = 0;
  53331. facetUV.length = 0;
  53332. facetCol.length = 0;
  53333. // iterate over "size" facets
  53334. var fi = 0;
  53335. for (var j = f * 3; j < (f + size) * 3; j++) {
  53336. facetInd.push(fi);
  53337. var i = meshInd[j];
  53338. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  53339. if (meshUV) {
  53340. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  53341. }
  53342. if (meshCol) {
  53343. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53344. }
  53345. fi++;
  53346. }
  53347. // create a model shape for each single particle
  53348. var idx = this.nbParticles;
  53349. var shape = this._posToShape(facetPos);
  53350. var shapeUV = this._uvsToShapeUV(facetUV);
  53351. // compute the barycenter of the shape
  53352. var v;
  53353. for (v = 0; v < shape.length; v++) {
  53354. barycenter.addInPlace(shape[v]);
  53355. }
  53356. barycenter.scaleInPlace(1 / shape.length);
  53357. // shift the shape from its barycenter to the origin
  53358. for (v = 0; v < shape.length; v++) {
  53359. shape[v].subtractInPlace(barycenter);
  53360. }
  53361. var bInfo;
  53362. if (this._particlesIntersect) {
  53363. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  53364. }
  53365. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  53366. // add the particle in the SPS
  53367. var currentPos = this._positions.length;
  53368. var currentInd = this._indices.length;
  53369. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  53370. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  53371. // initialize the particle position
  53372. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53373. this._index += shape.length;
  53374. idx++;
  53375. this.nbParticles++;
  53376. this._shapeCounter++;
  53377. f += size;
  53378. }
  53379. return this;
  53380. };
  53381. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  53382. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  53383. var index = 0;
  53384. var idx = 0;
  53385. for (var p = 0; p < this.particles.length; p++) {
  53386. this._particle = this.particles[p];
  53387. this._shape = this._particle._model._shape;
  53388. if (this._particle.rotationQuaternion) {
  53389. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53390. }
  53391. else {
  53392. this._yaw = this._particle.rotation.y;
  53393. this._pitch = this._particle.rotation.x;
  53394. this._roll = this._particle.rotation.z;
  53395. this._quaternionRotationYPR();
  53396. }
  53397. this._quaternionToRotationMatrix();
  53398. this._rotMatrix.invertToRef(this._invertMatrix);
  53399. for (var pt = 0; pt < this._shape.length; pt++) {
  53400. idx = index + pt * 3;
  53401. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  53402. this._fixedNormal32[idx] = this._normal.x;
  53403. this._fixedNormal32[idx + 1] = this._normal.y;
  53404. this._fixedNormal32[idx + 2] = this._normal.z;
  53405. }
  53406. index = idx + 3;
  53407. }
  53408. };
  53409. //reset copy
  53410. SolidParticleSystem.prototype._resetCopy = function () {
  53411. this._copy.position.x = 0;
  53412. this._copy.position.y = 0;
  53413. this._copy.position.z = 0;
  53414. this._copy.rotation.x = 0;
  53415. this._copy.rotation.y = 0;
  53416. this._copy.rotation.z = 0;
  53417. this._copy.rotationQuaternion = null;
  53418. this._copy.scaling.x = 1.0;
  53419. this._copy.scaling.y = 1.0;
  53420. this._copy.scaling.z = 1.0;
  53421. this._copy.uvs.x = 0;
  53422. this._copy.uvs.y = 0;
  53423. this._copy.uvs.z = 1.0;
  53424. this._copy.uvs.w = 1.0;
  53425. this._copy.color = null;
  53426. this._copy.translateFromPivot = false;
  53427. };
  53428. // _meshBuilder : inserts the shape model in the global SPS mesh
  53429. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  53430. var i;
  53431. var u = 0;
  53432. var c = 0;
  53433. var n = 0;
  53434. this._resetCopy();
  53435. if (options && options.positionFunction) {
  53436. options.positionFunction(this._copy, idx, idxInShape);
  53437. this._mustUnrotateFixedNormals = true;
  53438. }
  53439. if (this._copy.rotationQuaternion) {
  53440. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53441. }
  53442. else {
  53443. this._yaw = this._copy.rotation.y;
  53444. this._pitch = this._copy.rotation.x;
  53445. this._roll = this._copy.rotation.z;
  53446. this._quaternionRotationYPR();
  53447. }
  53448. this._quaternionToRotationMatrix();
  53449. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  53450. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  53451. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  53452. if (this._copy.translateFromPivot) {
  53453. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53454. }
  53455. else {
  53456. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53457. }
  53458. for (i = 0; i < shape.length; i++) {
  53459. this._vertex.x = shape[i].x;
  53460. this._vertex.y = shape[i].y;
  53461. this._vertex.z = shape[i].z;
  53462. if (options && options.vertexFunction) {
  53463. options.vertexFunction(this._copy, this._vertex, i);
  53464. }
  53465. this._vertex.x *= this._copy.scaling.x;
  53466. this._vertex.y *= this._copy.scaling.y;
  53467. this._vertex.z *= this._copy.scaling.z;
  53468. this._vertex.x -= this._scaledPivot.x;
  53469. this._vertex.y -= this._scaledPivot.y;
  53470. this._vertex.z -= this._scaledPivot.z;
  53471. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53472. this._rotated.addInPlace(this._pivotBackTranslation);
  53473. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  53474. if (meshUV) {
  53475. 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);
  53476. u += 2;
  53477. }
  53478. if (this._copy.color) {
  53479. this._color = this._copy.color;
  53480. }
  53481. else if (meshCol && meshCol[c] !== undefined) {
  53482. this._color.r = meshCol[c];
  53483. this._color.g = meshCol[c + 1];
  53484. this._color.b = meshCol[c + 2];
  53485. this._color.a = meshCol[c + 3];
  53486. }
  53487. else {
  53488. this._color.r = 1.0;
  53489. this._color.g = 1.0;
  53490. this._color.b = 1.0;
  53491. this._color.a = 1.0;
  53492. }
  53493. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  53494. c += 4;
  53495. if (!this.recomputeNormals && meshNor) {
  53496. this._normal.x = meshNor[n];
  53497. this._normal.y = meshNor[n + 1];
  53498. this._normal.z = meshNor[n + 2];
  53499. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  53500. normals.push(this._normal.x, this._normal.y, this._normal.z);
  53501. n += 3;
  53502. }
  53503. }
  53504. for (i = 0; i < meshInd.length; i++) {
  53505. var current_ind = p + meshInd[i];
  53506. indices.push(current_ind);
  53507. if (current_ind > 65535) {
  53508. this._needs32Bits = true;
  53509. }
  53510. }
  53511. if (this._pickable) {
  53512. var nbfaces = meshInd.length / 3;
  53513. for (i = 0; i < nbfaces; i++) {
  53514. this.pickedParticles.push({ idx: idx, faceId: i });
  53515. }
  53516. }
  53517. if (this._depthSort) {
  53518. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  53519. }
  53520. return this._copy;
  53521. };
  53522. // returns a shape array from positions array
  53523. SolidParticleSystem.prototype._posToShape = function (positions) {
  53524. var shape = [];
  53525. for (var i = 0; i < positions.length; i += 3) {
  53526. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  53527. }
  53528. return shape;
  53529. };
  53530. // returns a shapeUV array from a Vector4 uvs
  53531. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  53532. var shapeUV = [];
  53533. if (uvs) {
  53534. for (var i = 0; i < uvs.length; i++)
  53535. shapeUV.push(uvs[i]);
  53536. }
  53537. return shapeUV;
  53538. };
  53539. // adds a new particle object in the particles array
  53540. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  53541. if (bInfo === void 0) { bInfo = null; }
  53542. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  53543. this.particles.push(sp);
  53544. return sp;
  53545. };
  53546. /**
  53547. * Adds some particles to the SPS from the model shape. Returns the shape id.
  53548. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  53549. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  53550. * @param nb (positive integer) the number of particles to be created from this model
  53551. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  53552. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  53553. * @returns the number of shapes in the system
  53554. */
  53555. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  53556. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53557. var meshInd = mesh.getIndices();
  53558. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53559. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53560. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53561. var bbInfo;
  53562. if (this._particlesIntersect) {
  53563. bbInfo = mesh.getBoundingInfo();
  53564. }
  53565. var shape = this._posToShape(meshPos);
  53566. var shapeUV = this._uvsToShapeUV(meshUV);
  53567. var posfunc = options ? options.positionFunction : null;
  53568. var vtxfunc = options ? options.vertexFunction : null;
  53569. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  53570. // particles
  53571. var sp;
  53572. var currentCopy;
  53573. var idx = this.nbParticles;
  53574. for (var i = 0; i < nb; i++) {
  53575. var currentPos = this._positions.length;
  53576. var currentInd = this._indices.length;
  53577. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  53578. if (this._updatable) {
  53579. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  53580. sp.position.copyFrom(currentCopy.position);
  53581. sp.rotation.copyFrom(currentCopy.rotation);
  53582. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  53583. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  53584. }
  53585. if (currentCopy.color && sp.color) {
  53586. sp.color.copyFrom(currentCopy.color);
  53587. }
  53588. sp.scaling.copyFrom(currentCopy.scaling);
  53589. sp.uvs.copyFrom(currentCopy.uvs);
  53590. }
  53591. this._index += shape.length;
  53592. idx++;
  53593. }
  53594. this.nbParticles += nb;
  53595. this._shapeCounter++;
  53596. return this._shapeCounter - 1;
  53597. };
  53598. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  53599. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  53600. this._resetCopy();
  53601. if (particle._model._positionFunction) {
  53602. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  53603. }
  53604. if (this._copy.rotationQuaternion) {
  53605. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53606. }
  53607. else {
  53608. this._yaw = this._copy.rotation.y;
  53609. this._pitch = this._copy.rotation.x;
  53610. this._roll = this._copy.rotation.z;
  53611. this._quaternionRotationYPR();
  53612. }
  53613. this._quaternionToRotationMatrix();
  53614. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53615. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53616. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53617. if (this._copy.translateFromPivot) {
  53618. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53619. }
  53620. else {
  53621. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53622. }
  53623. this._shape = particle._model._shape;
  53624. for (var pt = 0; pt < this._shape.length; pt++) {
  53625. this._vertex.x = this._shape[pt].x;
  53626. this._vertex.y = this._shape[pt].y;
  53627. this._vertex.z = this._shape[pt].z;
  53628. if (particle._model._vertexFunction) {
  53629. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  53630. }
  53631. this._vertex.x *= this._copy.scaling.x;
  53632. this._vertex.y *= this._copy.scaling.y;
  53633. this._vertex.z *= this._copy.scaling.z;
  53634. this._vertex.x -= this._scaledPivot.x;
  53635. this._vertex.y -= this._scaledPivot.y;
  53636. this._vertex.z -= this._scaledPivot.z;
  53637. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53638. this._rotated.addInPlace(this._pivotBackTranslation);
  53639. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53640. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53641. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53642. }
  53643. particle.position.x = 0.0;
  53644. particle.position.y = 0.0;
  53645. particle.position.z = 0.0;
  53646. particle.rotation.x = 0.0;
  53647. particle.rotation.y = 0.0;
  53648. particle.rotation.z = 0.0;
  53649. particle.rotationQuaternion = null;
  53650. particle.scaling.x = 1.0;
  53651. particle.scaling.y = 1.0;
  53652. particle.scaling.z = 1.0;
  53653. particle.uvs.x = 0.0;
  53654. particle.uvs.y = 0.0;
  53655. particle.uvs.z = 1.0;
  53656. particle.uvs.w = 1.0;
  53657. particle.pivot.x = 0.0;
  53658. particle.pivot.y = 0.0;
  53659. particle.pivot.z = 0.0;
  53660. particle.translateFromPivot = false;
  53661. particle.parentId = null;
  53662. };
  53663. /**
  53664. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53665. * @returns the SPS.
  53666. */
  53667. SolidParticleSystem.prototype.rebuildMesh = function () {
  53668. for (var p = 0; p < this.particles.length; p++) {
  53669. this._rebuildParticle(this.particles[p]);
  53670. }
  53671. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53672. return this;
  53673. };
  53674. /**
  53675. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53676. * This method calls `updateParticle()` for each particle of the SPS.
  53677. * For an animated SPS, it is usually called within the render loop.
  53678. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53679. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53680. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53681. * @returns the SPS.
  53682. */
  53683. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53684. if (start === void 0) { start = 0; }
  53685. if (end === void 0) { end = this.nbParticles - 1; }
  53686. if (update === void 0) { update = true; }
  53687. if (!this._updatable) {
  53688. return this;
  53689. }
  53690. // custom beforeUpdate
  53691. this.beforeUpdateParticles(start, end, update);
  53692. this._cam_axisX.x = 1.0;
  53693. this._cam_axisX.y = 0.0;
  53694. this._cam_axisX.z = 0.0;
  53695. this._cam_axisY.x = 0.0;
  53696. this._cam_axisY.y = 1.0;
  53697. this._cam_axisY.z = 0.0;
  53698. this._cam_axisZ.x = 0.0;
  53699. this._cam_axisZ.y = 0.0;
  53700. this._cam_axisZ.z = 1.0;
  53701. // cases when the World Matrix is to be computed first
  53702. if (this.billboard || this._depthSort) {
  53703. this.mesh.computeWorldMatrix(true);
  53704. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53705. }
  53706. // if the particles will always face the camera
  53707. if (this.billboard) {
  53708. // compute the camera position and un-rotate it by the current mesh rotation
  53709. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53710. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53711. this._cam_axisZ.normalize();
  53712. // same for camera up vector extracted from the cam view matrix
  53713. var view = this._camera.getViewMatrix(true);
  53714. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53715. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53716. this._cam_axisY.normalize();
  53717. this._cam_axisX.normalize();
  53718. }
  53719. // if depthSort, compute the camera global position in the mesh local system
  53720. if (this._depthSort) {
  53721. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53722. }
  53723. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53724. var idx = 0; // current position index in the global array positions32
  53725. var index = 0; // position start index in the global array positions32 of the current particle
  53726. var colidx = 0; // current color index in the global array colors32
  53727. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53728. var uvidx = 0; // current uv index in the global array uvs32
  53729. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53730. var pt = 0; // current index in the particle model shape
  53731. if (this.mesh.isFacetDataEnabled) {
  53732. this._computeBoundingBox = true;
  53733. }
  53734. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53735. if (this._computeBoundingBox) {
  53736. if (start == 0 && end == this.nbParticles - 1) {
  53737. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53738. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53739. }
  53740. else {
  53741. if (this.mesh._boundingInfo) {
  53742. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53743. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53744. }
  53745. }
  53746. }
  53747. // particle loop
  53748. index = this.particles[start]._pos;
  53749. var vpos = (index / 3) | 0;
  53750. colorIndex = vpos * 4;
  53751. uvIndex = vpos * 2;
  53752. for (var p = start; p <= end; p++) {
  53753. this._particle = this.particles[p];
  53754. this._shape = this._particle._model._shape;
  53755. this._shapeUV = this._particle._model._shapeUV;
  53756. // call to custom user function to update the particle properties
  53757. this.updateParticle(this._particle);
  53758. // camera-particle distance for depth sorting
  53759. if (this._depthSort && this._depthSortParticles) {
  53760. var dsp = this.depthSortedParticles[p];
  53761. dsp.ind = this._particle._ind;
  53762. dsp.indicesLength = this._particle._model._indicesLength;
  53763. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53764. }
  53765. // skip the computations for inactive or already invisible particles
  53766. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53767. // increment indexes for the next particle
  53768. pt = this._shape.length;
  53769. index += pt * 3;
  53770. colorIndex += pt * 4;
  53771. uvIndex += pt * 2;
  53772. continue;
  53773. }
  53774. if (this._particle.isVisible) {
  53775. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53776. this._particleHasParent = (this._particle.parentId !== null);
  53777. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53778. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53779. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53780. // particle rotation matrix
  53781. if (this.billboard) {
  53782. this._particle.rotation.x = 0.0;
  53783. this._particle.rotation.y = 0.0;
  53784. }
  53785. if (this._computeParticleRotation || this.billboard) {
  53786. if (this._particle.rotationQuaternion) {
  53787. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53788. }
  53789. else {
  53790. this._yaw = this._particle.rotation.y;
  53791. this._pitch = this._particle.rotation.x;
  53792. this._roll = this._particle.rotation.z;
  53793. this._quaternionRotationYPR();
  53794. }
  53795. this._quaternionToRotationMatrix();
  53796. }
  53797. if (this._particleHasParent) {
  53798. this._parent = this.particles[this._particle.parentId];
  53799. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  53800. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  53801. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  53802. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53803. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53804. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53805. if (this._computeParticleRotation || this.billboard) {
  53806. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  53807. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  53808. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  53809. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  53810. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  53811. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  53812. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  53813. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  53814. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  53815. }
  53816. }
  53817. else {
  53818. this._particle._globalPosition.x = this._particle.position.x;
  53819. this._particle._globalPosition.y = this._particle.position.y;
  53820. this._particle._globalPosition.z = this._particle.position.z;
  53821. if (this._computeParticleRotation || this.billboard) {
  53822. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53823. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53824. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53825. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53826. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53827. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53828. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53829. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53830. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53831. }
  53832. }
  53833. if (this._particle.translateFromPivot) {
  53834. this._pivotBackTranslation.x = 0.0;
  53835. this._pivotBackTranslation.y = 0.0;
  53836. this._pivotBackTranslation.z = 0.0;
  53837. }
  53838. else {
  53839. this._pivotBackTranslation.x = this._scaledPivot.x;
  53840. this._pivotBackTranslation.y = this._scaledPivot.y;
  53841. this._pivotBackTranslation.z = this._scaledPivot.z;
  53842. }
  53843. // particle vertex loop
  53844. for (pt = 0; pt < this._shape.length; pt++) {
  53845. idx = index + pt * 3;
  53846. colidx = colorIndex + pt * 4;
  53847. uvidx = uvIndex + pt * 2;
  53848. this._vertex.x = this._shape[pt].x;
  53849. this._vertex.y = this._shape[pt].y;
  53850. this._vertex.z = this._shape[pt].z;
  53851. if (this._computeParticleVertex) {
  53852. this.updateParticleVertex(this._particle, this._vertex, pt);
  53853. }
  53854. // positions
  53855. this._vertex.x *= this._particle.scaling.x;
  53856. this._vertex.y *= this._particle.scaling.y;
  53857. this._vertex.z *= this._particle.scaling.z;
  53858. this._vertex.x -= this._scaledPivot.x;
  53859. this._vertex.y -= this._scaledPivot.y;
  53860. this._vertex.z -= this._scaledPivot.z;
  53861. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53862. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53863. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53864. this._rotated.x += this._pivotBackTranslation.x;
  53865. this._rotated.y += this._pivotBackTranslation.y;
  53866. this._rotated.z += this._pivotBackTranslation.z;
  53867. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53868. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  53869. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  53870. if (this._computeBoundingBox) {
  53871. if (this._positions32[idx] < this._minimum.x) {
  53872. this._minimum.x = this._positions32[idx];
  53873. }
  53874. if (this._positions32[idx] > this._maximum.x) {
  53875. this._maximum.x = this._positions32[idx];
  53876. }
  53877. if (this._positions32[idx + 1] < this._minimum.y) {
  53878. this._minimum.y = this._positions32[idx + 1];
  53879. }
  53880. if (this._positions32[idx + 1] > this._maximum.y) {
  53881. this._maximum.y = this._positions32[idx + 1];
  53882. }
  53883. if (this._positions32[idx + 2] < this._minimum.z) {
  53884. this._minimum.z = this._positions32[idx + 2];
  53885. }
  53886. if (this._positions32[idx + 2] > this._maximum.z) {
  53887. this._maximum.z = this._positions32[idx + 2];
  53888. }
  53889. }
  53890. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53891. if (!this._computeParticleVertex) {
  53892. this._normal.x = this._fixedNormal32[idx];
  53893. this._normal.y = this._fixedNormal32[idx + 1];
  53894. this._normal.z = this._fixedNormal32[idx + 2];
  53895. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53896. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53897. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53898. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53899. 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;
  53900. 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;
  53901. }
  53902. if (this._computeParticleColor && this._particle.color) {
  53903. this._colors32[colidx] = this._particle.color.r;
  53904. this._colors32[colidx + 1] = this._particle.color.g;
  53905. this._colors32[colidx + 2] = this._particle.color.b;
  53906. this._colors32[colidx + 3] = this._particle.color.a;
  53907. }
  53908. if (this._computeParticleTexture) {
  53909. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53910. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53911. }
  53912. }
  53913. }
  53914. else {
  53915. this._particle._stillInvisible = true; // mark the particle as invisible
  53916. for (pt = 0; pt < this._shape.length; pt++) {
  53917. idx = index + pt * 3;
  53918. colidx = colorIndex + pt * 4;
  53919. uvidx = uvIndex + pt * 2;
  53920. this._positions32[idx] = 0.0;
  53921. this._positions32[idx + 1] = 0.0;
  53922. this._positions32[idx + 2] = 0.0;
  53923. this._normals32[idx] = 0.0;
  53924. this._normals32[idx + 1] = 0.0;
  53925. this._normals32[idx + 2] = 0.0;
  53926. if (this._computeParticleColor && this._particle.color) {
  53927. this._colors32[colidx] = this._particle.color.r;
  53928. this._colors32[colidx + 1] = this._particle.color.g;
  53929. this._colors32[colidx + 2] = this._particle.color.b;
  53930. this._colors32[colidx + 3] = this._particle.color.a;
  53931. }
  53932. if (this._computeParticleTexture) {
  53933. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53934. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53935. }
  53936. }
  53937. }
  53938. // if the particle intersections must be computed : update the bbInfo
  53939. if (this._particlesIntersect) {
  53940. var bInfo = this._particle._boundingInfo;
  53941. var bBox = bInfo.boundingBox;
  53942. var bSphere = bInfo.boundingSphere;
  53943. if (!this._bSphereOnly) {
  53944. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53945. for (var b = 0; b < bBox.vectors.length; b++) {
  53946. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53947. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53948. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53949. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53950. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53951. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53952. 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;
  53953. 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;
  53954. 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;
  53955. }
  53956. bBox._update(this.mesh._worldMatrix);
  53957. }
  53958. // place and scale the particle bouding sphere in the SPS local system, then update it
  53959. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53960. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53961. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53962. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53963. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53964. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53965. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53966. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53967. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53968. 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));
  53969. bSphere._update(this.mesh._worldMatrix);
  53970. }
  53971. // increment indexes for the next particle
  53972. index = idx + 3;
  53973. colorIndex = colidx + 4;
  53974. uvIndex = uvidx + 2;
  53975. }
  53976. // if the VBO must be updated
  53977. if (update) {
  53978. if (this._computeParticleColor) {
  53979. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53980. }
  53981. if (this._computeParticleTexture) {
  53982. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53983. }
  53984. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53985. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53986. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53987. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53988. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53989. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53990. for (var i = 0; i < this._normals32.length; i++) {
  53991. this._fixedNormal32[i] = this._normals32[i];
  53992. }
  53993. }
  53994. if (!this.mesh.areNormalsFrozen) {
  53995. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53996. }
  53997. }
  53998. if (this._depthSort && this._depthSortParticles) {
  53999. this.depthSortedParticles.sort(this._depthSortFunction);
  54000. var dspl = this.depthSortedParticles.length;
  54001. var sorted = 0;
  54002. var lind = 0;
  54003. var sind = 0;
  54004. var sid = 0;
  54005. for (sorted = 0; sorted < dspl; sorted++) {
  54006. lind = this.depthSortedParticles[sorted].indicesLength;
  54007. sind = this.depthSortedParticles[sorted].ind;
  54008. for (var i = 0; i < lind; i++) {
  54009. this._indices32[sid] = this._indices[sind + i];
  54010. sid++;
  54011. }
  54012. }
  54013. this.mesh.updateIndices(this._indices32);
  54014. }
  54015. }
  54016. if (this._computeBoundingBox) {
  54017. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54018. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54019. }
  54020. this.afterUpdateParticles(start, end, update);
  54021. return this;
  54022. };
  54023. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54024. this._halfroll = this._roll * 0.5;
  54025. this._halfpitch = this._pitch * 0.5;
  54026. this._halfyaw = this._yaw * 0.5;
  54027. this._sinRoll = Math.sin(this._halfroll);
  54028. this._cosRoll = Math.cos(this._halfroll);
  54029. this._sinPitch = Math.sin(this._halfpitch);
  54030. this._cosPitch = Math.cos(this._halfpitch);
  54031. this._sinYaw = Math.sin(this._halfyaw);
  54032. this._cosYaw = Math.cos(this._halfyaw);
  54033. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54034. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54035. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54036. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54037. };
  54038. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54039. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54040. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54041. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54042. this._rotMatrix.m[3] = 0;
  54043. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54044. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54045. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54046. this._rotMatrix.m[7] = 0;
  54047. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54048. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54049. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54050. this._rotMatrix.m[11] = 0;
  54051. this._rotMatrix.m[12] = 0;
  54052. this._rotMatrix.m[13] = 0;
  54053. this._rotMatrix.m[14] = 0;
  54054. this._rotMatrix.m[15] = 1.0;
  54055. };
  54056. /**
  54057. * Disposes the SPS.
  54058. */
  54059. SolidParticleSystem.prototype.dispose = function () {
  54060. this.mesh.dispose();
  54061. this.vars = null;
  54062. // drop references to internal big arrays for the GC
  54063. this._positions = null;
  54064. this._indices = null;
  54065. this._normals = null;
  54066. this._uvs = null;
  54067. this._colors = null;
  54068. this._indices32 = null;
  54069. this._positions32 = null;
  54070. this._normals32 = null;
  54071. this._fixedNormal32 = null;
  54072. this._uvs32 = null;
  54073. this._colors32 = null;
  54074. this.pickedParticles = null;
  54075. };
  54076. /**
  54077. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54078. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54079. * @returns the SPS.
  54080. */
  54081. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54082. if (!this._isVisibilityBoxLocked) {
  54083. this.mesh.refreshBoundingInfo();
  54084. }
  54085. return this;
  54086. };
  54087. /**
  54088. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54089. * @param size the size (float) of the visibility box
  54090. * note : this doesn't lock the SPS mesh bounding box.
  54091. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54092. */
  54093. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54094. var vis = size / 2;
  54095. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54096. };
  54097. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54098. /**
  54099. * Gets whether the SPS as always visible or not
  54100. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54101. */
  54102. get: function () {
  54103. return this._alwaysVisible;
  54104. },
  54105. /**
  54106. * Sets the SPS as always visible or not
  54107. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54108. */
  54109. set: function (val) {
  54110. this._alwaysVisible = val;
  54111. this.mesh.alwaysSelectAsActiveMesh = val;
  54112. },
  54113. enumerable: true,
  54114. configurable: true
  54115. });
  54116. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54117. /**
  54118. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54119. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54120. */
  54121. get: function () {
  54122. return this._isVisibilityBoxLocked;
  54123. },
  54124. /**
  54125. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54126. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54127. */
  54128. set: function (val) {
  54129. this._isVisibilityBoxLocked = val;
  54130. var boundingInfo = this.mesh.getBoundingInfo();
  54131. boundingInfo.isLocked = val;
  54132. },
  54133. enumerable: true,
  54134. configurable: true
  54135. });
  54136. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54137. /**
  54138. * Gets if `setParticles()` computes the particle rotations or not.
  54139. * Default value : true. The SPS is faster when it's set to false.
  54140. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54141. */
  54142. get: function () {
  54143. return this._computeParticleRotation;
  54144. },
  54145. /**
  54146. * Tells to `setParticles()` to compute the particle rotations or not.
  54147. * Default value : true. The SPS is faster when it's set to false.
  54148. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54149. */
  54150. set: function (val) {
  54151. this._computeParticleRotation = val;
  54152. },
  54153. enumerable: true,
  54154. configurable: true
  54155. });
  54156. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54157. /**
  54158. * Gets if `setParticles()` computes the particle colors or not.
  54159. * Default value : true. The SPS is faster when it's set to false.
  54160. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54161. */
  54162. get: function () {
  54163. return this._computeParticleColor;
  54164. },
  54165. /**
  54166. * Tells to `setParticles()` to compute the particle colors or not.
  54167. * Default value : true. The SPS is faster when it's set to false.
  54168. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54169. */
  54170. set: function (val) {
  54171. this._computeParticleColor = val;
  54172. },
  54173. enumerable: true,
  54174. configurable: true
  54175. });
  54176. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54177. /**
  54178. * Gets if `setParticles()` computes the particle textures or not.
  54179. * Default value : true. The SPS is faster when it's set to false.
  54180. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54181. */
  54182. get: function () {
  54183. return this._computeParticleTexture;
  54184. },
  54185. set: function (val) {
  54186. this._computeParticleTexture = val;
  54187. },
  54188. enumerable: true,
  54189. configurable: true
  54190. });
  54191. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54192. /**
  54193. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54194. * Default value : false. The SPS is faster when it's set to false.
  54195. * Note : the particle custom vertex positions aren't stored values.
  54196. */
  54197. get: function () {
  54198. return this._computeParticleVertex;
  54199. },
  54200. /**
  54201. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54202. * Default value : false. The SPS is faster when it's set to false.
  54203. * Note : the particle custom vertex positions aren't stored values.
  54204. */
  54205. set: function (val) {
  54206. this._computeParticleVertex = val;
  54207. },
  54208. enumerable: true,
  54209. configurable: true
  54210. });
  54211. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54212. /**
  54213. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54214. */
  54215. get: function () {
  54216. return this._computeBoundingBox;
  54217. },
  54218. /**
  54219. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54220. */
  54221. set: function (val) {
  54222. this._computeBoundingBox = val;
  54223. },
  54224. enumerable: true,
  54225. configurable: true
  54226. });
  54227. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  54228. /**
  54229. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  54230. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54231. * Default : `true`
  54232. */
  54233. get: function () {
  54234. return this._depthSortParticles;
  54235. },
  54236. /**
  54237. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  54238. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54239. * Default : `true`
  54240. */
  54241. set: function (val) {
  54242. this._depthSortParticles = val;
  54243. },
  54244. enumerable: true,
  54245. configurable: true
  54246. });
  54247. // =======================================================================
  54248. // Particle behavior logic
  54249. // these following methods may be overwritten by the user to fit his needs
  54250. /**
  54251. * This function does nothing. It may be overwritten to set all the particle first values.
  54252. * The SPS doesn't call this function, you may have to call it by your own.
  54253. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54254. */
  54255. SolidParticleSystem.prototype.initParticles = function () {
  54256. };
  54257. /**
  54258. * This function does nothing. It may be overwritten to recycle a particle.
  54259. * The SPS doesn't call this function, you may have to call it by your own.
  54260. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54261. * @param particle The particle to recycle
  54262. * @returns the recycled particle
  54263. */
  54264. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54265. return particle;
  54266. };
  54267. /**
  54268. * Updates a particle : this function should be overwritten by the user.
  54269. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54270. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54271. * @example : just set a particle position or velocity and recycle conditions
  54272. * @param particle The particle to update
  54273. * @returns the updated particle
  54274. */
  54275. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54276. return particle;
  54277. };
  54278. /**
  54279. * Updates a vertex of a particle : it can be overwritten by the user.
  54280. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54281. * @param particle the current particle
  54282. * @param vertex the current index of the current particle
  54283. * @param pt the index of the current vertex in the particle shape
  54284. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54285. * @example : just set a vertex particle position
  54286. * @returns the updated vertex
  54287. */
  54288. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54289. return vertex;
  54290. };
  54291. /**
  54292. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54293. * This does nothing and may be overwritten by the user.
  54294. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54295. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54296. * @param update the boolean update value actually passed to setParticles()
  54297. */
  54298. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54299. };
  54300. /**
  54301. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54302. * This will be passed three parameters.
  54303. * This does nothing and may be overwritten by the user.
  54304. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54305. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54306. * @param update the boolean update value actually passed to setParticles()
  54307. */
  54308. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54309. };
  54310. return SolidParticleSystem;
  54311. }());
  54312. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54313. })(BABYLON || (BABYLON = {}));
  54314. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54315. "use strict";
  54316. var BABYLON;
  54317. (function (BABYLON) {
  54318. var ShaderMaterial = /** @class */ (function (_super) {
  54319. __extends(ShaderMaterial, _super);
  54320. function ShaderMaterial(name, scene, shaderPath, options) {
  54321. var _this = _super.call(this, name, scene) || this;
  54322. _this._textures = {};
  54323. _this._textureArrays = {};
  54324. _this._floats = {};
  54325. _this._ints = {};
  54326. _this._floatsArrays = {};
  54327. _this._colors3 = {};
  54328. _this._colors3Arrays = {};
  54329. _this._colors4 = {};
  54330. _this._vectors2 = {};
  54331. _this._vectors3 = {};
  54332. _this._vectors4 = {};
  54333. _this._matrices = {};
  54334. _this._matrices3x3 = {};
  54335. _this._matrices2x2 = {};
  54336. _this._vectors2Arrays = {};
  54337. _this._vectors3Arrays = {};
  54338. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  54339. _this._shaderPath = shaderPath;
  54340. options.needAlphaBlending = options.needAlphaBlending || false;
  54341. options.needAlphaTesting = options.needAlphaTesting || false;
  54342. options.attributes = options.attributes || ["position", "normal", "uv"];
  54343. options.uniforms = options.uniforms || ["worldViewProjection"];
  54344. options.uniformBuffers = options.uniformBuffers || [];
  54345. options.samplers = options.samplers || [];
  54346. options.defines = options.defines || [];
  54347. _this._options = options;
  54348. return _this;
  54349. }
  54350. ShaderMaterial.prototype.getClassName = function () {
  54351. return "ShaderMaterial";
  54352. };
  54353. ShaderMaterial.prototype.needAlphaBlending = function () {
  54354. return this._options.needAlphaBlending;
  54355. };
  54356. ShaderMaterial.prototype.needAlphaTesting = function () {
  54357. return this._options.needAlphaTesting;
  54358. };
  54359. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  54360. if (this._options.uniforms.indexOf(uniformName) === -1) {
  54361. this._options.uniforms.push(uniformName);
  54362. }
  54363. };
  54364. ShaderMaterial.prototype.setTexture = function (name, texture) {
  54365. if (this._options.samplers.indexOf(name) === -1) {
  54366. this._options.samplers.push(name);
  54367. }
  54368. this._textures[name] = texture;
  54369. return this;
  54370. };
  54371. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  54372. if (this._options.samplers.indexOf(name) === -1) {
  54373. this._options.samplers.push(name);
  54374. }
  54375. this._checkUniform(name);
  54376. this._textureArrays[name] = textures;
  54377. return this;
  54378. };
  54379. ShaderMaterial.prototype.setFloat = function (name, value) {
  54380. this._checkUniform(name);
  54381. this._floats[name] = value;
  54382. return this;
  54383. };
  54384. ShaderMaterial.prototype.setInt = function (name, value) {
  54385. this._checkUniform(name);
  54386. this._ints[name] = value;
  54387. return this;
  54388. };
  54389. ShaderMaterial.prototype.setFloats = function (name, value) {
  54390. this._checkUniform(name);
  54391. this._floatsArrays[name] = value;
  54392. return this;
  54393. };
  54394. ShaderMaterial.prototype.setColor3 = function (name, value) {
  54395. this._checkUniform(name);
  54396. this._colors3[name] = value;
  54397. return this;
  54398. };
  54399. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  54400. this._checkUniform(name);
  54401. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  54402. color.toArray(arr, arr.length);
  54403. return arr;
  54404. }, []);
  54405. return this;
  54406. };
  54407. ShaderMaterial.prototype.setColor4 = function (name, value) {
  54408. this._checkUniform(name);
  54409. this._colors4[name] = value;
  54410. return this;
  54411. };
  54412. ShaderMaterial.prototype.setVector2 = function (name, value) {
  54413. this._checkUniform(name);
  54414. this._vectors2[name] = value;
  54415. return this;
  54416. };
  54417. ShaderMaterial.prototype.setVector3 = function (name, value) {
  54418. this._checkUniform(name);
  54419. this._vectors3[name] = value;
  54420. return this;
  54421. };
  54422. ShaderMaterial.prototype.setVector4 = function (name, value) {
  54423. this._checkUniform(name);
  54424. this._vectors4[name] = value;
  54425. return this;
  54426. };
  54427. ShaderMaterial.prototype.setMatrix = function (name, value) {
  54428. this._checkUniform(name);
  54429. this._matrices[name] = value;
  54430. return this;
  54431. };
  54432. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  54433. this._checkUniform(name);
  54434. this._matrices3x3[name] = value;
  54435. return this;
  54436. };
  54437. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  54438. this._checkUniform(name);
  54439. this._matrices2x2[name] = value;
  54440. return this;
  54441. };
  54442. ShaderMaterial.prototype.setArray2 = function (name, value) {
  54443. this._checkUniform(name);
  54444. this._vectors2Arrays[name] = value;
  54445. return this;
  54446. };
  54447. ShaderMaterial.prototype.setArray3 = function (name, value) {
  54448. this._checkUniform(name);
  54449. this._vectors3Arrays[name] = value;
  54450. return this;
  54451. };
  54452. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  54453. if (!mesh) {
  54454. return true;
  54455. }
  54456. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  54457. return false;
  54458. }
  54459. return false;
  54460. };
  54461. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  54462. var scene = this.getScene();
  54463. var engine = scene.getEngine();
  54464. if (!this.checkReadyOnEveryCall) {
  54465. if (this._renderId === scene.getRenderId()) {
  54466. if (this._checkCache(scene, mesh, useInstances)) {
  54467. return true;
  54468. }
  54469. }
  54470. }
  54471. // Instances
  54472. var defines = [];
  54473. var attribs = [];
  54474. var fallbacks = new BABYLON.EffectFallbacks();
  54475. if (useInstances) {
  54476. defines.push("#define INSTANCES");
  54477. }
  54478. for (var index = 0; index < this._options.defines.length; index++) {
  54479. defines.push(this._options.defines[index]);
  54480. }
  54481. for (var index = 0; index < this._options.attributes.length; index++) {
  54482. attribs.push(this._options.attributes[index]);
  54483. }
  54484. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54485. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54486. defines.push("#define VERTEXCOLOR");
  54487. }
  54488. // Bones
  54489. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  54490. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54491. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54492. if (mesh.numBoneInfluencers > 4) {
  54493. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54494. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54495. }
  54496. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54497. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54498. fallbacks.addCPUSkinningFallback(0, mesh);
  54499. if (this._options.uniforms.indexOf("mBones") === -1) {
  54500. this._options.uniforms.push("mBones");
  54501. }
  54502. }
  54503. else {
  54504. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54505. }
  54506. // Textures
  54507. for (var name in this._textures) {
  54508. if (!this._textures[name].isReady()) {
  54509. return false;
  54510. }
  54511. }
  54512. // Alpha test
  54513. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  54514. defines.push("#define ALPHATEST");
  54515. }
  54516. var previousEffect = this._effect;
  54517. var join = defines.join("\n");
  54518. this._effect = engine.createEffect(this._shaderPath, {
  54519. attributes: attribs,
  54520. uniformsNames: this._options.uniforms,
  54521. uniformBuffersNames: this._options.uniformBuffers,
  54522. samplers: this._options.samplers,
  54523. defines: join,
  54524. fallbacks: fallbacks,
  54525. onCompiled: this.onCompiled,
  54526. onError: this.onError
  54527. }, engine);
  54528. if (!this._effect.isReady()) {
  54529. return false;
  54530. }
  54531. if (previousEffect !== this._effect) {
  54532. scene.resetCachedMaterial();
  54533. }
  54534. this._renderId = scene.getRenderId();
  54535. return true;
  54536. };
  54537. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54538. var scene = this.getScene();
  54539. if (!this._effect) {
  54540. return;
  54541. }
  54542. if (this._options.uniforms.indexOf("world") !== -1) {
  54543. this._effect.setMatrix("world", world);
  54544. }
  54545. if (this._options.uniforms.indexOf("worldView") !== -1) {
  54546. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  54547. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  54548. }
  54549. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  54550. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  54551. }
  54552. };
  54553. ShaderMaterial.prototype.bind = function (world, mesh) {
  54554. // Std values
  54555. this.bindOnlyWorldMatrix(world);
  54556. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  54557. if (this._options.uniforms.indexOf("view") !== -1) {
  54558. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  54559. }
  54560. if (this._options.uniforms.indexOf("projection") !== -1) {
  54561. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  54562. }
  54563. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  54564. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  54565. }
  54566. // Bones
  54567. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54568. var name;
  54569. // Texture
  54570. for (name in this._textures) {
  54571. this._effect.setTexture(name, this._textures[name]);
  54572. }
  54573. // Texture arrays
  54574. for (name in this._textureArrays) {
  54575. this._effect.setTextureArray(name, this._textureArrays[name]);
  54576. }
  54577. // Int
  54578. for (name in this._ints) {
  54579. this._effect.setInt(name, this._ints[name]);
  54580. }
  54581. // Float
  54582. for (name in this._floats) {
  54583. this._effect.setFloat(name, this._floats[name]);
  54584. }
  54585. // Floats
  54586. for (name in this._floatsArrays) {
  54587. this._effect.setArray(name, this._floatsArrays[name]);
  54588. }
  54589. // Color3
  54590. for (name in this._colors3) {
  54591. this._effect.setColor3(name, this._colors3[name]);
  54592. }
  54593. for (name in this._colors3Arrays) {
  54594. this._effect.setArray3(name, this._colors3Arrays[name]);
  54595. }
  54596. // Color4
  54597. for (name in this._colors4) {
  54598. var color = this._colors4[name];
  54599. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54600. }
  54601. // Vector2
  54602. for (name in this._vectors2) {
  54603. this._effect.setVector2(name, this._vectors2[name]);
  54604. }
  54605. // Vector3
  54606. for (name in this._vectors3) {
  54607. this._effect.setVector3(name, this._vectors3[name]);
  54608. }
  54609. // Vector4
  54610. for (name in this._vectors4) {
  54611. this._effect.setVector4(name, this._vectors4[name]);
  54612. }
  54613. // Matrix
  54614. for (name in this._matrices) {
  54615. this._effect.setMatrix(name, this._matrices[name]);
  54616. }
  54617. // Matrix 3x3
  54618. for (name in this._matrices3x3) {
  54619. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  54620. }
  54621. // Matrix 2x2
  54622. for (name in this._matrices2x2) {
  54623. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  54624. }
  54625. // Vector2Array
  54626. for (name in this._vectors2Arrays) {
  54627. this._effect.setArray2(name, this._vectors2Arrays[name]);
  54628. }
  54629. // Vector3Array
  54630. for (name in this._vectors3Arrays) {
  54631. this._effect.setArray3(name, this._vectors3Arrays[name]);
  54632. }
  54633. }
  54634. this._afterBind(mesh);
  54635. };
  54636. ShaderMaterial.prototype.getActiveTextures = function () {
  54637. var activeTextures = _super.prototype.getActiveTextures.call(this);
  54638. for (var name in this._textures) {
  54639. activeTextures.push(this._textures[name]);
  54640. }
  54641. for (var name in this._textureArrays) {
  54642. var array = this._textureArrays[name];
  54643. for (var index = 0; index < array.length; index++) {
  54644. activeTextures.push(array[index]);
  54645. }
  54646. }
  54647. return activeTextures;
  54648. };
  54649. ShaderMaterial.prototype.hasTexture = function (texture) {
  54650. if (_super.prototype.hasTexture.call(this, texture)) {
  54651. return true;
  54652. }
  54653. for (var name in this._textures) {
  54654. if (this._textures[name] === texture) {
  54655. return true;
  54656. }
  54657. }
  54658. for (var name in this._textureArrays) {
  54659. var array = this._textureArrays[name];
  54660. for (var index = 0; index < array.length; index++) {
  54661. if (array[index] === texture) {
  54662. return true;
  54663. }
  54664. }
  54665. }
  54666. return false;
  54667. };
  54668. ShaderMaterial.prototype.clone = function (name) {
  54669. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54670. return newShaderMaterial;
  54671. };
  54672. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54673. if (forceDisposeTextures) {
  54674. var name;
  54675. for (name in this._textures) {
  54676. this._textures[name].dispose();
  54677. }
  54678. for (name in this._textureArrays) {
  54679. var array = this._textureArrays[name];
  54680. for (var index = 0; index < array.length; index++) {
  54681. array[index].dispose();
  54682. }
  54683. }
  54684. }
  54685. this._textures = {};
  54686. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54687. };
  54688. ShaderMaterial.prototype.serialize = function () {
  54689. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54690. serializationObject.customType = "BABYLON.ShaderMaterial";
  54691. serializationObject.options = this._options;
  54692. serializationObject.shaderPath = this._shaderPath;
  54693. var name;
  54694. // Texture
  54695. serializationObject.textures = {};
  54696. for (name in this._textures) {
  54697. serializationObject.textures[name] = this._textures[name].serialize();
  54698. }
  54699. // Texture arrays
  54700. serializationObject.textureArrays = {};
  54701. for (name in this._textureArrays) {
  54702. serializationObject.textureArrays[name] = [];
  54703. var array = this._textureArrays[name];
  54704. for (var index = 0; index < array.length; index++) {
  54705. serializationObject.textureArrays[name].push(array[index].serialize());
  54706. }
  54707. }
  54708. // Float
  54709. serializationObject.floats = {};
  54710. for (name in this._floats) {
  54711. serializationObject.floats[name] = this._floats[name];
  54712. }
  54713. // Float s
  54714. serializationObject.FloatArrays = {};
  54715. for (name in this._floatsArrays) {
  54716. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54717. }
  54718. // Color3
  54719. serializationObject.colors3 = {};
  54720. for (name in this._colors3) {
  54721. serializationObject.colors3[name] = this._colors3[name].asArray();
  54722. }
  54723. // Color3 array
  54724. serializationObject.colors3Arrays = {};
  54725. for (name in this._colors3Arrays) {
  54726. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54727. }
  54728. // Color4
  54729. serializationObject.colors4 = {};
  54730. for (name in this._colors4) {
  54731. serializationObject.colors4[name] = this._colors4[name].asArray();
  54732. }
  54733. // Vector2
  54734. serializationObject.vectors2 = {};
  54735. for (name in this._vectors2) {
  54736. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54737. }
  54738. // Vector3
  54739. serializationObject.vectors3 = {};
  54740. for (name in this._vectors3) {
  54741. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54742. }
  54743. // Vector4
  54744. serializationObject.vectors4 = {};
  54745. for (name in this._vectors4) {
  54746. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54747. }
  54748. // Matrix
  54749. serializationObject.matrices = {};
  54750. for (name in this._matrices) {
  54751. serializationObject.matrices[name] = this._matrices[name].asArray();
  54752. }
  54753. // Matrix 3x3
  54754. serializationObject.matrices3x3 = {};
  54755. for (name in this._matrices3x3) {
  54756. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54757. }
  54758. // Matrix 2x2
  54759. serializationObject.matrices2x2 = {};
  54760. for (name in this._matrices2x2) {
  54761. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54762. }
  54763. // Vector2Array
  54764. serializationObject.vectors2Arrays = {};
  54765. for (name in this._vectors2Arrays) {
  54766. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54767. }
  54768. // Vector3Array
  54769. serializationObject.vectors3Arrays = {};
  54770. for (name in this._vectors3Arrays) {
  54771. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54772. }
  54773. return serializationObject;
  54774. };
  54775. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54776. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54777. var name;
  54778. // Texture
  54779. for (name in source.textures) {
  54780. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54781. }
  54782. // Texture arrays
  54783. for (name in source.textureArrays) {
  54784. var array = source.textureArrays[name];
  54785. var textureArray = new Array();
  54786. for (var index = 0; index < array.length; index++) {
  54787. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54788. }
  54789. material.setTextureArray(name, textureArray);
  54790. }
  54791. // Float
  54792. for (name in source.floats) {
  54793. material.setFloat(name, source.floats[name]);
  54794. }
  54795. // Float s
  54796. for (name in source.floatsArrays) {
  54797. material.setFloats(name, source.floatsArrays[name]);
  54798. }
  54799. // Color3
  54800. for (name in source.colors3) {
  54801. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54802. }
  54803. // Color3 arrays
  54804. for (name in source.colors3Arrays) {
  54805. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54806. if (i % 3 === 0) {
  54807. arr.push([num]);
  54808. }
  54809. else {
  54810. arr[arr.length - 1].push(num);
  54811. }
  54812. return arr;
  54813. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54814. material.setColor3Array(name, colors);
  54815. }
  54816. // Color4
  54817. for (name in source.colors4) {
  54818. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54819. }
  54820. // Vector2
  54821. for (name in source.vectors2) {
  54822. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54823. }
  54824. // Vector3
  54825. for (name in source.vectors3) {
  54826. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54827. }
  54828. // Vector4
  54829. for (name in source.vectors4) {
  54830. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54831. }
  54832. // Matrix
  54833. for (name in source.matrices) {
  54834. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54835. }
  54836. // Matrix 3x3
  54837. for (name in source.matrices3x3) {
  54838. material.setMatrix3x3(name, source.matrices3x3[name]);
  54839. }
  54840. // Matrix 2x2
  54841. for (name in source.matrices2x2) {
  54842. material.setMatrix2x2(name, source.matrices2x2[name]);
  54843. }
  54844. // Vector2Array
  54845. for (name in source.vectors2Arrays) {
  54846. material.setArray2(name, source.vectors2Arrays[name]);
  54847. }
  54848. // Vector3Array
  54849. for (name in source.vectors3Arrays) {
  54850. material.setArray3(name, source.vectors3Arrays[name]);
  54851. }
  54852. return material;
  54853. };
  54854. return ShaderMaterial;
  54855. }(BABYLON.Material));
  54856. BABYLON.ShaderMaterial = ShaderMaterial;
  54857. })(BABYLON || (BABYLON = {}));
  54858. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54859. "use strict";
  54860. var BABYLON;
  54861. (function (BABYLON) {
  54862. var GroundMesh = /** @class */ (function (_super) {
  54863. __extends(GroundMesh, _super);
  54864. function GroundMesh(name, scene) {
  54865. var _this = _super.call(this, name, scene) || this;
  54866. _this.generateOctree = false;
  54867. return _this;
  54868. }
  54869. GroundMesh.prototype.getClassName = function () {
  54870. return "GroundMesh";
  54871. };
  54872. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54873. get: function () {
  54874. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54875. },
  54876. enumerable: true,
  54877. configurable: true
  54878. });
  54879. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54880. get: function () {
  54881. return this._subdivisionsX;
  54882. },
  54883. enumerable: true,
  54884. configurable: true
  54885. });
  54886. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54887. get: function () {
  54888. return this._subdivisionsY;
  54889. },
  54890. enumerable: true,
  54891. configurable: true
  54892. });
  54893. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54894. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54895. this._subdivisionsX = chunksCount;
  54896. this._subdivisionsY = chunksCount;
  54897. this.subdivide(chunksCount);
  54898. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54899. };
  54900. /**
  54901. * Returns a height (y) value in the Worl system :
  54902. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54903. * Returns the ground y position if (x, z) are outside the ground surface.
  54904. */
  54905. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54906. var world = this.getWorldMatrix();
  54907. var invMat = BABYLON.Tmp.Matrix[5];
  54908. world.invertToRef(invMat);
  54909. var tmpVect = BABYLON.Tmp.Vector3[8];
  54910. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54911. x = tmpVect.x;
  54912. z = tmpVect.z;
  54913. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54914. return this.position.y;
  54915. }
  54916. if (!this._heightQuads || this._heightQuads.length == 0) {
  54917. this._initHeightQuads();
  54918. this._computeHeightQuads();
  54919. }
  54920. var facet = this._getFacetAt(x, z);
  54921. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54922. // return y in the World system
  54923. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54924. return tmpVect.y;
  54925. };
  54926. /**
  54927. * Returns a normalized vector (Vector3) orthogonal to the ground
  54928. * at the ground coordinates (x, z) expressed in the World system.
  54929. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54930. */
  54931. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54932. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54933. this.getNormalAtCoordinatesToRef(x, z, normal);
  54934. return normal;
  54935. };
  54936. /**
  54937. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54938. * at the ground coordinates (x, z) expressed in the World system.
  54939. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54940. * Returns the GroundMesh.
  54941. */
  54942. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54943. var world = this.getWorldMatrix();
  54944. var tmpMat = BABYLON.Tmp.Matrix[5];
  54945. world.invertToRef(tmpMat);
  54946. var tmpVect = BABYLON.Tmp.Vector3[8];
  54947. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54948. x = tmpVect.x;
  54949. z = tmpVect.z;
  54950. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54951. return this;
  54952. }
  54953. if (!this._heightQuads || this._heightQuads.length == 0) {
  54954. this._initHeightQuads();
  54955. this._computeHeightQuads();
  54956. }
  54957. var facet = this._getFacetAt(x, z);
  54958. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  54959. return this;
  54960. };
  54961. /**
  54962. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  54963. * if the ground has been updated.
  54964. * This can be used in the render loop.
  54965. * Returns the GroundMesh.
  54966. */
  54967. GroundMesh.prototype.updateCoordinateHeights = function () {
  54968. if (!this._heightQuads || this._heightQuads.length == 0) {
  54969. this._initHeightQuads();
  54970. }
  54971. this._computeHeightQuads();
  54972. return this;
  54973. };
  54974. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54975. GroundMesh.prototype._getFacetAt = function (x, z) {
  54976. // retrieve col and row from x, z coordinates in the ground local system
  54977. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54978. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54979. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54980. var facet;
  54981. if (z < quad.slope.x * x + quad.slope.y) {
  54982. facet = quad.facet1;
  54983. }
  54984. else {
  54985. facet = quad.facet2;
  54986. }
  54987. return facet;
  54988. };
  54989. // Creates and populates the heightMap array with "facet" elements :
  54990. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  54991. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54992. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54993. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54994. // Returns the GroundMesh.
  54995. GroundMesh.prototype._initHeightQuads = function () {
  54996. var subdivisionsX = this._subdivisionsX;
  54997. var subdivisionsY = this._subdivisionsY;
  54998. this._heightQuads = new Array();
  54999. for (var row = 0; row < subdivisionsY; row++) {
  55000. for (var col = 0; col < subdivisionsX; col++) {
  55001. 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) };
  55002. this._heightQuads[row * subdivisionsX + col] = quad;
  55003. }
  55004. }
  55005. return this;
  55006. };
  55007. // Compute each quad element values and update the the heightMap array :
  55008. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55009. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55010. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55011. // Returns the GroundMesh.
  55012. GroundMesh.prototype._computeHeightQuads = function () {
  55013. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55014. if (!positions) {
  55015. return this;
  55016. }
  55017. var v1 = BABYLON.Tmp.Vector3[3];
  55018. var v2 = BABYLON.Tmp.Vector3[2];
  55019. var v3 = BABYLON.Tmp.Vector3[1];
  55020. var v4 = BABYLON.Tmp.Vector3[0];
  55021. var v1v2 = BABYLON.Tmp.Vector3[4];
  55022. var v1v3 = BABYLON.Tmp.Vector3[5];
  55023. var v1v4 = BABYLON.Tmp.Vector3[6];
  55024. var norm1 = BABYLON.Tmp.Vector3[7];
  55025. var norm2 = BABYLON.Tmp.Vector3[8];
  55026. var i = 0;
  55027. var j = 0;
  55028. var k = 0;
  55029. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55030. var h = 0;
  55031. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55032. var d2 = 0;
  55033. var subdivisionsX = this._subdivisionsX;
  55034. var subdivisionsY = this._subdivisionsY;
  55035. for (var row = 0; row < subdivisionsY; row++) {
  55036. for (var col = 0; col < subdivisionsX; col++) {
  55037. i = col * 3;
  55038. j = row * (subdivisionsX + 1) * 3;
  55039. k = (row + 1) * (subdivisionsX + 1) * 3;
  55040. v1.x = positions[j + i];
  55041. v1.y = positions[j + i + 1];
  55042. v1.z = positions[j + i + 2];
  55043. v2.x = positions[j + i + 3];
  55044. v2.y = positions[j + i + 4];
  55045. v2.z = positions[j + i + 5];
  55046. v3.x = positions[k + i];
  55047. v3.y = positions[k + i + 1];
  55048. v3.z = positions[k + i + 2];
  55049. v4.x = positions[k + i + 3];
  55050. v4.y = positions[k + i + 4];
  55051. v4.z = positions[k + i + 5];
  55052. // 2D slope V1V4
  55053. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55054. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55055. // facet equations :
  55056. // we compute each facet normal vector
  55057. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55058. // we compute the value d by applying the equation to v1 which belongs to the plane
  55059. // then we store the facet equation in a Vector4
  55060. v2.subtractToRef(v1, v1v2);
  55061. v3.subtractToRef(v1, v1v3);
  55062. v4.subtractToRef(v1, v1v4);
  55063. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55064. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55065. norm1.normalize();
  55066. norm2.normalize();
  55067. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55068. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55069. var quad = this._heightQuads[row * subdivisionsX + col];
  55070. quad.slope.copyFromFloats(cd, h);
  55071. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55072. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55073. }
  55074. }
  55075. return this;
  55076. };
  55077. GroundMesh.prototype.serialize = function (serializationObject) {
  55078. _super.prototype.serialize.call(this, serializationObject);
  55079. serializationObject.subdivisionsX = this._subdivisionsX;
  55080. serializationObject.subdivisionsY = this._subdivisionsY;
  55081. serializationObject.minX = this._minX;
  55082. serializationObject.maxX = this._maxX;
  55083. serializationObject.minZ = this._minZ;
  55084. serializationObject.maxZ = this._maxZ;
  55085. serializationObject.width = this._width;
  55086. serializationObject.height = this._height;
  55087. };
  55088. GroundMesh.Parse = function (parsedMesh, scene) {
  55089. var result = new GroundMesh(parsedMesh.name, scene);
  55090. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55091. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55092. result._minX = parsedMesh.minX;
  55093. result._maxX = parsedMesh.maxX;
  55094. result._minZ = parsedMesh.minZ;
  55095. result._maxZ = parsedMesh.maxZ;
  55096. result._width = parsedMesh.width;
  55097. result._height = parsedMesh.height;
  55098. return result;
  55099. };
  55100. return GroundMesh;
  55101. }(BABYLON.Mesh));
  55102. BABYLON.GroundMesh = GroundMesh;
  55103. })(BABYLON || (BABYLON = {}));
  55104. //# sourceMappingURL=babylon.groundMesh.js.map
  55105. "use strict";
  55106. var BABYLON;
  55107. (function (BABYLON) {
  55108. /**
  55109. * Creates an instance based on a source mesh.
  55110. */
  55111. var InstancedMesh = /** @class */ (function (_super) {
  55112. __extends(InstancedMesh, _super);
  55113. function InstancedMesh(name, source) {
  55114. var _this = _super.call(this, name, source.getScene()) || this;
  55115. source.instances.push(_this);
  55116. _this._sourceMesh = source;
  55117. _this.position.copyFrom(source.position);
  55118. _this.rotation.copyFrom(source.rotation);
  55119. _this.scaling.copyFrom(source.scaling);
  55120. if (source.rotationQuaternion) {
  55121. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55122. }
  55123. _this.infiniteDistance = source.infiniteDistance;
  55124. _this.setPivotMatrix(source.getPivotMatrix());
  55125. _this.refreshBoundingInfo();
  55126. _this._syncSubMeshes();
  55127. return _this;
  55128. }
  55129. /**
  55130. * Returns the string "InstancedMesh".
  55131. */
  55132. InstancedMesh.prototype.getClassName = function () {
  55133. return "InstancedMesh";
  55134. };
  55135. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55136. // Methods
  55137. get: function () {
  55138. return this._sourceMesh.receiveShadows;
  55139. },
  55140. enumerable: true,
  55141. configurable: true
  55142. });
  55143. Object.defineProperty(InstancedMesh.prototype, "material", {
  55144. get: function () {
  55145. return this._sourceMesh.material;
  55146. },
  55147. enumerable: true,
  55148. configurable: true
  55149. });
  55150. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55151. get: function () {
  55152. return this._sourceMesh.visibility;
  55153. },
  55154. enumerable: true,
  55155. configurable: true
  55156. });
  55157. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55158. get: function () {
  55159. return this._sourceMesh.skeleton;
  55160. },
  55161. enumerable: true,
  55162. configurable: true
  55163. });
  55164. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55165. get: function () {
  55166. return this._sourceMesh.renderingGroupId;
  55167. },
  55168. set: function (value) {
  55169. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  55170. return;
  55171. }
  55172. //no-op with warning
  55173. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  55174. },
  55175. enumerable: true,
  55176. configurable: true
  55177. });
  55178. /**
  55179. * Returns the total number of vertices (integer).
  55180. */
  55181. InstancedMesh.prototype.getTotalVertices = function () {
  55182. return this._sourceMesh.getTotalVertices();
  55183. };
  55184. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55185. get: function () {
  55186. return this._sourceMesh;
  55187. },
  55188. enumerable: true,
  55189. configurable: true
  55190. });
  55191. /**
  55192. * Is this node ready to be used/rendered
  55193. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55194. * @return {boolean} is it ready
  55195. */
  55196. InstancedMesh.prototype.isReady = function (completeCheck) {
  55197. if (completeCheck === void 0) { completeCheck = false; }
  55198. return this._sourceMesh.isReady(completeCheck, true);
  55199. };
  55200. /**
  55201. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55202. */
  55203. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55204. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55205. };
  55206. /**
  55207. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55208. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55209. * The `data` are either a numeric array either a Float32Array.
  55210. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55211. * 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).
  55212. * Note that a new underlying VertexBuffer object is created each call.
  55213. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55214. *
  55215. * Possible `kind` values :
  55216. * - BABYLON.VertexBuffer.PositionKind
  55217. * - BABYLON.VertexBuffer.UVKind
  55218. * - BABYLON.VertexBuffer.UV2Kind
  55219. * - BABYLON.VertexBuffer.UV3Kind
  55220. * - BABYLON.VertexBuffer.UV4Kind
  55221. * - BABYLON.VertexBuffer.UV5Kind
  55222. * - BABYLON.VertexBuffer.UV6Kind
  55223. * - BABYLON.VertexBuffer.ColorKind
  55224. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55225. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55226. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55227. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55228. *
  55229. * Returns the Mesh.
  55230. */
  55231. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  55232. if (this.sourceMesh) {
  55233. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  55234. }
  55235. return this.sourceMesh;
  55236. };
  55237. /**
  55238. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  55239. * If the mesh has no geometry, it is simply returned as it is.
  55240. * The `data` are either a numeric array either a Float32Array.
  55241. * No new underlying VertexBuffer object is created.
  55242. * 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.
  55243. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  55244. *
  55245. * Possible `kind` values :
  55246. * - BABYLON.VertexBuffer.PositionKind
  55247. * - BABYLON.VertexBuffer.UVKind
  55248. * - BABYLON.VertexBuffer.UV2Kind
  55249. * - BABYLON.VertexBuffer.UV3Kind
  55250. * - BABYLON.VertexBuffer.UV4Kind
  55251. * - BABYLON.VertexBuffer.UV5Kind
  55252. * - BABYLON.VertexBuffer.UV6Kind
  55253. * - BABYLON.VertexBuffer.ColorKind
  55254. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55255. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55256. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55257. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55258. *
  55259. * Returns the Mesh.
  55260. */
  55261. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  55262. if (this.sourceMesh) {
  55263. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  55264. }
  55265. return this.sourceMesh;
  55266. };
  55267. /**
  55268. * Sets the mesh indices.
  55269. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  55270. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  55271. * This method creates a new index buffer each call.
  55272. * Returns the Mesh.
  55273. */
  55274. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  55275. if (totalVertices === void 0) { totalVertices = null; }
  55276. if (this.sourceMesh) {
  55277. this.sourceMesh.setIndices(indices, totalVertices);
  55278. }
  55279. return this.sourceMesh;
  55280. };
  55281. /**
  55282. * Boolean : True if the mesh owns the requested kind of data.
  55283. */
  55284. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  55285. return this._sourceMesh.isVerticesDataPresent(kind);
  55286. };
  55287. /**
  55288. * Returns an array of indices (IndicesArray).
  55289. */
  55290. InstancedMesh.prototype.getIndices = function () {
  55291. return this._sourceMesh.getIndices();
  55292. };
  55293. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  55294. get: function () {
  55295. return this._sourceMesh._positions;
  55296. },
  55297. enumerable: true,
  55298. configurable: true
  55299. });
  55300. /**
  55301. * Sets a new updated BoundingInfo to the mesh.
  55302. * Returns the mesh.
  55303. */
  55304. InstancedMesh.prototype.refreshBoundingInfo = function () {
  55305. var meshBB = this._sourceMesh.getBoundingInfo();
  55306. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  55307. this._updateBoundingInfo();
  55308. return this;
  55309. };
  55310. InstancedMesh.prototype._preActivate = function () {
  55311. if (this._currentLOD) {
  55312. this._currentLOD._preActivate();
  55313. }
  55314. return this;
  55315. };
  55316. InstancedMesh.prototype._activate = function (renderId) {
  55317. if (this._currentLOD) {
  55318. this._currentLOD._registerInstanceForRenderId(this, renderId);
  55319. }
  55320. return this;
  55321. };
  55322. /**
  55323. * Returns the current associated LOD AbstractMesh.
  55324. */
  55325. InstancedMesh.prototype.getLOD = function (camera) {
  55326. if (!camera) {
  55327. return this;
  55328. }
  55329. var boundingInfo = this.getBoundingInfo();
  55330. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  55331. if (this._currentLOD === this.sourceMesh) {
  55332. return this;
  55333. }
  55334. return this._currentLOD;
  55335. };
  55336. InstancedMesh.prototype._syncSubMeshes = function () {
  55337. this.releaseSubMeshes();
  55338. if (this._sourceMesh.subMeshes) {
  55339. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  55340. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  55341. }
  55342. }
  55343. return this;
  55344. };
  55345. InstancedMesh.prototype._generatePointsArray = function () {
  55346. return this._sourceMesh._generatePointsArray();
  55347. };
  55348. /**
  55349. * Creates a new InstancedMesh from the current mesh.
  55350. * - name (string) : the cloned mesh name
  55351. * - newParent (optional Node) : the optional Node to parent the clone to.
  55352. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  55353. *
  55354. * Returns the clone.
  55355. */
  55356. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55357. var result = this._sourceMesh.createInstance(name);
  55358. // Deep copy
  55359. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  55360. // Bounding info
  55361. this.refreshBoundingInfo();
  55362. // Parent
  55363. if (newParent) {
  55364. result.parent = newParent;
  55365. }
  55366. if (!doNotCloneChildren) {
  55367. // Children
  55368. for (var index = 0; index < this.getScene().meshes.length; index++) {
  55369. var mesh = this.getScene().meshes[index];
  55370. if (mesh.parent === this) {
  55371. mesh.clone(mesh.name, result);
  55372. }
  55373. }
  55374. }
  55375. result.computeWorldMatrix(true);
  55376. return result;
  55377. };
  55378. /**
  55379. * Disposes the InstancedMesh.
  55380. * Returns nothing.
  55381. */
  55382. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  55383. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  55384. // Remove from mesh
  55385. var index = this._sourceMesh.instances.indexOf(this);
  55386. this._sourceMesh.instances.splice(index, 1);
  55387. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  55388. };
  55389. return InstancedMesh;
  55390. }(BABYLON.AbstractMesh));
  55391. BABYLON.InstancedMesh = InstancedMesh;
  55392. })(BABYLON || (BABYLON = {}));
  55393. //# sourceMappingURL=babylon.instancedMesh.js.map
  55394. "use strict";
  55395. var BABYLON;
  55396. (function (BABYLON) {
  55397. var LinesMesh = /** @class */ (function (_super) {
  55398. __extends(LinesMesh, _super);
  55399. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  55400. if (scene === void 0) { scene = null; }
  55401. if (parent === void 0) { parent = null; }
  55402. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  55403. _this.useVertexColor = useVertexColor;
  55404. _this.useVertexAlpha = useVertexAlpha;
  55405. _this.color = new BABYLON.Color3(1, 1, 1);
  55406. _this.alpha = 1;
  55407. if (source) {
  55408. _this.color = source.color.clone();
  55409. _this.alpha = source.alpha;
  55410. _this.useVertexColor = source.useVertexColor;
  55411. _this.useVertexAlpha = source.useVertexAlpha;
  55412. }
  55413. _this._intersectionThreshold = 0.1;
  55414. var defines = [];
  55415. var options = {
  55416. attributes: [BABYLON.VertexBuffer.PositionKind],
  55417. uniforms: ["world", "viewProjection"],
  55418. needAlphaBlending: true,
  55419. defines: defines
  55420. };
  55421. if (useVertexAlpha === false) {
  55422. options.needAlphaBlending = false;
  55423. }
  55424. if (!useVertexColor) {
  55425. options.uniforms.push("color");
  55426. }
  55427. else {
  55428. options.defines.push("#define VERTEXCOLOR");
  55429. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  55430. }
  55431. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  55432. return _this;
  55433. }
  55434. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  55435. /**
  55436. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55437. * This margin is expressed in world space coordinates, so its value may vary.
  55438. * Default value is 0.1
  55439. * @returns the intersection Threshold value.
  55440. */
  55441. get: function () {
  55442. return this._intersectionThreshold;
  55443. },
  55444. /**
  55445. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55446. * This margin is expressed in world space coordinates, so its value may vary.
  55447. * @param value the new threshold to apply
  55448. */
  55449. set: function (value) {
  55450. if (this._intersectionThreshold === value) {
  55451. return;
  55452. }
  55453. this._intersectionThreshold = value;
  55454. if (this.geometry) {
  55455. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  55456. }
  55457. },
  55458. enumerable: true,
  55459. configurable: true
  55460. });
  55461. /**
  55462. * Returns the string "LineMesh"
  55463. */
  55464. LinesMesh.prototype.getClassName = function () {
  55465. return "LinesMesh";
  55466. };
  55467. Object.defineProperty(LinesMesh.prototype, "material", {
  55468. get: function () {
  55469. return this._colorShader;
  55470. },
  55471. set: function (value) {
  55472. // Do nothing
  55473. },
  55474. enumerable: true,
  55475. configurable: true
  55476. });
  55477. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  55478. get: function () {
  55479. return false;
  55480. },
  55481. enumerable: true,
  55482. configurable: true
  55483. });
  55484. LinesMesh.prototype.createInstance = function (name) {
  55485. throw new Error("LinesMeshes do not support createInstance.");
  55486. };
  55487. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  55488. if (!this._geometry) {
  55489. return this;
  55490. }
  55491. // VBOs
  55492. this._geometry._bind(this._colorShader.getEffect());
  55493. // Color
  55494. if (!this.useVertexColor) {
  55495. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  55496. }
  55497. return this;
  55498. };
  55499. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  55500. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  55501. return this;
  55502. }
  55503. var engine = this.getScene().getEngine();
  55504. // Draw order
  55505. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  55506. return this;
  55507. };
  55508. LinesMesh.prototype.dispose = function (doNotRecurse) {
  55509. this._colorShader.dispose();
  55510. _super.prototype.dispose.call(this, doNotRecurse);
  55511. };
  55512. /**
  55513. * Returns a new LineMesh object cloned from the current one.
  55514. */
  55515. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55516. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  55517. };
  55518. return LinesMesh;
  55519. }(BABYLON.Mesh));
  55520. BABYLON.LinesMesh = LinesMesh;
  55521. })(BABYLON || (BABYLON = {}));
  55522. //# sourceMappingURL=babylon.linesMesh.js.map
  55523. "use strict";
  55524. var BABYLON;
  55525. (function (BABYLON) {
  55526. var MeshBuilder = /** @class */ (function () {
  55527. function MeshBuilder() {
  55528. }
  55529. MeshBuilder.updateSideOrientation = function (orientation) {
  55530. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  55531. return BABYLON.Mesh.DOUBLESIDE;
  55532. }
  55533. if (orientation === undefined || orientation === null) {
  55534. return BABYLON.Mesh.FRONTSIDE;
  55535. }
  55536. return orientation;
  55537. };
  55538. /**
  55539. * Creates a box mesh.
  55540. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  55541. * The parameter `size` sets the size (float) of each box side (default 1).
  55542. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  55543. * 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).
  55544. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55545. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55546. * 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).
  55547. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55548. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55549. */
  55550. MeshBuilder.CreateBox = function (name, options, scene) {
  55551. if (scene === void 0) { scene = null; }
  55552. var box = new BABYLON.Mesh(name, scene);
  55553. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55554. box._originalBuilderSideOrientation = options.sideOrientation;
  55555. var vertexData = BABYLON.VertexData.CreateBox(options);
  55556. vertexData.applyToMesh(box, options.updatable);
  55557. return box;
  55558. };
  55559. /**
  55560. * Creates a sphere mesh.
  55561. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  55562. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  55563. * 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`).
  55564. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  55565. * 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
  55566. * 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).
  55567. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55568. * 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).
  55569. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55570. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55571. */
  55572. MeshBuilder.CreateSphere = function (name, options, scene) {
  55573. var sphere = new BABYLON.Mesh(name, scene);
  55574. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55575. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55576. var vertexData = BABYLON.VertexData.CreateSphere(options);
  55577. vertexData.applyToMesh(sphere, options.updatable);
  55578. return sphere;
  55579. };
  55580. /**
  55581. * Creates a plane polygonal mesh. By default, this is a disc.
  55582. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  55583. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  55584. * 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.
  55585. * 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
  55586. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55587. * 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).
  55588. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55589. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55590. */
  55591. MeshBuilder.CreateDisc = function (name, options, scene) {
  55592. if (scene === void 0) { scene = null; }
  55593. var disc = new BABYLON.Mesh(name, scene);
  55594. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55595. disc._originalBuilderSideOrientation = options.sideOrientation;
  55596. var vertexData = BABYLON.VertexData.CreateDisc(options);
  55597. vertexData.applyToMesh(disc, options.updatable);
  55598. return disc;
  55599. };
  55600. /**
  55601. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  55602. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  55603. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  55604. * 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`).
  55605. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  55606. * 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.
  55607. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55608. * 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).
  55609. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55610. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55611. */
  55612. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  55613. var sphere = new BABYLON.Mesh(name, scene);
  55614. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55615. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55616. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  55617. vertexData.applyToMesh(sphere, options.updatable);
  55618. return sphere;
  55619. };
  55620. ;
  55621. /**
  55622. * Creates a ribbon mesh.
  55623. * 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.
  55624. *
  55625. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  55626. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  55627. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  55628. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  55629. * 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.
  55630. * 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.
  55631. * 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
  55632. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55633. * 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).
  55634. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55635. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55636. * 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.
  55637. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  55638. * 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
  55639. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  55640. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  55641. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55642. */
  55643. MeshBuilder.CreateRibbon = function (name, options, scene) {
  55644. if (scene === void 0) { scene = null; }
  55645. var pathArray = options.pathArray;
  55646. var closeArray = options.closeArray;
  55647. var closePath = options.closePath;
  55648. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55649. var instance = options.instance;
  55650. var updatable = options.updatable;
  55651. if (instance) {
  55652. // positionFunction : ribbon case
  55653. // only pathArray and sideOrientation parameters are taken into account for positions update
  55654. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55655. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55656. var positionFunction = function (positions) {
  55657. var minlg = pathArray[0].length;
  55658. var i = 0;
  55659. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55660. for (var si = 1; si <= ns; si++) {
  55661. for (var p = 0; p < pathArray.length; p++) {
  55662. var path = pathArray[p];
  55663. var l = path.length;
  55664. minlg = (minlg < l) ? minlg : l;
  55665. var j = 0;
  55666. while (j < minlg) {
  55667. positions[i] = path[j].x;
  55668. positions[i + 1] = path[j].y;
  55669. positions[i + 2] = path[j].z;
  55670. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55671. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55672. }
  55673. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55674. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55675. }
  55676. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55677. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55678. }
  55679. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55680. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55681. }
  55682. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55683. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55684. }
  55685. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55686. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55687. }
  55688. j++;
  55689. i += 3;
  55690. }
  55691. if (instance._closePath) {
  55692. positions[i] = path[0].x;
  55693. positions[i + 1] = path[0].y;
  55694. positions[i + 2] = path[0].z;
  55695. i += 3;
  55696. }
  55697. }
  55698. }
  55699. };
  55700. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55701. positionFunction(positions);
  55702. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55703. instance._boundingInfo.update(instance._worldMatrix);
  55704. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55705. if (options.colors) {
  55706. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55707. for (var c = 0; c < options.colors.length; c++) {
  55708. colors[c * 4] = options.colors[c].r;
  55709. colors[c * 4 + 1] = options.colors[c].g;
  55710. colors[c * 4 + 2] = options.colors[c].b;
  55711. colors[c * 4 + 3] = options.colors[c].a;
  55712. }
  55713. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55714. }
  55715. if (options.uvs) {
  55716. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55717. for (var i = 0; i < options.uvs.length; i++) {
  55718. uvs[i * 2] = options.uvs[i].x;
  55719. uvs[i * 2 + 1] = options.uvs[i].y;
  55720. }
  55721. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55722. }
  55723. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55724. var indices = instance.getIndices();
  55725. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55726. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55727. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55728. if (instance._closePath) {
  55729. var indexFirst = 0;
  55730. var indexLast = 0;
  55731. for (var p = 0; p < pathArray.length; p++) {
  55732. indexFirst = instance._idx[p] * 3;
  55733. if (p + 1 < pathArray.length) {
  55734. indexLast = (instance._idx[p + 1] - 1) * 3;
  55735. }
  55736. else {
  55737. indexLast = normals.length - 3;
  55738. }
  55739. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55740. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55741. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55742. normals[indexLast] = normals[indexFirst];
  55743. normals[indexLast + 1] = normals[indexFirst + 1];
  55744. normals[indexLast + 2] = normals[indexFirst + 2];
  55745. }
  55746. }
  55747. if (!(instance.areNormalsFrozen)) {
  55748. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55749. }
  55750. }
  55751. return instance;
  55752. }
  55753. else {
  55754. var ribbon = new BABYLON.Mesh(name, scene);
  55755. ribbon._originalBuilderSideOrientation = sideOrientation;
  55756. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55757. if (closePath) {
  55758. ribbon._idx = vertexData._idx;
  55759. }
  55760. ribbon._closePath = closePath;
  55761. ribbon._closeArray = closeArray;
  55762. vertexData.applyToMesh(ribbon, updatable);
  55763. return ribbon;
  55764. }
  55765. };
  55766. /**
  55767. * Creates a cylinder or a cone mesh.
  55768. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55769. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55770. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55771. * 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.
  55772. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55773. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55774. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55775. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55776. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55777. * 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).
  55778. * 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
  55779. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55780. * 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
  55781. * 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.
  55782. * If `enclose` is false, a ring surface is one element.
  55783. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55784. * 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
  55785. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55786. * 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).
  55787. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55788. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55789. */
  55790. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55791. var cylinder = new BABYLON.Mesh(name, scene);
  55792. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55793. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55794. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55795. vertexData.applyToMesh(cylinder, options.updatable);
  55796. return cylinder;
  55797. };
  55798. /**
  55799. * Creates a torus mesh.
  55800. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55801. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55802. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55803. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55804. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55805. * 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).
  55806. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55807. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55808. */
  55809. MeshBuilder.CreateTorus = function (name, options, scene) {
  55810. var torus = new BABYLON.Mesh(name, scene);
  55811. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55812. torus._originalBuilderSideOrientation = options.sideOrientation;
  55813. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55814. vertexData.applyToMesh(torus, options.updatable);
  55815. return torus;
  55816. };
  55817. /**
  55818. * Creates a torus knot mesh.
  55819. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55820. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55821. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55822. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55823. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55824. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55825. * 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).
  55826. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55827. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55828. */
  55829. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55830. var torusKnot = new BABYLON.Mesh(name, scene);
  55831. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55832. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55833. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55834. vertexData.applyToMesh(torusKnot, options.updatable);
  55835. return torusKnot;
  55836. };
  55837. /**
  55838. * Creates a line system mesh.
  55839. * A line system is a pool of many lines gathered in a single mesh.
  55840. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55841. * 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.
  55842. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55843. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55844. * 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
  55845. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55846. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55847. * 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
  55848. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55849. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55850. */
  55851. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55852. var instance = options.instance;
  55853. var lines = options.lines;
  55854. var colors = options.colors;
  55855. if (instance) {
  55856. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55857. var vertexColor;
  55858. var lineColors;
  55859. if (colors) {
  55860. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55861. }
  55862. var i = 0;
  55863. var c = 0;
  55864. for (var l = 0; l < lines.length; l++) {
  55865. var points = lines[l];
  55866. for (var p = 0; p < points.length; p++) {
  55867. positions[i] = points[p].x;
  55868. positions[i + 1] = points[p].y;
  55869. positions[i + 2] = points[p].z;
  55870. if (colors && vertexColor) {
  55871. lineColors = colors[l];
  55872. vertexColor[c] = lineColors[p].r;
  55873. vertexColor[c + 1] = lineColors[p].g;
  55874. vertexColor[c + 2] = lineColors[p].b;
  55875. vertexColor[c + 3] = lineColors[p].a;
  55876. c += 4;
  55877. }
  55878. i += 3;
  55879. }
  55880. }
  55881. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55882. if (colors && vertexColor) {
  55883. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55884. }
  55885. return instance;
  55886. }
  55887. // line system creation
  55888. var useVertexColor = (colors) ? true : false;
  55889. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55890. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55891. vertexData.applyToMesh(lineSystem, options.updatable);
  55892. return lineSystem;
  55893. };
  55894. /**
  55895. * Creates a line mesh.
  55896. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55897. * 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.
  55898. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55899. * The parameter `points` is an array successive Vector3.
  55900. * 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
  55901. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55902. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55903. * When updating an instance, remember that only point positions can change, not the number of points.
  55904. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55905. */
  55906. MeshBuilder.CreateLines = function (name, options, scene) {
  55907. if (scene === void 0) { scene = null; }
  55908. var colors = (options.colors) ? [options.colors] : null;
  55909. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55910. return lines;
  55911. };
  55912. /**
  55913. * Creates a dashed line mesh.
  55914. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55915. * 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.
  55916. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55917. * The parameter `points` is an array successive Vector3.
  55918. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55919. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55920. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55921. * 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
  55922. * When updating an instance, remember that only point positions can change, not the number of points.
  55923. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55924. */
  55925. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55926. if (scene === void 0) { scene = null; }
  55927. var points = options.points;
  55928. var instance = options.instance;
  55929. var gapSize = options.gapSize || 1;
  55930. var dashSize = options.dashSize || 3;
  55931. if (instance) {
  55932. var positionFunction = function (positions) {
  55933. var curvect = BABYLON.Vector3.Zero();
  55934. var nbSeg = positions.length / 6;
  55935. var lg = 0;
  55936. var nb = 0;
  55937. var shft = 0;
  55938. var dashshft = 0;
  55939. var curshft = 0;
  55940. var p = 0;
  55941. var i = 0;
  55942. var j = 0;
  55943. for (i = 0; i < points.length - 1; i++) {
  55944. points[i + 1].subtractToRef(points[i], curvect);
  55945. lg += curvect.length();
  55946. }
  55947. shft = lg / nbSeg;
  55948. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55949. for (i = 0; i < points.length - 1; i++) {
  55950. points[i + 1].subtractToRef(points[i], curvect);
  55951. nb = Math.floor(curvect.length() / shft);
  55952. curvect.normalize();
  55953. j = 0;
  55954. while (j < nb && p < positions.length) {
  55955. curshft = shft * j;
  55956. positions[p] = points[i].x + curshft * curvect.x;
  55957. positions[p + 1] = points[i].y + curshft * curvect.y;
  55958. positions[p + 2] = points[i].z + curshft * curvect.z;
  55959. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  55960. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  55961. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  55962. p += 6;
  55963. j++;
  55964. }
  55965. }
  55966. while (p < positions.length) {
  55967. positions[p] = points[i].x;
  55968. positions[p + 1] = points[i].y;
  55969. positions[p + 2] = points[i].z;
  55970. p += 3;
  55971. }
  55972. };
  55973. instance.updateMeshPositions(positionFunction, false);
  55974. return instance;
  55975. }
  55976. // dashed lines creation
  55977. var dashedLines = new BABYLON.LinesMesh(name, scene);
  55978. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  55979. vertexData.applyToMesh(dashedLines, options.updatable);
  55980. dashedLines.dashSize = dashSize;
  55981. dashedLines.gapSize = gapSize;
  55982. return dashedLines;
  55983. };
  55984. /**
  55985. * Creates an extruded shape mesh.
  55986. * 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.
  55987. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55988. *
  55989. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55990. * 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
  55991. * extruded along the Z axis.
  55992. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55993. * 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.
  55994. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55995. * 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
  55996. * 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
  55997. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55998. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55999. * 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).
  56000. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56001. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56002. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56003. */
  56004. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56005. if (scene === void 0) { scene = null; }
  56006. var path = options.path;
  56007. var shape = options.shape;
  56008. var scale = options.scale || 1;
  56009. var rotation = options.rotation || 0;
  56010. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56011. var updatable = options.updatable;
  56012. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56013. var instance = options.instance || null;
  56014. var invertUV = options.invertUV || false;
  56015. 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);
  56016. };
  56017. /**
  56018. * Creates an custom extruded shape mesh.
  56019. * 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.
  56020. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56021. *
  56022. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56023. * 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
  56024. * extruded along the Z axis.
  56025. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56026. * 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
  56027. * and the distance of this point from the begining of the path :
  56028. * ```javascript
  56029. * var rotationFunction = function(i, distance) {
  56030. * // do things
  56031. * return rotationValue; }
  56032. * ```
  56033. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56034. * 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
  56035. * and the distance of this point from the begining of the path :
  56036. * ```javascript
  56037. * var scaleFunction = function(i, distance) {
  56038. * // do things
  56039. * return scaleValue;}
  56040. * ```
  56041. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56042. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56043. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56044. * 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
  56045. * 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
  56046. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56047. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56048. * 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).
  56049. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56050. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56051. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56052. */
  56053. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56054. var path = options.path;
  56055. var shape = options.shape;
  56056. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56057. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56058. var ribbonCloseArray = options.ribbonCloseArray || false;
  56059. var ribbonClosePath = options.ribbonClosePath || false;
  56060. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56061. var updatable = options.updatable;
  56062. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56063. var instance = options.instance;
  56064. var invertUV = options.invertUV || false;
  56065. 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);
  56066. };
  56067. /**
  56068. * Creates lathe mesh.
  56069. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56070. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56071. *
  56072. * 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
  56073. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56074. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56075. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56076. * 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.
  56077. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56078. * 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
  56079. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56080. * 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).
  56081. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56082. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56083. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56084. */
  56085. MeshBuilder.CreateLathe = function (name, options, scene) {
  56086. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56087. var closed = (options.closed === undefined) ? true : options.closed;
  56088. var shape = options.shape;
  56089. var radius = options.radius || 1;
  56090. var tessellation = options.tessellation || 64;
  56091. var updatable = options.updatable;
  56092. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56093. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56094. var pi2 = Math.PI * 2;
  56095. var paths = new Array();
  56096. var invertUV = options.invertUV || false;
  56097. var i = 0;
  56098. var p = 0;
  56099. var step = pi2 / tessellation * arc;
  56100. var rotated;
  56101. var path = new Array();
  56102. ;
  56103. for (i = 0; i <= tessellation; i++) {
  56104. var path = [];
  56105. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56106. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56107. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56108. }
  56109. for (p = 0; p < shape.length; p++) {
  56110. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56111. path.push(rotated);
  56112. }
  56113. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56114. 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));
  56115. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56116. }
  56117. paths.push(path);
  56118. }
  56119. // lathe ribbon
  56120. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56121. return lathe;
  56122. };
  56123. /**
  56124. * Creates a plane mesh.
  56125. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56126. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56127. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56128. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56129. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56130. * 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).
  56131. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56132. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56133. */
  56134. MeshBuilder.CreatePlane = function (name, options, scene) {
  56135. var plane = new BABYLON.Mesh(name, scene);
  56136. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56137. plane._originalBuilderSideOrientation = options.sideOrientation;
  56138. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56139. vertexData.applyToMesh(plane, options.updatable);
  56140. if (options.sourcePlane) {
  56141. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56142. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56143. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56144. plane.rotate(vectorProduct, product);
  56145. }
  56146. return plane;
  56147. };
  56148. /**
  56149. * Creates a ground mesh.
  56150. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56151. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56152. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56153. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56154. */
  56155. MeshBuilder.CreateGround = function (name, options, scene) {
  56156. var ground = new BABYLON.GroundMesh(name, scene);
  56157. ground._setReady(false);
  56158. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56159. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56160. ground._width = options.width || 1;
  56161. ground._height = options.height || 1;
  56162. ground._maxX = ground._width / 2;
  56163. ground._maxZ = ground._height / 2;
  56164. ground._minX = -ground._maxX;
  56165. ground._minZ = -ground._maxZ;
  56166. var vertexData = BABYLON.VertexData.CreateGround(options);
  56167. vertexData.applyToMesh(ground, options.updatable);
  56168. ground._setReady(true);
  56169. return ground;
  56170. };
  56171. /**
  56172. * Creates a tiled ground mesh.
  56173. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56174. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56175. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56176. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56177. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56178. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56179. * numbers of subdivisions on the ground width and height of each tile.
  56180. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56181. */
  56182. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56183. var tiledGround = new BABYLON.Mesh(name, scene);
  56184. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56185. vertexData.applyToMesh(tiledGround, options.updatable);
  56186. return tiledGround;
  56187. };
  56188. /**
  56189. * Creates a ground mesh from a height map.
  56190. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56191. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56192. * The parameter `url` sets the URL of the height map image resource.
  56193. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56194. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56195. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56196. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56197. * 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.
  56198. * 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).
  56199. * This function is passed the newly built mesh :
  56200. * ```javascript
  56201. * function(mesh) { // do things
  56202. * return; }
  56203. * ```
  56204. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56205. */
  56206. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56207. var width = options.width || 10.0;
  56208. var height = options.height || 10.0;
  56209. var subdivisions = options.subdivisions || 1 | 0;
  56210. var minHeight = options.minHeight || 0.0;
  56211. var maxHeight = options.maxHeight || 1.0;
  56212. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56213. var updatable = options.updatable;
  56214. var onReady = options.onReady;
  56215. var ground = new BABYLON.GroundMesh(name, scene);
  56216. ground._subdivisionsX = subdivisions;
  56217. ground._subdivisionsY = subdivisions;
  56218. ground._width = width;
  56219. ground._height = height;
  56220. ground._maxX = ground._width / 2.0;
  56221. ground._maxZ = ground._height / 2.0;
  56222. ground._minX = -ground._maxX;
  56223. ground._minZ = -ground._maxZ;
  56224. ground._setReady(false);
  56225. var onload = function (img) {
  56226. // Getting height map data
  56227. var canvas = document.createElement("canvas");
  56228. var context = canvas.getContext("2d");
  56229. if (!context) {
  56230. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  56231. }
  56232. if (scene.isDisposed) {
  56233. return;
  56234. }
  56235. var bufferWidth = img.width;
  56236. var bufferHeight = img.height;
  56237. canvas.width = bufferWidth;
  56238. canvas.height = bufferHeight;
  56239. context.drawImage(img, 0, 0);
  56240. // Create VertexData from map data
  56241. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  56242. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  56243. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  56244. width: width, height: height,
  56245. subdivisions: subdivisions,
  56246. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  56247. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  56248. });
  56249. vertexData.applyToMesh(ground, updatable);
  56250. //execute ready callback, if set
  56251. if (onReady) {
  56252. onReady(ground);
  56253. }
  56254. ground._setReady(true);
  56255. };
  56256. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  56257. return ground;
  56258. };
  56259. /**
  56260. * Creates a polygon mesh.
  56261. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  56262. * 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.
  56263. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56264. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56265. * 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).
  56266. * Remember you can only change the shape positions, not their number when updating a polygon.
  56267. */
  56268. MeshBuilder.CreatePolygon = function (name, options, scene) {
  56269. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56270. var shape = options.shape;
  56271. var holes = options.holes || [];
  56272. var depth = options.depth || 0;
  56273. var contours = [];
  56274. var hole = [];
  56275. for (var i = 0; i < shape.length; i++) {
  56276. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  56277. }
  56278. var epsilon = 0.00000001;
  56279. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  56280. contours.pop();
  56281. }
  56282. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  56283. for (var hNb = 0; hNb < holes.length; hNb++) {
  56284. hole = [];
  56285. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  56286. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  56287. }
  56288. polygonTriangulation.addHole(hole);
  56289. }
  56290. var polygon = polygonTriangulation.build(options.updatable, depth);
  56291. polygon._originalBuilderSideOrientation = options.sideOrientation;
  56292. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  56293. vertexData.applyToMesh(polygon, options.updatable);
  56294. return polygon;
  56295. };
  56296. ;
  56297. /**
  56298. * Creates an extruded polygon mesh, with depth in the Y direction.
  56299. * 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).
  56300. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56301. */
  56302. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  56303. return MeshBuilder.CreatePolygon(name, options, scene);
  56304. };
  56305. ;
  56306. /**
  56307. * Creates a tube mesh.
  56308. * 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.
  56309. *
  56310. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  56311. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  56312. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  56313. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  56314. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  56315. * 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.
  56316. * It must return a radius value (positive float) :
  56317. * ```javascript
  56318. * var radiusFunction = function(i, distance) {
  56319. * // do things
  56320. * return radius; }
  56321. * ```
  56322. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  56323. * 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
  56324. * 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
  56325. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56326. * 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).
  56327. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56328. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56329. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56330. */
  56331. MeshBuilder.CreateTube = function (name, options, scene) {
  56332. var path = options.path;
  56333. var instance = options.instance;
  56334. var radius = 1.0;
  56335. if (instance) {
  56336. radius = instance.radius;
  56337. }
  56338. if (options.radius !== undefined) {
  56339. radius = options.radius;
  56340. }
  56341. ;
  56342. var tessellation = options.tessellation || 64 | 0;
  56343. var radiusFunction = options.radiusFunction || null;
  56344. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56345. var invertUV = options.invertUV || false;
  56346. var updatable = options.updatable;
  56347. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56348. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  56349. // tube geometry
  56350. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  56351. var tangents = path3D.getTangents();
  56352. var normals = path3D.getNormals();
  56353. var distances = path3D.getDistances();
  56354. var pi2 = Math.PI * 2;
  56355. var step = pi2 / tessellation * arc;
  56356. var returnRadius = function () { return radius; };
  56357. var radiusFunctionFinal = radiusFunction || returnRadius;
  56358. var circlePath;
  56359. var rad;
  56360. var normal;
  56361. var rotated;
  56362. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56363. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56364. for (var i = 0; i < path.length; i++) {
  56365. rad = radiusFunctionFinal(i, distances[i]); // current radius
  56366. circlePath = Array(); // current circle array
  56367. normal = normals[i]; // current normal
  56368. for (var t = 0; t < tessellation; t++) {
  56369. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  56370. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  56371. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  56372. rotated.scaleInPlace(rad).addInPlace(path[i]);
  56373. circlePath[t] = rotated;
  56374. }
  56375. circlePaths[index] = circlePath;
  56376. index++;
  56377. }
  56378. // cap
  56379. var capPath = function (nbPoints, pathIndex) {
  56380. var pointCap = Array();
  56381. for (var i = 0; i < nbPoints; i++) {
  56382. pointCap.push(path[pathIndex]);
  56383. }
  56384. return pointCap;
  56385. };
  56386. switch (cap) {
  56387. case BABYLON.Mesh.NO_CAP:
  56388. break;
  56389. case BABYLON.Mesh.CAP_START:
  56390. circlePaths[0] = capPath(tessellation, 0);
  56391. circlePaths[1] = circlePaths[2].slice(0);
  56392. break;
  56393. case BABYLON.Mesh.CAP_END:
  56394. circlePaths[index] = circlePaths[index - 1].slice(0);
  56395. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56396. break;
  56397. case BABYLON.Mesh.CAP_ALL:
  56398. circlePaths[0] = capPath(tessellation, 0);
  56399. circlePaths[1] = circlePaths[2].slice(0);
  56400. circlePaths[index] = circlePaths[index - 1].slice(0);
  56401. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56402. break;
  56403. default:
  56404. break;
  56405. }
  56406. return circlePaths;
  56407. };
  56408. var path3D;
  56409. var pathArray;
  56410. if (instance) {
  56411. var arc = options.arc || instance.arc;
  56412. path3D = (instance.path3D).update(path);
  56413. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  56414. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  56415. instance.path3D = path3D;
  56416. instance.pathArray = pathArray;
  56417. instance.arc = arc;
  56418. instance.radius = radius;
  56419. return instance;
  56420. }
  56421. // tube creation
  56422. path3D = new BABYLON.Path3D(path);
  56423. var newPathArray = new Array();
  56424. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56425. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  56426. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56427. tube.pathArray = pathArray;
  56428. tube.path3D = path3D;
  56429. tube.tessellation = tessellation;
  56430. tube.cap = cap;
  56431. tube.arc = options.arc;
  56432. tube.radius = radius;
  56433. return tube;
  56434. };
  56435. /**
  56436. * Creates a polyhedron mesh.
  56437. *
  56438. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  56439. * 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
  56440. * to choose the wanted type.
  56441. * The parameter `size` (positive float, default 1) sets the polygon size.
  56442. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  56443. * 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`.
  56444. * 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
  56445. * 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)`).
  56446. * 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
  56447. * 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.
  56448. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56449. * 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).
  56450. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56451. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56452. */
  56453. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  56454. var polyhedron = new BABYLON.Mesh(name, scene);
  56455. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56456. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  56457. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  56458. vertexData.applyToMesh(polyhedron, options.updatable);
  56459. return polyhedron;
  56460. };
  56461. /**
  56462. * Creates a decal mesh.
  56463. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  56464. * 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.
  56465. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  56466. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  56467. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  56468. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  56469. */
  56470. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  56471. var indices = sourceMesh.getIndices();
  56472. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56473. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56474. var position = options.position || BABYLON.Vector3.Zero();
  56475. var normal = options.normal || BABYLON.Vector3.Up();
  56476. var size = options.size || BABYLON.Vector3.One();
  56477. var angle = options.angle || 0;
  56478. // Getting correct rotation
  56479. if (!normal) {
  56480. var target = new BABYLON.Vector3(0, 0, 1);
  56481. var camera = sourceMesh.getScene().activeCamera;
  56482. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  56483. normal = camera.globalPosition.subtract(cameraWorldTarget);
  56484. }
  56485. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  56486. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  56487. var pitch = Math.atan2(normal.y, len);
  56488. // Matrix
  56489. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  56490. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  56491. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  56492. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  56493. var vertexData = new BABYLON.VertexData();
  56494. vertexData.indices = [];
  56495. vertexData.positions = [];
  56496. vertexData.normals = [];
  56497. vertexData.uvs = [];
  56498. var currentVertexDataIndex = 0;
  56499. var extractDecalVector3 = function (indexId) {
  56500. var result = new BABYLON.PositionNormalVertex();
  56501. if (!indices || !positions || !normals) {
  56502. return result;
  56503. }
  56504. var vertexId = indices[indexId];
  56505. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  56506. // Send vector to decal local world
  56507. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  56508. // Get normal
  56509. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  56510. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  56511. return result;
  56512. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  56513. var clip = function (vertices, axis) {
  56514. if (vertices.length === 0) {
  56515. return vertices;
  56516. }
  56517. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  56518. var clipVertices = function (v0, v1) {
  56519. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  56520. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  56521. };
  56522. var result = new Array();
  56523. for (var index = 0; index < vertices.length; index += 3) {
  56524. var v1Out;
  56525. var v2Out;
  56526. var v3Out;
  56527. var total = 0;
  56528. var nV1 = null;
  56529. var nV2 = null;
  56530. var nV3 = null;
  56531. var nV4 = null;
  56532. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  56533. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  56534. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  56535. v1Out = d1 > 0;
  56536. v2Out = d2 > 0;
  56537. v3Out = d3 > 0;
  56538. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  56539. switch (total) {
  56540. case 0:
  56541. result.push(vertices[index]);
  56542. result.push(vertices[index + 1]);
  56543. result.push(vertices[index + 2]);
  56544. break;
  56545. case 1:
  56546. if (v1Out) {
  56547. nV1 = vertices[index + 1];
  56548. nV2 = vertices[index + 2];
  56549. nV3 = clipVertices(vertices[index], nV1);
  56550. nV4 = clipVertices(vertices[index], nV2);
  56551. }
  56552. if (v2Out) {
  56553. nV1 = vertices[index];
  56554. nV2 = vertices[index + 2];
  56555. nV3 = clipVertices(vertices[index + 1], nV1);
  56556. nV4 = clipVertices(vertices[index + 1], nV2);
  56557. result.push(nV3);
  56558. result.push(nV2.clone());
  56559. result.push(nV1.clone());
  56560. result.push(nV2.clone());
  56561. result.push(nV3.clone());
  56562. result.push(nV4);
  56563. break;
  56564. }
  56565. if (v3Out) {
  56566. nV1 = vertices[index];
  56567. nV2 = vertices[index + 1];
  56568. nV3 = clipVertices(vertices[index + 2], nV1);
  56569. nV4 = clipVertices(vertices[index + 2], nV2);
  56570. }
  56571. if (nV1 && nV2 && nV3 && nV4) {
  56572. result.push(nV1.clone());
  56573. result.push(nV2.clone());
  56574. result.push(nV3);
  56575. result.push(nV4);
  56576. result.push(nV3.clone());
  56577. result.push(nV2.clone());
  56578. }
  56579. break;
  56580. case 2:
  56581. if (!v1Out) {
  56582. nV1 = vertices[index].clone();
  56583. nV2 = clipVertices(nV1, vertices[index + 1]);
  56584. nV3 = clipVertices(nV1, vertices[index + 2]);
  56585. result.push(nV1);
  56586. result.push(nV2);
  56587. result.push(nV3);
  56588. }
  56589. if (!v2Out) {
  56590. nV1 = vertices[index + 1].clone();
  56591. nV2 = clipVertices(nV1, vertices[index + 2]);
  56592. nV3 = clipVertices(nV1, vertices[index]);
  56593. result.push(nV1);
  56594. result.push(nV2);
  56595. result.push(nV3);
  56596. }
  56597. if (!v3Out) {
  56598. nV1 = vertices[index + 2].clone();
  56599. nV2 = clipVertices(nV1, vertices[index]);
  56600. nV3 = clipVertices(nV1, vertices[index + 1]);
  56601. result.push(nV1);
  56602. result.push(nV2);
  56603. result.push(nV3);
  56604. }
  56605. break;
  56606. case 3:
  56607. break;
  56608. }
  56609. }
  56610. return result;
  56611. };
  56612. for (var index = 0; index < indices.length; index += 3) {
  56613. var faceVertices = new Array();
  56614. faceVertices.push(extractDecalVector3(index));
  56615. faceVertices.push(extractDecalVector3(index + 1));
  56616. faceVertices.push(extractDecalVector3(index + 2));
  56617. // Clip
  56618. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  56619. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  56620. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  56621. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  56622. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  56623. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  56624. if (faceVertices.length === 0) {
  56625. continue;
  56626. }
  56627. // Add UVs and get back to world
  56628. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  56629. var vertex = faceVertices[vIndex];
  56630. //TODO check for Int32Array | Uint32Array | Uint16Array
  56631. vertexData.indices.push(currentVertexDataIndex);
  56632. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  56633. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  56634. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  56635. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  56636. currentVertexDataIndex++;
  56637. }
  56638. }
  56639. // Return mesh
  56640. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  56641. vertexData.applyToMesh(decal);
  56642. decal.position = position.clone();
  56643. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  56644. return decal;
  56645. };
  56646. // Privates
  56647. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  56648. // extrusion geometry
  56649. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  56650. var tangents = path3D.getTangents();
  56651. var normals = path3D.getNormals();
  56652. var binormals = path3D.getBinormals();
  56653. var distances = path3D.getDistances();
  56654. var angle = 0;
  56655. var returnScale = function () { return scale !== null ? scale : 1; };
  56656. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56657. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56658. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56659. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56660. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56661. for (var i = 0; i < curve.length; i++) {
  56662. var shapePath = new Array();
  56663. var angleStep = rotate(i, distances[i]);
  56664. var scaleRatio = scl(i, distances[i]);
  56665. for (var p = 0; p < shape.length; p++) {
  56666. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56667. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56668. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56669. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56670. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56671. shapePath[p] = rotated;
  56672. }
  56673. shapePaths[index] = shapePath;
  56674. angle += angleStep;
  56675. index++;
  56676. }
  56677. // cap
  56678. var capPath = function (shapePath) {
  56679. var pointCap = Array();
  56680. var barycenter = BABYLON.Vector3.Zero();
  56681. var i;
  56682. for (i = 0; i < shapePath.length; i++) {
  56683. barycenter.addInPlace(shapePath[i]);
  56684. }
  56685. barycenter.scaleInPlace(1.0 / shapePath.length);
  56686. for (i = 0; i < shapePath.length; i++) {
  56687. pointCap.push(barycenter);
  56688. }
  56689. return pointCap;
  56690. };
  56691. switch (cap) {
  56692. case BABYLON.Mesh.NO_CAP:
  56693. break;
  56694. case BABYLON.Mesh.CAP_START:
  56695. shapePaths[0] = capPath(shapePaths[2]);
  56696. shapePaths[1] = shapePaths[2];
  56697. break;
  56698. case BABYLON.Mesh.CAP_END:
  56699. shapePaths[index] = shapePaths[index - 1];
  56700. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56701. break;
  56702. case BABYLON.Mesh.CAP_ALL:
  56703. shapePaths[0] = capPath(shapePaths[2]);
  56704. shapePaths[1] = shapePaths[2];
  56705. shapePaths[index] = shapePaths[index - 1];
  56706. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56707. break;
  56708. default:
  56709. break;
  56710. }
  56711. return shapePaths;
  56712. };
  56713. var path3D;
  56714. var pathArray;
  56715. if (instance) {
  56716. path3D = (instance.path3D).update(curve);
  56717. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56718. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56719. return instance;
  56720. }
  56721. // extruded shape creation
  56722. path3D = new BABYLON.Path3D(curve);
  56723. var newShapePaths = new Array();
  56724. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56725. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56726. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56727. extrudedGeneric.pathArray = pathArray;
  56728. extrudedGeneric.path3D = path3D;
  56729. extrudedGeneric.cap = cap;
  56730. return extrudedGeneric;
  56731. };
  56732. return MeshBuilder;
  56733. }());
  56734. BABYLON.MeshBuilder = MeshBuilder;
  56735. })(BABYLON || (BABYLON = {}));
  56736. //# sourceMappingURL=babylon.meshBuilder.js.map
  56737. "use strict";
  56738. var BABYLON;
  56739. (function (BABYLON) {
  56740. /**
  56741. * Draco compression (https://google.github.io/draco/)
  56742. */
  56743. var DracoCompression = /** @class */ (function () {
  56744. /**
  56745. * Constructor
  56746. * @param numWorkers The number of workers for async operations
  56747. */
  56748. function DracoCompression(numWorkers) {
  56749. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56750. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56751. if (!workerBlobUrl || !Worker) {
  56752. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  56753. return;
  56754. }
  56755. var workers = new Array(numWorkers);
  56756. for (var i = 0; i < workers.length; i++) {
  56757. var worker = new Worker(workerBlobUrl);
  56758. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56759. workers[i] = worker;
  56760. }
  56761. this._workerPool = new BABYLON.WorkerPool(workers);
  56762. }
  56763. /**
  56764. * Stop all async operations and release resources.
  56765. */
  56766. DracoCompression.prototype.dispose = function () {
  56767. this._workerPool.dispose();
  56768. delete this._workerPool;
  56769. };
  56770. /**
  56771. * Decode Draco compressed mesh data to vertex data.
  56772. * @param data The array buffer view for the Draco compression data
  56773. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56774. * @returns A promise that resolves with the decoded vertex data
  56775. */
  56776. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  56777. var _this = this;
  56778. return new Promise(function (resolve, reject) {
  56779. _this._workerPool.push(function (worker, onComplete) {
  56780. var vertexData = new BABYLON.VertexData();
  56781. var onError = function (error) {
  56782. worker.removeEventListener("error", onError);
  56783. worker.removeEventListener("message", onMessage);
  56784. reject(error);
  56785. onComplete();
  56786. };
  56787. var onMessage = function (message) {
  56788. if (message.data === "done") {
  56789. worker.removeEventListener("error", onError);
  56790. worker.removeEventListener("message", onMessage);
  56791. resolve(vertexData);
  56792. onComplete();
  56793. }
  56794. else if (message.data.id === "indices") {
  56795. vertexData.indices = message.data.value;
  56796. }
  56797. else {
  56798. vertexData.set(message.data.value, message.data.id);
  56799. }
  56800. };
  56801. worker.addEventListener("error", onError);
  56802. worker.addEventListener("message", onMessage);
  56803. var dataCopy = new Uint8Array(data.byteLength);
  56804. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56805. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56806. });
  56807. });
  56808. };
  56809. /**
  56810. * The worker function that gets converted to a blob url to pass into a worker.
  56811. */
  56812. DracoCompression._Worker = function () {
  56813. // self is actually a DedicatedWorkerGlobalScope
  56814. var _self = self;
  56815. var decodeMesh = function (data, attributes) {
  56816. var dracoModule = new DracoDecoderModule();
  56817. var buffer = new dracoModule.DecoderBuffer();
  56818. buffer.Init(data, data.byteLength);
  56819. var decoder = new dracoModule.Decoder();
  56820. var geometry;
  56821. var status;
  56822. try {
  56823. var type = decoder.GetEncodedGeometryType(buffer);
  56824. switch (type) {
  56825. case dracoModule.TRIANGULAR_MESH:
  56826. geometry = new dracoModule.Mesh();
  56827. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56828. break;
  56829. case dracoModule.POINT_CLOUD:
  56830. geometry = new dracoModule.PointCloud();
  56831. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56832. break;
  56833. default:
  56834. throw new Error("Invalid geometry type " + type);
  56835. }
  56836. if (!status.ok() || !geometry.ptr) {
  56837. throw new Error(status.error_msg());
  56838. }
  56839. var numPoints = geometry.num_points();
  56840. if (type === dracoModule.TRIANGULAR_MESH) {
  56841. var numFaces = geometry.num_faces();
  56842. var faceIndices = new dracoModule.DracoInt32Array();
  56843. try {
  56844. var indices = new Uint32Array(numFaces * 3);
  56845. for (var i = 0; i < numFaces; i++) {
  56846. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56847. var offset = i * 3;
  56848. indices[offset + 0] = faceIndices.GetValue(0);
  56849. indices[offset + 1] = faceIndices.GetValue(1);
  56850. indices[offset + 2] = faceIndices.GetValue(2);
  56851. }
  56852. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  56853. }
  56854. finally {
  56855. dracoModule.destroy(faceIndices);
  56856. }
  56857. }
  56858. for (var kind in attributes) {
  56859. var uniqueId = attributes[kind];
  56860. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56861. var dracoData = new dracoModule.DracoFloat32Array();
  56862. try {
  56863. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56864. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56865. for (var i = 0; i < babylonData.length; i++) {
  56866. babylonData[i] = dracoData.GetValue(i);
  56867. }
  56868. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  56869. }
  56870. finally {
  56871. dracoModule.destroy(dracoData);
  56872. }
  56873. }
  56874. }
  56875. finally {
  56876. if (geometry) {
  56877. dracoModule.destroy(geometry);
  56878. }
  56879. dracoModule.destroy(decoder);
  56880. dracoModule.destroy(buffer);
  56881. }
  56882. _self.postMessage("done");
  56883. };
  56884. _self.onmessage = function (event) {
  56885. switch (event.data.id) {
  56886. case "initDecoder": {
  56887. importScripts(event.data.url);
  56888. break;
  56889. }
  56890. case "decodeMesh": {
  56891. decodeMesh(event.data.data, event.data.attributes);
  56892. break;
  56893. }
  56894. }
  56895. };
  56896. };
  56897. DracoCompression._GetDefaultDecoderUrl = function () {
  56898. if (!BABYLON.Tools.IsWindowObjectExist) {
  56899. return null;
  56900. }
  56901. for (var i = 0; i < document.scripts.length; i++) {
  56902. if (document.scripts[i].type === "text/x-draco-decoder") {
  56903. return document.scripts[i].src;
  56904. }
  56905. }
  56906. return null;
  56907. };
  56908. /**
  56909. * Gets the url to the draco decoder if available.
  56910. */
  56911. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  56912. return DracoCompression;
  56913. }());
  56914. BABYLON.DracoCompression = DracoCompression;
  56915. })(BABYLON || (BABYLON = {}));
  56916. //# sourceMappingURL=babylon.dracoCompression.js.map
  56917. "use strict";
  56918. var BABYLON;
  56919. (function (BABYLON) {
  56920. var AudioEngine = /** @class */ (function () {
  56921. function AudioEngine() {
  56922. this._audioContext = null;
  56923. this._audioContextInitialized = false;
  56924. this.canUseWebAudio = false;
  56925. this.WarnedWebAudioUnsupported = false;
  56926. this.unlocked = false;
  56927. this.isMP3supported = false;
  56928. this.isOGGsupported = false;
  56929. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56930. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56931. this.canUseWebAudio = true;
  56932. }
  56933. var audioElem = document.createElement('audio');
  56934. try {
  56935. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56936. this.isMP3supported = true;
  56937. }
  56938. }
  56939. catch (e) {
  56940. // protect error during capability check.
  56941. }
  56942. try {
  56943. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56944. this.isOGGsupported = true;
  56945. }
  56946. }
  56947. catch (e) {
  56948. // protect error during capability check.
  56949. }
  56950. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56951. this._unlockiOSaudio();
  56952. }
  56953. else {
  56954. this.unlocked = true;
  56955. }
  56956. }
  56957. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56958. get: function () {
  56959. if (!this._audioContextInitialized) {
  56960. this._initializeAudioContext();
  56961. }
  56962. return this._audioContext;
  56963. },
  56964. enumerable: true,
  56965. configurable: true
  56966. });
  56967. AudioEngine.prototype._unlockiOSaudio = function () {
  56968. var _this = this;
  56969. var unlockaudio = function () {
  56970. if (!_this.audioContext) {
  56971. return;
  56972. }
  56973. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  56974. var source = _this.audioContext.createBufferSource();
  56975. source.buffer = buffer;
  56976. source.connect(_this.audioContext.destination);
  56977. source.start(0);
  56978. setTimeout(function () {
  56979. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  56980. _this.unlocked = true;
  56981. window.removeEventListener('touchend', unlockaudio, false);
  56982. if (_this.onAudioUnlocked) {
  56983. _this.onAudioUnlocked();
  56984. }
  56985. }
  56986. }, 0);
  56987. };
  56988. window.addEventListener('touchend', unlockaudio, false);
  56989. };
  56990. AudioEngine.prototype._initializeAudioContext = function () {
  56991. try {
  56992. if (this.canUseWebAudio) {
  56993. this._audioContext = new AudioContext();
  56994. // create a global volume gain node
  56995. this.masterGain = this._audioContext.createGain();
  56996. this.masterGain.gain.value = 1;
  56997. this.masterGain.connect(this._audioContext.destination);
  56998. this._audioContextInitialized = true;
  56999. }
  57000. }
  57001. catch (e) {
  57002. this.canUseWebAudio = false;
  57003. BABYLON.Tools.Error("Web Audio: " + e.message);
  57004. }
  57005. };
  57006. AudioEngine.prototype.dispose = function () {
  57007. if (this.canUseWebAudio && this._audioContextInitialized) {
  57008. if (this._connectedAnalyser && this._audioContext) {
  57009. this._connectedAnalyser.stopDebugCanvas();
  57010. this._connectedAnalyser.dispose();
  57011. this.masterGain.disconnect();
  57012. this.masterGain.connect(this._audioContext.destination);
  57013. this._connectedAnalyser = null;
  57014. }
  57015. this.masterGain.gain.value = 1;
  57016. }
  57017. this.WarnedWebAudioUnsupported = false;
  57018. };
  57019. AudioEngine.prototype.getGlobalVolume = function () {
  57020. if (this.canUseWebAudio && this._audioContextInitialized) {
  57021. return this.masterGain.gain.value;
  57022. }
  57023. else {
  57024. return -1;
  57025. }
  57026. };
  57027. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57028. if (this.canUseWebAudio && this._audioContextInitialized) {
  57029. this.masterGain.gain.value = newVolume;
  57030. }
  57031. };
  57032. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57033. if (this._connectedAnalyser) {
  57034. this._connectedAnalyser.stopDebugCanvas();
  57035. }
  57036. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57037. this._connectedAnalyser = analyser;
  57038. this.masterGain.disconnect();
  57039. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57040. }
  57041. };
  57042. return AudioEngine;
  57043. }());
  57044. BABYLON.AudioEngine = AudioEngine;
  57045. })(BABYLON || (BABYLON = {}));
  57046. //# sourceMappingURL=babylon.audioEngine.js.map
  57047. "use strict";
  57048. var BABYLON;
  57049. (function (BABYLON) {
  57050. var Sound = /** @class */ (function () {
  57051. /**
  57052. * Create a sound and attach it to a scene
  57053. * @param name Name of your sound
  57054. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57055. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57056. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57057. */
  57058. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57059. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57060. var _this = this;
  57061. this.autoplay = false;
  57062. this.loop = false;
  57063. this.useCustomAttenuation = false;
  57064. this.spatialSound = false;
  57065. this.refDistance = 1;
  57066. this.rolloffFactor = 1;
  57067. this.maxDistance = 100;
  57068. this.distanceModel = "linear";
  57069. this._panningModel = "equalpower";
  57070. this._playbackRate = 1;
  57071. this._streaming = false;
  57072. this._startTime = 0;
  57073. this._startOffset = 0;
  57074. this._position = BABYLON.Vector3.Zero();
  57075. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57076. this._volume = 1;
  57077. this._isReadyToPlay = false;
  57078. this.isPlaying = false;
  57079. this.isPaused = false;
  57080. this._isDirectional = false;
  57081. // Used if you'd like to create a directional sound.
  57082. // If not set, the sound will be omnidirectional
  57083. this._coneInnerAngle = 360;
  57084. this._coneOuterAngle = 360;
  57085. this._coneOuterGain = 0;
  57086. this._isOutputConnected = false;
  57087. this._urlType = "Unknown";
  57088. this.name = name;
  57089. this._scene = scene;
  57090. this._readyToPlayCallback = readyToPlayCallback;
  57091. // Default custom attenuation function is a linear attenuation
  57092. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57093. if (currentDistance < maxDistance) {
  57094. return currentVolume * (1 - currentDistance / maxDistance);
  57095. }
  57096. else {
  57097. return 0;
  57098. }
  57099. };
  57100. if (options) {
  57101. this.autoplay = options.autoplay || false;
  57102. this.loop = options.loop || false;
  57103. // if volume === 0, we need another way to check this option
  57104. if (options.volume !== undefined) {
  57105. this._volume = options.volume;
  57106. }
  57107. this.spatialSound = options.spatialSound || false;
  57108. this.maxDistance = options.maxDistance || 100;
  57109. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57110. this.rolloffFactor = options.rolloffFactor || 1;
  57111. this.refDistance = options.refDistance || 1;
  57112. this.distanceModel = options.distanceModel || "linear";
  57113. this._playbackRate = options.playbackRate || 1;
  57114. this._streaming = options.streaming || false;
  57115. }
  57116. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57117. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57118. this._soundGain.gain.value = this._volume;
  57119. this._inputAudioNode = this._soundGain;
  57120. this._ouputAudioNode = this._soundGain;
  57121. if (this.spatialSound) {
  57122. this._createSpatialParameters();
  57123. }
  57124. this._scene.mainSoundTrack.AddSound(this);
  57125. var validParameter = true;
  57126. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57127. if (urlOrArrayBuffer) {
  57128. if (typeof (urlOrArrayBuffer) === "string")
  57129. this._urlType = "String";
  57130. if (Array.isArray(urlOrArrayBuffer))
  57131. this._urlType = "Array";
  57132. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57133. this._urlType = "ArrayBuffer";
  57134. var urls = [];
  57135. var codecSupportedFound = false;
  57136. switch (this._urlType) {
  57137. case "ArrayBuffer":
  57138. if (urlOrArrayBuffer.byteLength > 0) {
  57139. codecSupportedFound = true;
  57140. this._soundLoaded(urlOrArrayBuffer);
  57141. }
  57142. break;
  57143. case "String":
  57144. urls.push(urlOrArrayBuffer);
  57145. case "Array":
  57146. if (urls.length === 0)
  57147. urls = urlOrArrayBuffer;
  57148. // If we found a supported format, we load it immediately and stop the loop
  57149. for (var i = 0; i < urls.length; i++) {
  57150. var url = urls[i];
  57151. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57152. codecSupportedFound = true;
  57153. }
  57154. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57155. codecSupportedFound = true;
  57156. }
  57157. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57158. codecSupportedFound = true;
  57159. }
  57160. if (url.indexOf("blob:") !== -1) {
  57161. codecSupportedFound = true;
  57162. }
  57163. if (codecSupportedFound) {
  57164. // Loading sound using XHR2
  57165. if (!this._streaming) {
  57166. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  57167. }
  57168. else {
  57169. this._htmlAudioElement = new Audio(url);
  57170. this._htmlAudioElement.controls = false;
  57171. this._htmlAudioElement.loop = this.loop;
  57172. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57173. this._htmlAudioElement.preload = "auto";
  57174. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57175. _this._isReadyToPlay = true;
  57176. if (_this.autoplay) {
  57177. _this.play();
  57178. }
  57179. if (_this._readyToPlayCallback) {
  57180. _this._readyToPlayCallback();
  57181. }
  57182. });
  57183. document.body.appendChild(this._htmlAudioElement);
  57184. }
  57185. break;
  57186. }
  57187. }
  57188. break;
  57189. default:
  57190. validParameter = false;
  57191. break;
  57192. }
  57193. if (!validParameter) {
  57194. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57195. }
  57196. else {
  57197. if (!codecSupportedFound) {
  57198. this._isReadyToPlay = true;
  57199. // Simulating a ready to play event to avoid breaking code path
  57200. if (this._readyToPlayCallback) {
  57201. window.setTimeout(function () {
  57202. if (_this._readyToPlayCallback) {
  57203. _this._readyToPlayCallback();
  57204. }
  57205. }, 1000);
  57206. }
  57207. }
  57208. }
  57209. }
  57210. }
  57211. else {
  57212. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57213. this._scene.mainSoundTrack.AddSound(this);
  57214. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57215. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57216. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57217. }
  57218. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57219. if (this._readyToPlayCallback) {
  57220. window.setTimeout(function () {
  57221. if (_this._readyToPlayCallback) {
  57222. _this._readyToPlayCallback();
  57223. }
  57224. }, 1000);
  57225. }
  57226. }
  57227. }
  57228. Sound.prototype.dispose = function () {
  57229. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  57230. if (this.isPlaying) {
  57231. this.stop();
  57232. }
  57233. this._isReadyToPlay = false;
  57234. if (this.soundTrackId === -1) {
  57235. this._scene.mainSoundTrack.RemoveSound(this);
  57236. }
  57237. else {
  57238. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  57239. }
  57240. if (this._soundGain) {
  57241. this._soundGain.disconnect();
  57242. this._soundGain = null;
  57243. }
  57244. if (this._soundPanner) {
  57245. this._soundPanner.disconnect();
  57246. this._soundPanner = null;
  57247. }
  57248. if (this._soundSource) {
  57249. this._soundSource.disconnect();
  57250. this._soundSource = null;
  57251. }
  57252. this._audioBuffer = null;
  57253. if (this._htmlAudioElement) {
  57254. this._htmlAudioElement.pause();
  57255. this._htmlAudioElement.src = "";
  57256. document.body.removeChild(this._htmlAudioElement);
  57257. }
  57258. if (this._connectedMesh && this._registerFunc) {
  57259. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57260. this._connectedMesh = null;
  57261. }
  57262. }
  57263. };
  57264. Sound.prototype.isReady = function () {
  57265. return this._isReadyToPlay;
  57266. };
  57267. Sound.prototype._soundLoaded = function (audioData) {
  57268. var _this = this;
  57269. if (!BABYLON.Engine.audioEngine.audioContext) {
  57270. return;
  57271. }
  57272. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  57273. _this._audioBuffer = buffer;
  57274. _this._isReadyToPlay = true;
  57275. if (_this.autoplay) {
  57276. _this.play();
  57277. }
  57278. if (_this._readyToPlayCallback) {
  57279. _this._readyToPlayCallback();
  57280. }
  57281. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  57282. };
  57283. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  57284. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57285. this._audioBuffer = audioBuffer;
  57286. this._isReadyToPlay = true;
  57287. }
  57288. };
  57289. Sound.prototype.updateOptions = function (options) {
  57290. if (options) {
  57291. this.loop = options.loop || this.loop;
  57292. this.maxDistance = options.maxDistance || this.maxDistance;
  57293. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  57294. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  57295. this.refDistance = options.refDistance || this.refDistance;
  57296. this.distanceModel = options.distanceModel || this.distanceModel;
  57297. this._playbackRate = options.playbackRate || this._playbackRate;
  57298. this._updateSpatialParameters();
  57299. if (this.isPlaying) {
  57300. if (this._streaming) {
  57301. this._htmlAudioElement.playbackRate = this._playbackRate;
  57302. }
  57303. else {
  57304. if (this._soundSource) {
  57305. this._soundSource.playbackRate.value = this._playbackRate;
  57306. }
  57307. }
  57308. }
  57309. }
  57310. };
  57311. Sound.prototype._createSpatialParameters = function () {
  57312. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57313. if (this._scene.headphone) {
  57314. this._panningModel = "HRTF";
  57315. }
  57316. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  57317. this._updateSpatialParameters();
  57318. this._soundPanner.connect(this._ouputAudioNode);
  57319. this._inputAudioNode = this._soundPanner;
  57320. }
  57321. };
  57322. Sound.prototype._updateSpatialParameters = function () {
  57323. if (this.spatialSound && this._soundPanner) {
  57324. if (this.useCustomAttenuation) {
  57325. // Tricks to disable in a way embedded Web Audio attenuation
  57326. this._soundPanner.distanceModel = "linear";
  57327. this._soundPanner.maxDistance = Number.MAX_VALUE;
  57328. this._soundPanner.refDistance = 1;
  57329. this._soundPanner.rolloffFactor = 1;
  57330. this._soundPanner.panningModel = this._panningModel;
  57331. }
  57332. else {
  57333. this._soundPanner.distanceModel = this.distanceModel;
  57334. this._soundPanner.maxDistance = this.maxDistance;
  57335. this._soundPanner.refDistance = this.refDistance;
  57336. this._soundPanner.rolloffFactor = this.rolloffFactor;
  57337. this._soundPanner.panningModel = this._panningModel;
  57338. }
  57339. }
  57340. };
  57341. Sound.prototype.switchPanningModelToHRTF = function () {
  57342. this._panningModel = "HRTF";
  57343. this._switchPanningModel();
  57344. };
  57345. Sound.prototype.switchPanningModelToEqualPower = function () {
  57346. this._panningModel = "equalpower";
  57347. this._switchPanningModel();
  57348. };
  57349. Sound.prototype._switchPanningModel = function () {
  57350. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57351. this._soundPanner.panningModel = this._panningModel;
  57352. }
  57353. };
  57354. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  57355. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57356. if (this._isOutputConnected) {
  57357. this._ouputAudioNode.disconnect();
  57358. }
  57359. this._ouputAudioNode.connect(soundTrackAudioNode);
  57360. this._isOutputConnected = true;
  57361. }
  57362. };
  57363. /**
  57364. * Transform this sound into a directional source
  57365. * @param coneInnerAngle Size of the inner cone in degree
  57366. * @param coneOuterAngle Size of the outer cone in degree
  57367. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  57368. */
  57369. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  57370. if (coneOuterAngle < coneInnerAngle) {
  57371. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  57372. return;
  57373. }
  57374. this._coneInnerAngle = coneInnerAngle;
  57375. this._coneOuterAngle = coneOuterAngle;
  57376. this._coneOuterGain = coneOuterGain;
  57377. this._isDirectional = true;
  57378. if (this.isPlaying && this.loop) {
  57379. this.stop();
  57380. this.play();
  57381. }
  57382. };
  57383. Sound.prototype.setPosition = function (newPosition) {
  57384. this._position = newPosition;
  57385. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57386. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57387. }
  57388. };
  57389. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  57390. this._localDirection = newLocalDirection;
  57391. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  57392. this._updateDirection();
  57393. }
  57394. };
  57395. Sound.prototype._updateDirection = function () {
  57396. if (!this._connectedMesh || !this._soundPanner) {
  57397. return;
  57398. }
  57399. var mat = this._connectedMesh.getWorldMatrix();
  57400. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  57401. direction.normalize();
  57402. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  57403. };
  57404. Sound.prototype.updateDistanceFromListener = function () {
  57405. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  57406. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  57407. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  57408. }
  57409. };
  57410. Sound.prototype.setAttenuationFunction = function (callback) {
  57411. this._customAttenuationFunction = callback;
  57412. };
  57413. /**
  57414. * Play the sound
  57415. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  57416. * @param offset (optional) Start the sound setting it at a specific time
  57417. */
  57418. Sound.prototype.play = function (time, offset) {
  57419. var _this = this;
  57420. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  57421. try {
  57422. if (this._startOffset < 0) {
  57423. time = -this._startOffset;
  57424. this._startOffset = 0;
  57425. }
  57426. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57427. if (!this._soundSource || !this._streamingSource) {
  57428. if (this.spatialSound && this._soundPanner) {
  57429. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57430. if (this._isDirectional) {
  57431. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  57432. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  57433. this._soundPanner.coneOuterGain = this._coneOuterGain;
  57434. if (this._connectedMesh) {
  57435. this._updateDirection();
  57436. }
  57437. else {
  57438. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  57439. }
  57440. }
  57441. }
  57442. }
  57443. if (this._streaming) {
  57444. if (!this._streamingSource) {
  57445. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  57446. this._htmlAudioElement.onended = function () { _this._onended(); };
  57447. this._htmlAudioElement.playbackRate = this._playbackRate;
  57448. }
  57449. this._streamingSource.disconnect();
  57450. this._streamingSource.connect(this._inputAudioNode);
  57451. this._htmlAudioElement.play();
  57452. }
  57453. else {
  57454. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  57455. this._soundSource.buffer = this._audioBuffer;
  57456. this._soundSource.connect(this._inputAudioNode);
  57457. this._soundSource.loop = this.loop;
  57458. this._soundSource.playbackRate.value = this._playbackRate;
  57459. this._soundSource.onended = function () { _this._onended(); };
  57460. if (this._soundSource.buffer) {
  57461. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  57462. }
  57463. }
  57464. this._startTime = startTime;
  57465. this.isPlaying = true;
  57466. this.isPaused = false;
  57467. }
  57468. catch (ex) {
  57469. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  57470. }
  57471. }
  57472. };
  57473. Sound.prototype._onended = function () {
  57474. this.isPlaying = false;
  57475. if (this.onended) {
  57476. this.onended();
  57477. }
  57478. };
  57479. /**
  57480. * Stop the sound
  57481. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  57482. */
  57483. Sound.prototype.stop = function (time) {
  57484. if (this.isPlaying) {
  57485. if (this._streaming) {
  57486. this._htmlAudioElement.pause();
  57487. // Test needed for Firefox or it will generate an Invalid State Error
  57488. if (this._htmlAudioElement.currentTime > 0) {
  57489. this._htmlAudioElement.currentTime = 0;
  57490. }
  57491. }
  57492. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  57493. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57494. this._soundSource.stop(stopTime);
  57495. this._soundSource.onended = function () { };
  57496. if (!this.isPaused) {
  57497. this._startOffset = 0;
  57498. }
  57499. }
  57500. this.isPlaying = false;
  57501. }
  57502. };
  57503. Sound.prototype.pause = function () {
  57504. if (this.isPlaying) {
  57505. this.isPaused = true;
  57506. if (this._streaming) {
  57507. this._htmlAudioElement.pause();
  57508. }
  57509. else if (BABYLON.Engine.audioEngine.audioContext) {
  57510. this.stop(0);
  57511. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  57512. }
  57513. }
  57514. };
  57515. Sound.prototype.setVolume = function (newVolume, time) {
  57516. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  57517. if (time && BABYLON.Engine.audioEngine.audioContext) {
  57518. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  57519. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  57520. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  57521. }
  57522. else {
  57523. this._soundGain.gain.value = newVolume;
  57524. }
  57525. }
  57526. this._volume = newVolume;
  57527. };
  57528. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  57529. this._playbackRate = newPlaybackRate;
  57530. if (this.isPlaying) {
  57531. if (this._streaming) {
  57532. this._htmlAudioElement.playbackRate = this._playbackRate;
  57533. }
  57534. else if (this._soundSource) {
  57535. this._soundSource.playbackRate.value = this._playbackRate;
  57536. }
  57537. }
  57538. };
  57539. Sound.prototype.getVolume = function () {
  57540. return this._volume;
  57541. };
  57542. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  57543. var _this = this;
  57544. if (this._connectedMesh && this._registerFunc) {
  57545. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57546. this._registerFunc = null;
  57547. }
  57548. this._connectedMesh = meshToConnectTo;
  57549. if (!this.spatialSound) {
  57550. this.spatialSound = true;
  57551. this._createSpatialParameters();
  57552. if (this.isPlaying && this.loop) {
  57553. this.stop();
  57554. this.play();
  57555. }
  57556. }
  57557. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  57558. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  57559. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  57560. };
  57561. Sound.prototype.detachFromMesh = function () {
  57562. if (this._connectedMesh && this._registerFunc) {
  57563. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57564. this._registerFunc = null;
  57565. this._connectedMesh = null;
  57566. }
  57567. };
  57568. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  57569. if (!node.getBoundingInfo) {
  57570. return;
  57571. }
  57572. var mesh = node;
  57573. var boundingInfo = mesh.getBoundingInfo();
  57574. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  57575. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  57576. this._updateDirection();
  57577. }
  57578. };
  57579. Sound.prototype.clone = function () {
  57580. var _this = this;
  57581. if (!this._streaming) {
  57582. var setBufferAndRun = function () {
  57583. if (_this._isReadyToPlay) {
  57584. clonedSound._audioBuffer = _this.getAudioBuffer();
  57585. clonedSound._isReadyToPlay = true;
  57586. if (clonedSound.autoplay) {
  57587. clonedSound.play();
  57588. }
  57589. }
  57590. else {
  57591. window.setTimeout(setBufferAndRun, 300);
  57592. }
  57593. };
  57594. var currentOptions = {
  57595. autoplay: this.autoplay, loop: this.loop,
  57596. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  57597. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  57598. refDistance: this.refDistance, distanceModel: this.distanceModel
  57599. };
  57600. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  57601. if (this.useCustomAttenuation) {
  57602. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  57603. }
  57604. clonedSound.setPosition(this._position);
  57605. clonedSound.setPlaybackRate(this._playbackRate);
  57606. setBufferAndRun();
  57607. return clonedSound;
  57608. }
  57609. else {
  57610. return null;
  57611. }
  57612. };
  57613. Sound.prototype.getAudioBuffer = function () {
  57614. return this._audioBuffer;
  57615. };
  57616. Sound.prototype.serialize = function () {
  57617. var serializationObject = {
  57618. name: this.name,
  57619. url: this.name,
  57620. autoplay: this.autoplay,
  57621. loop: this.loop,
  57622. volume: this._volume,
  57623. spatialSound: this.spatialSound,
  57624. maxDistance: this.maxDistance,
  57625. rolloffFactor: this.rolloffFactor,
  57626. refDistance: this.refDistance,
  57627. distanceModel: this.distanceModel,
  57628. playbackRate: this._playbackRate,
  57629. panningModel: this._panningModel,
  57630. soundTrackId: this.soundTrackId
  57631. };
  57632. if (this.spatialSound) {
  57633. if (this._connectedMesh)
  57634. serializationObject.connectedMeshId = this._connectedMesh.id;
  57635. serializationObject.position = this._position.asArray();
  57636. serializationObject.refDistance = this.refDistance;
  57637. serializationObject.distanceModel = this.distanceModel;
  57638. serializationObject.isDirectional = this._isDirectional;
  57639. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  57640. serializationObject.coneInnerAngle = this._coneInnerAngle;
  57641. serializationObject.coneOuterAngle = this._coneOuterAngle;
  57642. serializationObject.coneOuterGain = this._coneOuterGain;
  57643. }
  57644. return serializationObject;
  57645. };
  57646. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  57647. var soundName = parsedSound.name;
  57648. var soundUrl;
  57649. if (parsedSound.url) {
  57650. soundUrl = rootUrl + parsedSound.url;
  57651. }
  57652. else {
  57653. soundUrl = rootUrl + soundName;
  57654. }
  57655. var options = {
  57656. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57657. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57658. rolloffFactor: parsedSound.rolloffFactor,
  57659. refDistance: parsedSound.refDistance,
  57660. distanceModel: parsedSound.distanceModel,
  57661. playbackRate: parsedSound.playbackRate
  57662. };
  57663. var newSound;
  57664. if (!sourceSound) {
  57665. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57666. scene._addPendingData(newSound);
  57667. }
  57668. else {
  57669. var setBufferAndRun = function () {
  57670. if (sourceSound._isReadyToPlay) {
  57671. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57672. newSound._isReadyToPlay = true;
  57673. if (newSound.autoplay) {
  57674. newSound.play();
  57675. }
  57676. }
  57677. else {
  57678. window.setTimeout(setBufferAndRun, 300);
  57679. }
  57680. };
  57681. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57682. setBufferAndRun();
  57683. }
  57684. if (parsedSound.position) {
  57685. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57686. newSound.setPosition(soundPosition);
  57687. }
  57688. if (parsedSound.isDirectional) {
  57689. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57690. if (parsedSound.localDirectionToMesh) {
  57691. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57692. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57693. }
  57694. }
  57695. if (parsedSound.connectedMeshId) {
  57696. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57697. if (connectedMesh) {
  57698. newSound.attachToMesh(connectedMesh);
  57699. }
  57700. }
  57701. return newSound;
  57702. };
  57703. return Sound;
  57704. }());
  57705. BABYLON.Sound = Sound;
  57706. })(BABYLON || (BABYLON = {}));
  57707. //# sourceMappingURL=babylon.sound.js.map
  57708. "use strict";
  57709. var BABYLON;
  57710. (function (BABYLON) {
  57711. var SoundTrack = /** @class */ (function () {
  57712. function SoundTrack(scene, options) {
  57713. this.id = -1;
  57714. this._isMainTrack = false;
  57715. this._isInitialized = false;
  57716. this._scene = scene;
  57717. this.soundCollection = new Array();
  57718. this._options = options;
  57719. if (!this._isMainTrack) {
  57720. this._scene.soundTracks.push(this);
  57721. this.id = this._scene.soundTracks.length - 1;
  57722. }
  57723. }
  57724. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57725. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57726. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57727. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57728. if (this._options) {
  57729. if (this._options.volume) {
  57730. this._outputAudioNode.gain.value = this._options.volume;
  57731. }
  57732. if (this._options.mainTrack) {
  57733. this._isMainTrack = this._options.mainTrack;
  57734. }
  57735. }
  57736. this._isInitialized = true;
  57737. }
  57738. };
  57739. SoundTrack.prototype.dispose = function () {
  57740. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57741. if (this._connectedAnalyser) {
  57742. this._connectedAnalyser.stopDebugCanvas();
  57743. }
  57744. while (this.soundCollection.length) {
  57745. this.soundCollection[0].dispose();
  57746. }
  57747. if (this._outputAudioNode) {
  57748. this._outputAudioNode.disconnect();
  57749. }
  57750. this._outputAudioNode = null;
  57751. }
  57752. };
  57753. SoundTrack.prototype.AddSound = function (sound) {
  57754. if (!this._isInitialized) {
  57755. this._initializeSoundTrackAudioGraph();
  57756. }
  57757. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57758. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57759. }
  57760. if (sound.soundTrackId) {
  57761. if (sound.soundTrackId === -1) {
  57762. this._scene.mainSoundTrack.RemoveSound(sound);
  57763. }
  57764. else {
  57765. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  57766. }
  57767. }
  57768. this.soundCollection.push(sound);
  57769. sound.soundTrackId = this.id;
  57770. };
  57771. SoundTrack.prototype.RemoveSound = function (sound) {
  57772. var index = this.soundCollection.indexOf(sound);
  57773. if (index !== -1) {
  57774. this.soundCollection.splice(index, 1);
  57775. }
  57776. };
  57777. SoundTrack.prototype.setVolume = function (newVolume) {
  57778. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57779. this._outputAudioNode.gain.value = newVolume;
  57780. }
  57781. };
  57782. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57783. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57784. for (var i = 0; i < this.soundCollection.length; i++) {
  57785. this.soundCollection[i].switchPanningModelToHRTF();
  57786. }
  57787. }
  57788. };
  57789. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57790. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57791. for (var i = 0; i < this.soundCollection.length; i++) {
  57792. this.soundCollection[i].switchPanningModelToEqualPower();
  57793. }
  57794. }
  57795. };
  57796. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57797. if (this._connectedAnalyser) {
  57798. this._connectedAnalyser.stopDebugCanvas();
  57799. }
  57800. this._connectedAnalyser = analyser;
  57801. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57802. this._outputAudioNode.disconnect();
  57803. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57804. }
  57805. };
  57806. return SoundTrack;
  57807. }());
  57808. BABYLON.SoundTrack = SoundTrack;
  57809. })(BABYLON || (BABYLON = {}));
  57810. //# sourceMappingURL=babylon.soundtrack.js.map
  57811. "use strict";
  57812. var BABYLON;
  57813. (function (BABYLON) {
  57814. var Analyser = /** @class */ (function () {
  57815. function Analyser(scene) {
  57816. this.SMOOTHING = 0.75;
  57817. this.FFT_SIZE = 512;
  57818. this.BARGRAPHAMPLITUDE = 256;
  57819. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57820. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57821. this._scene = scene;
  57822. this._audioEngine = BABYLON.Engine.audioEngine;
  57823. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57824. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57825. this._webAudioAnalyser.minDecibels = -140;
  57826. this._webAudioAnalyser.maxDecibels = 0;
  57827. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57828. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57829. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57830. }
  57831. }
  57832. Analyser.prototype.getFrequencyBinCount = function () {
  57833. if (this._audioEngine.canUseWebAudio) {
  57834. return this._webAudioAnalyser.frequencyBinCount;
  57835. }
  57836. else {
  57837. return 0;
  57838. }
  57839. };
  57840. Analyser.prototype.getByteFrequencyData = function () {
  57841. if (this._audioEngine.canUseWebAudio) {
  57842. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57843. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57844. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57845. }
  57846. return this._byteFreqs;
  57847. };
  57848. Analyser.prototype.getByteTimeDomainData = function () {
  57849. if (this._audioEngine.canUseWebAudio) {
  57850. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57851. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57852. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57853. }
  57854. return this._byteTime;
  57855. };
  57856. Analyser.prototype.getFloatFrequencyData = function () {
  57857. if (this._audioEngine.canUseWebAudio) {
  57858. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57859. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57860. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57861. }
  57862. return this._floatFreqs;
  57863. };
  57864. Analyser.prototype.drawDebugCanvas = function () {
  57865. var _this = this;
  57866. if (this._audioEngine.canUseWebAudio) {
  57867. if (!this._debugCanvas) {
  57868. this._debugCanvas = document.createElement("canvas");
  57869. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57870. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57871. this._debugCanvas.style.position = "absolute";
  57872. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57873. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57874. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57875. document.body.appendChild(this._debugCanvas);
  57876. this._registerFunc = function () {
  57877. _this.drawDebugCanvas();
  57878. };
  57879. this._scene.registerBeforeRender(this._registerFunc);
  57880. }
  57881. if (this._registerFunc && this._debugCanvasContext) {
  57882. var workingArray = this.getByteFrequencyData();
  57883. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57884. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57885. // Draw the frequency domain chart.
  57886. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57887. var value = workingArray[i];
  57888. var percent = value / this.BARGRAPHAMPLITUDE;
  57889. var height = this.DEBUGCANVASSIZE.height * percent;
  57890. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57891. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57892. var hue = i / this.getFrequencyBinCount() * 360;
  57893. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57894. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57895. }
  57896. }
  57897. }
  57898. };
  57899. Analyser.prototype.stopDebugCanvas = function () {
  57900. if (this._debugCanvas) {
  57901. if (this._registerFunc) {
  57902. this._scene.unregisterBeforeRender(this._registerFunc);
  57903. this._registerFunc = null;
  57904. }
  57905. document.body.removeChild(this._debugCanvas);
  57906. this._debugCanvas = null;
  57907. this._debugCanvasContext = null;
  57908. }
  57909. };
  57910. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57911. if (this._audioEngine.canUseWebAudio) {
  57912. inputAudioNode.connect(this._webAudioAnalyser);
  57913. this._webAudioAnalyser.connect(outputAudioNode);
  57914. }
  57915. };
  57916. Analyser.prototype.dispose = function () {
  57917. if (this._audioEngine.canUseWebAudio) {
  57918. this._webAudioAnalyser.disconnect();
  57919. }
  57920. };
  57921. return Analyser;
  57922. }());
  57923. BABYLON.Analyser = Analyser;
  57924. })(BABYLON || (BABYLON = {}));
  57925. //# sourceMappingURL=babylon.analyser.js.map
  57926. "use strict";
  57927. var BABYLON;
  57928. (function (BABYLON) {
  57929. var CubeTexture = /** @class */ (function (_super) {
  57930. __extends(CubeTexture, _super);
  57931. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57932. if (extensions === void 0) { extensions = null; }
  57933. if (noMipmap === void 0) { noMipmap = false; }
  57934. if (files === void 0) { files = null; }
  57935. if (onLoad === void 0) { onLoad = null; }
  57936. if (onError === void 0) { onError = null; }
  57937. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57938. if (prefiltered === void 0) { prefiltered = false; }
  57939. if (forcedExtension === void 0) { forcedExtension = null; }
  57940. var _this = _super.call(this, scene) || this;
  57941. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57942. /**
  57943. * Gets or sets the center of the bounding box associated with the cube texture
  57944. * It must define where the camera used to render the texture was set
  57945. */
  57946. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57947. _this.name = rootUrl;
  57948. _this.url = rootUrl;
  57949. _this._noMipmap = noMipmap;
  57950. _this.hasAlpha = false;
  57951. _this._format = format;
  57952. _this._prefiltered = prefiltered;
  57953. _this.isCube = true;
  57954. _this._textureMatrix = BABYLON.Matrix.Identity();
  57955. if (prefiltered) {
  57956. _this.gammaSpace = false;
  57957. }
  57958. if (!rootUrl && !files) {
  57959. return _this;
  57960. }
  57961. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57962. var lastDot = rootUrl.lastIndexOf(".");
  57963. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57964. var isDDS = (extension === ".dds");
  57965. if (!files) {
  57966. if (!isDDS && !extensions) {
  57967. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  57968. }
  57969. files = [];
  57970. if (extensions) {
  57971. for (var index = 0; index < extensions.length; index++) {
  57972. files.push(rootUrl + extensions[index]);
  57973. }
  57974. }
  57975. }
  57976. _this._files = files;
  57977. if (!_this._texture) {
  57978. if (!scene.useDelayedTextureLoading) {
  57979. if (prefiltered) {
  57980. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  57981. }
  57982. else {
  57983. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  57984. }
  57985. }
  57986. else {
  57987. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57988. }
  57989. }
  57990. else if (onLoad) {
  57991. if (_this._texture.isReady) {
  57992. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  57993. }
  57994. else {
  57995. _this._texture.onLoadedObservable.add(onLoad);
  57996. }
  57997. }
  57998. return _this;
  57999. }
  58000. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58001. get: function () {
  58002. return this._boundingBoxSize;
  58003. },
  58004. /**
  58005. * Gets or sets the size of the bounding box associated with the cube texture
  58006. * When defined, the cubemap will switch to local mode
  58007. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58008. * @example https://www.babylonjs-playground.com/#RNASML
  58009. */
  58010. set: function (value) {
  58011. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58012. return;
  58013. }
  58014. this._boundingBoxSize = value;
  58015. var scene = this.getScene();
  58016. if (scene) {
  58017. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58018. }
  58019. },
  58020. enumerable: true,
  58021. configurable: true
  58022. });
  58023. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58024. var rootUrlKey = "";
  58025. files.forEach(function (url) { return rootUrlKey += url; });
  58026. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58027. };
  58028. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58029. if (forcedExtension === void 0) { forcedExtension = null; }
  58030. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58031. };
  58032. // Methods
  58033. CubeTexture.prototype.delayLoad = function () {
  58034. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58035. return;
  58036. }
  58037. var scene = this.getScene();
  58038. if (!scene) {
  58039. return;
  58040. }
  58041. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58042. this._texture = this._getFromCache(this.url, this._noMipmap);
  58043. if (!this._texture) {
  58044. if (this._prefiltered) {
  58045. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58046. }
  58047. else {
  58048. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58049. }
  58050. }
  58051. };
  58052. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58053. return this._textureMatrix;
  58054. };
  58055. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58056. this._textureMatrix = value;
  58057. };
  58058. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58059. var texture = BABYLON.SerializationHelper.Parse(function () {
  58060. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58061. }, parsedTexture, scene);
  58062. // Local Cubemaps
  58063. if (parsedTexture.boundingBoxPosition) {
  58064. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58065. }
  58066. if (parsedTexture.boundingBoxSize) {
  58067. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58068. }
  58069. // Animations
  58070. if (parsedTexture.animations) {
  58071. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58072. var parsedAnimation = parsedTexture.animations[animationIndex];
  58073. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58074. }
  58075. }
  58076. return texture;
  58077. };
  58078. CubeTexture.prototype.clone = function () {
  58079. var _this = this;
  58080. return BABYLON.SerializationHelper.Clone(function () {
  58081. var scene = _this.getScene();
  58082. if (!scene) {
  58083. return _this;
  58084. }
  58085. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58086. }, this);
  58087. };
  58088. return CubeTexture;
  58089. }(BABYLON.BaseTexture));
  58090. BABYLON.CubeTexture = CubeTexture;
  58091. })(BABYLON || (BABYLON = {}));
  58092. //# sourceMappingURL=babylon.cubeTexture.js.map
  58093. "use strict";
  58094. var BABYLON;
  58095. (function (BABYLON) {
  58096. var RenderTargetTexture = /** @class */ (function (_super) {
  58097. __extends(RenderTargetTexture, _super);
  58098. /**
  58099. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58100. * or used a shadow, depth texture...
  58101. * @param name The friendly name of the texture
  58102. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  58103. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  58104. * @param generateMipMaps True if mip maps need to be generated after render.
  58105. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  58106. * @param type The type of the buffer in the RTT (int, half float, float...)
  58107. * @param isCube True if a cube texture needs to be created
  58108. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  58109. * @param generateDepthBuffer True to generate a depth buffer
  58110. * @param generateStencilBuffer True to generate a stencil buffer
  58111. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58112. */
  58113. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58114. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  58115. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58116. if (isCube === void 0) { isCube = false; }
  58117. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58118. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58119. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58120. if (isMulti === void 0) { isMulti = false; }
  58121. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58122. _this.isCube = isCube;
  58123. /**
  58124. * Use this list to define the list of mesh you want to render.
  58125. */
  58126. _this.renderList = new Array();
  58127. _this.renderParticles = true;
  58128. _this.renderSprites = false;
  58129. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58130. _this.ignoreCameraViewport = false;
  58131. // Events
  58132. /**
  58133. * An event triggered when the texture is unbind.
  58134. * @type {BABYLON.Observable}
  58135. */
  58136. _this.onBeforeBindObservable = new BABYLON.Observable();
  58137. /**
  58138. * An event triggered when the texture is unbind.
  58139. * @type {BABYLON.Observable}
  58140. */
  58141. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58142. /**
  58143. * An event triggered before rendering the texture
  58144. * @type {BABYLON.Observable}
  58145. */
  58146. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58147. /**
  58148. * An event triggered after rendering the texture
  58149. * @type {BABYLON.Observable}
  58150. */
  58151. _this.onAfterRenderObservable = new BABYLON.Observable();
  58152. /**
  58153. * An event triggered after the texture clear
  58154. * @type {BABYLON.Observable}
  58155. */
  58156. _this.onClearObservable = new BABYLON.Observable();
  58157. _this._currentRefreshId = -1;
  58158. _this._refreshRate = 1;
  58159. _this._samples = 1;
  58160. /**
  58161. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58162. * It must define where the camera used to render the texture is set
  58163. */
  58164. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58165. scene = _this.getScene();
  58166. if (!scene) {
  58167. return _this;
  58168. }
  58169. _this._engine = scene.getEngine();
  58170. _this.name = name;
  58171. _this.isRenderTarget = true;
  58172. _this._initialSizeParameter = size;
  58173. _this._processSizeParameter(size);
  58174. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58175. });
  58176. _this._generateMipMaps = generateMipMaps ? true : false;
  58177. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58178. // Rendering groups
  58179. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58180. if (isMulti) {
  58181. return _this;
  58182. }
  58183. _this._renderTargetOptions = {
  58184. generateMipMaps: generateMipMaps,
  58185. type: type,
  58186. samplingMode: samplingMode,
  58187. generateDepthBuffer: generateDepthBuffer,
  58188. generateStencilBuffer: generateStencilBuffer
  58189. };
  58190. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58191. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58192. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58193. }
  58194. if (isCube) {
  58195. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58196. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58197. _this._textureMatrix = BABYLON.Matrix.Identity();
  58198. }
  58199. else {
  58200. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58201. }
  58202. return _this;
  58203. }
  58204. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58205. get: function () {
  58206. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58207. },
  58208. enumerable: true,
  58209. configurable: true
  58210. });
  58211. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58212. get: function () {
  58213. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58214. },
  58215. enumerable: true,
  58216. configurable: true
  58217. });
  58218. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58219. get: function () {
  58220. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58221. },
  58222. enumerable: true,
  58223. configurable: true
  58224. });
  58225. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  58226. set: function (callback) {
  58227. if (this._onAfterUnbindObserver) {
  58228. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  58229. }
  58230. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  58231. },
  58232. enumerable: true,
  58233. configurable: true
  58234. });
  58235. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  58236. set: function (callback) {
  58237. if (this._onBeforeRenderObserver) {
  58238. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58239. }
  58240. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58241. },
  58242. enumerable: true,
  58243. configurable: true
  58244. });
  58245. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  58246. set: function (callback) {
  58247. if (this._onAfterRenderObserver) {
  58248. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58249. }
  58250. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58251. },
  58252. enumerable: true,
  58253. configurable: true
  58254. });
  58255. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  58256. set: function (callback) {
  58257. if (this._onClearObserver) {
  58258. this.onClearObservable.remove(this._onClearObserver);
  58259. }
  58260. this._onClearObserver = this.onClearObservable.add(callback);
  58261. },
  58262. enumerable: true,
  58263. configurable: true
  58264. });
  58265. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  58266. get: function () {
  58267. return this._renderTargetOptions;
  58268. },
  58269. enumerable: true,
  58270. configurable: true
  58271. });
  58272. RenderTargetTexture.prototype._onRatioRescale = function () {
  58273. if (this._sizeRatio) {
  58274. this.resize(this._initialSizeParameter);
  58275. }
  58276. };
  58277. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  58278. get: function () {
  58279. return this._boundingBoxSize;
  58280. },
  58281. /**
  58282. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  58283. * When defined, the cubemap will switch to local mode
  58284. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58285. * @example https://www.babylonjs-playground.com/#RNASML
  58286. */
  58287. set: function (value) {
  58288. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58289. return;
  58290. }
  58291. this._boundingBoxSize = value;
  58292. var scene = this.getScene();
  58293. if (scene) {
  58294. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58295. }
  58296. },
  58297. enumerable: true,
  58298. configurable: true
  58299. });
  58300. /**
  58301. * Creates a depth stencil texture.
  58302. * This is only available in WebGL 2 or with the depth texture extension available.
  58303. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  58304. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  58305. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  58306. */
  58307. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  58308. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  58309. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  58310. if (generateStencil === void 0) { generateStencil = false; }
  58311. if (!this.getScene()) {
  58312. return;
  58313. }
  58314. var engine = this.getScene().getEngine();
  58315. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  58316. bilinearFiltering: bilinearFiltering,
  58317. comparisonFunction: comparisonFunction,
  58318. generateStencil: generateStencil,
  58319. isCube: this.isCube
  58320. });
  58321. engine.setFrameBufferDepthStencilTexture(this);
  58322. };
  58323. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  58324. if (size.ratio) {
  58325. this._sizeRatio = size.ratio;
  58326. this._size = {
  58327. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  58328. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  58329. };
  58330. }
  58331. else {
  58332. this._size = size;
  58333. }
  58334. };
  58335. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  58336. get: function () {
  58337. return this._samples;
  58338. },
  58339. set: function (value) {
  58340. if (this._samples === value) {
  58341. return;
  58342. }
  58343. var scene = this.getScene();
  58344. if (!scene) {
  58345. return;
  58346. }
  58347. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  58348. },
  58349. enumerable: true,
  58350. configurable: true
  58351. });
  58352. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  58353. this._currentRefreshId = -1;
  58354. };
  58355. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  58356. get: function () {
  58357. return this._refreshRate;
  58358. },
  58359. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58360. set: function (value) {
  58361. this._refreshRate = value;
  58362. this.resetRefreshCounter();
  58363. },
  58364. enumerable: true,
  58365. configurable: true
  58366. });
  58367. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  58368. if (!this._postProcessManager) {
  58369. var scene = this.getScene();
  58370. if (!scene) {
  58371. return;
  58372. }
  58373. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  58374. this._postProcesses = new Array();
  58375. }
  58376. this._postProcesses.push(postProcess);
  58377. this._postProcesses[0].autoClear = false;
  58378. };
  58379. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  58380. if (!this._postProcesses) {
  58381. return;
  58382. }
  58383. if (dispose) {
  58384. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  58385. var postProcess = _a[_i];
  58386. postProcess.dispose();
  58387. }
  58388. }
  58389. this._postProcesses = [];
  58390. };
  58391. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  58392. if (!this._postProcesses) {
  58393. return;
  58394. }
  58395. var index = this._postProcesses.indexOf(postProcess);
  58396. if (index === -1) {
  58397. return;
  58398. }
  58399. this._postProcesses.splice(index, 1);
  58400. if (this._postProcesses.length > 0) {
  58401. this._postProcesses[0].autoClear = false;
  58402. }
  58403. };
  58404. RenderTargetTexture.prototype._shouldRender = function () {
  58405. if (this._currentRefreshId === -1) {
  58406. this._currentRefreshId = 1;
  58407. return true;
  58408. }
  58409. if (this.refreshRate === this._currentRefreshId) {
  58410. this._currentRefreshId = 1;
  58411. return true;
  58412. }
  58413. this._currentRefreshId++;
  58414. return false;
  58415. };
  58416. RenderTargetTexture.prototype.getRenderSize = function () {
  58417. if (this._size.width) {
  58418. return this._size.width;
  58419. }
  58420. return this._size;
  58421. };
  58422. RenderTargetTexture.prototype.getRenderWidth = function () {
  58423. if (this._size.width) {
  58424. return this._size.width;
  58425. }
  58426. return this._size;
  58427. };
  58428. RenderTargetTexture.prototype.getRenderHeight = function () {
  58429. if (this._size.width) {
  58430. return this._size.height;
  58431. }
  58432. return this._size;
  58433. };
  58434. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  58435. get: function () {
  58436. return true;
  58437. },
  58438. enumerable: true,
  58439. configurable: true
  58440. });
  58441. RenderTargetTexture.prototype.scale = function (ratio) {
  58442. var newSize = this.getRenderSize() * ratio;
  58443. this.resize(newSize);
  58444. };
  58445. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  58446. if (this.isCube) {
  58447. return this._textureMatrix;
  58448. }
  58449. return _super.prototype.getReflectionTextureMatrix.call(this);
  58450. };
  58451. RenderTargetTexture.prototype.resize = function (size) {
  58452. this.releaseInternalTexture();
  58453. var scene = this.getScene();
  58454. if (!scene) {
  58455. return;
  58456. }
  58457. this._processSizeParameter(size);
  58458. if (this.isCube) {
  58459. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  58460. }
  58461. else {
  58462. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  58463. }
  58464. };
  58465. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  58466. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  58467. if (dumpForDebug === void 0) { dumpForDebug = false; }
  58468. var scene = this.getScene();
  58469. if (!scene) {
  58470. return;
  58471. }
  58472. var engine = scene.getEngine();
  58473. if (this.useCameraPostProcesses !== undefined) {
  58474. useCameraPostProcess = this.useCameraPostProcesses;
  58475. }
  58476. if (this._waitingRenderList) {
  58477. this.renderList = [];
  58478. for (var index = 0; index < this._waitingRenderList.length; index++) {
  58479. var id = this._waitingRenderList[index];
  58480. var mesh_1 = scene.getMeshByID(id);
  58481. if (mesh_1) {
  58482. this.renderList.push(mesh_1);
  58483. }
  58484. }
  58485. delete this._waitingRenderList;
  58486. }
  58487. // Is predicate defined?
  58488. if (this.renderListPredicate) {
  58489. if (this.renderList) {
  58490. this.renderList.splice(0); // Clear previous renderList
  58491. }
  58492. else {
  58493. this.renderList = [];
  58494. }
  58495. var scene = this.getScene();
  58496. if (!scene) {
  58497. return;
  58498. }
  58499. var sceneMeshes = scene.meshes;
  58500. for (var index = 0; index < sceneMeshes.length; index++) {
  58501. var mesh = sceneMeshes[index];
  58502. if (this.renderListPredicate(mesh)) {
  58503. this.renderList.push(mesh);
  58504. }
  58505. }
  58506. }
  58507. this.onBeforeBindObservable.notifyObservers(this);
  58508. // Set custom projection.
  58509. // Needs to be before binding to prevent changing the aspect ratio.
  58510. var camera;
  58511. if (this.activeCamera) {
  58512. camera = this.activeCamera;
  58513. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58514. if (this.activeCamera !== scene.activeCamera) {
  58515. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  58516. }
  58517. }
  58518. else {
  58519. camera = scene.activeCamera;
  58520. if (camera) {
  58521. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58522. }
  58523. }
  58524. // Prepare renderingManager
  58525. this._renderingManager.reset();
  58526. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  58527. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  58528. var sceneRenderId = scene.getRenderId();
  58529. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  58530. var mesh = currentRenderList[meshIndex];
  58531. if (mesh) {
  58532. if (!mesh.isReady(this.refreshRate === 0)) {
  58533. this.resetRefreshCounter();
  58534. continue;
  58535. }
  58536. mesh._preActivateForIntermediateRendering(sceneRenderId);
  58537. var isMasked = void 0;
  58538. if (!this.renderList && camera) {
  58539. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  58540. }
  58541. else {
  58542. isMasked = false;
  58543. }
  58544. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  58545. mesh._activate(sceneRenderId);
  58546. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  58547. var subMesh = mesh.subMeshes[subIndex];
  58548. scene._activeIndices.addCount(subMesh.indexCount, false);
  58549. this._renderingManager.dispatch(subMesh, mesh);
  58550. }
  58551. }
  58552. }
  58553. }
  58554. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  58555. var particleSystem = scene.particleSystems[particleIndex];
  58556. var emitter = particleSystem.emitter;
  58557. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  58558. continue;
  58559. }
  58560. if (currentRenderList.indexOf(emitter) >= 0) {
  58561. this._renderingManager.dispatchParticles(particleSystem);
  58562. }
  58563. }
  58564. if (this.isCube) {
  58565. for (var face = 0; face < 6; face++) {
  58566. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58567. scene.incrementRenderId();
  58568. scene.resetCachedMaterial();
  58569. }
  58570. }
  58571. else {
  58572. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58573. }
  58574. this.onAfterUnbindObservable.notifyObservers(this);
  58575. if (scene.activeCamera) {
  58576. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  58577. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  58578. }
  58579. engine.setViewport(scene.activeCamera.viewport);
  58580. }
  58581. scene.resetCachedMaterial();
  58582. };
  58583. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  58584. var minimum = 128;
  58585. var x = renderDimension * scale;
  58586. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  58587. // Ensure we don't exceed the render dimension (while staying POT)
  58588. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  58589. };
  58590. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58591. var _this = this;
  58592. if (!this._texture) {
  58593. return;
  58594. }
  58595. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  58596. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58597. });
  58598. };
  58599. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  58600. var scene = this.getScene();
  58601. if (!scene) {
  58602. return;
  58603. }
  58604. var engine = scene.getEngine();
  58605. if (!this._texture) {
  58606. return;
  58607. }
  58608. // Bind
  58609. if (this._postProcessManager) {
  58610. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  58611. }
  58612. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  58613. if (this._texture) {
  58614. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  58615. }
  58616. }
  58617. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  58618. // Clear
  58619. if (this.onClearObservable.hasObservers()) {
  58620. this.onClearObservable.notifyObservers(engine);
  58621. }
  58622. else {
  58623. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  58624. }
  58625. if (!this._doNotChangeAspectRatio) {
  58626. scene.updateTransformMatrix(true);
  58627. }
  58628. // Render
  58629. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  58630. if (this._postProcessManager) {
  58631. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  58632. }
  58633. else if (useCameraPostProcess) {
  58634. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  58635. }
  58636. if (!this._doNotChangeAspectRatio) {
  58637. scene.updateTransformMatrix(true);
  58638. }
  58639. // Dump ?
  58640. if (dumpForDebug) {
  58641. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  58642. }
  58643. // Unbind
  58644. if (!this.isCube || faceIndex === 5) {
  58645. if (this.isCube) {
  58646. if (faceIndex === 5) {
  58647. engine.generateMipMapsForCubemap(this._texture);
  58648. }
  58649. }
  58650. this.unbindFrameBuffer(engine, faceIndex);
  58651. }
  58652. else {
  58653. this.onAfterRenderObservable.notifyObservers(faceIndex);
  58654. }
  58655. };
  58656. /**
  58657. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  58658. * This allowed control for front to back rendering or reversly depending of the special needs.
  58659. *
  58660. * @param renderingGroupId The rendering group id corresponding to its index
  58661. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  58662. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  58663. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  58664. */
  58665. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  58666. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  58667. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  58668. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  58669. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  58670. };
  58671. /**
  58672. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  58673. *
  58674. * @param renderingGroupId The rendering group id corresponding to its index
  58675. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  58676. */
  58677. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  58678. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  58679. };
  58680. RenderTargetTexture.prototype.clone = function () {
  58681. var textureSize = this.getSize();
  58682. 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);
  58683. // Base texture
  58684. newTexture.hasAlpha = this.hasAlpha;
  58685. newTexture.level = this.level;
  58686. // RenderTarget Texture
  58687. newTexture.coordinatesMode = this.coordinatesMode;
  58688. if (this.renderList) {
  58689. newTexture.renderList = this.renderList.slice(0);
  58690. }
  58691. return newTexture;
  58692. };
  58693. RenderTargetTexture.prototype.serialize = function () {
  58694. if (!this.name) {
  58695. return null;
  58696. }
  58697. var serializationObject = _super.prototype.serialize.call(this);
  58698. serializationObject.renderTargetSize = this.getRenderSize();
  58699. serializationObject.renderList = [];
  58700. if (this.renderList) {
  58701. for (var index = 0; index < this.renderList.length; index++) {
  58702. serializationObject.renderList.push(this.renderList[index].id);
  58703. }
  58704. }
  58705. return serializationObject;
  58706. };
  58707. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58708. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58709. var objBuffer = this.getInternalTexture();
  58710. var scene = this.getScene();
  58711. if (objBuffer && scene) {
  58712. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58713. }
  58714. };
  58715. RenderTargetTexture.prototype.dispose = function () {
  58716. if (this._postProcessManager) {
  58717. this._postProcessManager.dispose();
  58718. this._postProcessManager = null;
  58719. }
  58720. this.clearPostProcesses(true);
  58721. if (this._resizeObserver) {
  58722. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58723. this._resizeObserver = null;
  58724. }
  58725. this.renderList = null;
  58726. // Remove from custom render targets
  58727. var scene = this.getScene();
  58728. if (!scene) {
  58729. return;
  58730. }
  58731. var index = scene.customRenderTargets.indexOf(this);
  58732. if (index >= 0) {
  58733. scene.customRenderTargets.splice(index, 1);
  58734. }
  58735. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58736. var camera = _a[_i];
  58737. index = camera.customRenderTargets.indexOf(this);
  58738. if (index >= 0) {
  58739. camera.customRenderTargets.splice(index, 1);
  58740. }
  58741. }
  58742. _super.prototype.dispose.call(this);
  58743. };
  58744. RenderTargetTexture.prototype._rebuild = function () {
  58745. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58746. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58747. }
  58748. if (this._postProcessManager) {
  58749. this._postProcessManager._rebuild();
  58750. }
  58751. };
  58752. /**
  58753. * Clear the info related to rendering groups preventing retention point in material dispose.
  58754. */
  58755. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  58756. if (this._renderingManager) {
  58757. this._renderingManager.freeRenderingGroups();
  58758. }
  58759. };
  58760. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58761. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58762. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58763. return RenderTargetTexture;
  58764. }(BABYLON.Texture));
  58765. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58766. })(BABYLON || (BABYLON = {}));
  58767. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58768. "use strict";
  58769. var BABYLON;
  58770. (function (BABYLON) {
  58771. ;
  58772. var MultiRenderTarget = /** @class */ (function (_super) {
  58773. __extends(MultiRenderTarget, _super);
  58774. function MultiRenderTarget(name, size, count, scene, options) {
  58775. var _this = this;
  58776. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  58777. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  58778. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  58779. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  58780. _this._engine = scene.getEngine();
  58781. if (!_this.isSupported) {
  58782. _this.dispose();
  58783. return;
  58784. }
  58785. var types = [];
  58786. var samplingModes = [];
  58787. for (var i = 0; i < count; i++) {
  58788. if (options && options.types && options.types[i] !== undefined) {
  58789. types.push(options.types[i]);
  58790. }
  58791. else {
  58792. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58793. }
  58794. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  58795. samplingModes.push(options.samplingModes[i]);
  58796. }
  58797. else {
  58798. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58799. }
  58800. }
  58801. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  58802. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  58803. _this._size = size;
  58804. _this._multiRenderTargetOptions = {
  58805. samplingModes: samplingModes,
  58806. generateMipMaps: generateMipMaps,
  58807. generateDepthBuffer: generateDepthBuffer,
  58808. generateStencilBuffer: generateStencilBuffer,
  58809. generateDepthTexture: generateDepthTexture,
  58810. types: types,
  58811. textureCount: count
  58812. };
  58813. _this._createInternalTextures();
  58814. _this._createTextures();
  58815. return _this;
  58816. }
  58817. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  58818. get: function () {
  58819. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  58820. },
  58821. enumerable: true,
  58822. configurable: true
  58823. });
  58824. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58825. get: function () {
  58826. return this._textures;
  58827. },
  58828. enumerable: true,
  58829. configurable: true
  58830. });
  58831. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58832. get: function () {
  58833. return this._textures[this._textures.length - 1];
  58834. },
  58835. enumerable: true,
  58836. configurable: true
  58837. });
  58838. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58839. set: function (wrap) {
  58840. if (this._textures) {
  58841. for (var i = 0; i < this._textures.length; i++) {
  58842. this._textures[i].wrapU = wrap;
  58843. }
  58844. }
  58845. },
  58846. enumerable: true,
  58847. configurable: true
  58848. });
  58849. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58850. set: function (wrap) {
  58851. if (this._textures) {
  58852. for (var i = 0; i < this._textures.length; i++) {
  58853. this._textures[i].wrapV = wrap;
  58854. }
  58855. }
  58856. },
  58857. enumerable: true,
  58858. configurable: true
  58859. });
  58860. MultiRenderTarget.prototype._rebuild = function () {
  58861. this.releaseInternalTextures();
  58862. this._createInternalTextures();
  58863. for (var i = 0; i < this._internalTextures.length; i++) {
  58864. var texture = this._textures[i];
  58865. texture._texture = this._internalTextures[i];
  58866. }
  58867. // Keeps references to frame buffer and stencil/depth buffer
  58868. this._texture = this._internalTextures[0];
  58869. };
  58870. MultiRenderTarget.prototype._createInternalTextures = function () {
  58871. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58872. };
  58873. MultiRenderTarget.prototype._createTextures = function () {
  58874. this._textures = [];
  58875. for (var i = 0; i < this._internalTextures.length; i++) {
  58876. var texture = new BABYLON.Texture(null, this.getScene());
  58877. texture._texture = this._internalTextures[i];
  58878. this._textures.push(texture);
  58879. }
  58880. // Keeps references to frame buffer and stencil/depth buffer
  58881. this._texture = this._internalTextures[0];
  58882. };
  58883. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58884. get: function () {
  58885. return this._samples;
  58886. },
  58887. set: function (value) {
  58888. if (this._samples === value) {
  58889. return;
  58890. }
  58891. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58892. },
  58893. enumerable: true,
  58894. configurable: true
  58895. });
  58896. MultiRenderTarget.prototype.resize = function (size) {
  58897. this.releaseInternalTextures();
  58898. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58899. this._createInternalTextures();
  58900. };
  58901. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58902. var _this = this;
  58903. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58904. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58905. });
  58906. };
  58907. MultiRenderTarget.prototype.dispose = function () {
  58908. this.releaseInternalTextures();
  58909. _super.prototype.dispose.call(this);
  58910. };
  58911. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58912. if (!this._internalTextures) {
  58913. return;
  58914. }
  58915. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58916. if (this._internalTextures[i] !== undefined) {
  58917. this._internalTextures[i].dispose();
  58918. this._internalTextures.splice(i, 1);
  58919. }
  58920. }
  58921. };
  58922. return MultiRenderTarget;
  58923. }(BABYLON.RenderTargetTexture));
  58924. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58925. })(BABYLON || (BABYLON = {}));
  58926. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58927. "use strict";
  58928. var BABYLON;
  58929. (function (BABYLON) {
  58930. var MirrorTexture = /** @class */ (function (_super) {
  58931. __extends(MirrorTexture, _super);
  58932. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58933. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58934. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58935. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58936. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58937. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58938. _this._transformMatrix = BABYLON.Matrix.Zero();
  58939. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58940. _this._adaptiveBlurKernel = 0;
  58941. _this._blurKernelX = 0;
  58942. _this._blurKernelY = 0;
  58943. _this._blurRatio = 1.0;
  58944. _this.ignoreCameraViewport = true;
  58945. _this.onBeforeRenderObservable.add(function () {
  58946. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58947. _this._savedViewMatrix = scene.getViewMatrix();
  58948. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58949. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58950. scene.clipPlane = _this.mirrorPlane;
  58951. scene.getEngine().cullBackFaces = false;
  58952. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58953. });
  58954. _this.onAfterRenderObservable.add(function () {
  58955. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58956. scene.getEngine().cullBackFaces = true;
  58957. scene._mirroredCameraPosition = null;
  58958. delete scene.clipPlane;
  58959. });
  58960. return _this;
  58961. }
  58962. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58963. get: function () {
  58964. return this._blurRatio;
  58965. },
  58966. set: function (value) {
  58967. if (this._blurRatio === value) {
  58968. return;
  58969. }
  58970. this._blurRatio = value;
  58971. this._preparePostProcesses();
  58972. },
  58973. enumerable: true,
  58974. configurable: true
  58975. });
  58976. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58977. set: function (value) {
  58978. this._adaptiveBlurKernel = value;
  58979. this._autoComputeBlurKernel();
  58980. },
  58981. enumerable: true,
  58982. configurable: true
  58983. });
  58984. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58985. set: function (value) {
  58986. this.blurKernelX = value;
  58987. this.blurKernelY = value;
  58988. },
  58989. enumerable: true,
  58990. configurable: true
  58991. });
  58992. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  58993. get: function () {
  58994. return this._blurKernelX;
  58995. },
  58996. set: function (value) {
  58997. if (this._blurKernelX === value) {
  58998. return;
  58999. }
  59000. this._blurKernelX = value;
  59001. this._preparePostProcesses();
  59002. },
  59003. enumerable: true,
  59004. configurable: true
  59005. });
  59006. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59007. get: function () {
  59008. return this._blurKernelY;
  59009. },
  59010. set: function (value) {
  59011. if (this._blurKernelY === value) {
  59012. return;
  59013. }
  59014. this._blurKernelY = value;
  59015. this._preparePostProcesses();
  59016. },
  59017. enumerable: true,
  59018. configurable: true
  59019. });
  59020. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59021. var engine = this.getScene().getEngine();
  59022. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59023. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59024. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59025. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59026. };
  59027. MirrorTexture.prototype._onRatioRescale = function () {
  59028. if (this._sizeRatio) {
  59029. this.resize(this._initialSizeParameter);
  59030. if (!this._adaptiveBlurKernel) {
  59031. this._preparePostProcesses();
  59032. }
  59033. }
  59034. if (this._adaptiveBlurKernel) {
  59035. this._autoComputeBlurKernel();
  59036. }
  59037. };
  59038. MirrorTexture.prototype._preparePostProcesses = function () {
  59039. this.clearPostProcesses(true);
  59040. if (this._blurKernelX && this._blurKernelY) {
  59041. var engine = this.getScene().getEngine();
  59042. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59043. 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);
  59044. this._blurX.autoClear = false;
  59045. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59046. this._blurX.inputTexture = this._texture;
  59047. }
  59048. else {
  59049. this._blurX.alwaysForcePOT = true;
  59050. }
  59051. 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);
  59052. this._blurY.autoClear = false;
  59053. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59054. this.addPostProcess(this._blurX);
  59055. this.addPostProcess(this._blurY);
  59056. }
  59057. else {
  59058. if (this._blurY) {
  59059. this.removePostProcess(this._blurY);
  59060. this._blurY.dispose();
  59061. this._blurY = null;
  59062. }
  59063. if (this._blurX) {
  59064. this.removePostProcess(this._blurX);
  59065. this._blurX.dispose();
  59066. this._blurX = null;
  59067. }
  59068. }
  59069. };
  59070. MirrorTexture.prototype.clone = function () {
  59071. var scene = this.getScene();
  59072. if (!scene) {
  59073. return this;
  59074. }
  59075. var textureSize = this.getSize();
  59076. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59077. // Base texture
  59078. newTexture.hasAlpha = this.hasAlpha;
  59079. newTexture.level = this.level;
  59080. // Mirror Texture
  59081. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59082. if (this.renderList) {
  59083. newTexture.renderList = this.renderList.slice(0);
  59084. }
  59085. return newTexture;
  59086. };
  59087. MirrorTexture.prototype.serialize = function () {
  59088. if (!this.name) {
  59089. return null;
  59090. }
  59091. var serializationObject = _super.prototype.serialize.call(this);
  59092. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59093. return serializationObject;
  59094. };
  59095. return MirrorTexture;
  59096. }(BABYLON.RenderTargetTexture));
  59097. BABYLON.MirrorTexture = MirrorTexture;
  59098. })(BABYLON || (BABYLON = {}));
  59099. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59100. "use strict";
  59101. var BABYLON;
  59102. (function (BABYLON) {
  59103. /**
  59104. * Creates a refraction texture used by refraction channel of the standard material.
  59105. * @param name the texture name
  59106. * @param size size of the underlying texture
  59107. * @param scene root scene
  59108. */
  59109. var RefractionTexture = /** @class */ (function (_super) {
  59110. __extends(RefractionTexture, _super);
  59111. function RefractionTexture(name, size, scene, generateMipMaps) {
  59112. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  59113. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  59114. _this.depth = 2.0;
  59115. _this.onBeforeRenderObservable.add(function () {
  59116. scene.clipPlane = _this.refractionPlane;
  59117. });
  59118. _this.onAfterRenderObservable.add(function () {
  59119. delete scene.clipPlane;
  59120. });
  59121. return _this;
  59122. }
  59123. RefractionTexture.prototype.clone = function () {
  59124. var scene = this.getScene();
  59125. if (!scene) {
  59126. return this;
  59127. }
  59128. var textureSize = this.getSize();
  59129. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  59130. // Base texture
  59131. newTexture.hasAlpha = this.hasAlpha;
  59132. newTexture.level = this.level;
  59133. // Refraction Texture
  59134. newTexture.refractionPlane = this.refractionPlane.clone();
  59135. if (this.renderList) {
  59136. newTexture.renderList = this.renderList.slice(0);
  59137. }
  59138. newTexture.depth = this.depth;
  59139. return newTexture;
  59140. };
  59141. RefractionTexture.prototype.serialize = function () {
  59142. if (!this.name) {
  59143. return null;
  59144. }
  59145. var serializationObject = _super.prototype.serialize.call(this);
  59146. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  59147. serializationObject.depth = this.depth;
  59148. return serializationObject;
  59149. };
  59150. return RefractionTexture;
  59151. }(BABYLON.RenderTargetTexture));
  59152. BABYLON.RefractionTexture = RefractionTexture;
  59153. })(BABYLON || (BABYLON = {}));
  59154. //# sourceMappingURL=babylon.refractionTexture.js.map
  59155. "use strict";
  59156. var BABYLON;
  59157. (function (BABYLON) {
  59158. var DynamicTexture = /** @class */ (function (_super) {
  59159. __extends(DynamicTexture, _super);
  59160. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59161. if (scene === void 0) { scene = null; }
  59162. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59163. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59164. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59165. _this.name = name;
  59166. _this._engine = _this.getScene().getEngine();
  59167. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59168. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59169. _this._generateMipMaps = generateMipMaps;
  59170. if (options.getContext) {
  59171. _this._canvas = options;
  59172. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59173. }
  59174. else {
  59175. _this._canvas = document.createElement("canvas");
  59176. if (options.width) {
  59177. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59178. }
  59179. else {
  59180. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59181. }
  59182. }
  59183. var textureSize = _this.getSize();
  59184. _this._canvas.width = textureSize.width;
  59185. _this._canvas.height = textureSize.height;
  59186. _this._context = _this._canvas.getContext("2d");
  59187. return _this;
  59188. }
  59189. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59190. get: function () {
  59191. return true;
  59192. },
  59193. enumerable: true,
  59194. configurable: true
  59195. });
  59196. DynamicTexture.prototype._recreate = function (textureSize) {
  59197. this._canvas.width = textureSize.width;
  59198. this._canvas.height = textureSize.height;
  59199. this.releaseInternalTexture();
  59200. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59201. };
  59202. DynamicTexture.prototype.scale = function (ratio) {
  59203. var textureSize = this.getSize();
  59204. textureSize.width *= ratio;
  59205. textureSize.height *= ratio;
  59206. this._recreate(textureSize);
  59207. };
  59208. DynamicTexture.prototype.scaleTo = function (width, height) {
  59209. var textureSize = this.getSize();
  59210. textureSize.width = width;
  59211. textureSize.height = height;
  59212. this._recreate(textureSize);
  59213. };
  59214. DynamicTexture.prototype.getContext = function () {
  59215. return this._context;
  59216. };
  59217. DynamicTexture.prototype.clear = function () {
  59218. var size = this.getSize();
  59219. this._context.fillRect(0, 0, size.width, size.height);
  59220. };
  59221. DynamicTexture.prototype.update = function (invertY) {
  59222. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  59223. };
  59224. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  59225. if (update === void 0) { update = true; }
  59226. var size = this.getSize();
  59227. if (clearColor) {
  59228. this._context.fillStyle = clearColor;
  59229. this._context.fillRect(0, 0, size.width, size.height);
  59230. }
  59231. this._context.font = font;
  59232. if (x === null || x === undefined) {
  59233. var textSize = this._context.measureText(text);
  59234. x = (size.width - textSize.width) / 2;
  59235. }
  59236. if (y === null || y === undefined) {
  59237. var fontSize = parseInt((font.replace(/\D/g, '')));
  59238. ;
  59239. y = (size.height / 2) + (fontSize / 3.65);
  59240. }
  59241. this._context.fillStyle = color;
  59242. this._context.fillText(text, x, y);
  59243. if (update) {
  59244. this.update(invertY);
  59245. }
  59246. };
  59247. DynamicTexture.prototype.clone = function () {
  59248. var scene = this.getScene();
  59249. if (!scene) {
  59250. return this;
  59251. }
  59252. var textureSize = this.getSize();
  59253. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  59254. // Base texture
  59255. newTexture.hasAlpha = this.hasAlpha;
  59256. newTexture.level = this.level;
  59257. // Dynamic Texture
  59258. newTexture.wrapU = this.wrapU;
  59259. newTexture.wrapV = this.wrapV;
  59260. return newTexture;
  59261. };
  59262. DynamicTexture.prototype._rebuild = function () {
  59263. this.update();
  59264. };
  59265. return DynamicTexture;
  59266. }(BABYLON.Texture));
  59267. BABYLON.DynamicTexture = DynamicTexture;
  59268. })(BABYLON || (BABYLON = {}));
  59269. //# sourceMappingURL=babylon.dynamicTexture.js.map
  59270. "use strict";
  59271. var BABYLON;
  59272. (function (BABYLON) {
  59273. var VideoTexture = /** @class */ (function (_super) {
  59274. __extends(VideoTexture, _super);
  59275. /**
  59276. * Creates a video texture.
  59277. * Sample : https://doc.babylonjs.com/how_to/video_texture
  59278. * @param {string | null} name optional name, will detect from video source, if not defined
  59279. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  59280. * @param {BABYLON.Scene} scene is obviously the current scene.
  59281. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  59282. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  59283. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  59284. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  59285. */
  59286. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  59287. if (generateMipMaps === void 0) { generateMipMaps = false; }
  59288. if (invertY === void 0) { invertY = false; }
  59289. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59290. if (settings === void 0) { settings = {
  59291. autoPlay: true,
  59292. loop: true,
  59293. autoUpdateTexture: true,
  59294. }; }
  59295. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59296. _this._createInternalTexture = function () {
  59297. if (_this._texture != null) {
  59298. return;
  59299. }
  59300. if (!_this._engine.needPOTTextures ||
  59301. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  59302. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59303. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59304. }
  59305. else {
  59306. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59307. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59308. _this._generateMipMaps = false;
  59309. }
  59310. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  59311. _this._texture.isReady = true;
  59312. _this._updateInternalTexture();
  59313. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  59314. _this.onLoadObservable.notifyObservers(_this);
  59315. }
  59316. };
  59317. _this.reset = function () {
  59318. if (_this._texture == null) {
  59319. return;
  59320. }
  59321. _this._texture.dispose();
  59322. _this._texture = null;
  59323. };
  59324. _this._updateInternalTexture = function (e) {
  59325. if (_this._texture == null || !_this._texture.isReady) {
  59326. return;
  59327. }
  59328. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  59329. return;
  59330. }
  59331. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  59332. };
  59333. _this._engine = _this.getScene().getEngine();
  59334. _this._generateMipMaps = generateMipMaps;
  59335. _this._samplingMode = samplingMode;
  59336. _this.autoUpdateTexture = settings.autoUpdateTexture;
  59337. _this.name = name || _this._getName(src);
  59338. _this.video = _this._getVideo(src);
  59339. if (settings.autoPlay !== undefined) {
  59340. _this.video.autoplay = settings.autoPlay;
  59341. }
  59342. if (settings.loop !== undefined) {
  59343. _this.video.loop = settings.loop;
  59344. }
  59345. _this.video.addEventListener("canplay", _this._createInternalTexture);
  59346. _this.video.addEventListener("paused", _this._updateInternalTexture);
  59347. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  59348. _this.video.addEventListener("emptied", _this.reset);
  59349. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  59350. _this._createInternalTexture();
  59351. }
  59352. return _this;
  59353. }
  59354. VideoTexture.prototype._getName = function (src) {
  59355. if (src instanceof HTMLVideoElement) {
  59356. return src.currentSrc;
  59357. }
  59358. if (typeof src === "object") {
  59359. return src.toString();
  59360. }
  59361. return src;
  59362. };
  59363. ;
  59364. VideoTexture.prototype._getVideo = function (src) {
  59365. if (src instanceof HTMLVideoElement) {
  59366. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  59367. return src;
  59368. }
  59369. var video = document.createElement("video");
  59370. if (typeof src === "string") {
  59371. BABYLON.Tools.SetCorsBehavior(src, video);
  59372. video.src = src;
  59373. }
  59374. else {
  59375. BABYLON.Tools.SetCorsBehavior(src[0], video);
  59376. src.forEach(function (url) {
  59377. var source = document.createElement("source");
  59378. source.src = url;
  59379. video.appendChild(source);
  59380. });
  59381. }
  59382. return video;
  59383. };
  59384. ;
  59385. /**
  59386. * Internal method to initiate `update`.
  59387. */
  59388. VideoTexture.prototype._rebuild = function () {
  59389. this.update();
  59390. };
  59391. /**
  59392. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  59393. */
  59394. VideoTexture.prototype.update = function () {
  59395. if (!this.autoUpdateTexture) {
  59396. // Expecting user to call `updateTexture` manually
  59397. return;
  59398. }
  59399. this.updateTexture(true);
  59400. };
  59401. /**
  59402. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  59403. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  59404. */
  59405. VideoTexture.prototype.updateTexture = function (isVisible) {
  59406. if (!isVisible) {
  59407. return;
  59408. }
  59409. if (this.video.paused) {
  59410. return;
  59411. }
  59412. this._updateInternalTexture();
  59413. };
  59414. /**
  59415. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  59416. * @param url New url.
  59417. */
  59418. VideoTexture.prototype.updateURL = function (url) {
  59419. this.video.src = url;
  59420. };
  59421. VideoTexture.prototype.dispose = function () {
  59422. _super.prototype.dispose.call(this);
  59423. this.video.removeEventListener("canplay", this._createInternalTexture);
  59424. this.video.removeEventListener("paused", this._updateInternalTexture);
  59425. this.video.removeEventListener("seeked", this._updateInternalTexture);
  59426. this.video.removeEventListener("emptied", this.reset);
  59427. this.video.pause();
  59428. };
  59429. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  59430. var video = document.createElement("video");
  59431. var constraintsDeviceId;
  59432. if (constraints && constraints.deviceId) {
  59433. constraintsDeviceId = {
  59434. exact: constraints.deviceId,
  59435. };
  59436. }
  59437. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  59438. if (navigator.mediaDevices) {
  59439. navigator.mediaDevices.getUserMedia({ video: constraints })
  59440. .then(function (stream) {
  59441. if (video.mozSrcObject !== undefined) {
  59442. // hack for Firefox < 19
  59443. video.mozSrcObject = stream;
  59444. }
  59445. else {
  59446. video.srcObject = stream;
  59447. }
  59448. var onPlaying = function () {
  59449. if (onReady) {
  59450. onReady(new VideoTexture("video", video, scene, true, true));
  59451. }
  59452. video.removeEventListener("playing", onPlaying);
  59453. };
  59454. video.addEventListener("playing", onPlaying);
  59455. video.play();
  59456. })
  59457. .catch(function (err) {
  59458. BABYLON.Tools.Error(err.name);
  59459. });
  59460. }
  59461. else {
  59462. navigator.getUserMedia =
  59463. navigator.getUserMedia ||
  59464. navigator.webkitGetUserMedia ||
  59465. navigator.mozGetUserMedia ||
  59466. navigator.msGetUserMedia;
  59467. if (navigator.getUserMedia) {
  59468. navigator.getUserMedia({
  59469. video: {
  59470. deviceId: constraintsDeviceId,
  59471. width: {
  59472. min: (constraints && constraints.minWidth) || 256,
  59473. max: (constraints && constraints.maxWidth) || 640,
  59474. },
  59475. height: {
  59476. min: (constraints && constraints.minHeight) || 256,
  59477. max: (constraints && constraints.maxHeight) || 480,
  59478. },
  59479. },
  59480. }, function (stream) {
  59481. if (video.mozSrcObject !== undefined) {
  59482. // hack for Firefox < 19
  59483. video.mozSrcObject = stream;
  59484. }
  59485. else {
  59486. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  59487. }
  59488. video.play();
  59489. if (onReady) {
  59490. onReady(new VideoTexture("video", video, scene, true, true));
  59491. }
  59492. }, function (e) {
  59493. BABYLON.Tools.Error(e.name);
  59494. });
  59495. }
  59496. }
  59497. };
  59498. return VideoTexture;
  59499. }(BABYLON.Texture));
  59500. BABYLON.VideoTexture = VideoTexture;
  59501. })(BABYLON || (BABYLON = {}));
  59502. //# sourceMappingURL=babylon.videoTexture.js.map
  59503. "use strict";
  59504. var BABYLON;
  59505. (function (BABYLON) {
  59506. var RawTexture = /** @class */ (function (_super) {
  59507. __extends(RawTexture, _super);
  59508. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  59509. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59510. if (invertY === void 0) { invertY = false; }
  59511. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59512. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59513. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59514. _this.format = format;
  59515. _this._engine = scene.getEngine();
  59516. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  59517. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59518. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59519. return _this;
  59520. }
  59521. RawTexture.prototype.update = function (data) {
  59522. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  59523. };
  59524. // Statics
  59525. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59526. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59527. if (invertY === void 0) { invertY = false; }
  59528. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59529. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  59530. };
  59531. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59532. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59533. if (invertY === void 0) { invertY = false; }
  59534. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59535. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59536. };
  59537. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59538. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59539. if (invertY === void 0) { invertY = false; }
  59540. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59541. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59542. };
  59543. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59544. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59545. if (invertY === void 0) { invertY = false; }
  59546. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59547. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59548. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  59549. };
  59550. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59551. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59552. if (invertY === void 0) { invertY = false; }
  59553. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59554. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59555. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  59556. };
  59557. return RawTexture;
  59558. }(BABYLON.Texture));
  59559. BABYLON.RawTexture = RawTexture;
  59560. })(BABYLON || (BABYLON = {}));
  59561. //# sourceMappingURL=babylon.rawTexture.js.map
  59562. "use strict";
  59563. var BABYLON;
  59564. (function (BABYLON) {
  59565. /**
  59566. * PostProcess can be used to apply a shader to a texture after it has been rendered
  59567. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  59568. */
  59569. var PostProcess = /** @class */ (function () {
  59570. /**
  59571. * Creates a new instance of @see PostProcess
  59572. * @param name The name of the PostProcess.
  59573. * @param fragmentUrl The url of the fragment shader to be used.
  59574. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  59575. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  59576. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  59577. * @param camera The camera to apply the render pass to.
  59578. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  59579. * @param engine The engine which the post process will be applied. (default: current engine)
  59580. * @param reusable If the post process can be reused on the same frame. (default: false)
  59581. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  59582. * @param textureType Type of textures used when performing the post process. (default: 0)
  59583. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  59584. * @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
  59585. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  59586. */
  59587. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  59588. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  59589. if (defines === void 0) { defines = null; }
  59590. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59591. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  59592. if (blockCompilation === void 0) { blockCompilation = false; }
  59593. this.name = name;
  59594. /**
  59595. * Width of the texture to apply the post process on
  59596. */
  59597. this.width = -1;
  59598. /**
  59599. * Height of the texture to apply the post process on
  59600. */
  59601. this.height = -1;
  59602. /**
  59603. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  59604. */
  59605. this._outputTexture = null;
  59606. /**
  59607. * If the buffer needs to be cleared before applying the post process. (default: true)
  59608. * Should be set to false if shader will overwrite all previous pixels.
  59609. */
  59610. this.autoClear = true;
  59611. /**
  59612. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  59613. */
  59614. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  59615. /**
  59616. * Animations to be used for the post processing
  59617. */
  59618. this.animations = new Array();
  59619. /**
  59620. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  59621. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  59622. */
  59623. this.enablePixelPerfectMode = false;
  59624. /**
  59625. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  59626. */
  59627. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  59628. /**
  59629. * Force textures to be a power of two (default: false)
  59630. */
  59631. this.alwaysForcePOT = false;
  59632. /**
  59633. * Number of sample textures (default: 1)
  59634. */
  59635. this.samples = 1;
  59636. /**
  59637. * Modify the scale of the post process to be the same as the viewport (default: false)
  59638. */
  59639. this.adaptScaleToCurrentViewport = false;
  59640. this._reusable = false;
  59641. /**
  59642. * Smart array of input and output textures for the post process.
  59643. */
  59644. this._textures = new BABYLON.SmartArray(2);
  59645. /**
  59646. * The index in _textures that corresponds to the output texture.
  59647. */
  59648. this._currentRenderTextureInd = 0;
  59649. this._scaleRatio = new BABYLON.Vector2(1, 1);
  59650. this._texelSize = BABYLON.Vector2.Zero();
  59651. // Events
  59652. /**
  59653. * An event triggered when the postprocess is activated.
  59654. * @type {BABYLON.Observable}
  59655. */
  59656. this.onActivateObservable = new BABYLON.Observable();
  59657. /**
  59658. * An event triggered when the postprocess changes its size.
  59659. * @type {BABYLON.Observable}
  59660. */
  59661. this.onSizeChangedObservable = new BABYLON.Observable();
  59662. /**
  59663. * An event triggered when the postprocess applies its effect.
  59664. * @type {BABYLON.Observable}
  59665. */
  59666. this.onApplyObservable = new BABYLON.Observable();
  59667. /**
  59668. * An event triggered before rendering the postprocess
  59669. * @type {BABYLON.Observable}
  59670. */
  59671. this.onBeforeRenderObservable = new BABYLON.Observable();
  59672. /**
  59673. * An event triggered after rendering the postprocess
  59674. * @type {BABYLON.Observable}
  59675. */
  59676. this.onAfterRenderObservable = new BABYLON.Observable();
  59677. if (camera != null) {
  59678. this._camera = camera;
  59679. this._scene = camera.getScene();
  59680. camera.attachPostProcess(this);
  59681. this._engine = this._scene.getEngine();
  59682. this._scene.postProcesses.push(this);
  59683. }
  59684. else if (engine) {
  59685. this._engine = engine;
  59686. this._engine.postProcesses.push(this);
  59687. }
  59688. this._options = options;
  59689. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  59690. this._reusable = reusable || false;
  59691. this._textureType = textureType;
  59692. this._samplers = samplers || [];
  59693. this._samplers.push("textureSampler");
  59694. this._fragmentUrl = fragmentUrl;
  59695. this._vertexUrl = vertexUrl;
  59696. this._parameters = parameters || [];
  59697. this._parameters.push("scale");
  59698. this._indexParameters = indexParameters;
  59699. if (!blockCompilation) {
  59700. this.updateEffect(defines);
  59701. }
  59702. }
  59703. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59704. /**
  59705. * A function that is added to the onActivateObservable
  59706. */
  59707. set: function (callback) {
  59708. if (this._onActivateObserver) {
  59709. this.onActivateObservable.remove(this._onActivateObserver);
  59710. }
  59711. if (callback) {
  59712. this._onActivateObserver = this.onActivateObservable.add(callback);
  59713. }
  59714. },
  59715. enumerable: true,
  59716. configurable: true
  59717. });
  59718. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59719. /**
  59720. * A function that is added to the onSizeChangedObservable
  59721. */
  59722. set: function (callback) {
  59723. if (this._onSizeChangedObserver) {
  59724. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59725. }
  59726. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59727. },
  59728. enumerable: true,
  59729. configurable: true
  59730. });
  59731. Object.defineProperty(PostProcess.prototype, "onApply", {
  59732. /**
  59733. * A function that is added to the onApplyObservable
  59734. */
  59735. set: function (callback) {
  59736. if (this._onApplyObserver) {
  59737. this.onApplyObservable.remove(this._onApplyObserver);
  59738. }
  59739. this._onApplyObserver = this.onApplyObservable.add(callback);
  59740. },
  59741. enumerable: true,
  59742. configurable: true
  59743. });
  59744. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59745. /**
  59746. * A function that is added to the onBeforeRenderObservable
  59747. */
  59748. set: function (callback) {
  59749. if (this._onBeforeRenderObserver) {
  59750. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59751. }
  59752. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59753. },
  59754. enumerable: true,
  59755. configurable: true
  59756. });
  59757. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59758. /**
  59759. * A function that is added to the onAfterRenderObservable
  59760. */
  59761. set: function (callback) {
  59762. if (this._onAfterRenderObserver) {
  59763. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59764. }
  59765. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59766. },
  59767. enumerable: true,
  59768. configurable: true
  59769. });
  59770. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59771. /**
  59772. * 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
  59773. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59774. */
  59775. get: function () {
  59776. return this._textures.data[this._currentRenderTextureInd];
  59777. },
  59778. set: function (value) {
  59779. this._forcedOutputTexture = value;
  59780. },
  59781. enumerable: true,
  59782. configurable: true
  59783. });
  59784. /**
  59785. * Gets the camera which post process is applied to.
  59786. * @returns The camera the post process is applied to.
  59787. */
  59788. PostProcess.prototype.getCamera = function () {
  59789. return this._camera;
  59790. };
  59791. Object.defineProperty(PostProcess.prototype, "texelSize", {
  59792. /**
  59793. * Gets the texel size of the postprocess.
  59794. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  59795. */
  59796. get: function () {
  59797. if (this._shareOutputWithPostProcess) {
  59798. return this._shareOutputWithPostProcess.texelSize;
  59799. }
  59800. if (this._forcedOutputTexture) {
  59801. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  59802. }
  59803. return this._texelSize;
  59804. },
  59805. enumerable: true,
  59806. configurable: true
  59807. });
  59808. /**
  59809. * Gets the engine which this post process belongs to.
  59810. * @returns The engine the post process was enabled with.
  59811. */
  59812. PostProcess.prototype.getEngine = function () {
  59813. return this._engine;
  59814. };
  59815. /**
  59816. * The effect that is created when initializing the post process.
  59817. * @returns The created effect corrisponding the the postprocess.
  59818. */
  59819. PostProcess.prototype.getEffect = function () {
  59820. return this._effect;
  59821. };
  59822. /**
  59823. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  59824. * @param postProcess The post process to share the output with.
  59825. * @returns This post process.
  59826. */
  59827. PostProcess.prototype.shareOutputWith = function (postProcess) {
  59828. this._disposeTextures();
  59829. this._shareOutputWithPostProcess = postProcess;
  59830. return this;
  59831. };
  59832. /**
  59833. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  59834. * This should be called if the post process that shares output with this post process is disabled/disposed.
  59835. */
  59836. PostProcess.prototype.useOwnOutput = function () {
  59837. if (this._textures.length == 0) {
  59838. this._textures = new BABYLON.SmartArray(2);
  59839. }
  59840. this._shareOutputWithPostProcess = null;
  59841. };
  59842. /**
  59843. * Updates the effect with the current post process compile time values and recompiles the shader.
  59844. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59845. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59846. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59847. * @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
  59848. * @param onCompiled Called when the shader has been compiled.
  59849. * @param onError Called if there is an error when compiling a shader.
  59850. */
  59851. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59852. if (defines === void 0) { defines = null; }
  59853. if (uniforms === void 0) { uniforms = null; }
  59854. if (samplers === void 0) { samplers = null; }
  59855. 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);
  59856. };
  59857. /**
  59858. * The post process is reusable if it can be used multiple times within one frame.
  59859. * @returns If the post process is reusable
  59860. */
  59861. PostProcess.prototype.isReusable = function () {
  59862. return this._reusable;
  59863. };
  59864. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59865. PostProcess.prototype.markTextureDirty = function () {
  59866. this.width = -1;
  59867. };
  59868. /**
  59869. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  59870. * 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.
  59871. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  59872. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  59873. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  59874. * @returns The target texture that was bound to be written to.
  59875. */
  59876. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  59877. var _this = this;
  59878. if (sourceTexture === void 0) { sourceTexture = null; }
  59879. camera = camera || this._camera;
  59880. var scene = camera.getScene();
  59881. var engine = scene.getEngine();
  59882. var maxSize = engine.getCaps().maxTextureSize;
  59883. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59884. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59885. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  59886. var webVRCamera = camera.parent;
  59887. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  59888. requiredWidth /= 2;
  59889. }
  59890. var desiredWidth = (this._options.width || requiredWidth);
  59891. var desiredHeight = this._options.height || requiredHeight;
  59892. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59893. if (this.adaptScaleToCurrentViewport) {
  59894. var currentViewport = engine.currentViewport;
  59895. if (currentViewport) {
  59896. desiredWidth *= currentViewport.width;
  59897. desiredHeight *= currentViewport.height;
  59898. }
  59899. }
  59900. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59901. if (!this._options.width) {
  59902. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59903. }
  59904. if (!this._options.height) {
  59905. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59906. }
  59907. }
  59908. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59909. if (this._textures.length > 0) {
  59910. for (var i = 0; i < this._textures.length; i++) {
  59911. this._engine._releaseTexture(this._textures.data[i]);
  59912. }
  59913. this._textures.reset();
  59914. }
  59915. this.width = desiredWidth;
  59916. this.height = desiredHeight;
  59917. var textureSize = { width: this.width, height: this.height };
  59918. var textureOptions = {
  59919. generateMipMaps: false,
  59920. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59921. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59922. samplingMode: this.renderTargetSamplingMode,
  59923. type: this._textureType
  59924. };
  59925. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59926. if (this._reusable) {
  59927. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59928. }
  59929. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59930. this.onSizeChangedObservable.notifyObservers(this);
  59931. }
  59932. this._textures.forEach(function (texture) {
  59933. if (texture.samples !== _this.samples) {
  59934. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59935. }
  59936. });
  59937. }
  59938. var target;
  59939. if (this._shareOutputWithPostProcess) {
  59940. target = this._shareOutputWithPostProcess.inputTexture;
  59941. }
  59942. else if (this._forcedOutputTexture) {
  59943. target = this._forcedOutputTexture;
  59944. this.width = this._forcedOutputTexture.width;
  59945. this.height = this._forcedOutputTexture.height;
  59946. }
  59947. else {
  59948. target = this.inputTexture;
  59949. }
  59950. // Bind the input of this post process to be used as the output of the previous post process.
  59951. if (this.enablePixelPerfectMode) {
  59952. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  59953. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59954. }
  59955. else {
  59956. this._scaleRatio.copyFromFloats(1, 1);
  59957. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59958. }
  59959. this.onActivateObservable.notifyObservers(camera);
  59960. // Clear
  59961. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59962. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59963. }
  59964. if (this._reusable) {
  59965. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59966. }
  59967. return target;
  59968. };
  59969. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59970. /**
  59971. * If the post process is supported.
  59972. */
  59973. get: function () {
  59974. return this._effect.isSupported;
  59975. },
  59976. enumerable: true,
  59977. configurable: true
  59978. });
  59979. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59980. /**
  59981. * The aspect ratio of the output texture.
  59982. */
  59983. get: function () {
  59984. if (this._shareOutputWithPostProcess) {
  59985. return this._shareOutputWithPostProcess.aspectRatio;
  59986. }
  59987. if (this._forcedOutputTexture) {
  59988. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59989. }
  59990. return this.width / this.height;
  59991. },
  59992. enumerable: true,
  59993. configurable: true
  59994. });
  59995. /**
  59996. * Get a value indicating if the post-process is ready to be used
  59997. * @returns true if the post-process is ready (shader is compiled)
  59998. */
  59999. PostProcess.prototype.isReady = function () {
  60000. return this._effect && this._effect.isReady();
  60001. };
  60002. /**
  60003. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60004. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60005. */
  60006. PostProcess.prototype.apply = function () {
  60007. // Check
  60008. if (!this._effect || !this._effect.isReady())
  60009. return null;
  60010. // States
  60011. this._engine.enableEffect(this._effect);
  60012. this._engine.setState(false);
  60013. this._engine.setDepthBuffer(false);
  60014. this._engine.setDepthWrite(false);
  60015. // Alpha
  60016. this._engine.setAlphaMode(this.alphaMode);
  60017. if (this.alphaConstants) {
  60018. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  60019. }
  60020. // Bind the output texture of the preivous post process as the input to this post process.
  60021. var source;
  60022. if (this._shareOutputWithPostProcess) {
  60023. source = this._shareOutputWithPostProcess.inputTexture;
  60024. }
  60025. else if (this._forcedOutputTexture) {
  60026. source = this._forcedOutputTexture;
  60027. }
  60028. else {
  60029. source = this.inputTexture;
  60030. }
  60031. this._effect._bindTexture("textureSampler", source);
  60032. // Parameters
  60033. this._effect.setVector2("scale", this._scaleRatio);
  60034. this.onApplyObservable.notifyObservers(this._effect);
  60035. return this._effect;
  60036. };
  60037. PostProcess.prototype._disposeTextures = function () {
  60038. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  60039. return;
  60040. }
  60041. if (this._textures.length > 0) {
  60042. for (var i = 0; i < this._textures.length; i++) {
  60043. this._engine._releaseTexture(this._textures.data[i]);
  60044. }
  60045. }
  60046. this._textures.dispose();
  60047. };
  60048. /**
  60049. * Disposes the post process.
  60050. * @param camera The camera to dispose the post process on.
  60051. */
  60052. PostProcess.prototype.dispose = function (camera) {
  60053. camera = camera || this._camera;
  60054. this._disposeTextures();
  60055. if (this._scene) {
  60056. var index_1 = this._scene.postProcesses.indexOf(this);
  60057. if (index_1 !== -1) {
  60058. this._scene.postProcesses.splice(index_1, 1);
  60059. }
  60060. }
  60061. else {
  60062. var index_2 = this._engine.postProcesses.indexOf(this);
  60063. if (index_2 !== -1) {
  60064. this._engine.postProcesses.splice(index_2, 1);
  60065. }
  60066. }
  60067. if (!camera) {
  60068. return;
  60069. }
  60070. camera.detachPostProcess(this);
  60071. var index = camera._postProcesses.indexOf(this);
  60072. if (index === 0 && camera._postProcesses.length > 0) {
  60073. var firstPostProcess = this._camera._getFirstPostProcess();
  60074. if (firstPostProcess) {
  60075. firstPostProcess.markTextureDirty();
  60076. }
  60077. }
  60078. this.onActivateObservable.clear();
  60079. this.onAfterRenderObservable.clear();
  60080. this.onApplyObservable.clear();
  60081. this.onBeforeRenderObservable.clear();
  60082. this.onSizeChangedObservable.clear();
  60083. };
  60084. return PostProcess;
  60085. }());
  60086. BABYLON.PostProcess = PostProcess;
  60087. })(BABYLON || (BABYLON = {}));
  60088. //# sourceMappingURL=babylon.postProcess.js.map
  60089. "use strict";
  60090. var BABYLON;
  60091. (function (BABYLON) {
  60092. var PassPostProcess = /** @class */ (function (_super) {
  60093. __extends(PassPostProcess, _super);
  60094. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  60095. if (camera === void 0) { camera = null; }
  60096. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60097. if (blockCompilation === void 0) { blockCompilation = false; }
  60098. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  60099. }
  60100. return PassPostProcess;
  60101. }(BABYLON.PostProcess));
  60102. BABYLON.PassPostProcess = PassPostProcess;
  60103. })(BABYLON || (BABYLON = {}));
  60104. //# sourceMappingURL=babylon.passPostProcess.js.map
  60105. "use strict";
  60106. var __assign = (this && this.__assign) || Object.assign || function(t) {
  60107. for (var s, i = 1, n = arguments.length; i < n; i++) {
  60108. s = arguments[i];
  60109. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  60110. t[p] = s[p];
  60111. }
  60112. return t;
  60113. };
  60114. var BABYLON;
  60115. (function (BABYLON) {
  60116. /**
  60117. * Default implementation of @see IShadowGenerator.
  60118. * This is the main object responsible of generating shadows in the framework.
  60119. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  60120. */
  60121. var ShadowGenerator = /** @class */ (function () {
  60122. /**
  60123. * Creates a ShadowGenerator object.
  60124. * A ShadowGenerator is the required tool to use the shadows.
  60125. * Each light casting shadows needs to use its own ShadowGenerator.
  60126. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  60127. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  60128. * @param light The light object generating the shadows.
  60129. * @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.
  60130. */
  60131. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  60132. this._bias = 0.00005;
  60133. this._normalBias = 0;
  60134. this._blurBoxOffset = 1;
  60135. this._blurScale = 2;
  60136. this._blurKernel = 1;
  60137. this._useKernelBlur = false;
  60138. this._filter = ShadowGenerator.FILTER_NONE;
  60139. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  60140. this._contactHardeningLightSizeUVRatio = 0.1;
  60141. this._darkness = 0;
  60142. this._transparencyShadow = false;
  60143. /**
  60144. * Controls the extent to which the shadows fade out at the edge of the frustum
  60145. * Used only by directionals and spots
  60146. */
  60147. this.frustumEdgeFalloff = 0;
  60148. /**
  60149. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  60150. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  60151. * It might on the other hand introduce peter panning.
  60152. */
  60153. this.forceBackFacesOnly = false;
  60154. this._lightDirection = BABYLON.Vector3.Zero();
  60155. this._viewMatrix = BABYLON.Matrix.Zero();
  60156. this._projectionMatrix = BABYLON.Matrix.Zero();
  60157. this._transformMatrix = BABYLON.Matrix.Zero();
  60158. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60159. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60160. this._currentFaceIndex = 0;
  60161. this._currentFaceIndexCache = 0;
  60162. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  60163. this._mapSize = mapSize;
  60164. this._light = light;
  60165. this._scene = light.getScene();
  60166. light._shadowGenerator = this;
  60167. // Texture type fallback from float to int if not supported.
  60168. var caps = this._scene.getEngine().getCaps();
  60169. if (!useFullFloatFirst) {
  60170. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60171. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60172. }
  60173. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60174. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60175. }
  60176. else {
  60177. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60178. }
  60179. }
  60180. else {
  60181. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60182. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60183. }
  60184. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60185. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60186. }
  60187. else {
  60188. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60189. }
  60190. }
  60191. this._initializeGenerator();
  60192. this._applyFilterValues();
  60193. }
  60194. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60195. /**
  60196. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  60197. */
  60198. get: function () {
  60199. return this._bias;
  60200. },
  60201. /**
  60202. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  60203. */
  60204. set: function (bias) {
  60205. this._bias = bias;
  60206. },
  60207. enumerable: true,
  60208. configurable: true
  60209. });
  60210. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  60211. /**
  60212. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60213. */
  60214. get: function () {
  60215. return this._normalBias;
  60216. },
  60217. /**
  60218. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60219. */
  60220. set: function (normalBias) {
  60221. this._normalBias = normalBias;
  60222. },
  60223. enumerable: true,
  60224. configurable: true
  60225. });
  60226. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  60227. /**
  60228. * Gets the blur box offset: offset applied during the blur pass.
  60229. * Only usefull if useKernelBlur = false
  60230. */
  60231. get: function () {
  60232. return this._blurBoxOffset;
  60233. },
  60234. /**
  60235. * Sets the blur box offset: offset applied during the blur pass.
  60236. * Only usefull if useKernelBlur = false
  60237. */
  60238. set: function (value) {
  60239. if (this._blurBoxOffset === value) {
  60240. return;
  60241. }
  60242. this._blurBoxOffset = value;
  60243. this._disposeBlurPostProcesses();
  60244. },
  60245. enumerable: true,
  60246. configurable: true
  60247. });
  60248. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  60249. /**
  60250. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  60251. * 2 means half of the size.
  60252. */
  60253. get: function () {
  60254. return this._blurScale;
  60255. },
  60256. /**
  60257. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  60258. * 2 means half of the size.
  60259. */
  60260. set: function (value) {
  60261. if (this._blurScale === value) {
  60262. return;
  60263. }
  60264. this._blurScale = value;
  60265. this._disposeBlurPostProcesses();
  60266. },
  60267. enumerable: true,
  60268. configurable: true
  60269. });
  60270. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  60271. /**
  60272. * Gets the blur kernel: kernel size of the blur pass.
  60273. * Only usefull if useKernelBlur = true
  60274. */
  60275. get: function () {
  60276. return this._blurKernel;
  60277. },
  60278. /**
  60279. * Sets the blur kernel: kernel size of the blur pass.
  60280. * Only usefull if useKernelBlur = true
  60281. */
  60282. set: function (value) {
  60283. if (this._blurKernel === value) {
  60284. return;
  60285. }
  60286. this._blurKernel = value;
  60287. this._disposeBlurPostProcesses();
  60288. },
  60289. enumerable: true,
  60290. configurable: true
  60291. });
  60292. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  60293. /**
  60294. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  60295. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60296. */
  60297. get: function () {
  60298. return this._useKernelBlur;
  60299. },
  60300. /**
  60301. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  60302. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60303. */
  60304. set: function (value) {
  60305. if (this._useKernelBlur === value) {
  60306. return;
  60307. }
  60308. this._useKernelBlur = value;
  60309. this._disposeBlurPostProcesses();
  60310. },
  60311. enumerable: true,
  60312. configurable: true
  60313. });
  60314. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  60315. /**
  60316. * Gets the depth scale used in ESM mode.
  60317. */
  60318. get: function () {
  60319. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  60320. },
  60321. /**
  60322. * Sets the depth scale used in ESM mode.
  60323. * This can override the scale stored on the light.
  60324. */
  60325. set: function (value) {
  60326. this._depthScale = value;
  60327. },
  60328. enumerable: true,
  60329. configurable: true
  60330. });
  60331. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  60332. /**
  60333. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  60334. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60335. */
  60336. get: function () {
  60337. return this._filter;
  60338. },
  60339. /**
  60340. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  60341. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60342. */
  60343. set: function (value) {
  60344. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  60345. if (this._light.needCube()) {
  60346. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60347. this.useExponentialShadowMap = true;
  60348. return;
  60349. }
  60350. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60351. this.useCloseExponentialShadowMap = true;
  60352. return;
  60353. }
  60354. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  60355. this.usePoissonSampling = true;
  60356. return;
  60357. }
  60358. }
  60359. // Weblg1 fallback for PCF.
  60360. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  60361. if (this._scene.getEngine().webGLVersion === 1) {
  60362. this.usePoissonSampling = true;
  60363. return;
  60364. }
  60365. }
  60366. if (this._filter === value) {
  60367. return;
  60368. }
  60369. this._filter = value;
  60370. this._disposeBlurPostProcesses();
  60371. this._applyFilterValues();
  60372. this._light._markMeshesAsLightDirty();
  60373. },
  60374. enumerable: true,
  60375. configurable: true
  60376. });
  60377. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  60378. /**
  60379. * Gets if the current filter is set to Poisson Sampling.
  60380. */
  60381. get: function () {
  60382. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  60383. },
  60384. /**
  60385. * Sets the current filter to Poisson Sampling.
  60386. */
  60387. set: function (value) {
  60388. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  60389. return;
  60390. }
  60391. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  60392. },
  60393. enumerable: true,
  60394. configurable: true
  60395. });
  60396. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  60397. /**
  60398. * Gets if the current filter is set to VSM.
  60399. * DEPRECATED. Should use useExponentialShadowMap instead.
  60400. */
  60401. get: function () {
  60402. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60403. return this.useExponentialShadowMap;
  60404. },
  60405. /**
  60406. * Sets the current filter is to VSM.
  60407. * DEPRECATED. Should use useExponentialShadowMap instead.
  60408. */
  60409. set: function (value) {
  60410. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60411. this.useExponentialShadowMap = value;
  60412. },
  60413. enumerable: true,
  60414. configurable: true
  60415. });
  60416. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  60417. /**
  60418. * Gets if the current filter is set to blurred VSM.
  60419. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60420. */
  60421. get: function () {
  60422. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60423. return this.useBlurExponentialShadowMap;
  60424. },
  60425. /**
  60426. * Sets the current filter is to blurred VSM.
  60427. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60428. */
  60429. set: function (value) {
  60430. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60431. this.useBlurExponentialShadowMap = value;
  60432. },
  60433. enumerable: true,
  60434. configurable: true
  60435. });
  60436. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  60437. /**
  60438. * Gets if the current filter is set to ESM.
  60439. */
  60440. get: function () {
  60441. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  60442. },
  60443. /**
  60444. * Sets the current filter is to ESM.
  60445. */
  60446. set: function (value) {
  60447. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  60448. return;
  60449. }
  60450. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60451. },
  60452. enumerable: true,
  60453. configurable: true
  60454. });
  60455. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  60456. /**
  60457. * Gets if the current filter is set to filtered ESM.
  60458. */
  60459. get: function () {
  60460. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  60461. },
  60462. /**
  60463. * Gets if the current filter is set to filtered ESM.
  60464. */
  60465. set: function (value) {
  60466. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60467. return;
  60468. }
  60469. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60470. },
  60471. enumerable: true,
  60472. configurable: true
  60473. });
  60474. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  60475. /**
  60476. * Gets if the current filter is set to "close ESM" (using the inverse of the
  60477. * exponential to prevent steep falloff artifacts).
  60478. */
  60479. get: function () {
  60480. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60481. },
  60482. /**
  60483. * Sets the current filter to "close ESM" (using the inverse of the
  60484. * exponential to prevent steep falloff artifacts).
  60485. */
  60486. set: function (value) {
  60487. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  60488. return;
  60489. }
  60490. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60491. },
  60492. enumerable: true,
  60493. configurable: true
  60494. });
  60495. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  60496. /**
  60497. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  60498. * exponential to prevent steep falloff artifacts).
  60499. */
  60500. get: function () {
  60501. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60502. },
  60503. /**
  60504. * Sets the current filter to filtered "close ESM" (using the inverse of the
  60505. * exponential to prevent steep falloff artifacts).
  60506. */
  60507. set: function (value) {
  60508. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60509. return;
  60510. }
  60511. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60512. },
  60513. enumerable: true,
  60514. configurable: true
  60515. });
  60516. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  60517. /**
  60518. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  60519. */
  60520. get: function () {
  60521. return this.filter === ShadowGenerator.FILTER_PCF;
  60522. },
  60523. /**
  60524. * Sets the current filter to "PCF" (percentage closer filtering).
  60525. */
  60526. set: function (value) {
  60527. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  60528. return;
  60529. }
  60530. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  60531. },
  60532. enumerable: true,
  60533. configurable: true
  60534. });
  60535. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  60536. /**
  60537. * Gets the PCF or PCSS Quality.
  60538. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  60539. */
  60540. get: function () {
  60541. return this._filteringQuality;
  60542. },
  60543. /**
  60544. * Sets the PCF or PCSS Quality.
  60545. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  60546. */
  60547. set: function (filteringQuality) {
  60548. this._filteringQuality = filteringQuality;
  60549. },
  60550. enumerable: true,
  60551. configurable: true
  60552. });
  60553. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  60554. /**
  60555. * Gets if the current filter is set to "PCSS" (contact hardening).
  60556. */
  60557. get: function () {
  60558. return this.filter === ShadowGenerator.FILTER_PCSS;
  60559. },
  60560. /**
  60561. * Sets the current filter to "PCSS" (contact hardening).
  60562. */
  60563. set: function (value) {
  60564. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  60565. return;
  60566. }
  60567. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  60568. },
  60569. enumerable: true,
  60570. configurable: true
  60571. });
  60572. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  60573. /**
  60574. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  60575. * Using a ratio helps keeping shape stability independently of the map size.
  60576. *
  60577. * It does not account for the light projection as it was having too much
  60578. * instability during the light setup or during light position changes.
  60579. *
  60580. * Only valid if useContactHardeningShadow is true.
  60581. */
  60582. get: function () {
  60583. return this._contactHardeningLightSizeUVRatio;
  60584. },
  60585. /**
  60586. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  60587. * Using a ratio helps keeping shape stability independently of the map size.
  60588. *
  60589. * It does not account for the light projection as it was having too much
  60590. * instability during the light setup or during light position changes.
  60591. *
  60592. * Only valid if useContactHardeningShadow is true.
  60593. */
  60594. set: function (contactHardeningLightSizeUVRatio) {
  60595. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  60596. },
  60597. enumerable: true,
  60598. configurable: true
  60599. });
  60600. /**
  60601. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  60602. * 0 means strongest and 1 would means no shadow.
  60603. * @returns the darkness.
  60604. */
  60605. ShadowGenerator.prototype.getDarkness = function () {
  60606. return this._darkness;
  60607. };
  60608. /**
  60609. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  60610. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  60611. * @returns the shadow generator allowing fluent coding.
  60612. */
  60613. ShadowGenerator.prototype.setDarkness = function (darkness) {
  60614. if (darkness >= 1.0)
  60615. this._darkness = 1.0;
  60616. else if (darkness <= 0.0)
  60617. this._darkness = 0.0;
  60618. else
  60619. this._darkness = darkness;
  60620. return this;
  60621. };
  60622. /**
  60623. * Sets the ability to have transparent shadow (boolean).
  60624. * @param transparent True if transparent else False
  60625. * @returns the shadow generator allowing fluent coding
  60626. */
  60627. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  60628. this._transparencyShadow = transparent;
  60629. return this;
  60630. };
  60631. /**
  60632. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  60633. * @returns The render target texture if present otherwise, null
  60634. */
  60635. ShadowGenerator.prototype.getShadowMap = function () {
  60636. return this._shadowMap;
  60637. };
  60638. /**
  60639. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  60640. * @returns The render target texture if the shadow map is present otherwise, null
  60641. */
  60642. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  60643. if (this._shadowMap2) {
  60644. return this._shadowMap2;
  60645. }
  60646. return this._shadowMap;
  60647. };
  60648. /**
  60649. * Helper function to add a mesh and its descendants to the list of shadow casters.
  60650. * @param mesh Mesh to add
  60651. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  60652. * @returns the Shadow Generator itself
  60653. */
  60654. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  60655. if (includeDescendants === void 0) { includeDescendants = true; }
  60656. if (!this._shadowMap) {
  60657. return this;
  60658. }
  60659. if (!this._shadowMap.renderList) {
  60660. this._shadowMap.renderList = [];
  60661. }
  60662. this._shadowMap.renderList.push(mesh);
  60663. if (includeDescendants) {
  60664. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  60665. }
  60666. return this;
  60667. var _a;
  60668. };
  60669. /**
  60670. * Helper function to remove a mesh and its descendants from the list of shadow casters
  60671. * @param mesh Mesh to remove
  60672. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  60673. * @returns the Shadow Generator itself
  60674. */
  60675. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  60676. if (includeDescendants === void 0) { includeDescendants = true; }
  60677. if (!this._shadowMap || !this._shadowMap.renderList) {
  60678. return this;
  60679. }
  60680. var index = this._shadowMap.renderList.indexOf(mesh);
  60681. if (index !== -1) {
  60682. this._shadowMap.renderList.splice(index, 1);
  60683. }
  60684. if (includeDescendants) {
  60685. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  60686. var child = _a[_i];
  60687. this.removeShadowCaster(child);
  60688. }
  60689. }
  60690. return this;
  60691. };
  60692. /**
  60693. * Returns the associated light object.
  60694. * @returns the light generating the shadow
  60695. */
  60696. ShadowGenerator.prototype.getLight = function () {
  60697. return this._light;
  60698. };
  60699. ShadowGenerator.prototype._initializeGenerator = function () {
  60700. this._light._markMeshesAsLightDirty();
  60701. this._initializeShadowMap();
  60702. };
  60703. ShadowGenerator.prototype._initializeShadowMap = function () {
  60704. var _this = this;
  60705. // Render target
  60706. var engine = this._scene.getEngine();
  60707. if (engine.webGLVersion > 1) {
  60708. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  60709. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  60710. }
  60711. else {
  60712. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  60713. }
  60714. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60715. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60716. this._shadowMap.anisotropicFilteringLevel = 1;
  60717. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60718. this._shadowMap.renderParticles = false;
  60719. this._shadowMap.ignoreCameraViewport = true;
  60720. // Record Face Index before render.
  60721. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  60722. _this._currentFaceIndex = faceIndex;
  60723. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  60724. engine.setColorWrite(false);
  60725. }
  60726. });
  60727. // Custom render function.
  60728. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  60729. // Blur if required afer render.
  60730. this._shadowMap.onAfterUnbindObservable.add(function () {
  60731. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  60732. engine.setColorWrite(true);
  60733. }
  60734. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  60735. return;
  60736. }
  60737. var shadowMap = _this.getShadowMapForRendering();
  60738. if (shadowMap) {
  60739. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  60740. }
  60741. });
  60742. // Clear according to the chosen filter.
  60743. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  60744. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60745. this._shadowMap.onClearObservable.add(function (engine) {
  60746. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  60747. engine.clear(clearOne, false, true, false);
  60748. }
  60749. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  60750. engine.clear(clearZero, true, true, false);
  60751. }
  60752. else {
  60753. engine.clear(clearOne, true, true, false);
  60754. }
  60755. });
  60756. };
  60757. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  60758. var _this = this;
  60759. var engine = this._scene.getEngine();
  60760. var targetSize = this._mapSize / this.blurScale;
  60761. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  60762. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60763. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60764. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60765. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60766. }
  60767. if (this.useKernelBlur) {
  60768. 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);
  60769. this._kernelBlurXPostprocess.width = targetSize;
  60770. this._kernelBlurXPostprocess.height = targetSize;
  60771. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60772. effect.setTexture("textureSampler", _this._shadowMap);
  60773. });
  60774. 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);
  60775. this._kernelBlurXPostprocess.autoClear = false;
  60776. this._kernelBlurYPostprocess.autoClear = false;
  60777. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60778. this._kernelBlurXPostprocess.packedFloat = true;
  60779. this._kernelBlurYPostprocess.packedFloat = true;
  60780. }
  60781. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60782. }
  60783. else {
  60784. 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);
  60785. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  60786. effect.setFloat2("screenSize", targetSize, targetSize);
  60787. effect.setTexture("textureSampler", _this._shadowMap);
  60788. });
  60789. this._boxBlurPostprocess.autoClear = false;
  60790. this._blurPostProcesses = [this._boxBlurPostprocess];
  60791. }
  60792. };
  60793. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60794. var index;
  60795. var engine = this._scene.getEngine();
  60796. if (depthOnlySubMeshes.length) {
  60797. engine.setColorWrite(false);
  60798. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60799. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  60800. }
  60801. engine.setColorWrite(true);
  60802. }
  60803. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60804. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  60805. }
  60806. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60807. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  60808. }
  60809. if (this._transparencyShadow) {
  60810. for (index = 0; index < transparentSubMeshes.length; index++) {
  60811. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  60812. }
  60813. }
  60814. };
  60815. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  60816. var _this = this;
  60817. var mesh = subMesh.getRenderingMesh();
  60818. var scene = this._scene;
  60819. var engine = scene.getEngine();
  60820. var material = subMesh.getMaterial();
  60821. if (!material) {
  60822. return;
  60823. }
  60824. // Culling
  60825. engine.setState(material.backFaceCulling);
  60826. // Managing instances
  60827. var batch = mesh._getInstancesRenderList(subMesh._id);
  60828. if (batch.mustReturn) {
  60829. return;
  60830. }
  60831. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60832. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  60833. engine.enableEffect(this._effect);
  60834. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60835. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  60836. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  60837. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  60838. this._effect.setVector3("lightData", this._cachedDirection);
  60839. }
  60840. else {
  60841. this._effect.setVector3("lightData", this._cachedPosition);
  60842. }
  60843. if (scene.activeCamera) {
  60844. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  60845. }
  60846. // Alpha test
  60847. if (material && material.needAlphaTesting()) {
  60848. var alphaTexture = material.getAlphaTestTexture();
  60849. if (alphaTexture) {
  60850. this._effect.setTexture("diffuseSampler", alphaTexture);
  60851. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  60852. }
  60853. }
  60854. // Bones
  60855. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60856. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  60857. }
  60858. if (this.forceBackFacesOnly) {
  60859. engine.setState(true, 0, false, true);
  60860. }
  60861. // Draw
  60862. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60863. if (this.forceBackFacesOnly) {
  60864. engine.setState(true, 0, false, false);
  60865. }
  60866. }
  60867. else {
  60868. // Need to reset refresh rate of the shadowMap
  60869. if (this._shadowMap) {
  60870. this._shadowMap.resetRefreshCounter();
  60871. }
  60872. }
  60873. };
  60874. ShadowGenerator.prototype._applyFilterValues = function () {
  60875. if (!this._shadowMap) {
  60876. return;
  60877. }
  60878. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  60879. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60880. }
  60881. else {
  60882. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60883. }
  60884. };
  60885. /**
  60886. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60887. * @param onCompiled Callback triggered at the and of the effects compilation
  60888. * @param options Sets of optional options forcing the compilation with different modes
  60889. */
  60890. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  60891. var _this = this;
  60892. var localOptions = __assign({ useInstances: false }, options);
  60893. var shadowMap = this.getShadowMap();
  60894. if (!shadowMap) {
  60895. if (onCompiled) {
  60896. onCompiled(this);
  60897. }
  60898. return;
  60899. }
  60900. var renderList = shadowMap.renderList;
  60901. if (!renderList) {
  60902. if (onCompiled) {
  60903. onCompiled(this);
  60904. }
  60905. return;
  60906. }
  60907. var subMeshes = new Array();
  60908. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  60909. var mesh = renderList_1[_i];
  60910. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60911. }
  60912. if (subMeshes.length === 0) {
  60913. if (onCompiled) {
  60914. onCompiled(this);
  60915. }
  60916. return;
  60917. }
  60918. var currentIndex = 0;
  60919. var checkReady = function () {
  60920. if (!_this._scene || !_this._scene.getEngine()) {
  60921. return;
  60922. }
  60923. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60924. currentIndex++;
  60925. if (currentIndex >= subMeshes.length) {
  60926. if (onCompiled) {
  60927. onCompiled(_this);
  60928. }
  60929. return;
  60930. }
  60931. }
  60932. setTimeout(checkReady, 16);
  60933. };
  60934. checkReady();
  60935. };
  60936. /**
  60937. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60938. * @param options Sets of optional options forcing the compilation with different modes
  60939. * @returns A promise that resolves when the compilation completes
  60940. */
  60941. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  60942. var _this = this;
  60943. return new Promise(function (resolve) {
  60944. _this.forceCompilation(function () {
  60945. resolve();
  60946. }, options);
  60947. });
  60948. };
  60949. /**
  60950. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  60951. * @param subMesh The submesh we want to render in the shadow map
  60952. * @param useInstances Defines wether will draw in the map using instances
  60953. * @returns true if ready otherwise, false
  60954. */
  60955. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  60956. var defines = [];
  60957. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60958. defines.push("#define FLOAT");
  60959. }
  60960. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60961. defines.push("#define ESM");
  60962. }
  60963. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  60964. defines.push("#define DEPTHTEXTURE");
  60965. }
  60966. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60967. var mesh = subMesh.getMesh();
  60968. var material = subMesh.getMaterial();
  60969. // Normal bias.
  60970. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  60971. attribs.push(BABYLON.VertexBuffer.NormalKind);
  60972. defines.push("#define NORMAL");
  60973. if (mesh.nonUniformScaling) {
  60974. defines.push("#define NONUNIFORMSCALING");
  60975. }
  60976. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  60977. defines.push("#define DIRECTIONINLIGHTDATA");
  60978. }
  60979. }
  60980. // Alpha test
  60981. if (material && material.needAlphaTesting()) {
  60982. var alphaTexture = material.getAlphaTestTexture();
  60983. if (alphaTexture) {
  60984. defines.push("#define ALPHATEST");
  60985. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60986. attribs.push(BABYLON.VertexBuffer.UVKind);
  60987. defines.push("#define UV1");
  60988. }
  60989. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60990. if (alphaTexture.coordinatesIndex === 1) {
  60991. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60992. defines.push("#define UV2");
  60993. }
  60994. }
  60995. }
  60996. }
  60997. // Bones
  60998. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60999. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61000. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61001. if (mesh.numBoneInfluencers > 4) {
  61002. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61003. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61004. }
  61005. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61006. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61007. }
  61008. else {
  61009. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61010. }
  61011. // Instances
  61012. if (useInstances) {
  61013. defines.push("#define INSTANCES");
  61014. attribs.push("world0");
  61015. attribs.push("world1");
  61016. attribs.push("world2");
  61017. attribs.push("world3");
  61018. }
  61019. // Get correct effect
  61020. var join = defines.join("\n");
  61021. if (this._cachedDefines !== join) {
  61022. this._cachedDefines = join;
  61023. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  61024. }
  61025. if (!this._effect.isReady()) {
  61026. return false;
  61027. }
  61028. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61029. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  61030. this._initializeBlurRTTAndPostProcesses();
  61031. }
  61032. }
  61033. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  61034. return false;
  61035. }
  61036. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  61037. return false;
  61038. }
  61039. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  61040. return false;
  61041. }
  61042. return true;
  61043. };
  61044. /**
  61045. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  61046. * @param defines Defines of the material we want to update
  61047. * @param lightIndex Index of the light in the enabled light list of the material
  61048. */
  61049. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  61050. var scene = this._scene;
  61051. var light = this._light;
  61052. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61053. return;
  61054. }
  61055. defines["SHADOW" + lightIndex] = true;
  61056. if (this.useContactHardeningShadow) {
  61057. defines["SHADOWPCSS" + lightIndex] = true;
  61058. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61059. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61060. }
  61061. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61062. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61063. }
  61064. // else default to high.
  61065. }
  61066. if (this.usePercentageCloserFiltering) {
  61067. defines["SHADOWPCF" + lightIndex] = true;
  61068. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61069. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61070. }
  61071. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61072. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61073. }
  61074. // else default to high.
  61075. }
  61076. else if (this.usePoissonSampling) {
  61077. defines["SHADOWPOISSON" + lightIndex] = true;
  61078. }
  61079. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61080. defines["SHADOWESM" + lightIndex] = true;
  61081. }
  61082. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61083. defines["SHADOWCLOSEESM" + lightIndex] = true;
  61084. }
  61085. if (light.needCube()) {
  61086. defines["SHADOWCUBE" + lightIndex] = true;
  61087. }
  61088. };
  61089. /**
  61090. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  61091. * defined in the generator but impacting the effect).
  61092. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  61093. * @param effect The effect we are binfing the information for
  61094. */
  61095. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  61096. var light = this._light;
  61097. var scene = this._scene;
  61098. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61099. return;
  61100. }
  61101. var camera = scene.activeCamera;
  61102. if (!camera) {
  61103. return;
  61104. }
  61105. var shadowMap = this.getShadowMap();
  61106. if (!shadowMap) {
  61107. return;
  61108. }
  61109. if (!light.needCube()) {
  61110. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  61111. }
  61112. // Only PCF uses depth stencil texture.
  61113. if (this._filter === ShadowGenerator.FILTER_PCF) {
  61114. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61115. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61116. }
  61117. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  61118. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61119. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  61120. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61121. }
  61122. else {
  61123. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61124. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  61125. }
  61126. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  61127. };
  61128. /**
  61129. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  61130. * (eq to shadow prjection matrix * light transform matrix)
  61131. * @returns The transform matrix used to create the shadow map
  61132. */
  61133. ShadowGenerator.prototype.getTransformMatrix = function () {
  61134. var scene = this._scene;
  61135. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  61136. return this._transformMatrix;
  61137. }
  61138. this._currentRenderID = scene.getRenderId();
  61139. this._currentFaceIndexCache = this._currentFaceIndex;
  61140. var lightPosition = this._light.position;
  61141. if (this._light.computeTransformedInformation()) {
  61142. lightPosition = this._light.transformedPosition;
  61143. }
  61144. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  61145. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  61146. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  61147. }
  61148. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  61149. this._cachedPosition.copyFrom(lightPosition);
  61150. this._cachedDirection.copyFrom(this._lightDirection);
  61151. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  61152. var shadowMap = this.getShadowMap();
  61153. if (shadowMap) {
  61154. var renderList = shadowMap.renderList;
  61155. if (renderList) {
  61156. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  61157. }
  61158. }
  61159. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  61160. }
  61161. return this._transformMatrix;
  61162. };
  61163. /**
  61164. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  61165. * Cube and 2D textures for instance.
  61166. */
  61167. ShadowGenerator.prototype.recreateShadowMap = function () {
  61168. var shadowMap = this._shadowMap;
  61169. if (!shadowMap) {
  61170. return;
  61171. }
  61172. // Track render list.
  61173. var renderList = shadowMap.renderList;
  61174. // Clean up existing data.
  61175. this._disposeRTTandPostProcesses();
  61176. // Reinitializes.
  61177. this._initializeGenerator();
  61178. // Reaffect the filter to ensure a correct fallback if necessary.
  61179. this.filter = this.filter;
  61180. // Reaffect the filter.
  61181. this._applyFilterValues();
  61182. // Reaffect Render List.
  61183. this._shadowMap.renderList = renderList;
  61184. };
  61185. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  61186. if (this._shadowMap2) {
  61187. this._shadowMap2.dispose();
  61188. this._shadowMap2 = null;
  61189. }
  61190. if (this._boxBlurPostprocess) {
  61191. this._boxBlurPostprocess.dispose();
  61192. this._boxBlurPostprocess = null;
  61193. }
  61194. if (this._kernelBlurXPostprocess) {
  61195. this._kernelBlurXPostprocess.dispose();
  61196. this._kernelBlurXPostprocess = null;
  61197. }
  61198. if (this._kernelBlurYPostprocess) {
  61199. this._kernelBlurYPostprocess.dispose();
  61200. this._kernelBlurYPostprocess = null;
  61201. }
  61202. this._blurPostProcesses = [];
  61203. };
  61204. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  61205. if (this._shadowMap) {
  61206. this._shadowMap.dispose();
  61207. this._shadowMap = null;
  61208. }
  61209. this._disposeBlurPostProcesses();
  61210. };
  61211. /**
  61212. * Disposes the ShadowGenerator.
  61213. * Returns nothing.
  61214. */
  61215. ShadowGenerator.prototype.dispose = function () {
  61216. this._disposeRTTandPostProcesses();
  61217. if (this._light) {
  61218. this._light._shadowGenerator = null;
  61219. this._light._markMeshesAsLightDirty();
  61220. }
  61221. };
  61222. /**
  61223. * Serializes the shadow generator setup to a json object.
  61224. * @returns The serialized JSON object
  61225. */
  61226. ShadowGenerator.prototype.serialize = function () {
  61227. var serializationObject = {};
  61228. var shadowMap = this.getShadowMap();
  61229. if (!shadowMap) {
  61230. return serializationObject;
  61231. }
  61232. serializationObject.lightId = this._light.id;
  61233. serializationObject.mapSize = shadowMap.getRenderSize();
  61234. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  61235. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  61236. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61237. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61238. serializationObject.usePoissonSampling = this.usePoissonSampling;
  61239. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  61240. serializationObject.depthScale = this.depthScale;
  61241. serializationObject.darkness = this.getDarkness();
  61242. serializationObject.blurBoxOffset = this.blurBoxOffset;
  61243. serializationObject.blurKernel = this.blurKernel;
  61244. serializationObject.blurScale = this.blurScale;
  61245. serializationObject.useKernelBlur = this.useKernelBlur;
  61246. serializationObject.transparencyShadow = this._transparencyShadow;
  61247. serializationObject.bias = this.bias;
  61248. serializationObject.normalBias = this.normalBias;
  61249. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  61250. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  61251. serializationObject.filteringQuality = this.filteringQuality;
  61252. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  61253. serializationObject.renderList = [];
  61254. if (shadowMap.renderList) {
  61255. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  61256. var mesh = shadowMap.renderList[meshIndex];
  61257. serializationObject.renderList.push(mesh.id);
  61258. }
  61259. }
  61260. return serializationObject;
  61261. };
  61262. /**
  61263. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  61264. * @param parsedShadowGenerator The JSON object to parse
  61265. * @param scene The scene to create the shadow map for
  61266. * @returns The parsed shadow generator
  61267. */
  61268. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  61269. //casting to point light, as light is missing the position attr and typescript complains.
  61270. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  61271. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  61272. var shadowMap = shadowGenerator.getShadowMap();
  61273. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  61274. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  61275. meshes.forEach(function (mesh) {
  61276. if (!shadowMap) {
  61277. return;
  61278. }
  61279. if (!shadowMap.renderList) {
  61280. shadowMap.renderList = [];
  61281. }
  61282. shadowMap.renderList.push(mesh);
  61283. });
  61284. }
  61285. if (parsedShadowGenerator.usePoissonSampling) {
  61286. shadowGenerator.usePoissonSampling = true;
  61287. }
  61288. else if (parsedShadowGenerator.useExponentialShadowMap) {
  61289. shadowGenerator.useExponentialShadowMap = true;
  61290. }
  61291. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  61292. shadowGenerator.useBlurExponentialShadowMap = true;
  61293. }
  61294. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  61295. shadowGenerator.useCloseExponentialShadowMap = true;
  61296. }
  61297. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  61298. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  61299. }
  61300. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  61301. shadowGenerator.usePercentageCloserFiltering = true;
  61302. }
  61303. else if (parsedShadowGenerator.useContactHardeningShadow) {
  61304. shadowGenerator.useContactHardeningShadow = true;
  61305. }
  61306. if (parsedShadowGenerator.filteringQuality) {
  61307. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  61308. }
  61309. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  61310. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  61311. }
  61312. else if (parsedShadowGenerator.useVarianceShadowMap) {
  61313. shadowGenerator.useExponentialShadowMap = true;
  61314. }
  61315. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  61316. shadowGenerator.useBlurExponentialShadowMap = true;
  61317. }
  61318. if (parsedShadowGenerator.depthScale) {
  61319. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  61320. }
  61321. if (parsedShadowGenerator.blurScale) {
  61322. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  61323. }
  61324. if (parsedShadowGenerator.blurBoxOffset) {
  61325. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  61326. }
  61327. if (parsedShadowGenerator.useKernelBlur) {
  61328. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  61329. }
  61330. if (parsedShadowGenerator.blurKernel) {
  61331. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  61332. }
  61333. if (parsedShadowGenerator.bias !== undefined) {
  61334. shadowGenerator.bias = parsedShadowGenerator.bias;
  61335. }
  61336. if (parsedShadowGenerator.normalBias !== undefined) {
  61337. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  61338. }
  61339. if (parsedShadowGenerator.darkness) {
  61340. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  61341. }
  61342. if (parsedShadowGenerator.transparencyShadow) {
  61343. shadowGenerator.setTransparencyShadow(true);
  61344. }
  61345. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  61346. return shadowGenerator;
  61347. };
  61348. /**
  61349. * Shadow generator mode None: no filtering applied.
  61350. */
  61351. ShadowGenerator.FILTER_NONE = 0;
  61352. /**
  61353. * Shadow generator mode ESM: Exponential Shadow Mapping.
  61354. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61355. */
  61356. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  61357. /**
  61358. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  61359. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  61360. */
  61361. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  61362. /**
  61363. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  61364. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61365. */
  61366. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  61367. /**
  61368. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  61369. * edge artifacts on steep falloff.
  61370. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61371. */
  61372. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  61373. /**
  61374. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  61375. * edge artifacts on steep falloff.
  61376. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61377. */
  61378. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  61379. /**
  61380. * Shadow generator mode PCF: Percentage Closer Filtering
  61381. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  61382. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  61383. */
  61384. ShadowGenerator.FILTER_PCF = 6;
  61385. /**
  61386. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  61387. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  61388. * Contact Hardening
  61389. */
  61390. ShadowGenerator.FILTER_PCSS = 7;
  61391. /**
  61392. * Reserved for PCF and PCSS
  61393. * Highest Quality.
  61394. *
  61395. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  61396. *
  61397. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  61398. */
  61399. ShadowGenerator.QUALITY_HIGH = 0;
  61400. /**
  61401. * Reserved for PCF and PCSS
  61402. * Good tradeoff for quality/perf cross devices
  61403. *
  61404. * Execute PCF on a 3*3 kernel.
  61405. *
  61406. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  61407. */
  61408. ShadowGenerator.QUALITY_MEDIUM = 1;
  61409. /**
  61410. * Reserved for PCF and PCSS
  61411. * The lowest quality but the fastest.
  61412. *
  61413. * Execute PCF on a 1*1 kernel.
  61414. *
  61415. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  61416. */
  61417. ShadowGenerator.QUALITY_LOW = 2;
  61418. return ShadowGenerator;
  61419. }());
  61420. BABYLON.ShadowGenerator = ShadowGenerator;
  61421. })(BABYLON || (BABYLON = {}));
  61422. //# sourceMappingURL=babylon.shadowGenerator.js.map
  61423. "use strict";
  61424. var BABYLON;
  61425. (function (BABYLON) {
  61426. var DefaultLoadingScreen = /** @class */ (function () {
  61427. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  61428. if (_loadingText === void 0) { _loadingText = ""; }
  61429. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  61430. var _this = this;
  61431. this._renderingCanvas = _renderingCanvas;
  61432. this._loadingText = _loadingText;
  61433. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  61434. // Resize
  61435. this._resizeLoadingUI = function () {
  61436. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  61437. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  61438. if (!_this._loadingDiv) {
  61439. return;
  61440. }
  61441. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  61442. _this._loadingDiv.style.left = canvasRect.left + "px";
  61443. _this._loadingDiv.style.top = canvasRect.top + "px";
  61444. _this._loadingDiv.style.width = canvasRect.width + "px";
  61445. _this._loadingDiv.style.height = canvasRect.height + "px";
  61446. };
  61447. }
  61448. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  61449. if (this._loadingDiv) {
  61450. // Do not add a loading screen if there is already one
  61451. return;
  61452. }
  61453. this._loadingDiv = document.createElement("div");
  61454. this._loadingDiv.id = "babylonjsLoadingDiv";
  61455. this._loadingDiv.style.opacity = "0";
  61456. this._loadingDiv.style.transition = "opacity 1.5s ease";
  61457. this._loadingDiv.style.pointerEvents = "none";
  61458. // Loading text
  61459. this._loadingTextDiv = document.createElement("div");
  61460. this._loadingTextDiv.style.position = "absolute";
  61461. this._loadingTextDiv.style.left = "0";
  61462. this._loadingTextDiv.style.top = "50%";
  61463. this._loadingTextDiv.style.marginTop = "80px";
  61464. this._loadingTextDiv.style.width = "100%";
  61465. this._loadingTextDiv.style.height = "20px";
  61466. this._loadingTextDiv.style.fontFamily = "Arial";
  61467. this._loadingTextDiv.style.fontSize = "14px";
  61468. this._loadingTextDiv.style.color = "white";
  61469. this._loadingTextDiv.style.textAlign = "center";
  61470. this._loadingTextDiv.innerHTML = "Loading";
  61471. this._loadingDiv.appendChild(this._loadingTextDiv);
  61472. //set the predefined text
  61473. this._loadingTextDiv.innerHTML = this._loadingText;
  61474. // Generating keyframes
  61475. var style = document.createElement('style');
  61476. style.type = 'text/css';
  61477. 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 }";
  61478. style.innerHTML = keyFrames;
  61479. document.getElementsByTagName('head')[0].appendChild(style);
  61480. // Loading img
  61481. var imgBack = new Image();
  61482. 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";
  61483. imgBack.style.position = "absolute";
  61484. imgBack.style.left = "50%";
  61485. imgBack.style.top = "50%";
  61486. imgBack.style.marginLeft = "-60px";
  61487. imgBack.style.marginTop = "-60px";
  61488. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  61489. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  61490. imgBack.style.transformOrigin = "50% 50%";
  61491. imgBack.style.webkitTransformOrigin = "50% 50%";
  61492. this._loadingDiv.appendChild(imgBack);
  61493. this._resizeLoadingUI();
  61494. window.addEventListener("resize", this._resizeLoadingUI);
  61495. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61496. document.body.appendChild(this._loadingDiv);
  61497. this._loadingDiv.style.opacity = "1";
  61498. };
  61499. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  61500. var _this = this;
  61501. if (!this._loadingDiv) {
  61502. return;
  61503. }
  61504. var onTransitionEnd = function () {
  61505. if (!_this._loadingDiv) {
  61506. return;
  61507. }
  61508. document.body.removeChild(_this._loadingDiv);
  61509. window.removeEventListener("resize", _this._resizeLoadingUI);
  61510. _this._loadingDiv = null;
  61511. };
  61512. this._loadingDiv.style.opacity = "0";
  61513. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  61514. };
  61515. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  61516. set: function (text) {
  61517. this._loadingText = text;
  61518. if (this._loadingTextDiv) {
  61519. this._loadingTextDiv.innerHTML = this._loadingText;
  61520. }
  61521. },
  61522. enumerable: true,
  61523. configurable: true
  61524. });
  61525. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  61526. get: function () {
  61527. return this._loadingDivBackgroundColor;
  61528. },
  61529. set: function (color) {
  61530. this._loadingDivBackgroundColor = color;
  61531. if (!this._loadingDiv) {
  61532. return;
  61533. }
  61534. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61535. },
  61536. enumerable: true,
  61537. configurable: true
  61538. });
  61539. return DefaultLoadingScreen;
  61540. }());
  61541. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  61542. })(BABYLON || (BABYLON = {}));
  61543. //# sourceMappingURL=babylon.loadingScreen.js.map
  61544. "use strict";
  61545. var BABYLON;
  61546. (function (BABYLON) {
  61547. var SceneLoaderProgressEvent = /** @class */ (function () {
  61548. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  61549. this.lengthComputable = lengthComputable;
  61550. this.loaded = loaded;
  61551. this.total = total;
  61552. }
  61553. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  61554. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  61555. };
  61556. return SceneLoaderProgressEvent;
  61557. }());
  61558. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  61559. var SceneLoader = /** @class */ (function () {
  61560. function SceneLoader() {
  61561. }
  61562. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  61563. get: function () {
  61564. return 0;
  61565. },
  61566. enumerable: true,
  61567. configurable: true
  61568. });
  61569. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  61570. get: function () {
  61571. return 1;
  61572. },
  61573. enumerable: true,
  61574. configurable: true
  61575. });
  61576. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  61577. get: function () {
  61578. return 2;
  61579. },
  61580. enumerable: true,
  61581. configurable: true
  61582. });
  61583. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  61584. get: function () {
  61585. return 3;
  61586. },
  61587. enumerable: true,
  61588. configurable: true
  61589. });
  61590. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  61591. get: function () {
  61592. return SceneLoader._ForceFullSceneLoadingForIncremental;
  61593. },
  61594. set: function (value) {
  61595. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  61596. },
  61597. enumerable: true,
  61598. configurable: true
  61599. });
  61600. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  61601. get: function () {
  61602. return SceneLoader._ShowLoadingScreen;
  61603. },
  61604. set: function (value) {
  61605. SceneLoader._ShowLoadingScreen = value;
  61606. },
  61607. enumerable: true,
  61608. configurable: true
  61609. });
  61610. Object.defineProperty(SceneLoader, "loggingLevel", {
  61611. get: function () {
  61612. return SceneLoader._loggingLevel;
  61613. },
  61614. set: function (value) {
  61615. SceneLoader._loggingLevel = value;
  61616. },
  61617. enumerable: true,
  61618. configurable: true
  61619. });
  61620. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  61621. get: function () {
  61622. return SceneLoader._CleanBoneMatrixWeights;
  61623. },
  61624. set: function (value) {
  61625. SceneLoader._CleanBoneMatrixWeights = value;
  61626. },
  61627. enumerable: true,
  61628. configurable: true
  61629. });
  61630. SceneLoader._getDefaultPlugin = function () {
  61631. return SceneLoader._registeredPlugins[".babylon"];
  61632. };
  61633. SceneLoader._getPluginForExtension = function (extension) {
  61634. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  61635. if (registeredPlugin) {
  61636. return registeredPlugin;
  61637. }
  61638. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  61639. return SceneLoader._getDefaultPlugin();
  61640. };
  61641. SceneLoader._getPluginForDirectLoad = function (data) {
  61642. for (var extension in SceneLoader._registeredPlugins) {
  61643. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  61644. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  61645. return SceneLoader._registeredPlugins[extension];
  61646. }
  61647. }
  61648. return SceneLoader._getDefaultPlugin();
  61649. };
  61650. SceneLoader._getPluginForFilename = function (sceneFilename) {
  61651. if (sceneFilename.name) {
  61652. sceneFilename = sceneFilename.name;
  61653. }
  61654. var queryStringPosition = sceneFilename.indexOf("?");
  61655. if (queryStringPosition !== -1) {
  61656. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  61657. }
  61658. var dotPosition = sceneFilename.lastIndexOf(".");
  61659. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  61660. return SceneLoader._getPluginForExtension(extension);
  61661. };
  61662. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  61663. SceneLoader._getDirectLoad = function (sceneFilename) {
  61664. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  61665. return sceneFilename.substr(5);
  61666. }
  61667. return null;
  61668. };
  61669. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  61670. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  61671. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  61672. var plugin;
  61673. if (registeredPlugin.plugin.createPlugin) {
  61674. plugin = registeredPlugin.plugin.createPlugin();
  61675. }
  61676. else {
  61677. plugin = registeredPlugin.plugin;
  61678. }
  61679. var useArrayBuffer = registeredPlugin.isBinary;
  61680. var database;
  61681. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  61682. var dataCallback = function (data, responseURL) {
  61683. if (scene.isDisposed) {
  61684. onError("Scene has been disposed");
  61685. return;
  61686. }
  61687. scene.database = database;
  61688. onSuccess(plugin, data, responseURL);
  61689. };
  61690. var request = null;
  61691. var pluginDisposed = false;
  61692. var onDisposeObservable = plugin.onDisposeObservable;
  61693. if (onDisposeObservable) {
  61694. onDisposeObservable.add(function () {
  61695. pluginDisposed = true;
  61696. if (request) {
  61697. request.abort();
  61698. request = null;
  61699. }
  61700. onDispose();
  61701. });
  61702. }
  61703. var manifestChecked = function () {
  61704. if (pluginDisposed) {
  61705. return;
  61706. }
  61707. var url = rootUrl + sceneFilename;
  61708. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  61709. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  61710. } : undefined, database, useArrayBuffer, function (request, exception) {
  61711. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  61712. });
  61713. };
  61714. if (directLoad) {
  61715. dataCallback(directLoad);
  61716. return plugin;
  61717. }
  61718. if (rootUrl.indexOf("file:") === -1) {
  61719. if (scene.getEngine().enableOfflineSupport) {
  61720. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  61721. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  61722. }
  61723. else {
  61724. manifestChecked();
  61725. }
  61726. }
  61727. else {
  61728. var fileOrString = sceneFilename;
  61729. if (fileOrString.name) {
  61730. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  61731. }
  61732. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  61733. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  61734. }
  61735. else {
  61736. onError("Unable to find file named " + sceneFilename);
  61737. }
  61738. }
  61739. return plugin;
  61740. };
  61741. // Public functions
  61742. SceneLoader.GetPluginForExtension = function (extension) {
  61743. return SceneLoader._getPluginForExtension(extension).plugin;
  61744. };
  61745. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  61746. return !!SceneLoader._registeredPlugins[extension];
  61747. };
  61748. SceneLoader.RegisterPlugin = function (plugin) {
  61749. if (typeof plugin.extensions === "string") {
  61750. var extension = plugin.extensions;
  61751. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61752. plugin: plugin,
  61753. isBinary: false
  61754. };
  61755. }
  61756. else {
  61757. var extensions = plugin.extensions;
  61758. Object.keys(extensions).forEach(function (extension) {
  61759. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61760. plugin: plugin,
  61761. isBinary: extensions[extension].isBinary
  61762. };
  61763. });
  61764. }
  61765. };
  61766. /**
  61767. * Import meshes into a scene
  61768. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61769. * @param rootUrl a string that defines the root url for scene and resources
  61770. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61771. * @param scene the instance of BABYLON.Scene to append to
  61772. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  61773. * @param onProgress a callback with a progress event for each file being loaded
  61774. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61775. * @param pluginExtension the extension used to determine the plugin
  61776. * @returns The loaded plugin
  61777. */
  61778. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61779. if (onSuccess === void 0) { onSuccess = null; }
  61780. if (onProgress === void 0) { onProgress = null; }
  61781. if (onError === void 0) { onError = null; }
  61782. if (pluginExtension === void 0) { pluginExtension = null; }
  61783. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61784. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61785. return null;
  61786. }
  61787. var loadingToken = {};
  61788. scene._addPendingData(loadingToken);
  61789. var disposeHandler = function () {
  61790. scene._removePendingData(loadingToken);
  61791. };
  61792. var errorHandler = function (message, exception) {
  61793. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  61794. if (onError) {
  61795. onError(scene, errorMessage, exception);
  61796. }
  61797. else {
  61798. BABYLON.Tools.Error(errorMessage);
  61799. // should the exception be thrown?
  61800. }
  61801. disposeHandler();
  61802. };
  61803. var progressHandler = onProgress ? function (event) {
  61804. try {
  61805. onProgress(event);
  61806. }
  61807. catch (e) {
  61808. errorHandler("Error in onProgress callback", e);
  61809. }
  61810. } : undefined;
  61811. var successHandler = function (meshes, particleSystems, skeletons) {
  61812. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  61813. if (onSuccess) {
  61814. try {
  61815. onSuccess(meshes, particleSystems, skeletons);
  61816. }
  61817. catch (e) {
  61818. errorHandler("Error in onSuccess callback", e);
  61819. }
  61820. }
  61821. scene._removePendingData(loadingToken);
  61822. };
  61823. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61824. if (plugin.rewriteRootURL) {
  61825. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  61826. }
  61827. if (sceneFilename === "") {
  61828. if (sceneFilename === "") {
  61829. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61830. }
  61831. }
  61832. if (plugin.importMesh) {
  61833. var syncedPlugin = plugin;
  61834. var meshes = new Array();
  61835. var particleSystems = new Array();
  61836. var skeletons = new Array();
  61837. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  61838. return;
  61839. }
  61840. scene.loadingPluginName = plugin.name;
  61841. successHandler(meshes, particleSystems, skeletons);
  61842. }
  61843. else {
  61844. var asyncedPlugin = plugin;
  61845. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  61846. scene.loadingPluginName = plugin.name;
  61847. successHandler(result.meshes, result.particleSystems, result.skeletons);
  61848. }).catch(function (error) {
  61849. errorHandler(error.message, error);
  61850. });
  61851. }
  61852. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61853. };
  61854. /**
  61855. * Import meshes into a scene
  61856. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61857. * @param rootUrl a string that defines the root url for scene and resources
  61858. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61859. * @param scene the instance of BABYLON.Scene to append to
  61860. * @param onProgress a callback with a progress event for each file being loaded
  61861. * @param pluginExtension the extension used to determine the plugin
  61862. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  61863. */
  61864. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61865. if (onProgress === void 0) { onProgress = null; }
  61866. if (pluginExtension === void 0) { pluginExtension = null; }
  61867. return new Promise(function (resolve, reject) {
  61868. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61869. resolve({
  61870. meshes: meshes,
  61871. particleSystems: particleSystems,
  61872. skeletons: skeletons
  61873. });
  61874. }, onProgress, function (scene, message, exception) {
  61875. reject(exception || new Error(message));
  61876. });
  61877. });
  61878. };
  61879. /**
  61880. * Load a scene
  61881. * @param rootUrl a string that defines the root url for scene and resources
  61882. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61883. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61884. * @param onSuccess a callback with the scene when import succeeds
  61885. * @param onProgress a callback with a progress event for each file being loaded
  61886. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61887. * @param pluginExtension the extension used to determine the plugin
  61888. * @returns The loaded plugin
  61889. */
  61890. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  61891. if (onSuccess === void 0) { onSuccess = null; }
  61892. if (onProgress === void 0) { onProgress = null; }
  61893. if (onError === void 0) { onError = null; }
  61894. if (pluginExtension === void 0) { pluginExtension = null; }
  61895. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  61896. };
  61897. /**
  61898. * Load a scene
  61899. * @param rootUrl a string that defines the root url for scene and resources
  61900. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61901. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61902. * @param onProgress a callback with a progress event for each file being loaded
  61903. * @param pluginExtension the extension used to determine the plugin
  61904. * @returns The loaded scene
  61905. */
  61906. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  61907. if (onProgress === void 0) { onProgress = null; }
  61908. if (pluginExtension === void 0) { pluginExtension = null; }
  61909. return new Promise(function (resolve, reject) {
  61910. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  61911. resolve(scene);
  61912. }, onProgress, function (scene, message, exception) {
  61913. reject(exception || new Error(message));
  61914. }, pluginExtension);
  61915. });
  61916. };
  61917. /**
  61918. * Append a scene
  61919. * @param rootUrl a string that defines the root url for scene and resources
  61920. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61921. * @param scene is the instance of BABYLON.Scene to append to
  61922. * @param onSuccess a callback with the scene when import succeeds
  61923. * @param onProgress a callback with a progress event for each file being loaded
  61924. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61925. * @param pluginExtension the extension used to determine the plugin
  61926. * @returns The loaded plugin
  61927. */
  61928. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61929. if (onSuccess === void 0) { onSuccess = null; }
  61930. if (onProgress === void 0) { onProgress = null; }
  61931. if (onError === void 0) { onError = null; }
  61932. if (pluginExtension === void 0) { pluginExtension = null; }
  61933. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61934. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61935. return null;
  61936. }
  61937. if (SceneLoader.ShowLoadingScreen) {
  61938. scene.getEngine().displayLoadingUI();
  61939. }
  61940. var loadingToken = {};
  61941. scene._addPendingData(loadingToken);
  61942. var disposeHandler = function () {
  61943. scene._removePendingData(loadingToken);
  61944. scene.getEngine().hideLoadingUI();
  61945. };
  61946. var errorHandler = function (message, exception) {
  61947. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61948. if (onError) {
  61949. onError(scene, errorMessage, exception);
  61950. }
  61951. else {
  61952. BABYLON.Tools.Error(errorMessage);
  61953. // should the exception be thrown?
  61954. }
  61955. disposeHandler();
  61956. };
  61957. var progressHandler = onProgress ? function (event) {
  61958. try {
  61959. onProgress(event);
  61960. }
  61961. catch (e) {
  61962. errorHandler("Error in onProgress callback", e);
  61963. }
  61964. } : undefined;
  61965. var successHandler = function () {
  61966. if (onSuccess) {
  61967. try {
  61968. onSuccess(scene);
  61969. }
  61970. catch (e) {
  61971. errorHandler("Error in onSuccess callback", e);
  61972. }
  61973. }
  61974. scene._removePendingData(loadingToken);
  61975. };
  61976. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61977. if (sceneFilename === "") {
  61978. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61979. }
  61980. if (plugin.load) {
  61981. var syncedPlugin = plugin;
  61982. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  61983. return;
  61984. }
  61985. scene.loadingPluginName = plugin.name;
  61986. successHandler();
  61987. }
  61988. else {
  61989. var asyncedPlugin = plugin;
  61990. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  61991. scene.loadingPluginName = plugin.name;
  61992. successHandler();
  61993. }).catch(function (error) {
  61994. errorHandler(error.message, error);
  61995. });
  61996. }
  61997. if (SceneLoader.ShowLoadingScreen) {
  61998. scene.executeWhenReady(function () {
  61999. scene.getEngine().hideLoadingUI();
  62000. });
  62001. }
  62002. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62003. };
  62004. /**
  62005. * Append a scene
  62006. * @param rootUrl a string that defines the root url for scene and resources
  62007. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62008. * @param scene is the instance of BABYLON.Scene to append to
  62009. * @param onProgress a callback with a progress event for each file being loaded
  62010. * @param pluginExtension the extension used to determine the plugin
  62011. * @returns The given scene
  62012. */
  62013. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62014. if (onProgress === void 0) { onProgress = null; }
  62015. if (pluginExtension === void 0) { pluginExtension = null; }
  62016. return new Promise(function (resolve, reject) {
  62017. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  62018. resolve(scene);
  62019. }, onProgress, function (scene, message, exception) {
  62020. reject(exception || new Error(message));
  62021. }, pluginExtension);
  62022. });
  62023. };
  62024. /**
  62025. * Load a scene into an asset container
  62026. * @param rootUrl a string that defines the root url for scene and resources
  62027. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62028. * @param scene is the instance of BABYLON.Scene to append to
  62029. * @param onSuccess a callback with the scene when import succeeds
  62030. * @param onProgress a callback with a progress event for each file being loaded
  62031. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62032. * @param pluginExtension the extension used to determine the plugin
  62033. * @returns The loaded plugin
  62034. */
  62035. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62036. if (onSuccess === void 0) { onSuccess = null; }
  62037. if (onProgress === void 0) { onProgress = null; }
  62038. if (onError === void 0) { onError = null; }
  62039. if (pluginExtension === void 0) { pluginExtension = null; }
  62040. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62041. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62042. return null;
  62043. }
  62044. var loadingToken = {};
  62045. scene._addPendingData(loadingToken);
  62046. var disposeHandler = function () {
  62047. scene._removePendingData(loadingToken);
  62048. };
  62049. var errorHandler = function (message, exception) {
  62050. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62051. if (onError) {
  62052. onError(scene, errorMessage, exception);
  62053. }
  62054. else {
  62055. BABYLON.Tools.Error(errorMessage);
  62056. // should the exception be thrown?
  62057. }
  62058. disposeHandler();
  62059. };
  62060. var progressHandler = onProgress ? function (event) {
  62061. try {
  62062. onProgress(event);
  62063. }
  62064. catch (e) {
  62065. errorHandler("Error in onProgress callback", e);
  62066. }
  62067. } : undefined;
  62068. var successHandler = function (assets) {
  62069. if (onSuccess) {
  62070. try {
  62071. onSuccess(assets);
  62072. }
  62073. catch (e) {
  62074. errorHandler("Error in onSuccess callback", e);
  62075. }
  62076. }
  62077. scene._removePendingData(loadingToken);
  62078. };
  62079. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62080. if (plugin.loadAssetContainer) {
  62081. var syncedPlugin = plugin;
  62082. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  62083. if (!assetContainer) {
  62084. return;
  62085. }
  62086. scene.loadingPluginName = plugin.name;
  62087. successHandler(assetContainer);
  62088. }
  62089. else if (plugin.loadAssetContainerAsync) {
  62090. var asyncedPlugin = plugin;
  62091. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  62092. scene.loadingPluginName = plugin.name;
  62093. successHandler(assetContainer);
  62094. }).catch(function (error) {
  62095. errorHandler(error.message, error);
  62096. });
  62097. }
  62098. else {
  62099. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  62100. }
  62101. if (SceneLoader.ShowLoadingScreen) {
  62102. scene.executeWhenReady(function () {
  62103. scene.getEngine().hideLoadingUI();
  62104. });
  62105. }
  62106. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62107. };
  62108. /**
  62109. * Load a scene into an asset container
  62110. * @param rootUrl a string that defines the root url for scene and resources
  62111. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62112. * @param scene is the instance of BABYLON.Scene to append to
  62113. * @param onProgress a callback with a progress event for each file being loaded
  62114. * @param pluginExtension the extension used to determine the plugin
  62115. * @returns The loaded asset container
  62116. */
  62117. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62118. if (onProgress === void 0) { onProgress = null; }
  62119. if (pluginExtension === void 0) { pluginExtension = null; }
  62120. return new Promise(function (resolve, reject) {
  62121. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  62122. resolve(assetContainer);
  62123. }, onProgress, function (scene, message, exception) {
  62124. reject(exception || new Error(message));
  62125. }, pluginExtension);
  62126. });
  62127. };
  62128. // Flags
  62129. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  62130. SceneLoader._ShowLoadingScreen = true;
  62131. SceneLoader._CleanBoneMatrixWeights = false;
  62132. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  62133. // Members
  62134. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  62135. SceneLoader._registeredPlugins = {};
  62136. return SceneLoader;
  62137. }());
  62138. BABYLON.SceneLoader = SceneLoader;
  62139. ;
  62140. })(BABYLON || (BABYLON = {}));
  62141. //# sourceMappingURL=babylon.sceneLoader.js.map
  62142. "use strict";
  62143. var BABYLON;
  62144. (function (BABYLON) {
  62145. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  62146. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62147. var parsedMaterial = parsedData.materials[index];
  62148. if (parsedMaterial.id === id) {
  62149. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62150. }
  62151. }
  62152. return null;
  62153. };
  62154. var isDescendantOf = function (mesh, names, hierarchyIds) {
  62155. for (var i in names) {
  62156. if (mesh.name === names[i]) {
  62157. hierarchyIds.push(mesh.id);
  62158. return true;
  62159. }
  62160. }
  62161. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  62162. hierarchyIds.push(mesh.id);
  62163. return true;
  62164. }
  62165. return false;
  62166. };
  62167. var logOperation = function (operation, producer) {
  62168. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  62169. };
  62170. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  62171. if (addToScene === void 0) { addToScene = false; }
  62172. var container = new BABYLON.AssetContainer(scene);
  62173. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62174. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62175. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62176. // and avoid problems with multiple concurrent .babylon loads.
  62177. var log = "importScene has failed JSON parse";
  62178. try {
  62179. var parsedData = JSON.parse(data);
  62180. log = "";
  62181. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62182. var index;
  62183. var cache;
  62184. // Lights
  62185. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  62186. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  62187. var parsedLight = parsedData.lights[index];
  62188. var light = BABYLON.Light.Parse(parsedLight, scene);
  62189. if (light) {
  62190. container.lights.push(light);
  62191. log += (index === 0 ? "\n\tLights:" : "");
  62192. log += "\n\t\t" + light.toString(fullDetails);
  62193. }
  62194. }
  62195. }
  62196. // Animations
  62197. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  62198. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  62199. var parsedAnimation = parsedData.animations[index];
  62200. var animation = BABYLON.Animation.Parse(parsedAnimation);
  62201. scene.animations.push(animation);
  62202. container.animations.push(animation);
  62203. log += (index === 0 ? "\n\tAnimations:" : "");
  62204. log += "\n\t\t" + animation.toString(fullDetails);
  62205. }
  62206. }
  62207. // Materials
  62208. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  62209. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62210. var parsedMaterial = parsedData.materials[index];
  62211. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62212. container.materials.push(mat);
  62213. log += (index === 0 ? "\n\tMaterials:" : "");
  62214. log += "\n\t\t" + mat.toString(fullDetails);
  62215. }
  62216. }
  62217. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62218. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  62219. var parsedMultiMaterial = parsedData.multiMaterials[index];
  62220. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62221. container.multiMaterials.push(mmat);
  62222. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  62223. log += "\n\t\t" + mmat.toString(fullDetails);
  62224. }
  62225. }
  62226. // Morph targets
  62227. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  62228. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  62229. var managerData = _a[_i];
  62230. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  62231. }
  62232. }
  62233. // Skeletons
  62234. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62235. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  62236. var parsedSkeleton = parsedData.skeletons[index];
  62237. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62238. container.skeletons.push(skeleton);
  62239. log += (index === 0 ? "\n\tSkeletons:" : "");
  62240. log += "\n\t\t" + skeleton.toString(fullDetails);
  62241. }
  62242. }
  62243. // Geometries
  62244. var geometries = parsedData.geometries;
  62245. if (geometries !== undefined && geometries !== null) {
  62246. var addedGeometry = new Array();
  62247. // Boxes
  62248. var boxes = geometries.boxes;
  62249. if (boxes !== undefined && boxes !== null) {
  62250. for (index = 0, cache = boxes.length; index < cache; index++) {
  62251. var parsedBox = boxes[index];
  62252. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  62253. }
  62254. }
  62255. // Spheres
  62256. var spheres = geometries.spheres;
  62257. if (spheres !== undefined && spheres !== null) {
  62258. for (index = 0, cache = spheres.length; index < cache; index++) {
  62259. var parsedSphere = spheres[index];
  62260. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  62261. }
  62262. }
  62263. // Cylinders
  62264. var cylinders = geometries.cylinders;
  62265. if (cylinders !== undefined && cylinders !== null) {
  62266. for (index = 0, cache = cylinders.length; index < cache; index++) {
  62267. var parsedCylinder = cylinders[index];
  62268. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  62269. }
  62270. }
  62271. // Toruses
  62272. var toruses = geometries.toruses;
  62273. if (toruses !== undefined && toruses !== null) {
  62274. for (index = 0, cache = toruses.length; index < cache; index++) {
  62275. var parsedTorus = toruses[index];
  62276. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  62277. }
  62278. }
  62279. // Grounds
  62280. var grounds = geometries.grounds;
  62281. if (grounds !== undefined && grounds !== null) {
  62282. for (index = 0, cache = grounds.length; index < cache; index++) {
  62283. var parsedGround = grounds[index];
  62284. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  62285. }
  62286. }
  62287. // Planes
  62288. var planes = geometries.planes;
  62289. if (planes !== undefined && planes !== null) {
  62290. for (index = 0, cache = planes.length; index < cache; index++) {
  62291. var parsedPlane = planes[index];
  62292. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  62293. }
  62294. }
  62295. // TorusKnots
  62296. var torusKnots = geometries.torusKnots;
  62297. if (torusKnots !== undefined && torusKnots !== null) {
  62298. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  62299. var parsedTorusKnot = torusKnots[index];
  62300. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  62301. }
  62302. }
  62303. // VertexData
  62304. var vertexData = geometries.vertexData;
  62305. if (vertexData !== undefined && vertexData !== null) {
  62306. for (index = 0, cache = vertexData.length; index < cache; index++) {
  62307. var parsedVertexData = vertexData[index];
  62308. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  62309. }
  62310. }
  62311. addedGeometry.forEach(function (g) {
  62312. if (g) {
  62313. container.geometries.push(g);
  62314. }
  62315. });
  62316. }
  62317. // Transform nodes
  62318. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  62319. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  62320. var parsedTransformNode = parsedData.transformNodes[index];
  62321. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  62322. container.transformNodes.push(node);
  62323. }
  62324. }
  62325. // Meshes
  62326. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62327. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62328. var parsedMesh = parsedData.meshes[index];
  62329. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62330. container.meshes.push(mesh);
  62331. log += (index === 0 ? "\n\tMeshes:" : "");
  62332. log += "\n\t\t" + mesh.toString(fullDetails);
  62333. }
  62334. }
  62335. // Cameras
  62336. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  62337. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  62338. var parsedCamera = parsedData.cameras[index];
  62339. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  62340. container.cameras.push(camera);
  62341. log += (index === 0 ? "\n\tCameras:" : "");
  62342. log += "\n\t\t" + camera.toString(fullDetails);
  62343. }
  62344. }
  62345. // Browsing all the graph to connect the dots
  62346. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  62347. var camera = scene.cameras[index];
  62348. if (camera._waitingParentId) {
  62349. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  62350. camera._waitingParentId = null;
  62351. }
  62352. }
  62353. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62354. var light_1 = scene.lights[index];
  62355. if (light_1 && light_1._waitingParentId) {
  62356. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  62357. light_1._waitingParentId = null;
  62358. }
  62359. }
  62360. // Sounds
  62361. // TODO: add sound
  62362. var loadedSounds = [];
  62363. var loadedSound;
  62364. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  62365. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  62366. var parsedSound = parsedData.sounds[index];
  62367. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62368. if (!parsedSound.url)
  62369. parsedSound.url = parsedSound.name;
  62370. if (!loadedSounds[parsedSound.url]) {
  62371. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  62372. loadedSounds[parsedSound.url] = loadedSound;
  62373. container.sounds.push(loadedSound);
  62374. }
  62375. else {
  62376. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  62377. }
  62378. }
  62379. else {
  62380. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  62381. }
  62382. }
  62383. }
  62384. loadedSounds = [];
  62385. // Connect parents & children and parse actions
  62386. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  62387. var transformNode = scene.transformNodes[index];
  62388. if (transformNode._waitingParentId) {
  62389. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  62390. transformNode._waitingParentId = null;
  62391. }
  62392. }
  62393. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62394. var mesh = scene.meshes[index];
  62395. if (mesh._waitingParentId) {
  62396. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  62397. mesh._waitingParentId = null;
  62398. }
  62399. if (mesh._waitingActions) {
  62400. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  62401. mesh._waitingActions = null;
  62402. }
  62403. }
  62404. // freeze world matrix application
  62405. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62406. var currentMesh = scene.meshes[index];
  62407. if (currentMesh._waitingFreezeWorldMatrix) {
  62408. currentMesh.freezeWorldMatrix();
  62409. currentMesh._waitingFreezeWorldMatrix = null;
  62410. }
  62411. else {
  62412. currentMesh.computeWorldMatrix(true);
  62413. }
  62414. }
  62415. // Particles Systems
  62416. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62417. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62418. var parsedParticleSystem = parsedData.particleSystems[index];
  62419. if (parsedParticleSystem.activeParticleCount) {
  62420. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62421. container.particleSystems.push(ps);
  62422. }
  62423. else {
  62424. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62425. container.particleSystems.push(ps);
  62426. }
  62427. }
  62428. }
  62429. // Lens flares
  62430. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  62431. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  62432. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  62433. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  62434. container.lensFlareSystems.push(lf);
  62435. }
  62436. }
  62437. // Shadows
  62438. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  62439. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  62440. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  62441. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  62442. container.shadowGenerators.push(sg);
  62443. }
  62444. }
  62445. // Lights exclusions / inclusions
  62446. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62447. var light_2 = scene.lights[index];
  62448. // Excluded check
  62449. if (light_2._excludedMeshesIds.length > 0) {
  62450. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  62451. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  62452. if (excludedMesh) {
  62453. light_2.excludedMeshes.push(excludedMesh);
  62454. }
  62455. }
  62456. light_2._excludedMeshesIds = [];
  62457. }
  62458. // Included check
  62459. if (light_2._includedOnlyMeshesIds.length > 0) {
  62460. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  62461. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  62462. if (includedOnlyMesh) {
  62463. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  62464. }
  62465. }
  62466. light_2._includedOnlyMeshesIds = [];
  62467. }
  62468. }
  62469. // Actions (scene)
  62470. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  62471. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  62472. }
  62473. if (!addToScene) {
  62474. container.removeAllFromScene();
  62475. }
  62476. }
  62477. catch (err) {
  62478. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  62479. if (onError) {
  62480. onError(msg, err);
  62481. }
  62482. else {
  62483. BABYLON.Tools.Log(msg);
  62484. throw err;
  62485. }
  62486. }
  62487. finally {
  62488. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62489. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62490. }
  62491. }
  62492. return container;
  62493. };
  62494. BABYLON.SceneLoader.RegisterPlugin({
  62495. name: "babylon.js",
  62496. extensions: ".babylon",
  62497. canDirectLoad: function (data) {
  62498. if (data.indexOf("babylon") !== -1) {
  62499. return true;
  62500. }
  62501. return false;
  62502. },
  62503. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  62504. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62505. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62506. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62507. // and avoid problems with multiple concurrent .babylon loads.
  62508. var log = "importMesh has failed JSON parse";
  62509. try {
  62510. var parsedData = JSON.parse(data);
  62511. log = "";
  62512. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62513. if (!meshesNames) {
  62514. meshesNames = null;
  62515. }
  62516. else if (!Array.isArray(meshesNames)) {
  62517. meshesNames = [meshesNames];
  62518. }
  62519. var hierarchyIds = new Array();
  62520. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62521. var loadedSkeletonsIds = [];
  62522. var loadedMaterialsIds = [];
  62523. var index;
  62524. var cache;
  62525. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62526. var parsedMesh = parsedData.meshes[index];
  62527. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  62528. if (meshesNames !== null) {
  62529. // Remove found mesh name from list.
  62530. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  62531. }
  62532. //Geometry?
  62533. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  62534. //does the file contain geometries?
  62535. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  62536. //find the correct geometry and add it to the scene
  62537. var found = false;
  62538. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  62539. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  62540. return;
  62541. }
  62542. else {
  62543. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  62544. if (parsedGeometryData.id === parsedMesh.geometryId) {
  62545. switch (geometryType) {
  62546. case "boxes":
  62547. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  62548. break;
  62549. case "spheres":
  62550. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  62551. break;
  62552. case "cylinders":
  62553. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  62554. break;
  62555. case "toruses":
  62556. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  62557. break;
  62558. case "grounds":
  62559. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  62560. break;
  62561. case "planes":
  62562. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  62563. break;
  62564. case "torusKnots":
  62565. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  62566. break;
  62567. case "vertexData":
  62568. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  62569. break;
  62570. }
  62571. found = true;
  62572. }
  62573. });
  62574. }
  62575. });
  62576. if (found === false) {
  62577. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  62578. }
  62579. }
  62580. }
  62581. // Material ?
  62582. if (parsedMesh.materialId) {
  62583. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  62584. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62585. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  62586. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  62587. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  62588. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  62589. var subMatId = parsedMultiMaterial.materials[matIndex];
  62590. loadedMaterialsIds.push(subMatId);
  62591. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  62592. if (mat) {
  62593. log += "\n\tMaterial " + mat.toString(fullDetails);
  62594. }
  62595. }
  62596. loadedMaterialsIds.push(parsedMultiMaterial.id);
  62597. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62598. if (mmat) {
  62599. materialFound = true;
  62600. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  62601. }
  62602. break;
  62603. }
  62604. }
  62605. }
  62606. if (materialFound === false) {
  62607. loadedMaterialsIds.push(parsedMesh.materialId);
  62608. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  62609. if (!mat) {
  62610. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  62611. }
  62612. else {
  62613. log += "\n\tMaterial " + mat.toString(fullDetails);
  62614. }
  62615. }
  62616. }
  62617. // Skeleton ?
  62618. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62619. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  62620. if (skeletonAlreadyLoaded === false) {
  62621. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  62622. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  62623. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  62624. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62625. skeletons.push(skeleton);
  62626. loadedSkeletonsIds.push(parsedSkeleton.id);
  62627. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  62628. }
  62629. }
  62630. }
  62631. }
  62632. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62633. meshes.push(mesh);
  62634. log += "\n\tMesh " + mesh.toString(fullDetails);
  62635. }
  62636. }
  62637. // Connecting parents
  62638. var currentMesh;
  62639. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62640. currentMesh = scene.meshes[index];
  62641. if (currentMesh._waitingParentId) {
  62642. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  62643. currentMesh._waitingParentId = null;
  62644. }
  62645. }
  62646. // freeze and compute world matrix application
  62647. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62648. currentMesh = scene.meshes[index];
  62649. if (currentMesh._waitingFreezeWorldMatrix) {
  62650. currentMesh.freezeWorldMatrix();
  62651. currentMesh._waitingFreezeWorldMatrix = null;
  62652. }
  62653. else {
  62654. currentMesh.computeWorldMatrix(true);
  62655. }
  62656. }
  62657. }
  62658. // Particles
  62659. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62660. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62661. var parsedParticleSystem = parsedData.particleSystems[index];
  62662. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  62663. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  62664. }
  62665. }
  62666. }
  62667. return true;
  62668. }
  62669. catch (err) {
  62670. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  62671. if (onError) {
  62672. onError(msg, err);
  62673. }
  62674. else {
  62675. BABYLON.Tools.Log(msg);
  62676. throw err;
  62677. }
  62678. }
  62679. finally {
  62680. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62681. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62682. }
  62683. }
  62684. return false;
  62685. },
  62686. load: function (scene, data, rootUrl, onError) {
  62687. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62688. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62689. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62690. // and avoid problems with multiple concurrent .babylon loads.
  62691. var log = "importScene has failed JSON parse";
  62692. try {
  62693. var parsedData = JSON.parse(data);
  62694. log = "";
  62695. // Scene
  62696. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  62697. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  62698. }
  62699. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  62700. scene.autoClear = parsedData.autoClear;
  62701. }
  62702. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  62703. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  62704. }
  62705. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  62706. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  62707. }
  62708. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  62709. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  62710. }
  62711. // Fog
  62712. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  62713. scene.fogMode = parsedData.fogMode;
  62714. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  62715. scene.fogStart = parsedData.fogStart;
  62716. scene.fogEnd = parsedData.fogEnd;
  62717. scene.fogDensity = parsedData.fogDensity;
  62718. log += "\tFog mode for scene: ";
  62719. switch (scene.fogMode) {
  62720. // getters not compiling, so using hardcoded
  62721. case 1:
  62722. log += "exp\n";
  62723. break;
  62724. case 2:
  62725. log += "exp2\n";
  62726. break;
  62727. case 3:
  62728. log += "linear\n";
  62729. break;
  62730. }
  62731. }
  62732. //Physics
  62733. if (parsedData.physicsEnabled) {
  62734. var physicsPlugin;
  62735. if (parsedData.physicsEngine === "cannon") {
  62736. physicsPlugin = new BABYLON.CannonJSPlugin();
  62737. }
  62738. else if (parsedData.physicsEngine === "oimo") {
  62739. physicsPlugin = new BABYLON.OimoJSPlugin();
  62740. }
  62741. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  62742. //else - default engine, which is currently oimo
  62743. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  62744. scene.enablePhysics(physicsGravity, physicsPlugin);
  62745. }
  62746. // Metadata
  62747. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  62748. scene.metadata = parsedData.metadata;
  62749. }
  62750. //collisions, if defined. otherwise, default is true
  62751. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  62752. scene.collisionsEnabled = parsedData.collisionsEnabled;
  62753. }
  62754. scene.workerCollisions = !!parsedData.workerCollisions;
  62755. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  62756. if (!container) {
  62757. return false;
  62758. }
  62759. if (parsedData.autoAnimate) {
  62760. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  62761. }
  62762. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  62763. scene.setActiveCameraByID(parsedData.activeCameraID);
  62764. }
  62765. // Environment texture
  62766. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  62767. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  62768. if (parsedData.createDefaultSkybox === true) {
  62769. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  62770. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  62771. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  62772. }
  62773. }
  62774. // Finish
  62775. return true;
  62776. }
  62777. catch (err) {
  62778. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  62779. if (onError) {
  62780. onError(msg, err);
  62781. }
  62782. else {
  62783. BABYLON.Tools.Log(msg);
  62784. throw err;
  62785. }
  62786. }
  62787. finally {
  62788. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62789. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62790. }
  62791. }
  62792. return false;
  62793. },
  62794. loadAssetContainer: function (scene, data, rootUrl, onError) {
  62795. var container = loadAssetContainer(scene, data, rootUrl, onError);
  62796. return container;
  62797. }
  62798. });
  62799. })(BABYLON || (BABYLON = {}));
  62800. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  62801. "use strict";
  62802. var BABYLON;
  62803. (function (BABYLON) {
  62804. var FilesInput = /** @class */ (function () {
  62805. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  62806. this.onProcessFileCallback = function () { return true; };
  62807. this._engine = engine;
  62808. this._currentScene = scene;
  62809. this._sceneLoadedCallback = sceneLoadedCallback;
  62810. this._progressCallback = progressCallback;
  62811. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  62812. this._textureLoadingCallback = textureLoadingCallback;
  62813. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  62814. this._onReloadCallback = onReloadCallback;
  62815. this._errorCallback = errorCallback;
  62816. }
  62817. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  62818. var _this = this;
  62819. if (elementToMonitor) {
  62820. this._elementToMonitor = elementToMonitor;
  62821. this._dragEnterHandler = function (e) { _this.drag(e); };
  62822. this._dragOverHandler = function (e) { _this.drag(e); };
  62823. this._dropHandler = function (e) { _this.drop(e); };
  62824. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  62825. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  62826. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  62827. }
  62828. };
  62829. FilesInput.prototype.dispose = function () {
  62830. if (!this._elementToMonitor) {
  62831. return;
  62832. }
  62833. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  62834. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  62835. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  62836. };
  62837. FilesInput.prototype.renderFunction = function () {
  62838. if (this._additionalRenderLoopLogicCallback) {
  62839. this._additionalRenderLoopLogicCallback();
  62840. }
  62841. if (this._currentScene) {
  62842. if (this._textureLoadingCallback) {
  62843. var remaining = this._currentScene.getWaitingItemsCount();
  62844. if (remaining > 0) {
  62845. this._textureLoadingCallback(remaining);
  62846. }
  62847. }
  62848. this._currentScene.render();
  62849. }
  62850. };
  62851. FilesInput.prototype.drag = function (e) {
  62852. e.stopPropagation();
  62853. e.preventDefault();
  62854. };
  62855. FilesInput.prototype.drop = function (eventDrop) {
  62856. eventDrop.stopPropagation();
  62857. eventDrop.preventDefault();
  62858. this.loadFiles(eventDrop);
  62859. };
  62860. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  62861. var _this = this;
  62862. var reader = folder.createReader();
  62863. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  62864. reader.readEntries(function (entries) {
  62865. remaining.count += entries.length;
  62866. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  62867. var entry = entries_1[_i];
  62868. if (entry.isFile) {
  62869. entry.file(function (file) {
  62870. file.correctName = relativePath + file.name;
  62871. files.push(file);
  62872. if (--remaining.count === 0) {
  62873. callback();
  62874. }
  62875. });
  62876. }
  62877. else if (entry.isDirectory) {
  62878. _this._traverseFolder(entry, files, remaining, callback);
  62879. }
  62880. }
  62881. if (--remaining.count) {
  62882. callback();
  62883. }
  62884. });
  62885. };
  62886. FilesInput.prototype._processFiles = function (files) {
  62887. for (var i = 0; i < files.length; i++) {
  62888. var name = files[i].correctName.toLowerCase();
  62889. var extension = name.split('.').pop();
  62890. if (!this.onProcessFileCallback(files[i], name, extension)) {
  62891. continue;
  62892. }
  62893. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  62894. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  62895. this._sceneFileToLoad = files[i];
  62896. }
  62897. else {
  62898. FilesInput.FilesToLoad[name] = files[i];
  62899. }
  62900. }
  62901. };
  62902. FilesInput.prototype.loadFiles = function (event) {
  62903. var _this = this;
  62904. if (this._startingProcessingFilesCallback)
  62905. this._startingProcessingFilesCallback();
  62906. // Handling data transfer via drag'n'drop
  62907. if (event && event.dataTransfer && event.dataTransfer.files) {
  62908. this._filesToLoad = event.dataTransfer.files;
  62909. }
  62910. // Handling files from input files
  62911. if (event && event.target && event.target.files) {
  62912. this._filesToLoad = event.target.files;
  62913. }
  62914. if (this._filesToLoad && this._filesToLoad.length > 0) {
  62915. var files_1 = new Array();
  62916. var folders = [];
  62917. var items = event.dataTransfer ? event.dataTransfer.items : null;
  62918. for (var i = 0; i < this._filesToLoad.length; i++) {
  62919. var fileToLoad = this._filesToLoad[i];
  62920. var name_1 = fileToLoad.name.toLowerCase();
  62921. var entry = void 0;
  62922. fileToLoad.correctName = name_1;
  62923. if (items) {
  62924. var item = items[i];
  62925. if (item.getAsEntry) {
  62926. entry = item.getAsEntry();
  62927. }
  62928. else if (item.webkitGetAsEntry) {
  62929. entry = item.webkitGetAsEntry();
  62930. }
  62931. }
  62932. if (!entry) {
  62933. files_1.push(fileToLoad);
  62934. }
  62935. else {
  62936. if (entry.isDirectory) {
  62937. folders.push(entry);
  62938. }
  62939. else {
  62940. files_1.push(fileToLoad);
  62941. }
  62942. }
  62943. }
  62944. if (folders.length === 0) {
  62945. this._processFiles(files_1);
  62946. this._processReload();
  62947. }
  62948. else {
  62949. var remaining = { count: folders.length };
  62950. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  62951. var folder = folders_1[_i];
  62952. this._traverseFolder(folder, files_1, remaining, function () {
  62953. _this._processFiles(files_1);
  62954. if (remaining.count === 0) {
  62955. _this._processReload();
  62956. }
  62957. });
  62958. }
  62959. }
  62960. }
  62961. };
  62962. FilesInput.prototype._processReload = function () {
  62963. if (this._onReloadCallback) {
  62964. this._onReloadCallback(this._sceneFileToLoad);
  62965. }
  62966. else {
  62967. this.reload();
  62968. }
  62969. };
  62970. FilesInput.prototype.reload = function () {
  62971. var _this = this;
  62972. // If a scene file has been provided
  62973. if (this._sceneFileToLoad) {
  62974. if (this._currentScene) {
  62975. if (BABYLON.Tools.errorsCount > 0) {
  62976. BABYLON.Tools.ClearLogCache();
  62977. }
  62978. this._engine.stopRenderLoop();
  62979. this._currentScene.dispose();
  62980. }
  62981. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  62982. if (_this._progressCallback) {
  62983. _this._progressCallback(progress);
  62984. }
  62985. }).then(function (scene) {
  62986. _this._currentScene = scene;
  62987. if (_this._sceneLoadedCallback) {
  62988. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  62989. }
  62990. // Wait for textures and shaders to be ready
  62991. _this._currentScene.executeWhenReady(function () {
  62992. _this._engine.runRenderLoop(function () {
  62993. _this.renderFunction();
  62994. });
  62995. });
  62996. }).catch(function (error) {
  62997. if (_this._errorCallback) {
  62998. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  62999. }
  63000. });
  63001. }
  63002. else {
  63003. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  63004. }
  63005. };
  63006. FilesInput.FilesToLoad = {};
  63007. return FilesInput;
  63008. }());
  63009. BABYLON.FilesInput = FilesInput;
  63010. })(BABYLON || (BABYLON = {}));
  63011. //# sourceMappingURL=babylon.filesInput.js.map
  63012. "use strict";
  63013. var BABYLON;
  63014. (function (BABYLON) {
  63015. /**
  63016. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63017. * The underlying implementation relies on an associative array to ensure the best performances.
  63018. * The value can be anything including 'null' but except 'undefined'
  63019. */
  63020. var StringDictionary = /** @class */ (function () {
  63021. function StringDictionary() {
  63022. this._count = 0;
  63023. this._data = {};
  63024. }
  63025. /**
  63026. * This will clear this dictionary and copy the content from the 'source' one.
  63027. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63028. * @param source the dictionary to take the content from and copy to this dictionary
  63029. */
  63030. StringDictionary.prototype.copyFrom = function (source) {
  63031. var _this = this;
  63032. this.clear();
  63033. source.forEach(function (t, v) { return _this.add(t, v); });
  63034. };
  63035. /**
  63036. * Get a value based from its key
  63037. * @param key the given key to get the matching value from
  63038. * @return the value if found, otherwise undefined is returned
  63039. */
  63040. StringDictionary.prototype.get = function (key) {
  63041. var val = this._data[key];
  63042. if (val !== undefined) {
  63043. return val;
  63044. }
  63045. return undefined;
  63046. };
  63047. /**
  63048. * Get a value from its key or add it if it doesn't exist.
  63049. * This method will ensure you that a given key/data will be present in the dictionary.
  63050. * @param key the given key to get the matching value from
  63051. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63052. * The factory will only be invoked if there's no data for the given key.
  63053. * @return the value corresponding to the key.
  63054. */
  63055. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63056. var val = this.get(key);
  63057. if (val !== undefined) {
  63058. return val;
  63059. }
  63060. val = factory(key);
  63061. if (val) {
  63062. this.add(key, val);
  63063. }
  63064. return val;
  63065. };
  63066. /**
  63067. * Get a value from its key if present in the dictionary otherwise add it
  63068. * @param key the key to get the value from
  63069. * @param val if there's no such key/value pair in the dictionary add it with this value
  63070. * @return the value corresponding to the key
  63071. */
  63072. StringDictionary.prototype.getOrAdd = function (key, val) {
  63073. var curVal = this.get(key);
  63074. if (curVal !== undefined) {
  63075. return curVal;
  63076. }
  63077. this.add(key, val);
  63078. return val;
  63079. };
  63080. /**
  63081. * Check if there's a given key in the dictionary
  63082. * @param key the key to check for
  63083. * @return true if the key is present, false otherwise
  63084. */
  63085. StringDictionary.prototype.contains = function (key) {
  63086. return this._data[key] !== undefined;
  63087. };
  63088. /**
  63089. * Add a new key and its corresponding value
  63090. * @param key the key to add
  63091. * @param value the value corresponding to the key
  63092. * @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
  63093. */
  63094. StringDictionary.prototype.add = function (key, value) {
  63095. if (this._data[key] !== undefined) {
  63096. return false;
  63097. }
  63098. this._data[key] = value;
  63099. ++this._count;
  63100. return true;
  63101. };
  63102. StringDictionary.prototype.set = function (key, value) {
  63103. if (this._data[key] === undefined) {
  63104. return false;
  63105. }
  63106. this._data[key] = value;
  63107. return true;
  63108. };
  63109. /**
  63110. * Get the element of the given key and remove it from the dictionary
  63111. * @param key
  63112. */
  63113. StringDictionary.prototype.getAndRemove = function (key) {
  63114. var val = this.get(key);
  63115. if (val !== undefined) {
  63116. delete this._data[key];
  63117. --this._count;
  63118. return val;
  63119. }
  63120. return null;
  63121. };
  63122. /**
  63123. * Remove a key/value from the dictionary.
  63124. * @param key the key to remove
  63125. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63126. */
  63127. StringDictionary.prototype.remove = function (key) {
  63128. if (this.contains(key)) {
  63129. delete this._data[key];
  63130. --this._count;
  63131. return true;
  63132. }
  63133. return false;
  63134. };
  63135. /**
  63136. * Clear the whole content of the dictionary
  63137. */
  63138. StringDictionary.prototype.clear = function () {
  63139. this._data = {};
  63140. this._count = 0;
  63141. };
  63142. Object.defineProperty(StringDictionary.prototype, "count", {
  63143. get: function () {
  63144. return this._count;
  63145. },
  63146. enumerable: true,
  63147. configurable: true
  63148. });
  63149. /**
  63150. * Execute a callback on each key/val of the dictionary.
  63151. * Note that you can remove any element in this dictionary in the callback implementation
  63152. * @param callback the callback to execute on a given key/value pair
  63153. */
  63154. StringDictionary.prototype.forEach = function (callback) {
  63155. for (var cur in this._data) {
  63156. var val = this._data[cur];
  63157. callback(cur, val);
  63158. }
  63159. };
  63160. /**
  63161. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63162. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63163. * Note that you can remove any element in this dictionary in the callback implementation
  63164. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63165. */
  63166. StringDictionary.prototype.first = function (callback) {
  63167. for (var cur in this._data) {
  63168. var val = this._data[cur];
  63169. var res = callback(cur, val);
  63170. if (res) {
  63171. return res;
  63172. }
  63173. }
  63174. return null;
  63175. };
  63176. return StringDictionary;
  63177. }());
  63178. BABYLON.StringDictionary = StringDictionary;
  63179. })(BABYLON || (BABYLON = {}));
  63180. //# sourceMappingURL=babylon.stringDictionary.js.map
  63181. "use strict";
  63182. var BABYLON;
  63183. (function (BABYLON) {
  63184. var Tags = /** @class */ (function () {
  63185. function Tags() {
  63186. }
  63187. Tags.EnableFor = function (obj) {
  63188. obj._tags = obj._tags || {};
  63189. obj.hasTags = function () {
  63190. return Tags.HasTags(obj);
  63191. };
  63192. obj.addTags = function (tagsString) {
  63193. return Tags.AddTagsTo(obj, tagsString);
  63194. };
  63195. obj.removeTags = function (tagsString) {
  63196. return Tags.RemoveTagsFrom(obj, tagsString);
  63197. };
  63198. obj.matchesTagsQuery = function (tagsQuery) {
  63199. return Tags.MatchesQuery(obj, tagsQuery);
  63200. };
  63201. };
  63202. Tags.DisableFor = function (obj) {
  63203. delete obj._tags;
  63204. delete obj.hasTags;
  63205. delete obj.addTags;
  63206. delete obj.removeTags;
  63207. delete obj.matchesTagsQuery;
  63208. };
  63209. Tags.HasTags = function (obj) {
  63210. if (!obj._tags) {
  63211. return false;
  63212. }
  63213. return !BABYLON.Tools.IsEmpty(obj._tags);
  63214. };
  63215. Tags.GetTags = function (obj, asString) {
  63216. if (asString === void 0) { asString = true; }
  63217. if (!obj._tags) {
  63218. return null;
  63219. }
  63220. if (asString) {
  63221. var tagsArray = [];
  63222. for (var tag in obj._tags) {
  63223. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  63224. tagsArray.push(tag);
  63225. }
  63226. }
  63227. return tagsArray.join(" ");
  63228. }
  63229. else {
  63230. return obj._tags;
  63231. }
  63232. };
  63233. // the tags 'true' and 'false' are reserved and cannot be used as tags
  63234. // a tag cannot start with '||', '&&', and '!'
  63235. // it cannot contain whitespaces
  63236. Tags.AddTagsTo = function (obj, tagsString) {
  63237. if (!tagsString) {
  63238. return;
  63239. }
  63240. if (typeof tagsString !== "string") {
  63241. return;
  63242. }
  63243. var tags = tagsString.split(" ");
  63244. tags.forEach(function (tag, index, array) {
  63245. Tags._AddTagTo(obj, tag);
  63246. });
  63247. };
  63248. Tags._AddTagTo = function (obj, tag) {
  63249. tag = tag.trim();
  63250. if (tag === "" || tag === "true" || tag === "false") {
  63251. return;
  63252. }
  63253. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  63254. return;
  63255. }
  63256. Tags.EnableFor(obj);
  63257. obj._tags[tag] = true;
  63258. };
  63259. Tags.RemoveTagsFrom = function (obj, tagsString) {
  63260. if (!Tags.HasTags(obj)) {
  63261. return;
  63262. }
  63263. var tags = tagsString.split(" ");
  63264. for (var t in tags) {
  63265. Tags._RemoveTagFrom(obj, tags[t]);
  63266. }
  63267. };
  63268. Tags._RemoveTagFrom = function (obj, tag) {
  63269. delete obj._tags[tag];
  63270. };
  63271. Tags.MatchesQuery = function (obj, tagsQuery) {
  63272. if (tagsQuery === undefined) {
  63273. return true;
  63274. }
  63275. if (tagsQuery === "") {
  63276. return Tags.HasTags(obj);
  63277. }
  63278. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  63279. };
  63280. return Tags;
  63281. }());
  63282. BABYLON.Tags = Tags;
  63283. })(BABYLON || (BABYLON = {}));
  63284. //# sourceMappingURL=babylon.tags.js.map
  63285. "use strict";
  63286. var BABYLON;
  63287. (function (BABYLON) {
  63288. var AndOrNotEvaluator = /** @class */ (function () {
  63289. function AndOrNotEvaluator() {
  63290. }
  63291. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  63292. if (!query.match(/\([^\(\)]*\)/g)) {
  63293. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  63294. }
  63295. else {
  63296. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  63297. // remove parenthesis
  63298. r = r.slice(1, r.length - 1);
  63299. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  63300. });
  63301. }
  63302. if (query === "true") {
  63303. return true;
  63304. }
  63305. if (query === "false") {
  63306. return false;
  63307. }
  63308. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  63309. };
  63310. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  63311. evaluateCallback = evaluateCallback || (function (r) {
  63312. return r === "true" ? true : false;
  63313. });
  63314. var result;
  63315. var or = parenthesisContent.split("||");
  63316. for (var i in or) {
  63317. if (or.hasOwnProperty(i)) {
  63318. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  63319. var and = ori.split("&&");
  63320. if (and.length > 1) {
  63321. for (var j = 0; j < and.length; ++j) {
  63322. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  63323. if (andj !== "true" && andj !== "false") {
  63324. if (andj[0] === "!") {
  63325. result = !evaluateCallback(andj.substring(1));
  63326. }
  63327. else {
  63328. result = evaluateCallback(andj);
  63329. }
  63330. }
  63331. else {
  63332. result = andj === "true" ? true : false;
  63333. }
  63334. if (!result) {
  63335. ori = "false";
  63336. break;
  63337. }
  63338. }
  63339. }
  63340. if (result || ori === "true") {
  63341. result = true;
  63342. break;
  63343. }
  63344. // result equals false (or undefined)
  63345. if (ori !== "true" && ori !== "false") {
  63346. if (ori[0] === "!") {
  63347. result = !evaluateCallback(ori.substring(1));
  63348. }
  63349. else {
  63350. result = evaluateCallback(ori);
  63351. }
  63352. }
  63353. else {
  63354. result = ori === "true" ? true : false;
  63355. }
  63356. }
  63357. }
  63358. // the whole parenthesis scope is replaced by 'true' or 'false'
  63359. return result ? "true" : "false";
  63360. };
  63361. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  63362. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  63363. // remove whitespaces
  63364. r = r.replace(/[\s]/g, function () { return ""; });
  63365. return r.length % 2 ? "!" : "";
  63366. });
  63367. booleanString = booleanString.trim();
  63368. if (booleanString === "!true") {
  63369. booleanString = "false";
  63370. }
  63371. else if (booleanString === "!false") {
  63372. booleanString = "true";
  63373. }
  63374. return booleanString;
  63375. };
  63376. return AndOrNotEvaluator;
  63377. }());
  63378. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  63379. })(BABYLON || (BABYLON = {}));
  63380. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  63381. "use strict";
  63382. var BABYLON;
  63383. (function (BABYLON) {
  63384. var Database = /** @class */ (function () {
  63385. function Database(urlToScene, callbackManifestChecked) {
  63386. // Handling various flavors of prefixed version of IndexedDB
  63387. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  63388. this.callbackManifestChecked = callbackManifestChecked;
  63389. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  63390. this.db = null;
  63391. this._enableSceneOffline = false;
  63392. this._enableTexturesOffline = false;
  63393. this.manifestVersionFound = 0;
  63394. this.mustUpdateRessources = false;
  63395. this.hasReachedQuota = false;
  63396. if (!Database.IDBStorageEnabled) {
  63397. this.callbackManifestChecked(true);
  63398. }
  63399. else {
  63400. this.checkManifestFile();
  63401. }
  63402. }
  63403. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  63404. get: function () {
  63405. return this._enableSceneOffline;
  63406. },
  63407. enumerable: true,
  63408. configurable: true
  63409. });
  63410. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  63411. get: function () {
  63412. return this._enableTexturesOffline;
  63413. },
  63414. enumerable: true,
  63415. configurable: true
  63416. });
  63417. Database.prototype.checkManifestFile = function () {
  63418. var _this = this;
  63419. var noManifestFile = function () {
  63420. _this._enableSceneOffline = false;
  63421. _this._enableTexturesOffline = false;
  63422. _this.callbackManifestChecked(false);
  63423. };
  63424. var timeStampUsed = false;
  63425. var manifestURL = this.currentSceneUrl + ".manifest";
  63426. var xhr = new XMLHttpRequest();
  63427. if (navigator.onLine) {
  63428. // Adding a timestamp to by-pass browsers' cache
  63429. timeStampUsed = true;
  63430. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  63431. }
  63432. xhr.open("GET", manifestURL, true);
  63433. xhr.addEventListener("load", function () {
  63434. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63435. try {
  63436. var manifestFile = JSON.parse(xhr.response);
  63437. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  63438. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  63439. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  63440. _this.manifestVersionFound = manifestFile.version;
  63441. }
  63442. if (_this.callbackManifestChecked) {
  63443. _this.callbackManifestChecked(true);
  63444. }
  63445. }
  63446. catch (ex) {
  63447. noManifestFile();
  63448. }
  63449. }
  63450. else {
  63451. noManifestFile();
  63452. }
  63453. }, false);
  63454. xhr.addEventListener("error", function (event) {
  63455. if (timeStampUsed) {
  63456. timeStampUsed = false;
  63457. // Let's retry without the timeStamp
  63458. // It could fail when coupled with HTML5 Offline API
  63459. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  63460. xhr.open("GET", retryManifestURL, true);
  63461. xhr.send();
  63462. }
  63463. else {
  63464. noManifestFile();
  63465. }
  63466. }, false);
  63467. try {
  63468. xhr.send();
  63469. }
  63470. catch (ex) {
  63471. BABYLON.Tools.Error("Error on XHR send request.");
  63472. this.callbackManifestChecked(false);
  63473. }
  63474. };
  63475. Database.prototype.openAsync = function (successCallback, errorCallback) {
  63476. var _this = this;
  63477. var handleError = function () {
  63478. _this.isSupported = false;
  63479. if (errorCallback)
  63480. errorCallback();
  63481. };
  63482. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  63483. // Your browser doesn't support IndexedDB
  63484. this.isSupported = false;
  63485. if (errorCallback)
  63486. errorCallback();
  63487. }
  63488. else {
  63489. // If the DB hasn't been opened or created yet
  63490. if (!this.db) {
  63491. this.hasReachedQuota = false;
  63492. this.isSupported = true;
  63493. var request = this.idbFactory.open("babylonjs", 1);
  63494. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  63495. request.onerror = function (event) {
  63496. handleError();
  63497. };
  63498. // executes when a version change transaction cannot complete due to other active transactions
  63499. request.onblocked = function (event) {
  63500. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  63501. handleError();
  63502. };
  63503. // DB has been opened successfully
  63504. request.onsuccess = function (event) {
  63505. _this.db = request.result;
  63506. successCallback();
  63507. };
  63508. // Initialization of the DB. Creating Scenes & Textures stores
  63509. request.onupgradeneeded = function (event) {
  63510. _this.db = (event.target).result;
  63511. if (_this.db) {
  63512. try {
  63513. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  63514. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  63515. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  63516. }
  63517. catch (ex) {
  63518. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  63519. handleError();
  63520. }
  63521. }
  63522. };
  63523. }
  63524. else {
  63525. if (successCallback)
  63526. successCallback();
  63527. }
  63528. }
  63529. };
  63530. Database.prototype.loadImageFromDB = function (url, image) {
  63531. var _this = this;
  63532. var completeURL = Database.ReturnFullUrlLocation(url);
  63533. var saveAndLoadImage = function () {
  63534. if (!_this.hasReachedQuota && _this.db !== null) {
  63535. // the texture is not yet in the DB, let's try to save it
  63536. _this._saveImageIntoDBAsync(completeURL, image);
  63537. }
  63538. else {
  63539. image.src = url;
  63540. }
  63541. };
  63542. if (!this.mustUpdateRessources) {
  63543. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  63544. }
  63545. else {
  63546. saveAndLoadImage();
  63547. }
  63548. };
  63549. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  63550. if (this.isSupported && this.db !== null) {
  63551. var texture;
  63552. var transaction = this.db.transaction(["textures"]);
  63553. transaction.onabort = function (event) {
  63554. image.src = url;
  63555. };
  63556. transaction.oncomplete = function (event) {
  63557. var blobTextureURL;
  63558. if (texture) {
  63559. var URL = window.URL || window.webkitURL;
  63560. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  63561. image.onerror = function () {
  63562. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  63563. image.src = url;
  63564. };
  63565. image.src = blobTextureURL;
  63566. }
  63567. else {
  63568. notInDBCallback();
  63569. }
  63570. };
  63571. var getRequest = transaction.objectStore("textures").get(url);
  63572. getRequest.onsuccess = function (event) {
  63573. texture = (event.target).result;
  63574. };
  63575. getRequest.onerror = function (event) {
  63576. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  63577. image.src = url;
  63578. };
  63579. }
  63580. else {
  63581. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63582. image.src = url;
  63583. }
  63584. };
  63585. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  63586. var _this = this;
  63587. if (this.isSupported) {
  63588. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  63589. var generateBlobUrl = function () {
  63590. var blobTextureURL;
  63591. if (blob) {
  63592. var URL = window.URL || window.webkitURL;
  63593. try {
  63594. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  63595. }
  63596. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  63597. catch (ex) {
  63598. blobTextureURL = URL.createObjectURL(blob);
  63599. }
  63600. }
  63601. if (blobTextureURL) {
  63602. image.src = blobTextureURL;
  63603. }
  63604. };
  63605. if (Database.IsUASupportingBlobStorage) {
  63606. var xhr = new XMLHttpRequest(), blob;
  63607. xhr.open("GET", url, true);
  63608. xhr.responseType = "blob";
  63609. xhr.addEventListener("load", function () {
  63610. if (xhr.status === 200 && _this.db) {
  63611. // Blob as response (XHR2)
  63612. blob = xhr.response;
  63613. var transaction = _this.db.transaction(["textures"], "readwrite");
  63614. // the transaction could abort because of a QuotaExceededError error
  63615. transaction.onabort = function (event) {
  63616. try {
  63617. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63618. var srcElement = (event.srcElement || event.target);
  63619. var error = srcElement.error;
  63620. if (error && error.name === "QuotaExceededError") {
  63621. _this.hasReachedQuota = true;
  63622. }
  63623. }
  63624. catch (ex) { }
  63625. generateBlobUrl();
  63626. };
  63627. transaction.oncomplete = function (event) {
  63628. generateBlobUrl();
  63629. };
  63630. var newTexture = { textureUrl: url, data: blob };
  63631. try {
  63632. // Put the blob into the dabase
  63633. var addRequest = transaction.objectStore("textures").put(newTexture);
  63634. addRequest.onsuccess = function (event) {
  63635. };
  63636. addRequest.onerror = function (event) {
  63637. generateBlobUrl();
  63638. };
  63639. }
  63640. catch (ex) {
  63641. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  63642. if (ex.code === 25) {
  63643. Database.IsUASupportingBlobStorage = false;
  63644. }
  63645. image.src = url;
  63646. }
  63647. }
  63648. else {
  63649. image.src = url;
  63650. }
  63651. }, false);
  63652. xhr.addEventListener("error", function (event) {
  63653. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  63654. image.src = url;
  63655. }, false);
  63656. xhr.send();
  63657. }
  63658. else {
  63659. image.src = url;
  63660. }
  63661. }
  63662. else {
  63663. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63664. image.src = url;
  63665. }
  63666. };
  63667. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  63668. var _this = this;
  63669. var updateVersion = function () {
  63670. // the version is not yet in the DB or we need to update it
  63671. _this._saveVersionIntoDBAsync(url, versionLoaded);
  63672. };
  63673. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  63674. };
  63675. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  63676. var _this = this;
  63677. if (this.isSupported && this.db) {
  63678. var version;
  63679. try {
  63680. var transaction = this.db.transaction(["versions"]);
  63681. transaction.oncomplete = function (event) {
  63682. if (version) {
  63683. // If the version in the JSON file is > than the version in DB
  63684. if (_this.manifestVersionFound > version.data) {
  63685. _this.mustUpdateRessources = true;
  63686. updateInDBCallback();
  63687. }
  63688. else {
  63689. callback(version.data);
  63690. }
  63691. }
  63692. else {
  63693. _this.mustUpdateRessources = true;
  63694. updateInDBCallback();
  63695. }
  63696. };
  63697. transaction.onabort = function (event) {
  63698. callback(-1);
  63699. };
  63700. var getRequest = transaction.objectStore("versions").get(url);
  63701. getRequest.onsuccess = function (event) {
  63702. version = (event.target).result;
  63703. };
  63704. getRequest.onerror = function (event) {
  63705. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  63706. callback(-1);
  63707. };
  63708. }
  63709. catch (ex) {
  63710. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  63711. callback(-1);
  63712. }
  63713. }
  63714. else {
  63715. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63716. callback(-1);
  63717. }
  63718. };
  63719. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  63720. var _this = this;
  63721. if (this.isSupported && !this.hasReachedQuota && this.db) {
  63722. try {
  63723. // Open a transaction to the database
  63724. var transaction = this.db.transaction(["versions"], "readwrite");
  63725. // the transaction could abort because of a QuotaExceededError error
  63726. transaction.onabort = function (event) {
  63727. try {
  63728. var error = event.srcElement['error'];
  63729. if (error && error.name === "QuotaExceededError") {
  63730. _this.hasReachedQuota = true;
  63731. }
  63732. }
  63733. catch (ex) { }
  63734. callback(-1);
  63735. };
  63736. transaction.oncomplete = function (event) {
  63737. callback(_this.manifestVersionFound);
  63738. };
  63739. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  63740. // Put the scene into the database
  63741. var addRequest = transaction.objectStore("versions").put(newVersion);
  63742. addRequest.onsuccess = function (event) {
  63743. };
  63744. addRequest.onerror = function (event) {
  63745. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  63746. };
  63747. }
  63748. catch (ex) {
  63749. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  63750. callback(-1);
  63751. }
  63752. }
  63753. else {
  63754. callback(-1);
  63755. }
  63756. };
  63757. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  63758. var _this = this;
  63759. var completeUrl = Database.ReturnFullUrlLocation(url);
  63760. var saveAndLoadFile = function () {
  63761. // the scene is not yet in the DB, let's try to save it
  63762. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  63763. };
  63764. this._checkVersionFromDB(completeUrl, function (version) {
  63765. if (version !== -1) {
  63766. if (!_this.mustUpdateRessources) {
  63767. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  63768. }
  63769. else {
  63770. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  63771. }
  63772. }
  63773. else {
  63774. if (errorCallback) {
  63775. errorCallback();
  63776. }
  63777. }
  63778. });
  63779. };
  63780. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  63781. if (this.isSupported && this.db) {
  63782. var targetStore;
  63783. if (url.indexOf(".babylon") !== -1) {
  63784. targetStore = "scenes";
  63785. }
  63786. else {
  63787. targetStore = "textures";
  63788. }
  63789. var file;
  63790. var transaction = this.db.transaction([targetStore]);
  63791. transaction.oncomplete = function (event) {
  63792. if (file) {
  63793. callback(file.data);
  63794. }
  63795. else {
  63796. notInDBCallback();
  63797. }
  63798. };
  63799. transaction.onabort = function (event) {
  63800. notInDBCallback();
  63801. };
  63802. var getRequest = transaction.objectStore(targetStore).get(url);
  63803. getRequest.onsuccess = function (event) {
  63804. file = (event.target).result;
  63805. };
  63806. getRequest.onerror = function (event) {
  63807. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  63808. notInDBCallback();
  63809. };
  63810. }
  63811. else {
  63812. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63813. callback();
  63814. }
  63815. };
  63816. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  63817. var _this = this;
  63818. if (this.isSupported) {
  63819. var targetStore;
  63820. if (url.indexOf(".babylon") !== -1) {
  63821. targetStore = "scenes";
  63822. }
  63823. else {
  63824. targetStore = "textures";
  63825. }
  63826. // Create XHR
  63827. var xhr = new XMLHttpRequest();
  63828. var fileData;
  63829. xhr.open("GET", url, true);
  63830. if (useArrayBuffer) {
  63831. xhr.responseType = "arraybuffer";
  63832. }
  63833. if (progressCallback) {
  63834. xhr.onprogress = progressCallback;
  63835. }
  63836. xhr.addEventListener("load", function () {
  63837. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  63838. // Blob as response (XHR2)
  63839. //fileData = xhr.responseText;
  63840. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  63841. if (!_this.hasReachedQuota && _this.db) {
  63842. // Open a transaction to the database
  63843. var transaction = _this.db.transaction([targetStore], "readwrite");
  63844. // the transaction could abort because of a QuotaExceededError error
  63845. transaction.onabort = function (event) {
  63846. try {
  63847. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63848. var error = event.srcElement['error'];
  63849. if (error && error.name === "QuotaExceededError") {
  63850. _this.hasReachedQuota = true;
  63851. }
  63852. }
  63853. catch (ex) { }
  63854. callback(fileData);
  63855. };
  63856. transaction.oncomplete = function (event) {
  63857. callback(fileData);
  63858. };
  63859. var newFile;
  63860. if (targetStore === "scenes") {
  63861. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  63862. }
  63863. else {
  63864. newFile = { textureUrl: url, data: fileData };
  63865. }
  63866. try {
  63867. // Put the scene into the database
  63868. var addRequest = transaction.objectStore(targetStore).put(newFile);
  63869. addRequest.onsuccess = function (event) {
  63870. };
  63871. addRequest.onerror = function (event) {
  63872. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  63873. };
  63874. }
  63875. catch (ex) {
  63876. callback(fileData);
  63877. }
  63878. }
  63879. else {
  63880. callback(fileData);
  63881. }
  63882. }
  63883. else {
  63884. callback();
  63885. }
  63886. }, false);
  63887. xhr.addEventListener("error", function (event) {
  63888. BABYLON.Tools.Error("error on XHR request.");
  63889. callback();
  63890. }, false);
  63891. xhr.send();
  63892. }
  63893. else {
  63894. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63895. callback();
  63896. }
  63897. };
  63898. Database.IsUASupportingBlobStorage = true;
  63899. Database.IDBStorageEnabled = true;
  63900. Database.parseURL = function (url) {
  63901. var a = document.createElement('a');
  63902. a.href = url;
  63903. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  63904. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  63905. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  63906. return absLocation;
  63907. };
  63908. Database.ReturnFullUrlLocation = function (url) {
  63909. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  63910. return (Database.parseURL(window.location.href) + url);
  63911. }
  63912. else {
  63913. return url;
  63914. }
  63915. };
  63916. return Database;
  63917. }());
  63918. BABYLON.Database = Database;
  63919. })(BABYLON || (BABYLON = {}));
  63920. //# sourceMappingURL=babylon.database.js.map
  63921. "use strict";
  63922. var BABYLON;
  63923. (function (BABYLON) {
  63924. var FresnelParameters = /** @class */ (function () {
  63925. function FresnelParameters() {
  63926. this._isEnabled = true;
  63927. this.leftColor = BABYLON.Color3.White();
  63928. this.rightColor = BABYLON.Color3.Black();
  63929. this.bias = 0;
  63930. this.power = 1;
  63931. }
  63932. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  63933. get: function () {
  63934. return this._isEnabled;
  63935. },
  63936. set: function (value) {
  63937. if (this._isEnabled === value) {
  63938. return;
  63939. }
  63940. this._isEnabled = value;
  63941. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  63942. },
  63943. enumerable: true,
  63944. configurable: true
  63945. });
  63946. FresnelParameters.prototype.clone = function () {
  63947. var newFresnelParameters = new FresnelParameters();
  63948. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  63949. return newFresnelParameters;
  63950. };
  63951. FresnelParameters.prototype.serialize = function () {
  63952. var serializationObject = {};
  63953. serializationObject.isEnabled = this.isEnabled;
  63954. serializationObject.leftColor = this.leftColor;
  63955. serializationObject.rightColor = this.rightColor;
  63956. serializationObject.bias = this.bias;
  63957. serializationObject.power = this.power;
  63958. return serializationObject;
  63959. };
  63960. FresnelParameters.Parse = function (parsedFresnelParameters) {
  63961. var fresnelParameters = new FresnelParameters();
  63962. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  63963. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  63964. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  63965. fresnelParameters.bias = parsedFresnelParameters.bias;
  63966. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  63967. return fresnelParameters;
  63968. };
  63969. return FresnelParameters;
  63970. }());
  63971. BABYLON.FresnelParameters = FresnelParameters;
  63972. })(BABYLON || (BABYLON = {}));
  63973. //# sourceMappingURL=babylon.fresnelParameters.js.map
  63974. "use strict";
  63975. var BABYLON;
  63976. (function (BABYLON) {
  63977. var MultiMaterial = /** @class */ (function (_super) {
  63978. __extends(MultiMaterial, _super);
  63979. function MultiMaterial(name, scene) {
  63980. var _this = _super.call(this, name, scene, true) || this;
  63981. scene.multiMaterials.push(_this);
  63982. _this.subMaterials = new Array();
  63983. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  63984. return _this;
  63985. }
  63986. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  63987. get: function () {
  63988. return this._subMaterials;
  63989. },
  63990. set: function (value) {
  63991. this._subMaterials = value;
  63992. this._hookArray(value);
  63993. },
  63994. enumerable: true,
  63995. configurable: true
  63996. });
  63997. MultiMaterial.prototype._hookArray = function (array) {
  63998. var _this = this;
  63999. var oldPush = array.push;
  64000. array.push = function () {
  64001. var items = [];
  64002. for (var _i = 0; _i < arguments.length; _i++) {
  64003. items[_i] = arguments[_i];
  64004. }
  64005. var result = oldPush.apply(array, items);
  64006. _this._markAllSubMeshesAsTexturesDirty();
  64007. return result;
  64008. };
  64009. var oldSplice = array.splice;
  64010. array.splice = function (index, deleteCount) {
  64011. var deleted = oldSplice.apply(array, [index, deleteCount]);
  64012. _this._markAllSubMeshesAsTexturesDirty();
  64013. return deleted;
  64014. };
  64015. };
  64016. // Properties
  64017. MultiMaterial.prototype.getSubMaterial = function (index) {
  64018. if (index < 0 || index >= this.subMaterials.length) {
  64019. return this.getScene().defaultMaterial;
  64020. }
  64021. return this.subMaterials[index];
  64022. };
  64023. MultiMaterial.prototype.getActiveTextures = function () {
  64024. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  64025. if (subMaterial) {
  64026. return subMaterial.getActiveTextures();
  64027. }
  64028. else {
  64029. return [];
  64030. }
  64031. }));
  64032. var _a;
  64033. };
  64034. // Methods
  64035. MultiMaterial.prototype.getClassName = function () {
  64036. return "MultiMaterial";
  64037. };
  64038. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  64039. for (var index = 0; index < this.subMaterials.length; index++) {
  64040. var subMaterial = this.subMaterials[index];
  64041. if (subMaterial) {
  64042. if (subMaterial.storeEffectOnSubMeshes) {
  64043. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  64044. return false;
  64045. }
  64046. continue;
  64047. }
  64048. if (!subMaterial.isReady(mesh)) {
  64049. return false;
  64050. }
  64051. }
  64052. }
  64053. return true;
  64054. };
  64055. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  64056. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  64057. for (var index = 0; index < this.subMaterials.length; index++) {
  64058. var subMaterial = null;
  64059. var current = this.subMaterials[index];
  64060. if (cloneChildren && current) {
  64061. subMaterial = current.clone(name + "-" + current.name);
  64062. }
  64063. else {
  64064. subMaterial = this.subMaterials[index];
  64065. }
  64066. newMultiMaterial.subMaterials.push(subMaterial);
  64067. }
  64068. return newMultiMaterial;
  64069. };
  64070. MultiMaterial.prototype.serialize = function () {
  64071. var serializationObject = {};
  64072. serializationObject.name = this.name;
  64073. serializationObject.id = this.id;
  64074. if (BABYLON.Tags) {
  64075. serializationObject.tags = BABYLON.Tags.GetTags(this);
  64076. }
  64077. serializationObject.materials = [];
  64078. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  64079. var subMat = this.subMaterials[matIndex];
  64080. if (subMat) {
  64081. serializationObject.materials.push(subMat.id);
  64082. }
  64083. else {
  64084. serializationObject.materials.push(null);
  64085. }
  64086. }
  64087. return serializationObject;
  64088. };
  64089. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  64090. var scene = this.getScene();
  64091. if (!scene) {
  64092. return;
  64093. }
  64094. var index = scene.multiMaterials.indexOf(this);
  64095. if (index >= 0) {
  64096. scene.multiMaterials.splice(index, 1);
  64097. }
  64098. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  64099. };
  64100. return MultiMaterial;
  64101. }(BABYLON.Material));
  64102. BABYLON.MultiMaterial = MultiMaterial;
  64103. })(BABYLON || (BABYLON = {}));
  64104. //# sourceMappingURL=babylon.multiMaterial.js.map
  64105. "use strict";
  64106. var BABYLON;
  64107. (function (BABYLON) {
  64108. var FreeCameraTouchInput = /** @class */ (function () {
  64109. function FreeCameraTouchInput() {
  64110. this._offsetX = null;
  64111. this._offsetY = null;
  64112. this._pointerPressed = new Array();
  64113. this.touchAngularSensibility = 200000.0;
  64114. this.touchMoveSensibility = 250.0;
  64115. }
  64116. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  64117. var _this = this;
  64118. var previousPosition = null;
  64119. if (this._pointerInput === undefined) {
  64120. this._onLostFocus = function (evt) {
  64121. _this._offsetX = null;
  64122. _this._offsetY = null;
  64123. };
  64124. this._pointerInput = function (p, s) {
  64125. var evt = p.event;
  64126. if (evt.pointerType === "mouse") {
  64127. return;
  64128. }
  64129. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  64130. if (!noPreventDefault) {
  64131. evt.preventDefault();
  64132. }
  64133. _this._pointerPressed.push(evt.pointerId);
  64134. if (_this._pointerPressed.length !== 1) {
  64135. return;
  64136. }
  64137. previousPosition = {
  64138. x: evt.clientX,
  64139. y: evt.clientY
  64140. };
  64141. }
  64142. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  64143. if (!noPreventDefault) {
  64144. evt.preventDefault();
  64145. }
  64146. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64147. if (index === -1) {
  64148. return;
  64149. }
  64150. _this._pointerPressed.splice(index, 1);
  64151. if (index != 0) {
  64152. return;
  64153. }
  64154. previousPosition = null;
  64155. _this._offsetX = null;
  64156. _this._offsetY = null;
  64157. }
  64158. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  64159. if (!noPreventDefault) {
  64160. evt.preventDefault();
  64161. }
  64162. if (!previousPosition) {
  64163. return;
  64164. }
  64165. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64166. if (index != 0) {
  64167. return;
  64168. }
  64169. _this._offsetX = evt.clientX - previousPosition.x;
  64170. _this._offsetY = -(evt.clientY - previousPosition.y);
  64171. }
  64172. };
  64173. }
  64174. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  64175. if (this._onLostFocus) {
  64176. element.addEventListener("blur", this._onLostFocus);
  64177. }
  64178. };
  64179. FreeCameraTouchInput.prototype.detachControl = function (element) {
  64180. if (this._pointerInput && element) {
  64181. if (this._observer) {
  64182. this.camera.getScene().onPointerObservable.remove(this._observer);
  64183. this._observer = null;
  64184. }
  64185. if (this._onLostFocus) {
  64186. element.removeEventListener("blur", this._onLostFocus);
  64187. this._onLostFocus = null;
  64188. }
  64189. this._pointerPressed = [];
  64190. this._offsetX = null;
  64191. this._offsetY = null;
  64192. }
  64193. };
  64194. FreeCameraTouchInput.prototype.checkInputs = function () {
  64195. if (this._offsetX && this._offsetY) {
  64196. var camera = this.camera;
  64197. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  64198. if (this._pointerPressed.length > 1) {
  64199. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  64200. }
  64201. else {
  64202. var speed = camera._computeLocalCameraSpeed();
  64203. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  64204. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  64205. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  64206. }
  64207. }
  64208. };
  64209. FreeCameraTouchInput.prototype.getClassName = function () {
  64210. return "FreeCameraTouchInput";
  64211. };
  64212. FreeCameraTouchInput.prototype.getSimpleName = function () {
  64213. return "touch";
  64214. };
  64215. __decorate([
  64216. BABYLON.serialize()
  64217. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  64218. __decorate([
  64219. BABYLON.serialize()
  64220. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  64221. return FreeCameraTouchInput;
  64222. }());
  64223. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  64224. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  64225. })(BABYLON || (BABYLON = {}));
  64226. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  64227. "use strict";
  64228. var BABYLON;
  64229. (function (BABYLON) {
  64230. // We're mainly based on the logic defined into the FreeCamera code
  64231. var TouchCamera = /** @class */ (function (_super) {
  64232. __extends(TouchCamera, _super);
  64233. //-- end properties for backward compatibility for inputs
  64234. function TouchCamera(name, position, scene) {
  64235. var _this = _super.call(this, name, position, scene) || this;
  64236. _this.inputs.addTouch();
  64237. _this._setupInputs();
  64238. return _this;
  64239. }
  64240. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  64241. //-- Begin properties for backward compatibility for inputs
  64242. get: function () {
  64243. var touch = this.inputs.attached["touch"];
  64244. if (touch)
  64245. return touch.touchAngularSensibility;
  64246. return 0;
  64247. },
  64248. set: function (value) {
  64249. var touch = this.inputs.attached["touch"];
  64250. if (touch)
  64251. touch.touchAngularSensibility = value;
  64252. },
  64253. enumerable: true,
  64254. configurable: true
  64255. });
  64256. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  64257. get: function () {
  64258. var touch = this.inputs.attached["touch"];
  64259. if (touch)
  64260. return touch.touchMoveSensibility;
  64261. return 0;
  64262. },
  64263. set: function (value) {
  64264. var touch = this.inputs.attached["touch"];
  64265. if (touch)
  64266. touch.touchMoveSensibility = value;
  64267. },
  64268. enumerable: true,
  64269. configurable: true
  64270. });
  64271. TouchCamera.prototype.getClassName = function () {
  64272. return "TouchCamera";
  64273. };
  64274. TouchCamera.prototype._setupInputs = function () {
  64275. var mouse = this.inputs.attached["mouse"];
  64276. if (mouse) {
  64277. mouse.touchEnabled = false;
  64278. }
  64279. };
  64280. return TouchCamera;
  64281. }(BABYLON.FreeCamera));
  64282. BABYLON.TouchCamera = TouchCamera;
  64283. })(BABYLON || (BABYLON = {}));
  64284. //# sourceMappingURL=babylon.touchCamera.js.map
  64285. "use strict";
  64286. var BABYLON;
  64287. (function (BABYLON) {
  64288. var ProceduralTexture = /** @class */ (function (_super) {
  64289. __extends(ProceduralTexture, _super);
  64290. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  64291. if (fallbackTexture === void 0) { fallbackTexture = null; }
  64292. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64293. if (isCube === void 0) { isCube = false; }
  64294. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64295. _this.isCube = isCube;
  64296. _this.isEnabled = true;
  64297. _this._currentRefreshId = -1;
  64298. _this._refreshRate = 1;
  64299. _this._vertexBuffers = {};
  64300. _this._uniforms = new Array();
  64301. _this._samplers = new Array();
  64302. _this._textures = {};
  64303. _this._floats = {};
  64304. _this._floatsArrays = {};
  64305. _this._colors3 = {};
  64306. _this._colors4 = {};
  64307. _this._vectors2 = {};
  64308. _this._vectors3 = {};
  64309. _this._matrices = {};
  64310. _this._fallbackTextureUsed = false;
  64311. scene._proceduralTextures.push(_this);
  64312. _this._engine = scene.getEngine();
  64313. _this.name = name;
  64314. _this.isRenderTarget = true;
  64315. _this._size = size;
  64316. _this._generateMipMaps = generateMipMaps;
  64317. _this.setFragment(fragment);
  64318. _this._fallbackTexture = fallbackTexture;
  64319. if (isCube) {
  64320. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  64321. _this.setFloat("face", 0);
  64322. }
  64323. else {
  64324. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  64325. }
  64326. // VBO
  64327. var vertices = [];
  64328. vertices.push(1, 1);
  64329. vertices.push(-1, 1);
  64330. vertices.push(-1, -1);
  64331. vertices.push(1, -1);
  64332. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64333. _this._createIndexBuffer();
  64334. return _this;
  64335. }
  64336. ProceduralTexture.prototype._createIndexBuffer = function () {
  64337. var engine = this._engine;
  64338. // Indices
  64339. var indices = [];
  64340. indices.push(0);
  64341. indices.push(1);
  64342. indices.push(2);
  64343. indices.push(0);
  64344. indices.push(2);
  64345. indices.push(3);
  64346. this._indexBuffer = engine.createIndexBuffer(indices);
  64347. };
  64348. ProceduralTexture.prototype._rebuild = function () {
  64349. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64350. if (vb) {
  64351. vb._rebuild();
  64352. }
  64353. this._createIndexBuffer();
  64354. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64355. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64356. }
  64357. };
  64358. ProceduralTexture.prototype.reset = function () {
  64359. if (this._effect === undefined) {
  64360. return;
  64361. }
  64362. var engine = this._engine;
  64363. engine._releaseEffect(this._effect);
  64364. };
  64365. ProceduralTexture.prototype.isReady = function () {
  64366. var _this = this;
  64367. var engine = this._engine;
  64368. var shaders;
  64369. if (!this._fragment) {
  64370. return false;
  64371. }
  64372. if (this._fallbackTextureUsed) {
  64373. return true;
  64374. }
  64375. if (this._fragment.fragmentElement !== undefined) {
  64376. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  64377. }
  64378. else {
  64379. shaders = { vertex: "procedural", fragment: this._fragment };
  64380. }
  64381. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  64382. _this.releaseInternalTexture();
  64383. if (_this._fallbackTexture) {
  64384. _this._texture = _this._fallbackTexture._texture;
  64385. if (_this._texture) {
  64386. _this._texture.incrementReferences();
  64387. }
  64388. }
  64389. _this._fallbackTextureUsed = true;
  64390. });
  64391. return this._effect.isReady();
  64392. };
  64393. ProceduralTexture.prototype.resetRefreshCounter = function () {
  64394. this._currentRefreshId = -1;
  64395. };
  64396. ProceduralTexture.prototype.setFragment = function (fragment) {
  64397. this._fragment = fragment;
  64398. };
  64399. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  64400. get: function () {
  64401. return this._refreshRate;
  64402. },
  64403. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64404. set: function (value) {
  64405. this._refreshRate = value;
  64406. this.resetRefreshCounter();
  64407. },
  64408. enumerable: true,
  64409. configurable: true
  64410. });
  64411. ProceduralTexture.prototype._shouldRender = function () {
  64412. if (!this.isEnabled || !this.isReady() || !this._texture) {
  64413. return false;
  64414. }
  64415. if (this._fallbackTextureUsed) {
  64416. return false;
  64417. }
  64418. if (this._currentRefreshId === -1) {
  64419. this._currentRefreshId = 1;
  64420. return true;
  64421. }
  64422. if (this.refreshRate === this._currentRefreshId) {
  64423. this._currentRefreshId = 1;
  64424. return true;
  64425. }
  64426. this._currentRefreshId++;
  64427. return false;
  64428. };
  64429. ProceduralTexture.prototype.getRenderSize = function () {
  64430. return this._size;
  64431. };
  64432. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  64433. if (this._fallbackTextureUsed) {
  64434. return;
  64435. }
  64436. this.releaseInternalTexture();
  64437. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  64438. };
  64439. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  64440. if (this._uniforms.indexOf(uniformName) === -1) {
  64441. this._uniforms.push(uniformName);
  64442. }
  64443. };
  64444. ProceduralTexture.prototype.setTexture = function (name, texture) {
  64445. if (this._samplers.indexOf(name) === -1) {
  64446. this._samplers.push(name);
  64447. }
  64448. this._textures[name] = texture;
  64449. return this;
  64450. };
  64451. ProceduralTexture.prototype.setFloat = function (name, value) {
  64452. this._checkUniform(name);
  64453. this._floats[name] = value;
  64454. return this;
  64455. };
  64456. ProceduralTexture.prototype.setFloats = function (name, value) {
  64457. this._checkUniform(name);
  64458. this._floatsArrays[name] = value;
  64459. return this;
  64460. };
  64461. ProceduralTexture.prototype.setColor3 = function (name, value) {
  64462. this._checkUniform(name);
  64463. this._colors3[name] = value;
  64464. return this;
  64465. };
  64466. ProceduralTexture.prototype.setColor4 = function (name, value) {
  64467. this._checkUniform(name);
  64468. this._colors4[name] = value;
  64469. return this;
  64470. };
  64471. ProceduralTexture.prototype.setVector2 = function (name, value) {
  64472. this._checkUniform(name);
  64473. this._vectors2[name] = value;
  64474. return this;
  64475. };
  64476. ProceduralTexture.prototype.setVector3 = function (name, value) {
  64477. this._checkUniform(name);
  64478. this._vectors3[name] = value;
  64479. return this;
  64480. };
  64481. ProceduralTexture.prototype.setMatrix = function (name, value) {
  64482. this._checkUniform(name);
  64483. this._matrices[name] = value;
  64484. return this;
  64485. };
  64486. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64487. var scene = this.getScene();
  64488. if (!scene) {
  64489. return;
  64490. }
  64491. var engine = this._engine;
  64492. // Render
  64493. engine.enableEffect(this._effect);
  64494. engine.setState(false);
  64495. // Texture
  64496. for (var name in this._textures) {
  64497. this._effect.setTexture(name, this._textures[name]);
  64498. }
  64499. // Float
  64500. for (name in this._floats) {
  64501. this._effect.setFloat(name, this._floats[name]);
  64502. }
  64503. // Floats
  64504. for (name in this._floatsArrays) {
  64505. this._effect.setArray(name, this._floatsArrays[name]);
  64506. }
  64507. // Color3
  64508. for (name in this._colors3) {
  64509. this._effect.setColor3(name, this._colors3[name]);
  64510. }
  64511. // Color4
  64512. for (name in this._colors4) {
  64513. var color = this._colors4[name];
  64514. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64515. }
  64516. // Vector2
  64517. for (name in this._vectors2) {
  64518. this._effect.setVector2(name, this._vectors2[name]);
  64519. }
  64520. // Vector3
  64521. for (name in this._vectors3) {
  64522. this._effect.setVector3(name, this._vectors3[name]);
  64523. }
  64524. // Matrix
  64525. for (name in this._matrices) {
  64526. this._effect.setMatrix(name, this._matrices[name]);
  64527. }
  64528. if (!this._texture) {
  64529. return;
  64530. }
  64531. if (this.isCube) {
  64532. for (var face = 0; face < 6; face++) {
  64533. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  64534. // VBOs
  64535. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64536. this._effect.setFloat("face", face);
  64537. // Clear
  64538. engine.clear(scene.clearColor, true, true, true);
  64539. // Draw order
  64540. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64541. // Mipmaps
  64542. if (face === 5) {
  64543. engine.generateMipMapsForCubemap(this._texture);
  64544. }
  64545. }
  64546. }
  64547. else {
  64548. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  64549. // VBOs
  64550. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64551. // Clear
  64552. engine.clear(scene.clearColor, true, true, true);
  64553. // Draw order
  64554. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64555. }
  64556. // Unbind
  64557. engine.unBindFramebuffer(this._texture, this.isCube);
  64558. if (this.onGenerated) {
  64559. this.onGenerated();
  64560. }
  64561. };
  64562. ProceduralTexture.prototype.clone = function () {
  64563. var textureSize = this.getSize();
  64564. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  64565. // Base texture
  64566. newTexture.hasAlpha = this.hasAlpha;
  64567. newTexture.level = this.level;
  64568. // RenderTarget Texture
  64569. newTexture.coordinatesMode = this.coordinatesMode;
  64570. return newTexture;
  64571. };
  64572. ProceduralTexture.prototype.dispose = function () {
  64573. var scene = this.getScene();
  64574. if (!scene) {
  64575. return;
  64576. }
  64577. var index = scene._proceduralTextures.indexOf(this);
  64578. if (index >= 0) {
  64579. scene._proceduralTextures.splice(index, 1);
  64580. }
  64581. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64582. if (vertexBuffer) {
  64583. vertexBuffer.dispose();
  64584. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64585. }
  64586. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  64587. this._indexBuffer = null;
  64588. }
  64589. _super.prototype.dispose.call(this);
  64590. };
  64591. return ProceduralTexture;
  64592. }(BABYLON.Texture));
  64593. BABYLON.ProceduralTexture = ProceduralTexture;
  64594. })(BABYLON || (BABYLON = {}));
  64595. //# sourceMappingURL=babylon.proceduralTexture.js.map
  64596. "use strict";
  64597. var BABYLON;
  64598. (function (BABYLON) {
  64599. var CustomProceduralTexture = /** @class */ (function (_super) {
  64600. __extends(CustomProceduralTexture, _super);
  64601. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  64602. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  64603. _this._animate = true;
  64604. _this._time = 0;
  64605. _this._texturePath = texturePath;
  64606. //Try to load json
  64607. _this.loadJson(texturePath);
  64608. _this.refreshRate = 1;
  64609. return _this;
  64610. }
  64611. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  64612. var _this = this;
  64613. var noConfigFile = function () {
  64614. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  64615. try {
  64616. _this.setFragment(_this._texturePath);
  64617. }
  64618. catch (ex) {
  64619. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  64620. }
  64621. };
  64622. var configFileUrl = jsonUrl + "/config.json";
  64623. var xhr = new XMLHttpRequest();
  64624. xhr.open("GET", configFileUrl, true);
  64625. xhr.addEventListener("load", function () {
  64626. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64627. try {
  64628. _this._config = JSON.parse(xhr.response);
  64629. _this.updateShaderUniforms();
  64630. _this.updateTextures();
  64631. _this.setFragment(_this._texturePath + "/custom");
  64632. _this._animate = _this._config.animate;
  64633. _this.refreshRate = _this._config.refreshrate;
  64634. }
  64635. catch (ex) {
  64636. noConfigFile();
  64637. }
  64638. }
  64639. else {
  64640. noConfigFile();
  64641. }
  64642. }, false);
  64643. xhr.addEventListener("error", function () {
  64644. noConfigFile();
  64645. }, false);
  64646. try {
  64647. xhr.send();
  64648. }
  64649. catch (ex) {
  64650. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  64651. }
  64652. };
  64653. CustomProceduralTexture.prototype.isReady = function () {
  64654. if (!_super.prototype.isReady.call(this)) {
  64655. return false;
  64656. }
  64657. for (var name in this._textures) {
  64658. var texture = this._textures[name];
  64659. if (!texture.isReady()) {
  64660. return false;
  64661. }
  64662. }
  64663. return true;
  64664. };
  64665. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64666. var scene = this.getScene();
  64667. if (this._animate && scene) {
  64668. this._time += scene.getAnimationRatio() * 0.03;
  64669. this.updateShaderUniforms();
  64670. }
  64671. _super.prototype.render.call(this, useCameraPostProcess);
  64672. };
  64673. CustomProceduralTexture.prototype.updateTextures = function () {
  64674. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  64675. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  64676. }
  64677. };
  64678. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  64679. if (this._config) {
  64680. for (var j = 0; j < this._config.uniforms.length; j++) {
  64681. var uniform = this._config.uniforms[j];
  64682. switch (uniform.type) {
  64683. case "float":
  64684. this.setFloat(uniform.name, uniform.value);
  64685. break;
  64686. case "color3":
  64687. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  64688. break;
  64689. case "color4":
  64690. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  64691. break;
  64692. case "vector2":
  64693. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  64694. break;
  64695. case "vector3":
  64696. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  64697. break;
  64698. }
  64699. }
  64700. }
  64701. this.setFloat("time", this._time);
  64702. };
  64703. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  64704. get: function () {
  64705. return this._animate;
  64706. },
  64707. set: function (value) {
  64708. this._animate = value;
  64709. },
  64710. enumerable: true,
  64711. configurable: true
  64712. });
  64713. return CustomProceduralTexture;
  64714. }(BABYLON.ProceduralTexture));
  64715. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  64716. })(BABYLON || (BABYLON = {}));
  64717. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  64718. "use strict";
  64719. var BABYLON;
  64720. (function (BABYLON) {
  64721. var FreeCameraGamepadInput = /** @class */ (function () {
  64722. function FreeCameraGamepadInput() {
  64723. this.gamepadAngularSensibility = 200;
  64724. this.gamepadMoveSensibility = 40;
  64725. // private members
  64726. this._cameraTransform = BABYLON.Matrix.Identity();
  64727. this._deltaTransform = BABYLON.Vector3.Zero();
  64728. this._vector3 = BABYLON.Vector3.Zero();
  64729. this._vector2 = BABYLON.Vector2.Zero();
  64730. }
  64731. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64732. var _this = this;
  64733. var manager = this.camera.getScene().gamepadManager;
  64734. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64735. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64736. // prioritize XBOX gamepads.
  64737. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64738. _this.gamepad = gamepad;
  64739. }
  64740. }
  64741. });
  64742. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64743. if (_this.gamepad === gamepad) {
  64744. _this.gamepad = null;
  64745. }
  64746. });
  64747. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64748. };
  64749. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  64750. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64751. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64752. this.gamepad = null;
  64753. };
  64754. FreeCameraGamepadInput.prototype.checkInputs = function () {
  64755. if (this.gamepad && this.gamepad.leftStick) {
  64756. var camera = this.camera;
  64757. var LSValues = this.gamepad.leftStick;
  64758. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  64759. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64760. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  64761. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  64762. var RSValues = this.gamepad.rightStick;
  64763. if (RSValues) {
  64764. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  64765. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  64766. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  64767. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  64768. }
  64769. else {
  64770. RSValues = { x: 0, y: 0 };
  64771. }
  64772. if (!camera.rotationQuaternion) {
  64773. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  64774. }
  64775. else {
  64776. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  64777. }
  64778. var speed = camera._computeLocalCameraSpeed() * 50.0;
  64779. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  64780. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  64781. camera.cameraDirection.addInPlace(this._deltaTransform);
  64782. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  64783. camera.cameraRotation.addInPlace(this._vector2);
  64784. }
  64785. };
  64786. FreeCameraGamepadInput.prototype.getClassName = function () {
  64787. return "FreeCameraGamepadInput";
  64788. };
  64789. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  64790. return "gamepad";
  64791. };
  64792. __decorate([
  64793. BABYLON.serialize()
  64794. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  64795. __decorate([
  64796. BABYLON.serialize()
  64797. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64798. return FreeCameraGamepadInput;
  64799. }());
  64800. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  64801. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  64802. })(BABYLON || (BABYLON = {}));
  64803. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  64804. "use strict";
  64805. var BABYLON;
  64806. (function (BABYLON) {
  64807. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  64808. function ArcRotateCameraGamepadInput() {
  64809. this.gamepadRotationSensibility = 80;
  64810. this.gamepadMoveSensibility = 40;
  64811. }
  64812. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64813. var _this = this;
  64814. var manager = this.camera.getScene().gamepadManager;
  64815. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64816. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64817. // prioritize XBOX gamepads.
  64818. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64819. _this.gamepad = gamepad;
  64820. }
  64821. }
  64822. });
  64823. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64824. if (_this.gamepad === gamepad) {
  64825. _this.gamepad = null;
  64826. }
  64827. });
  64828. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64829. };
  64830. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  64831. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64832. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64833. this.gamepad = null;
  64834. };
  64835. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  64836. if (this.gamepad) {
  64837. var camera = this.camera;
  64838. var RSValues = this.gamepad.rightStick;
  64839. if (RSValues) {
  64840. if (RSValues.x != 0) {
  64841. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  64842. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  64843. camera.inertialAlphaOffset += normalizedRX;
  64844. }
  64845. }
  64846. if (RSValues.y != 0) {
  64847. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  64848. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  64849. camera.inertialBetaOffset += normalizedRY;
  64850. }
  64851. }
  64852. }
  64853. var LSValues = this.gamepad.leftStick;
  64854. if (LSValues && LSValues.y != 0) {
  64855. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64856. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  64857. this.camera.inertialRadiusOffset -= normalizedLY;
  64858. }
  64859. }
  64860. }
  64861. };
  64862. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  64863. return "ArcRotateCameraGamepadInput";
  64864. };
  64865. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  64866. return "gamepad";
  64867. };
  64868. __decorate([
  64869. BABYLON.serialize()
  64870. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  64871. __decorate([
  64872. BABYLON.serialize()
  64873. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64874. return ArcRotateCameraGamepadInput;
  64875. }());
  64876. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  64877. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  64878. })(BABYLON || (BABYLON = {}));
  64879. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  64880. "use strict";
  64881. var BABYLON;
  64882. (function (BABYLON) {
  64883. var GamepadManager = /** @class */ (function () {
  64884. function GamepadManager(_scene) {
  64885. var _this = this;
  64886. this._scene = _scene;
  64887. this._babylonGamepads = [];
  64888. this._oneGamepadConnected = false;
  64889. this._isMonitoring = false;
  64890. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  64891. if (!BABYLON.Tools.IsWindowObjectExist()) {
  64892. this._gamepadEventSupported = false;
  64893. }
  64894. else {
  64895. this._gamepadEventSupported = 'GamepadEvent' in window;
  64896. this._gamepadSupport = (navigator.getGamepads ||
  64897. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  64898. }
  64899. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  64900. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  64901. for (var i in _this._babylonGamepads) {
  64902. var gamepad = _this._babylonGamepads[i];
  64903. if (gamepad && gamepad._isConnected) {
  64904. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  64905. }
  64906. }
  64907. });
  64908. this._onGamepadConnectedEvent = function (evt) {
  64909. var gamepad = evt.gamepad;
  64910. if (gamepad.index in _this._babylonGamepads) {
  64911. if (_this._babylonGamepads[gamepad.index].isConnected) {
  64912. return;
  64913. }
  64914. }
  64915. var newGamepad;
  64916. if (_this._babylonGamepads[gamepad.index]) {
  64917. newGamepad = _this._babylonGamepads[gamepad.index];
  64918. newGamepad.browserGamepad = gamepad;
  64919. newGamepad._isConnected = true;
  64920. }
  64921. else {
  64922. newGamepad = _this._addNewGamepad(gamepad);
  64923. }
  64924. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64925. _this._startMonitoringGamepads();
  64926. };
  64927. this._onGamepadDisconnectedEvent = function (evt) {
  64928. var gamepad = evt.gamepad;
  64929. // Remove the gamepad from the list of gamepads to monitor.
  64930. for (var i in _this._babylonGamepads) {
  64931. if (_this._babylonGamepads[i].index === gamepad.index) {
  64932. var disconnectedGamepad = _this._babylonGamepads[i];
  64933. disconnectedGamepad._isConnected = false;
  64934. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  64935. break;
  64936. }
  64937. }
  64938. };
  64939. if (this._gamepadSupport) {
  64940. //first add already-connected gamepads
  64941. this._updateGamepadObjects();
  64942. if (this._babylonGamepads.length) {
  64943. this._startMonitoringGamepads();
  64944. }
  64945. // Checking if the gamepad connected event is supported (like in Firefox)
  64946. if (this._gamepadEventSupported) {
  64947. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  64948. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  64949. }
  64950. else {
  64951. this._startMonitoringGamepads();
  64952. }
  64953. }
  64954. }
  64955. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  64956. get: function () {
  64957. return this._babylonGamepads;
  64958. },
  64959. enumerable: true,
  64960. configurable: true
  64961. });
  64962. GamepadManager.prototype.getGamepadByType = function (type) {
  64963. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  64964. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  64965. var gamepad = _a[_i];
  64966. if (gamepad && gamepad.type === type) {
  64967. return gamepad;
  64968. }
  64969. }
  64970. return null;
  64971. };
  64972. GamepadManager.prototype.dispose = function () {
  64973. if (this._gamepadEventSupported) {
  64974. if (this._onGamepadConnectedEvent) {
  64975. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  64976. }
  64977. if (this._onGamepadDisconnectedEvent) {
  64978. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  64979. }
  64980. this._onGamepadConnectedEvent = null;
  64981. this._onGamepadDisconnectedEvent = null;
  64982. }
  64983. this._babylonGamepads.forEach(function (gamepad) {
  64984. gamepad.dispose();
  64985. });
  64986. this.onGamepadConnectedObservable.clear();
  64987. this.onGamepadDisconnectedObservable.clear();
  64988. this._oneGamepadConnected = false;
  64989. this._stopMonitoringGamepads();
  64990. this._babylonGamepads = [];
  64991. };
  64992. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  64993. if (!this._oneGamepadConnected) {
  64994. this._oneGamepadConnected = true;
  64995. }
  64996. var newGamepad;
  64997. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  64998. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  64999. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  65000. }
  65001. else if (gamepad.pose) {
  65002. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  65003. }
  65004. else {
  65005. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  65006. }
  65007. this._babylonGamepads[newGamepad.index] = newGamepad;
  65008. return newGamepad;
  65009. };
  65010. GamepadManager.prototype._startMonitoringGamepads = function () {
  65011. if (!this._isMonitoring) {
  65012. this._isMonitoring = true;
  65013. //back-comp
  65014. if (!this._scene) {
  65015. this._checkGamepadsStatus();
  65016. }
  65017. }
  65018. };
  65019. GamepadManager.prototype._stopMonitoringGamepads = function () {
  65020. this._isMonitoring = false;
  65021. };
  65022. GamepadManager.prototype._checkGamepadsStatus = function () {
  65023. var _this = this;
  65024. // Hack to be compatible Chrome
  65025. this._updateGamepadObjects();
  65026. for (var i in this._babylonGamepads) {
  65027. var gamepad = this._babylonGamepads[i];
  65028. if (!gamepad || !gamepad.isConnected) {
  65029. continue;
  65030. }
  65031. gamepad.update();
  65032. }
  65033. if (this._isMonitoring && !this._scene) {
  65034. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  65035. }
  65036. };
  65037. // This function is called only on Chrome, which does not properly support
  65038. // connection/disconnection events and forces you to recopy again the gamepad object
  65039. GamepadManager.prototype._updateGamepadObjects = function () {
  65040. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  65041. for (var i = 0; i < gamepads.length; i++) {
  65042. if (gamepads[i]) {
  65043. if (!this._babylonGamepads[gamepads[i].index]) {
  65044. var newGamepad = this._addNewGamepad(gamepads[i]);
  65045. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65046. }
  65047. else {
  65048. // Forced to copy again this object for Chrome for unknown reason
  65049. this._babylonGamepads[i].browserGamepad = gamepads[i];
  65050. if (!this._babylonGamepads[i].isConnected) {
  65051. this._babylonGamepads[i]._isConnected = true;
  65052. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  65053. }
  65054. }
  65055. }
  65056. }
  65057. };
  65058. return GamepadManager;
  65059. }());
  65060. BABYLON.GamepadManager = GamepadManager;
  65061. })(BABYLON || (BABYLON = {}));
  65062. //# sourceMappingURL=babylon.gamepadManager.js.map
  65063. "use strict";
  65064. var BABYLON;
  65065. (function (BABYLON) {
  65066. var StickValues = /** @class */ (function () {
  65067. function StickValues(x, y) {
  65068. this.x = x;
  65069. this.y = y;
  65070. }
  65071. return StickValues;
  65072. }());
  65073. BABYLON.StickValues = StickValues;
  65074. var Gamepad = /** @class */ (function () {
  65075. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  65076. if (leftStickX === void 0) { leftStickX = 0; }
  65077. if (leftStickY === void 0) { leftStickY = 1; }
  65078. if (rightStickX === void 0) { rightStickX = 2; }
  65079. if (rightStickY === void 0) { rightStickY = 3; }
  65080. this.id = id;
  65081. this.index = index;
  65082. this.browserGamepad = browserGamepad;
  65083. this._isConnected = true;
  65084. this._invertLeftStickY = false;
  65085. this.type = Gamepad.GAMEPAD;
  65086. this._leftStickAxisX = leftStickX;
  65087. this._leftStickAxisY = leftStickY;
  65088. this._rightStickAxisX = rightStickX;
  65089. this._rightStickAxisY = rightStickY;
  65090. if (this.browserGamepad.axes.length >= 2) {
  65091. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65092. }
  65093. if (this.browserGamepad.axes.length >= 4) {
  65094. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65095. }
  65096. }
  65097. Object.defineProperty(Gamepad.prototype, "isConnected", {
  65098. get: function () {
  65099. return this._isConnected;
  65100. },
  65101. enumerable: true,
  65102. configurable: true
  65103. });
  65104. Gamepad.prototype.onleftstickchanged = function (callback) {
  65105. this._onleftstickchanged = callback;
  65106. };
  65107. Gamepad.prototype.onrightstickchanged = function (callback) {
  65108. this._onrightstickchanged = callback;
  65109. };
  65110. Object.defineProperty(Gamepad.prototype, "leftStick", {
  65111. get: function () {
  65112. return this._leftStick;
  65113. },
  65114. set: function (newValues) {
  65115. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  65116. this._onleftstickchanged(newValues);
  65117. }
  65118. this._leftStick = newValues;
  65119. },
  65120. enumerable: true,
  65121. configurable: true
  65122. });
  65123. Object.defineProperty(Gamepad.prototype, "rightStick", {
  65124. get: function () {
  65125. return this._rightStick;
  65126. },
  65127. set: function (newValues) {
  65128. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  65129. this._onrightstickchanged(newValues);
  65130. }
  65131. this._rightStick = newValues;
  65132. },
  65133. enumerable: true,
  65134. configurable: true
  65135. });
  65136. Gamepad.prototype.update = function () {
  65137. if (this._leftStick) {
  65138. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65139. if (this._invertLeftStickY) {
  65140. this.leftStick.y *= -1;
  65141. }
  65142. }
  65143. if (this._rightStick) {
  65144. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65145. }
  65146. };
  65147. Gamepad.prototype.dispose = function () {
  65148. };
  65149. Gamepad.GAMEPAD = 0;
  65150. Gamepad.GENERIC = 1;
  65151. Gamepad.XBOX = 2;
  65152. Gamepad.POSE_ENABLED = 3;
  65153. return Gamepad;
  65154. }());
  65155. BABYLON.Gamepad = Gamepad;
  65156. var GenericPad = /** @class */ (function (_super) {
  65157. __extends(GenericPad, _super);
  65158. function GenericPad(id, index, browserGamepad) {
  65159. var _this = _super.call(this, id, index, browserGamepad) || this;
  65160. _this.onButtonDownObservable = new BABYLON.Observable();
  65161. _this.onButtonUpObservable = new BABYLON.Observable();
  65162. _this.type = Gamepad.GENERIC;
  65163. _this._buttons = new Array(browserGamepad.buttons.length);
  65164. return _this;
  65165. }
  65166. GenericPad.prototype.onbuttondown = function (callback) {
  65167. this._onbuttondown = callback;
  65168. };
  65169. GenericPad.prototype.onbuttonup = function (callback) {
  65170. this._onbuttonup = callback;
  65171. };
  65172. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  65173. if (newValue !== currentValue) {
  65174. if (newValue === 1) {
  65175. if (this._onbuttondown) {
  65176. this._onbuttondown(buttonIndex);
  65177. }
  65178. this.onButtonDownObservable.notifyObservers(buttonIndex);
  65179. }
  65180. if (newValue === 0) {
  65181. if (this._onbuttonup) {
  65182. this._onbuttonup(buttonIndex);
  65183. }
  65184. this.onButtonUpObservable.notifyObservers(buttonIndex);
  65185. }
  65186. }
  65187. return newValue;
  65188. };
  65189. GenericPad.prototype.update = function () {
  65190. _super.prototype.update.call(this);
  65191. for (var index = 0; index < this._buttons.length; index++) {
  65192. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  65193. }
  65194. };
  65195. GenericPad.prototype.dispose = function () {
  65196. _super.prototype.dispose.call(this);
  65197. this.onButtonDownObservable.clear();
  65198. this.onButtonUpObservable.clear();
  65199. };
  65200. return GenericPad;
  65201. }(Gamepad));
  65202. BABYLON.GenericPad = GenericPad;
  65203. })(BABYLON || (BABYLON = {}));
  65204. //# sourceMappingURL=babylon.gamepad.js.map
  65205. "use strict";
  65206. var BABYLON;
  65207. (function (BABYLON) {
  65208. var Xbox360Button;
  65209. (function (Xbox360Button) {
  65210. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  65211. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  65212. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  65213. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  65214. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  65215. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  65216. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  65217. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  65218. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  65219. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  65220. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  65221. var Xbox360Dpad;
  65222. (function (Xbox360Dpad) {
  65223. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  65224. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  65225. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  65226. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  65227. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  65228. var Xbox360Pad = /** @class */ (function (_super) {
  65229. __extends(Xbox360Pad, _super);
  65230. function Xbox360Pad(id, index, gamepad, xboxOne) {
  65231. if (xboxOne === void 0) { xboxOne = false; }
  65232. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  65233. _this._leftTrigger = 0;
  65234. _this._rightTrigger = 0;
  65235. _this.onButtonDownObservable = new BABYLON.Observable();
  65236. _this.onButtonUpObservable = new BABYLON.Observable();
  65237. _this.onPadDownObservable = new BABYLON.Observable();
  65238. _this.onPadUpObservable = new BABYLON.Observable();
  65239. _this._buttonA = 0;
  65240. _this._buttonB = 0;
  65241. _this._buttonX = 0;
  65242. _this._buttonY = 0;
  65243. _this._buttonBack = 0;
  65244. _this._buttonStart = 0;
  65245. _this._buttonLB = 0;
  65246. _this._buttonRB = 0;
  65247. _this._buttonLeftStick = 0;
  65248. _this._buttonRightStick = 0;
  65249. _this._dPadUp = 0;
  65250. _this._dPadDown = 0;
  65251. _this._dPadLeft = 0;
  65252. _this._dPadRight = 0;
  65253. _this._isXboxOnePad = false;
  65254. _this.type = BABYLON.Gamepad.XBOX;
  65255. _this._isXboxOnePad = xboxOne;
  65256. return _this;
  65257. }
  65258. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  65259. this._onlefttriggerchanged = callback;
  65260. };
  65261. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  65262. this._onrighttriggerchanged = callback;
  65263. };
  65264. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  65265. get: function () {
  65266. return this._leftTrigger;
  65267. },
  65268. set: function (newValue) {
  65269. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  65270. this._onlefttriggerchanged(newValue);
  65271. }
  65272. this._leftTrigger = newValue;
  65273. },
  65274. enumerable: true,
  65275. configurable: true
  65276. });
  65277. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  65278. get: function () {
  65279. return this._rightTrigger;
  65280. },
  65281. set: function (newValue) {
  65282. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  65283. this._onrighttriggerchanged(newValue);
  65284. }
  65285. this._rightTrigger = newValue;
  65286. },
  65287. enumerable: true,
  65288. configurable: true
  65289. });
  65290. Xbox360Pad.prototype.onbuttondown = function (callback) {
  65291. this._onbuttondown = callback;
  65292. };
  65293. Xbox360Pad.prototype.onbuttonup = function (callback) {
  65294. this._onbuttonup = callback;
  65295. };
  65296. Xbox360Pad.prototype.ondpaddown = function (callback) {
  65297. this._ondpaddown = callback;
  65298. };
  65299. Xbox360Pad.prototype.ondpadup = function (callback) {
  65300. this._ondpadup = callback;
  65301. };
  65302. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  65303. if (newValue !== currentValue) {
  65304. if (newValue === 1) {
  65305. if (this._onbuttondown) {
  65306. this._onbuttondown(buttonType);
  65307. }
  65308. this.onButtonDownObservable.notifyObservers(buttonType);
  65309. }
  65310. if (newValue === 0) {
  65311. if (this._onbuttonup) {
  65312. this._onbuttonup(buttonType);
  65313. }
  65314. this.onButtonUpObservable.notifyObservers(buttonType);
  65315. }
  65316. }
  65317. return newValue;
  65318. };
  65319. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  65320. if (newValue !== currentValue) {
  65321. if (newValue === 1) {
  65322. if (this._ondpaddown) {
  65323. this._ondpaddown(buttonType);
  65324. }
  65325. this.onPadDownObservable.notifyObservers(buttonType);
  65326. }
  65327. if (newValue === 0) {
  65328. if (this._ondpadup) {
  65329. this._ondpadup(buttonType);
  65330. }
  65331. this.onPadUpObservable.notifyObservers(buttonType);
  65332. }
  65333. }
  65334. return newValue;
  65335. };
  65336. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  65337. get: function () {
  65338. return this._buttonA;
  65339. },
  65340. set: function (value) {
  65341. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  65342. },
  65343. enumerable: true,
  65344. configurable: true
  65345. });
  65346. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  65347. get: function () {
  65348. return this._buttonB;
  65349. },
  65350. set: function (value) {
  65351. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  65352. },
  65353. enumerable: true,
  65354. configurable: true
  65355. });
  65356. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  65357. get: function () {
  65358. return this._buttonX;
  65359. },
  65360. set: function (value) {
  65361. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  65362. },
  65363. enumerable: true,
  65364. configurable: true
  65365. });
  65366. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  65367. get: function () {
  65368. return this._buttonY;
  65369. },
  65370. set: function (value) {
  65371. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  65372. },
  65373. enumerable: true,
  65374. configurable: true
  65375. });
  65376. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  65377. get: function () {
  65378. return this._buttonStart;
  65379. },
  65380. set: function (value) {
  65381. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  65382. },
  65383. enumerable: true,
  65384. configurable: true
  65385. });
  65386. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  65387. get: function () {
  65388. return this._buttonBack;
  65389. },
  65390. set: function (value) {
  65391. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  65392. },
  65393. enumerable: true,
  65394. configurable: true
  65395. });
  65396. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  65397. get: function () {
  65398. return this._buttonLB;
  65399. },
  65400. set: function (value) {
  65401. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  65402. },
  65403. enumerable: true,
  65404. configurable: true
  65405. });
  65406. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  65407. get: function () {
  65408. return this._buttonRB;
  65409. },
  65410. set: function (value) {
  65411. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  65412. },
  65413. enumerable: true,
  65414. configurable: true
  65415. });
  65416. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  65417. get: function () {
  65418. return this._buttonLeftStick;
  65419. },
  65420. set: function (value) {
  65421. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  65422. },
  65423. enumerable: true,
  65424. configurable: true
  65425. });
  65426. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  65427. get: function () {
  65428. return this._buttonRightStick;
  65429. },
  65430. set: function (value) {
  65431. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  65432. },
  65433. enumerable: true,
  65434. configurable: true
  65435. });
  65436. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  65437. get: function () {
  65438. return this._dPadUp;
  65439. },
  65440. set: function (value) {
  65441. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  65442. },
  65443. enumerable: true,
  65444. configurable: true
  65445. });
  65446. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  65447. get: function () {
  65448. return this._dPadDown;
  65449. },
  65450. set: function (value) {
  65451. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  65452. },
  65453. enumerable: true,
  65454. configurable: true
  65455. });
  65456. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  65457. get: function () {
  65458. return this._dPadLeft;
  65459. },
  65460. set: function (value) {
  65461. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  65462. },
  65463. enumerable: true,
  65464. configurable: true
  65465. });
  65466. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  65467. get: function () {
  65468. return this._dPadRight;
  65469. },
  65470. set: function (value) {
  65471. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  65472. },
  65473. enumerable: true,
  65474. configurable: true
  65475. });
  65476. Xbox360Pad.prototype.update = function () {
  65477. _super.prototype.update.call(this);
  65478. if (this._isXboxOnePad) {
  65479. this.buttonA = this.browserGamepad.buttons[0].value;
  65480. this.buttonB = this.browserGamepad.buttons[1].value;
  65481. this.buttonX = this.browserGamepad.buttons[2].value;
  65482. this.buttonY = this.browserGamepad.buttons[3].value;
  65483. this.buttonLB = this.browserGamepad.buttons[4].value;
  65484. this.buttonRB = this.browserGamepad.buttons[5].value;
  65485. this.leftTrigger = this.browserGamepad.axes[2];
  65486. this.rightTrigger = this.browserGamepad.axes[5];
  65487. this.buttonBack = this.browserGamepad.buttons[9].value;
  65488. this.buttonStart = this.browserGamepad.buttons[8].value;
  65489. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  65490. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  65491. this.dPadUp = this.browserGamepad.buttons[11].value;
  65492. this.dPadDown = this.browserGamepad.buttons[12].value;
  65493. this.dPadLeft = this.browserGamepad.buttons[13].value;
  65494. this.dPadRight = this.browserGamepad.buttons[14].value;
  65495. }
  65496. else {
  65497. this.buttonA = this.browserGamepad.buttons[0].value;
  65498. this.buttonB = this.browserGamepad.buttons[1].value;
  65499. this.buttonX = this.browserGamepad.buttons[2].value;
  65500. this.buttonY = this.browserGamepad.buttons[3].value;
  65501. this.buttonLB = this.browserGamepad.buttons[4].value;
  65502. this.buttonRB = this.browserGamepad.buttons[5].value;
  65503. this.leftTrigger = this.browserGamepad.buttons[6].value;
  65504. this.rightTrigger = this.browserGamepad.buttons[7].value;
  65505. this.buttonBack = this.browserGamepad.buttons[8].value;
  65506. this.buttonStart = this.browserGamepad.buttons[9].value;
  65507. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  65508. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  65509. this.dPadUp = this.browserGamepad.buttons[12].value;
  65510. this.dPadDown = this.browserGamepad.buttons[13].value;
  65511. this.dPadLeft = this.browserGamepad.buttons[14].value;
  65512. this.dPadRight = this.browserGamepad.buttons[15].value;
  65513. }
  65514. };
  65515. Xbox360Pad.prototype.dispose = function () {
  65516. _super.prototype.dispose.call(this);
  65517. this.onButtonDownObservable.clear();
  65518. this.onButtonUpObservable.clear();
  65519. this.onPadDownObservable.clear();
  65520. this.onPadUpObservable.clear();
  65521. };
  65522. return Xbox360Pad;
  65523. }(BABYLON.Gamepad));
  65524. BABYLON.Xbox360Pad = Xbox360Pad;
  65525. })(BABYLON || (BABYLON = {}));
  65526. //# sourceMappingURL=babylon.xboxGamepad.js.map
  65527. "use strict";
  65528. var BABYLON;
  65529. (function (BABYLON) {
  65530. var PoseEnabledControllerType;
  65531. (function (PoseEnabledControllerType) {
  65532. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  65533. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  65534. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  65535. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  65536. /**
  65537. * Google Daydream
  65538. */
  65539. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  65540. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  65541. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  65542. var PoseEnabledControllerHelper = /** @class */ (function () {
  65543. function PoseEnabledControllerHelper() {
  65544. }
  65545. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  65546. // Oculus Touch
  65547. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  65548. return new BABYLON.OculusTouchController(vrGamepad);
  65549. }
  65550. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  65551. return new BABYLON.WindowsMotionController(vrGamepad);
  65552. }
  65553. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  65554. return new BABYLON.ViveController(vrGamepad);
  65555. }
  65556. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  65557. return new BABYLON.GearVRController(vrGamepad);
  65558. }
  65559. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  65560. return new BABYLON.DaydreamController(vrGamepad);
  65561. }
  65562. else {
  65563. return new BABYLON.GenericController(vrGamepad);
  65564. }
  65565. };
  65566. return PoseEnabledControllerHelper;
  65567. }());
  65568. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  65569. var PoseEnabledController = /** @class */ (function (_super) {
  65570. __extends(PoseEnabledController, _super);
  65571. function PoseEnabledController(browserGamepad) {
  65572. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  65573. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  65574. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  65575. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  65576. // Represents device position and rotation in babylon space
  65577. _this.devicePosition = BABYLON.Vector3.Zero();
  65578. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  65579. _this.deviceScaleFactor = 1;
  65580. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  65581. _this._deviceToWorld = BABYLON.Matrix.Identity();
  65582. /**
  65583. * Node to be used when casting a ray from the controller
  65584. */
  65585. _this._pointingPoseNode = null;
  65586. _this._workingMatrix = BABYLON.Matrix.Identity();
  65587. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  65588. _this.controllerType = PoseEnabledControllerType.GENERIC;
  65589. _this.position = BABYLON.Vector3.Zero();
  65590. _this.rotationQuaternion = new BABYLON.Quaternion();
  65591. _this._calculatedPosition = BABYLON.Vector3.Zero();
  65592. _this._calculatedRotation = new BABYLON.Quaternion();
  65593. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  65594. return _this;
  65595. }
  65596. PoseEnabledController.prototype.update = function () {
  65597. _super.prototype.update.call(this);
  65598. var pose = this.browserGamepad.pose;
  65599. this.updateFromDevice(pose);
  65600. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  65601. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  65602. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  65603. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  65604. if (this._mesh) {
  65605. this._mesh.position.copyFrom(this.devicePosition);
  65606. if (this._mesh.rotationQuaternion) {
  65607. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65608. }
  65609. }
  65610. };
  65611. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  65612. if (poseData) {
  65613. this.rawPose = poseData;
  65614. if (poseData.position) {
  65615. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  65616. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  65617. this._deviceRoomPosition.z *= -1;
  65618. }
  65619. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  65620. this._calculatedPosition.addInPlace(this.position);
  65621. }
  65622. var pose = this.rawPose;
  65623. if (poseData.orientation && pose.orientation) {
  65624. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  65625. if (this._mesh) {
  65626. if (this._mesh.getScene().useRightHandedSystem) {
  65627. this._deviceRoomRotationQuaternion.z *= -1;
  65628. this._deviceRoomRotationQuaternion.w *= -1;
  65629. }
  65630. else {
  65631. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  65632. }
  65633. }
  65634. // if the camera is set, rotate to the camera's rotation
  65635. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  65636. }
  65637. }
  65638. };
  65639. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  65640. if (this._mesh) {
  65641. this._mesh.parent = null;
  65642. }
  65643. this._mesh = mesh;
  65644. if (this._poseControlledCamera) {
  65645. this._mesh.parent = this._poseControlledCamera;
  65646. }
  65647. if (!this._mesh.rotationQuaternion) {
  65648. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  65649. }
  65650. };
  65651. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  65652. this._poseControlledCamera = camera;
  65653. if (this._mesh) {
  65654. this._mesh.parent = this._poseControlledCamera;
  65655. }
  65656. };
  65657. PoseEnabledController.prototype.dispose = function () {
  65658. if (this._mesh) {
  65659. this._mesh.dispose();
  65660. }
  65661. this._mesh = null;
  65662. _super.prototype.dispose.call(this);
  65663. };
  65664. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  65665. get: function () {
  65666. return this._mesh;
  65667. },
  65668. enumerable: true,
  65669. configurable: true
  65670. });
  65671. PoseEnabledController.prototype.getForwardRay = function (length) {
  65672. if (length === void 0) { length = 100; }
  65673. if (!this.mesh) {
  65674. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  65675. }
  65676. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  65677. var origin = m.getTranslation();
  65678. var forward = new BABYLON.Vector3(0, 0, -1);
  65679. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65680. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65681. return new BABYLON.Ray(origin, direction, length);
  65682. };
  65683. /**
  65684. * Name of the child mesh that can be used to cast a ray from the controller
  65685. */
  65686. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  65687. return PoseEnabledController;
  65688. }(BABYLON.Gamepad));
  65689. BABYLON.PoseEnabledController = PoseEnabledController;
  65690. })(BABYLON || (BABYLON = {}));
  65691. //# sourceMappingURL=babylon.poseEnabledController.js.map
  65692. "use strict";
  65693. var BABYLON;
  65694. (function (BABYLON) {
  65695. var WebVRController = /** @class */ (function (_super) {
  65696. __extends(WebVRController, _super);
  65697. function WebVRController(vrGamepad) {
  65698. var _this = _super.call(this, vrGamepad) || this;
  65699. // Observables
  65700. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  65701. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  65702. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  65703. _this.onPadStateChangedObservable = new BABYLON.Observable();
  65704. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  65705. _this.pad = { x: 0, y: 0 };
  65706. // avoid GC, store state in a tmp object
  65707. _this._changes = {
  65708. pressChanged: false,
  65709. touchChanged: false,
  65710. valueChanged: false,
  65711. changed: false
  65712. };
  65713. _this._buttons = new Array(vrGamepad.buttons.length);
  65714. _this.hand = vrGamepad.hand;
  65715. return _this;
  65716. }
  65717. WebVRController.prototype.onButtonStateChange = function (callback) {
  65718. this._onButtonStateChange = callback;
  65719. };
  65720. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  65721. get: function () {
  65722. return this._defaultModel;
  65723. },
  65724. enumerable: true,
  65725. configurable: true
  65726. });
  65727. WebVRController.prototype.update = function () {
  65728. _super.prototype.update.call(this);
  65729. for (var index = 0; index < this._buttons.length; index++) {
  65730. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  65731. }
  65732. ;
  65733. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  65734. this.pad.x = this.leftStick.x;
  65735. this.pad.y = this.leftStick.y;
  65736. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  65737. }
  65738. };
  65739. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  65740. if (!newState) {
  65741. newState = {
  65742. pressed: false,
  65743. touched: false,
  65744. value: 0
  65745. };
  65746. }
  65747. if (!currentState) {
  65748. this._buttons[buttonIndex] = {
  65749. pressed: newState.pressed,
  65750. touched: newState.touched,
  65751. value: newState.value
  65752. };
  65753. return;
  65754. }
  65755. this._checkChanges(newState, currentState);
  65756. if (this._changes.changed) {
  65757. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  65758. this._handleButtonChange(buttonIndex, newState, this._changes);
  65759. }
  65760. this._buttons[buttonIndex].pressed = newState.pressed;
  65761. this._buttons[buttonIndex].touched = newState.touched;
  65762. // oculus triggers are never 0, thou not touched.
  65763. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  65764. };
  65765. WebVRController.prototype._checkChanges = function (newState, currentState) {
  65766. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  65767. this._changes.touchChanged = newState.touched !== currentState.touched;
  65768. this._changes.valueChanged = newState.value !== currentState.value;
  65769. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  65770. return this._changes;
  65771. };
  65772. WebVRController.prototype.dispose = function () {
  65773. _super.prototype.dispose.call(this);
  65774. this.onTriggerStateChangedObservable.clear();
  65775. this.onMainButtonStateChangedObservable.clear();
  65776. this.onSecondaryButtonStateChangedObservable.clear();
  65777. this.onPadStateChangedObservable.clear();
  65778. this.onPadValuesChangedObservable.clear();
  65779. };
  65780. return WebVRController;
  65781. }(BABYLON.PoseEnabledController));
  65782. BABYLON.WebVRController = WebVRController;
  65783. })(BABYLON || (BABYLON = {}));
  65784. //# sourceMappingURL=babylon.webVRController.js.map
  65785. "use strict";
  65786. var BABYLON;
  65787. (function (BABYLON) {
  65788. var OculusTouchController = /** @class */ (function (_super) {
  65789. __extends(OculusTouchController, _super);
  65790. function OculusTouchController(vrGamepad) {
  65791. var _this = _super.call(this, vrGamepad) || this;
  65792. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  65793. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  65794. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  65795. return _this;
  65796. }
  65797. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65798. var _this = this;
  65799. var meshName;
  65800. // Hand
  65801. if (this.hand === 'left') {
  65802. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  65803. }
  65804. else {
  65805. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  65806. }
  65807. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  65808. /*
  65809. Parent Mesh name: oculus_touch_left
  65810. - body
  65811. - trigger
  65812. - thumbstick
  65813. - grip
  65814. - button_y
  65815. - button_x
  65816. - button_enter
  65817. */
  65818. _this._defaultModel = newMeshes[1];
  65819. _this.attachToMesh(_this._defaultModel);
  65820. if (meshLoaded) {
  65821. meshLoaded(_this._defaultModel);
  65822. }
  65823. });
  65824. };
  65825. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  65826. // helper getters for left and right hand.
  65827. get: function () {
  65828. if (this.hand === 'right') {
  65829. return this.onMainButtonStateChangedObservable;
  65830. }
  65831. else {
  65832. throw new Error('No A button on left hand');
  65833. }
  65834. },
  65835. enumerable: true,
  65836. configurable: true
  65837. });
  65838. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  65839. get: function () {
  65840. if (this.hand === 'right') {
  65841. return this.onSecondaryButtonStateChangedObservable;
  65842. }
  65843. else {
  65844. throw new Error('No B button on left hand');
  65845. }
  65846. },
  65847. enumerable: true,
  65848. configurable: true
  65849. });
  65850. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  65851. get: function () {
  65852. if (this.hand === 'left') {
  65853. return this.onMainButtonStateChangedObservable;
  65854. }
  65855. else {
  65856. throw new Error('No X button on right hand');
  65857. }
  65858. },
  65859. enumerable: true,
  65860. configurable: true
  65861. });
  65862. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  65863. get: function () {
  65864. if (this.hand === 'left') {
  65865. return this.onSecondaryButtonStateChangedObservable;
  65866. }
  65867. else {
  65868. throw new Error('No Y button on right hand');
  65869. }
  65870. },
  65871. enumerable: true,
  65872. configurable: true
  65873. });
  65874. /*
  65875. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  65876. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  65877. 2) secondary trigger (same)
  65878. 3) A (right) X (left), touch, pressed = value
  65879. 4) B / Y
  65880. 5) thumb rest
  65881. */
  65882. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65883. var notifyObject = state; //{ state: state, changes: changes };
  65884. var triggerDirection = this.hand === 'right' ? -1 : 1;
  65885. switch (buttonIdx) {
  65886. case 0:
  65887. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65888. return;
  65889. case 1:// index trigger
  65890. if (this._defaultModel) {
  65891. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  65892. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  65893. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  65894. }
  65895. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65896. return;
  65897. case 2:// secondary trigger
  65898. if (this._defaultModel) {
  65899. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  65900. }
  65901. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  65902. return;
  65903. case 3:
  65904. if (this._defaultModel) {
  65905. if (notifyObject.pressed) {
  65906. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  65907. }
  65908. else {
  65909. (this._defaultModel.getChildren()[1]).position.y = 0;
  65910. }
  65911. }
  65912. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65913. return;
  65914. case 4:
  65915. if (this._defaultModel) {
  65916. if (notifyObject.pressed) {
  65917. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65918. }
  65919. else {
  65920. (this._defaultModel.getChildren()[2]).position.y = 0;
  65921. }
  65922. }
  65923. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65924. return;
  65925. case 5:
  65926. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  65927. return;
  65928. }
  65929. };
  65930. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  65931. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  65932. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  65933. return OculusTouchController;
  65934. }(BABYLON.WebVRController));
  65935. BABYLON.OculusTouchController = OculusTouchController;
  65936. })(BABYLON || (BABYLON = {}));
  65937. //# sourceMappingURL=babylon.oculusTouchController.js.map
  65938. "use strict";
  65939. var BABYLON;
  65940. (function (BABYLON) {
  65941. var ViveController = /** @class */ (function (_super) {
  65942. __extends(ViveController, _super);
  65943. function ViveController(vrGamepad) {
  65944. var _this = _super.call(this, vrGamepad) || this;
  65945. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  65946. _this._invertLeftStickY = true;
  65947. return _this;
  65948. }
  65949. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65950. var _this = this;
  65951. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  65952. /*
  65953. Parent Mesh name: ViveWand
  65954. - body
  65955. - r_gripper
  65956. - l_gripper
  65957. - menu_button
  65958. - system_button
  65959. - trackpad
  65960. - trigger
  65961. - LED
  65962. */
  65963. _this._defaultModel = newMeshes[1];
  65964. _this.attachToMesh(_this._defaultModel);
  65965. if (meshLoaded) {
  65966. meshLoaded(_this._defaultModel);
  65967. }
  65968. });
  65969. };
  65970. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  65971. get: function () {
  65972. return this.onMainButtonStateChangedObservable;
  65973. },
  65974. enumerable: true,
  65975. configurable: true
  65976. });
  65977. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  65978. get: function () {
  65979. return this.onMainButtonStateChangedObservable;
  65980. },
  65981. enumerable: true,
  65982. configurable: true
  65983. });
  65984. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  65985. get: function () {
  65986. return this.onSecondaryButtonStateChangedObservable;
  65987. },
  65988. enumerable: true,
  65989. configurable: true
  65990. });
  65991. /**
  65992. * Vive mapping:
  65993. * 0: touchpad
  65994. * 1: trigger
  65995. * 2: left AND right buttons
  65996. * 3: menu button
  65997. */
  65998. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65999. var notifyObject = state; //{ state: state, changes: changes };
  66000. switch (buttonIdx) {
  66001. case 0:
  66002. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66003. return;
  66004. case 1:// index trigger
  66005. if (this._defaultModel) {
  66006. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  66007. }
  66008. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66009. return;
  66010. case 2:// left AND right button
  66011. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66012. return;
  66013. case 3:
  66014. if (this._defaultModel) {
  66015. if (notifyObject.pressed) {
  66016. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66017. }
  66018. else {
  66019. (this._defaultModel.getChildren()[2]).position.y = 0;
  66020. }
  66021. }
  66022. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66023. return;
  66024. }
  66025. };
  66026. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  66027. ViveController.MODEL_FILENAME = 'wand.babylon';
  66028. return ViveController;
  66029. }(BABYLON.WebVRController));
  66030. BABYLON.ViveController = ViveController;
  66031. })(BABYLON || (BABYLON = {}));
  66032. //# sourceMappingURL=babylon.viveController.js.map
  66033. "use strict";
  66034. var BABYLON;
  66035. (function (BABYLON) {
  66036. var GenericController = /** @class */ (function (_super) {
  66037. __extends(GenericController, _super);
  66038. function GenericController(vrGamepad) {
  66039. return _super.call(this, vrGamepad) || this;
  66040. }
  66041. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66042. var _this = this;
  66043. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  66044. _this._defaultModel = newMeshes[1];
  66045. _this.attachToMesh(_this._defaultModel);
  66046. if (meshLoaded) {
  66047. meshLoaded(_this._defaultModel);
  66048. }
  66049. });
  66050. };
  66051. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66052. console.log("Button id: " + buttonIdx + "state: ");
  66053. console.dir(state);
  66054. };
  66055. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66056. GenericController.MODEL_FILENAME = 'generic.babylon';
  66057. return GenericController;
  66058. }(BABYLON.WebVRController));
  66059. BABYLON.GenericController = GenericController;
  66060. })(BABYLON || (BABYLON = {}));
  66061. //# sourceMappingURL=babylon.genericController.js.map
  66062. "use strict";
  66063. var BABYLON;
  66064. (function (BABYLON) {
  66065. var LoadedMeshInfo = /** @class */ (function () {
  66066. function LoadedMeshInfo() {
  66067. this.buttonMeshes = {};
  66068. this.axisMeshes = {};
  66069. }
  66070. return LoadedMeshInfo;
  66071. }());
  66072. var WindowsMotionController = /** @class */ (function (_super) {
  66073. __extends(WindowsMotionController, _super);
  66074. function WindowsMotionController(vrGamepad) {
  66075. var _this = _super.call(this, vrGamepad) || this;
  66076. _this._mapping = {
  66077. // Semantic button names
  66078. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  66079. // A mapping of the button name to glTF model node name
  66080. // that should be transformed by button value.
  66081. buttonMeshNames: {
  66082. 'trigger': 'SELECT',
  66083. 'menu': 'MENU',
  66084. 'grip': 'GRASP',
  66085. 'thumbstick': 'THUMBSTICK_PRESS',
  66086. 'trackpad': 'TOUCHPAD_PRESS'
  66087. },
  66088. // This mapping is used to translate from the Motion Controller to Babylon semantics
  66089. buttonObservableNames: {
  66090. 'trigger': 'onTriggerStateChangedObservable',
  66091. 'menu': 'onSecondaryButtonStateChangedObservable',
  66092. 'grip': 'onMainButtonStateChangedObservable',
  66093. 'thumbstick': 'onPadStateChangedObservable',
  66094. 'trackpad': 'onTrackpadChangedObservable'
  66095. },
  66096. // A mapping of the axis name to glTF model node name
  66097. // that should be transformed by axis value.
  66098. // This array mirrors the browserGamepad.axes array, such that
  66099. // the mesh corresponding to axis 0 is in this array index 0.
  66100. axisMeshNames: [
  66101. 'THUMBSTICK_X',
  66102. 'THUMBSTICK_Y',
  66103. 'TOUCHPAD_TOUCH_X',
  66104. 'TOUCHPAD_TOUCH_Y'
  66105. ],
  66106. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  66107. };
  66108. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  66109. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  66110. _this.trackpad = { x: 0, y: 0 };
  66111. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  66112. _this._loadedMeshInfo = null;
  66113. return _this;
  66114. }
  66115. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  66116. get: function () {
  66117. return this.onTriggerStateChangedObservable;
  66118. },
  66119. enumerable: true,
  66120. configurable: true
  66121. });
  66122. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  66123. get: function () {
  66124. return this.onSecondaryButtonStateChangedObservable;
  66125. },
  66126. enumerable: true,
  66127. configurable: true
  66128. });
  66129. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  66130. get: function () {
  66131. return this.onMainButtonStateChangedObservable;
  66132. },
  66133. enumerable: true,
  66134. configurable: true
  66135. });
  66136. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  66137. get: function () {
  66138. return this.onPadStateChangedObservable;
  66139. },
  66140. enumerable: true,
  66141. configurable: true
  66142. });
  66143. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  66144. get: function () {
  66145. return this.onTrackpadChangedObservable;
  66146. },
  66147. enumerable: true,
  66148. configurable: true
  66149. });
  66150. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  66151. get: function () {
  66152. return this.onTrackpadValuesChangedObservable;
  66153. },
  66154. enumerable: true,
  66155. configurable: true
  66156. });
  66157. /**
  66158. * Called once per frame by the engine.
  66159. */
  66160. WindowsMotionController.prototype.update = function () {
  66161. _super.prototype.update.call(this);
  66162. if (this.browserGamepad.axes) {
  66163. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  66164. this.trackpad.x = this.browserGamepad["axes"][2];
  66165. this.trackpad.y = this.browserGamepad["axes"][3];
  66166. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  66167. }
  66168. // Only need to animate axes if there is a loaded mesh
  66169. if (this._loadedMeshInfo) {
  66170. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  66171. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  66172. }
  66173. }
  66174. }
  66175. };
  66176. /**
  66177. * Called once for each button that changed state since the last frame
  66178. * @param buttonIdx Which button index changed
  66179. * @param state New state of the button
  66180. * @param changes Which properties on the state changed since last frame
  66181. */
  66182. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66183. var buttonName = this._mapping.buttons[buttonIdx];
  66184. if (!buttonName) {
  66185. return;
  66186. }
  66187. // Only emit events for buttons that we know how to map from index to name
  66188. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  66189. if (observable) {
  66190. observable.notifyObservers(state);
  66191. }
  66192. this.lerpButtonTransform(buttonName, state.value);
  66193. };
  66194. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  66195. // If there is no loaded mesh, there is nothing to transform.
  66196. if (!this._loadedMeshInfo) {
  66197. return;
  66198. }
  66199. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  66200. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66201. return;
  66202. }
  66203. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  66204. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  66205. };
  66206. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  66207. if (!this._loadedMeshInfo) {
  66208. return;
  66209. }
  66210. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  66211. if (!meshInfo) {
  66212. return;
  66213. }
  66214. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66215. return;
  66216. }
  66217. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  66218. var lerpValue = axisValue * 0.5 + 0.5;
  66219. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  66220. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  66221. };
  66222. /**
  66223. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  66224. * @param scene scene in which to add meshes
  66225. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  66226. */
  66227. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  66228. var _this = this;
  66229. if (forceDefault === void 0) { forceDefault = false; }
  66230. var path;
  66231. var filename;
  66232. // Checking if GLB loader is present
  66233. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  66234. // Determine the device specific folder based on the ID suffix
  66235. var device = 'default';
  66236. if (this.id && !forceDefault) {
  66237. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  66238. device = ((match && match[0]) || device);
  66239. }
  66240. // Hand
  66241. if (this.hand === 'left') {
  66242. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  66243. }
  66244. else {
  66245. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  66246. }
  66247. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  66248. }
  66249. else {
  66250. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  66251. path = BABYLON.GenericController.MODEL_BASE_URL;
  66252. filename = BABYLON.GenericController.MODEL_FILENAME;
  66253. }
  66254. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  66255. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  66256. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  66257. if (!_this._loadedMeshInfo) {
  66258. return;
  66259. }
  66260. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  66261. _this.attachToMesh(_this._defaultModel);
  66262. if (meshLoaded) {
  66263. meshLoaded(_this._defaultModel);
  66264. }
  66265. }, null, function (scene, message) {
  66266. BABYLON.Tools.Log(message);
  66267. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  66268. if (!forceDefault) {
  66269. _this.initControllerMesh(scene, meshLoaded, true);
  66270. }
  66271. });
  66272. };
  66273. /**
  66274. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  66275. * can be transformed by button presses and axes values, based on this._mapping.
  66276. *
  66277. * @param scene scene in which the meshes exist
  66278. * @param meshes list of meshes that make up the controller model to process
  66279. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  66280. */
  66281. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  66282. var loadedMeshInfo = null;
  66283. // Create a new mesh to contain the glTF hierarchy
  66284. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  66285. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  66286. var childMesh = null;
  66287. for (var i = 0; i < meshes.length; i++) {
  66288. var mesh = meshes[i];
  66289. if (!mesh.parent) {
  66290. // Exclude controller meshes from picking results
  66291. mesh.isPickable = false;
  66292. // Handle root node, attach to the new parentMesh
  66293. childMesh = mesh;
  66294. break;
  66295. }
  66296. }
  66297. if (childMesh) {
  66298. childMesh.setParent(parentMesh);
  66299. // Create our mesh info. Note that this method will always return non-null.
  66300. loadedMeshInfo = this.createMeshInfo(parentMesh);
  66301. }
  66302. else {
  66303. BABYLON.Tools.Warn('Could not find root node in model file.');
  66304. }
  66305. return loadedMeshInfo;
  66306. };
  66307. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  66308. var loadedMeshInfo = new LoadedMeshInfo();
  66309. var i;
  66310. loadedMeshInfo.rootNode = rootNode;
  66311. // Reset the caches
  66312. loadedMeshInfo.buttonMeshes = {};
  66313. loadedMeshInfo.axisMeshes = {};
  66314. // Button Meshes
  66315. for (i = 0; i < this._mapping.buttons.length; i++) {
  66316. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  66317. if (!buttonMeshName) {
  66318. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  66319. continue;
  66320. }
  66321. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  66322. if (!buttonMesh) {
  66323. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  66324. continue;
  66325. }
  66326. var buttonMeshInfo = {
  66327. index: i,
  66328. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  66329. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  66330. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  66331. };
  66332. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  66333. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  66334. }
  66335. else {
  66336. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  66337. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  66338. '(VALUE: ' + !!buttonMeshInfo.value +
  66339. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  66340. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  66341. ')');
  66342. }
  66343. }
  66344. // Axis Meshes
  66345. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  66346. var axisMeshName = this._mapping.axisMeshNames[i];
  66347. if (!axisMeshName) {
  66348. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  66349. continue;
  66350. }
  66351. var axisMesh = getChildByName(rootNode, axisMeshName);
  66352. if (!axisMesh) {
  66353. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  66354. continue;
  66355. }
  66356. var axisMeshInfo = {
  66357. index: i,
  66358. value: getImmediateChildByName(axisMesh, 'VALUE'),
  66359. min: getImmediateChildByName(axisMesh, 'MIN'),
  66360. max: getImmediateChildByName(axisMesh, 'MAX')
  66361. };
  66362. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  66363. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  66364. }
  66365. else {
  66366. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  66367. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  66368. '(VALUE: ' + !!axisMeshInfo.value +
  66369. ', MIN: ' + !!axisMeshInfo.min +
  66370. ', MAX:' + !!axisMeshInfo.max +
  66371. ')');
  66372. }
  66373. }
  66374. // Pointing Ray
  66375. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  66376. if (!loadedMeshInfo.pointingPoseNode) {
  66377. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  66378. }
  66379. return loadedMeshInfo;
  66380. // Look through all children recursively. This will return null if no mesh exists with the given name.
  66381. function getChildByName(node, name) {
  66382. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  66383. }
  66384. // Look through only immediate children. This will return null if no mesh exists with the given name.
  66385. function getImmediateChildByName(node, name) {
  66386. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  66387. }
  66388. };
  66389. WindowsMotionController.prototype.getForwardRay = function (length) {
  66390. if (length === void 0) { length = 100; }
  66391. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  66392. return _super.prototype.getForwardRay.call(this, length);
  66393. }
  66394. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  66395. var origin = m.getTranslation();
  66396. var forward = new BABYLON.Vector3(0, 0, -1);
  66397. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66398. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66399. return new BABYLON.Ray(origin, direction, length);
  66400. };
  66401. WindowsMotionController.prototype.dispose = function () {
  66402. _super.prototype.dispose.call(this);
  66403. this.onTrackpadChangedObservable.clear();
  66404. };
  66405. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  66406. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  66407. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  66408. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  66409. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  66410. return WindowsMotionController;
  66411. }(BABYLON.WebVRController));
  66412. BABYLON.WindowsMotionController = WindowsMotionController;
  66413. })(BABYLON || (BABYLON = {}));
  66414. //# sourceMappingURL=babylon.windowsMotionController.js.map
  66415. "use strict";
  66416. var BABYLON;
  66417. (function (BABYLON) {
  66418. var GearVRController = /** @class */ (function (_super) {
  66419. __extends(GearVRController, _super);
  66420. function GearVRController(vrGamepad) {
  66421. var _this = _super.call(this, vrGamepad) || this;
  66422. _this._buttonIndexToObservableNameMap = [
  66423. 'onTrackpadChangedObservable',
  66424. 'onTriggerStateChangedObservable' // Trigger
  66425. ];
  66426. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  66427. return _this;
  66428. }
  66429. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66430. var _this = this;
  66431. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  66432. _this._defaultModel = newMeshes[1];
  66433. _this.attachToMesh(_this._defaultModel);
  66434. if (meshLoaded) {
  66435. meshLoaded(_this._defaultModel);
  66436. }
  66437. });
  66438. };
  66439. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66440. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  66441. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  66442. // Only emit events for buttons that we know how to map from index to observable
  66443. var observable = this[observableName];
  66444. if (observable) {
  66445. observable.notifyObservers(state);
  66446. }
  66447. }
  66448. };
  66449. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66450. GearVRController.MODEL_FILENAME = 'generic.babylon';
  66451. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  66452. return GearVRController;
  66453. }(BABYLON.WebVRController));
  66454. BABYLON.GearVRController = GearVRController;
  66455. })(BABYLON || (BABYLON = {}));
  66456. //# sourceMappingURL=babylon.gearVRController.js.map
  66457. "use strict";
  66458. var BABYLON;
  66459. (function (BABYLON) {
  66460. /**
  66461. * Google Daydream controller
  66462. */
  66463. var DaydreamController = /** @class */ (function (_super) {
  66464. __extends(DaydreamController, _super);
  66465. function DaydreamController(vrGamepad) {
  66466. var _this = _super.call(this, vrGamepad) || this;
  66467. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  66468. return _this;
  66469. }
  66470. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66471. var _this = this;
  66472. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  66473. _this._defaultModel = newMeshes[1];
  66474. _this.attachToMesh(_this._defaultModel);
  66475. if (meshLoaded) {
  66476. meshLoaded(_this._defaultModel);
  66477. }
  66478. });
  66479. };
  66480. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66481. // Daydream controller only has 1 GamepadButton (on the trackpad).
  66482. if (buttonIdx === 0) {
  66483. var observable = this.onTriggerStateChangedObservable;
  66484. if (observable) {
  66485. observable.notifyObservers(state);
  66486. }
  66487. }
  66488. else {
  66489. // If the app or home buttons are ever made available
  66490. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  66491. }
  66492. };
  66493. /**
  66494. * Base Url for the controller model.
  66495. */
  66496. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66497. /**
  66498. * File name for the controller model.
  66499. */
  66500. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  66501. /**
  66502. * Gamepad Id prefix used to identify Daydream Controller.
  66503. */
  66504. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  66505. return DaydreamController;
  66506. }(BABYLON.WebVRController));
  66507. BABYLON.DaydreamController = DaydreamController;
  66508. })(BABYLON || (BABYLON = {}));
  66509. //# sourceMappingURL=babylon.daydreamController.js.map
  66510. "use strict";
  66511. var BABYLON;
  66512. (function (BABYLON) {
  66513. var FollowCamera = /** @class */ (function (_super) {
  66514. __extends(FollowCamera, _super);
  66515. function FollowCamera(name, position, scene, lockedTarget) {
  66516. if (lockedTarget === void 0) { lockedTarget = null; }
  66517. var _this = _super.call(this, name, position, scene) || this;
  66518. _this.radius = 12;
  66519. _this.rotationOffset = 0;
  66520. _this.heightOffset = 4;
  66521. _this.cameraAcceleration = 0.05;
  66522. _this.maxCameraSpeed = 20;
  66523. _this.lockedTarget = lockedTarget;
  66524. return _this;
  66525. }
  66526. FollowCamera.prototype.getRadians = function (degrees) {
  66527. return degrees * Math.PI / 180;
  66528. };
  66529. FollowCamera.prototype.follow = function (cameraTarget) {
  66530. if (!cameraTarget)
  66531. return;
  66532. var yRotation;
  66533. if (cameraTarget.rotationQuaternion) {
  66534. var rotMatrix = new BABYLON.Matrix();
  66535. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  66536. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  66537. }
  66538. else {
  66539. yRotation = cameraTarget.rotation.y;
  66540. }
  66541. var radians = this.getRadians(this.rotationOffset) + yRotation;
  66542. var targetPosition = cameraTarget.getAbsolutePosition();
  66543. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  66544. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  66545. var dx = targetX - this.position.x;
  66546. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  66547. var dz = (targetZ) - this.position.z;
  66548. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  66549. var vy = dy * this.cameraAcceleration;
  66550. var vz = dz * this.cameraAcceleration * 2;
  66551. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  66552. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66553. }
  66554. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  66555. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66556. }
  66557. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  66558. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66559. }
  66560. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  66561. this.setTarget(targetPosition);
  66562. };
  66563. FollowCamera.prototype._checkInputs = function () {
  66564. _super.prototype._checkInputs.call(this);
  66565. if (this.lockedTarget) {
  66566. this.follow(this.lockedTarget);
  66567. }
  66568. };
  66569. FollowCamera.prototype.getClassName = function () {
  66570. return "FollowCamera";
  66571. };
  66572. __decorate([
  66573. BABYLON.serialize()
  66574. ], FollowCamera.prototype, "radius", void 0);
  66575. __decorate([
  66576. BABYLON.serialize()
  66577. ], FollowCamera.prototype, "rotationOffset", void 0);
  66578. __decorate([
  66579. BABYLON.serialize()
  66580. ], FollowCamera.prototype, "heightOffset", void 0);
  66581. __decorate([
  66582. BABYLON.serialize()
  66583. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  66584. __decorate([
  66585. BABYLON.serialize()
  66586. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  66587. __decorate([
  66588. BABYLON.serializeAsMeshReference("lockedTargetId")
  66589. ], FollowCamera.prototype, "lockedTarget", void 0);
  66590. return FollowCamera;
  66591. }(BABYLON.TargetCamera));
  66592. BABYLON.FollowCamera = FollowCamera;
  66593. var ArcFollowCamera = /** @class */ (function (_super) {
  66594. __extends(ArcFollowCamera, _super);
  66595. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  66596. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  66597. _this.alpha = alpha;
  66598. _this.beta = beta;
  66599. _this.radius = radius;
  66600. _this.target = target;
  66601. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  66602. _this.follow();
  66603. return _this;
  66604. }
  66605. ArcFollowCamera.prototype.follow = function () {
  66606. if (!this.target) {
  66607. return;
  66608. }
  66609. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  66610. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  66611. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  66612. var targetPosition = this.target.getAbsolutePosition();
  66613. this.position = targetPosition.add(this._cartesianCoordinates);
  66614. this.setTarget(targetPosition);
  66615. };
  66616. ArcFollowCamera.prototype._checkInputs = function () {
  66617. _super.prototype._checkInputs.call(this);
  66618. this.follow();
  66619. };
  66620. ArcFollowCamera.prototype.getClassName = function () {
  66621. return "ArcFollowCamera";
  66622. };
  66623. return ArcFollowCamera;
  66624. }(BABYLON.TargetCamera));
  66625. BABYLON.ArcFollowCamera = ArcFollowCamera;
  66626. })(BABYLON || (BABYLON = {}));
  66627. //# sourceMappingURL=babylon.followCamera.js.map
  66628. "use strict";
  66629. var BABYLON;
  66630. (function (BABYLON) {
  66631. // We're mainly based on the logic defined into the FreeCamera code
  66632. var UniversalCamera = /** @class */ (function (_super) {
  66633. __extends(UniversalCamera, _super);
  66634. //-- end properties for backward compatibility for inputs
  66635. function UniversalCamera(name, position, scene) {
  66636. var _this = _super.call(this, name, position, scene) || this;
  66637. _this.inputs.addGamepad();
  66638. return _this;
  66639. }
  66640. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  66641. //-- Begin properties for backward compatibility for inputs
  66642. get: function () {
  66643. var gamepad = this.inputs.attached["gamepad"];
  66644. if (gamepad)
  66645. return gamepad.gamepadAngularSensibility;
  66646. return 0;
  66647. },
  66648. set: function (value) {
  66649. var gamepad = this.inputs.attached["gamepad"];
  66650. if (gamepad)
  66651. gamepad.gamepadAngularSensibility = value;
  66652. },
  66653. enumerable: true,
  66654. configurable: true
  66655. });
  66656. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  66657. get: function () {
  66658. var gamepad = this.inputs.attached["gamepad"];
  66659. if (gamepad)
  66660. return gamepad.gamepadMoveSensibility;
  66661. return 0;
  66662. },
  66663. set: function (value) {
  66664. var gamepad = this.inputs.attached["gamepad"];
  66665. if (gamepad)
  66666. gamepad.gamepadMoveSensibility = value;
  66667. },
  66668. enumerable: true,
  66669. configurable: true
  66670. });
  66671. UniversalCamera.prototype.getClassName = function () {
  66672. return "UniversalCamera";
  66673. };
  66674. return UniversalCamera;
  66675. }(BABYLON.TouchCamera));
  66676. BABYLON.UniversalCamera = UniversalCamera;
  66677. })(BABYLON || (BABYLON = {}));
  66678. //# sourceMappingURL=babylon.universalCamera.js.map
  66679. "use strict";
  66680. var BABYLON;
  66681. (function (BABYLON) {
  66682. // We're mainly based on the logic defined into the FreeCamera code
  66683. var GamepadCamera = /** @class */ (function (_super) {
  66684. __extends(GamepadCamera, _super);
  66685. //-- end properties for backward compatibility for inputs
  66686. function GamepadCamera(name, position, scene) {
  66687. return _super.call(this, name, position, scene) || this;
  66688. }
  66689. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  66690. //-- Begin properties for backward compatibility for inputs
  66691. get: function () {
  66692. var gamepad = this.inputs.attached["gamepad"];
  66693. if (gamepad)
  66694. return gamepad.gamepadAngularSensibility;
  66695. return 0;
  66696. },
  66697. set: function (value) {
  66698. var gamepad = this.inputs.attached["gamepad"];
  66699. if (gamepad)
  66700. gamepad.gamepadAngularSensibility = value;
  66701. },
  66702. enumerable: true,
  66703. configurable: true
  66704. });
  66705. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  66706. get: function () {
  66707. var gamepad = this.inputs.attached["gamepad"];
  66708. if (gamepad)
  66709. return gamepad.gamepadMoveSensibility;
  66710. return 0;
  66711. },
  66712. set: function (value) {
  66713. var gamepad = this.inputs.attached["gamepad"];
  66714. if (gamepad)
  66715. gamepad.gamepadMoveSensibility = value;
  66716. },
  66717. enumerable: true,
  66718. configurable: true
  66719. });
  66720. GamepadCamera.prototype.getClassName = function () {
  66721. return "GamepadCamera";
  66722. };
  66723. return GamepadCamera;
  66724. }(BABYLON.UniversalCamera));
  66725. BABYLON.GamepadCamera = GamepadCamera;
  66726. })(BABYLON || (BABYLON = {}));
  66727. //# sourceMappingURL=babylon.gamepadCamera.js.map
  66728. "use strict";
  66729. var BABYLON;
  66730. (function (BABYLON) {
  66731. var PostProcessRenderPipelineManager = /** @class */ (function () {
  66732. function PostProcessRenderPipelineManager() {
  66733. this._renderPipelines = {};
  66734. }
  66735. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  66736. this._renderPipelines[renderPipeline._name] = renderPipeline;
  66737. };
  66738. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  66739. if (unique === void 0) { unique = false; }
  66740. var renderPipeline = this._renderPipelines[renderPipelineName];
  66741. if (!renderPipeline) {
  66742. return;
  66743. }
  66744. renderPipeline._attachCameras(cameras, unique);
  66745. };
  66746. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  66747. var renderPipeline = this._renderPipelines[renderPipelineName];
  66748. if (!renderPipeline) {
  66749. return;
  66750. }
  66751. renderPipeline._detachCameras(cameras);
  66752. };
  66753. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66754. var renderPipeline = this._renderPipelines[renderPipelineName];
  66755. if (!renderPipeline) {
  66756. return;
  66757. }
  66758. renderPipeline._enableEffect(renderEffectName, cameras);
  66759. };
  66760. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66761. var renderPipeline = this._renderPipelines[renderPipelineName];
  66762. if (!renderPipeline) {
  66763. return;
  66764. }
  66765. renderPipeline._disableEffect(renderEffectName, cameras);
  66766. };
  66767. PostProcessRenderPipelineManager.prototype.update = function () {
  66768. for (var renderPipelineName in this._renderPipelines) {
  66769. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66770. var pipeline = this._renderPipelines[renderPipelineName];
  66771. if (!pipeline.isSupported) {
  66772. pipeline.dispose();
  66773. delete this._renderPipelines[renderPipelineName];
  66774. }
  66775. else {
  66776. pipeline._update();
  66777. }
  66778. }
  66779. }
  66780. };
  66781. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  66782. for (var renderPipelineName in this._renderPipelines) {
  66783. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66784. var pipeline = this._renderPipelines[renderPipelineName];
  66785. pipeline._rebuild();
  66786. }
  66787. }
  66788. };
  66789. PostProcessRenderPipelineManager.prototype.dispose = function () {
  66790. for (var renderPipelineName in this._renderPipelines) {
  66791. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66792. var pipeline = this._renderPipelines[renderPipelineName];
  66793. pipeline.dispose();
  66794. }
  66795. }
  66796. };
  66797. return PostProcessRenderPipelineManager;
  66798. }());
  66799. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  66800. })(BABYLON || (BABYLON = {}));
  66801. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  66802. "use strict";
  66803. var BABYLON;
  66804. (function (BABYLON) {
  66805. /**
  66806. * This represents a set of one or more post processes in Babylon.
  66807. * A post process can be used to apply a shader to a texture after it is rendered.
  66808. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  66809. */
  66810. var PostProcessRenderEffect = /** @class */ (function () {
  66811. /**
  66812. * Instantiates a post process render effect.
  66813. * A post process can be used to apply a shader to a texture after it is rendered.
  66814. * @param engine The engine the effect is tied to
  66815. * @param name The name of the effect
  66816. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  66817. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  66818. */
  66819. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  66820. this._name = name;
  66821. this._singleInstance = singleInstance || true;
  66822. this._getPostProcesses = getPostProcesses;
  66823. this._cameras = {};
  66824. this._indicesForCamera = {};
  66825. this._postProcesses = {};
  66826. }
  66827. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  66828. /**
  66829. * Checks if all the post processes in the effect are supported.
  66830. */
  66831. get: function () {
  66832. for (var index in this._postProcesses) {
  66833. for (var ppIndex in this._postProcesses[index]) {
  66834. if (!this._postProcesses[index][ppIndex].isSupported) {
  66835. return false;
  66836. }
  66837. }
  66838. }
  66839. return true;
  66840. },
  66841. enumerable: true,
  66842. configurable: true
  66843. });
  66844. /**
  66845. * Updates the current state of the effect
  66846. */
  66847. PostProcessRenderEffect.prototype._update = function () {
  66848. };
  66849. /**
  66850. * Attaches the effect on cameras
  66851. * @param cameras The camera to attach to.
  66852. */
  66853. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  66854. var _this = this;
  66855. var cameraKey;
  66856. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66857. if (!cams) {
  66858. return;
  66859. }
  66860. for (var i = 0; i < cams.length; i++) {
  66861. var camera = cams[i];
  66862. var cameraName = camera.name;
  66863. if (this._singleInstance) {
  66864. cameraKey = 0;
  66865. }
  66866. else {
  66867. cameraKey = cameraName;
  66868. }
  66869. if (!this._postProcesses[cameraKey]) {
  66870. var postProcess = this._getPostProcesses();
  66871. if (postProcess) {
  66872. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  66873. }
  66874. }
  66875. if (!this._indicesForCamera[cameraName]) {
  66876. this._indicesForCamera[cameraName] = [];
  66877. }
  66878. this._postProcesses[cameraKey].forEach(function (postProcess) {
  66879. var index = camera.attachPostProcess(postProcess);
  66880. _this._indicesForCamera[cameraName].push(index);
  66881. });
  66882. if (!this._cameras[cameraName]) {
  66883. this._cameras[cameraName] = camera;
  66884. }
  66885. }
  66886. };
  66887. /**
  66888. * Detatches the effect on cameras
  66889. * @param cameras The camera to detatch from.
  66890. */
  66891. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  66892. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66893. if (!cams) {
  66894. return;
  66895. }
  66896. for (var i = 0; i < cams.length; i++) {
  66897. var camera = cams[i];
  66898. var cameraName = camera.name;
  66899. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66900. camera.detachPostProcess(postProcess);
  66901. });
  66902. if (this._cameras[cameraName]) {
  66903. //this._indicesForCamera.splice(index, 1);
  66904. this._cameras[cameraName] = null;
  66905. }
  66906. }
  66907. };
  66908. /**
  66909. * Enables the effect on given cameras
  66910. * @param cameras The camera to enable.
  66911. */
  66912. PostProcessRenderEffect.prototype._enable = function (cameras) {
  66913. var _this = this;
  66914. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66915. if (!cams) {
  66916. return;
  66917. }
  66918. for (var i = 0; i < cams.length; i++) {
  66919. var camera = cams[i];
  66920. var cameraName = camera.name;
  66921. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  66922. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  66923. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66924. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  66925. });
  66926. }
  66927. }
  66928. }
  66929. };
  66930. /**
  66931. * Disables the effect on the given cameras
  66932. * @param cameras The camera to disable.
  66933. */
  66934. PostProcessRenderEffect.prototype._disable = function (cameras) {
  66935. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66936. if (!cams) {
  66937. return;
  66938. }
  66939. for (var i = 0; i < cams.length; i++) {
  66940. var camera = cams[i];
  66941. var cameraName = camera.name;
  66942. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66943. camera.detachPostProcess(postProcess);
  66944. });
  66945. }
  66946. };
  66947. /**
  66948. * Gets a list of the post processes contained in the effect.
  66949. * @param camera The camera to get the post processes on.
  66950. * @returns The list of the post processes in the effect.
  66951. */
  66952. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  66953. if (this._singleInstance) {
  66954. return this._postProcesses[0];
  66955. }
  66956. else {
  66957. if (!camera) {
  66958. return null;
  66959. }
  66960. return this._postProcesses[camera.name];
  66961. }
  66962. };
  66963. return PostProcessRenderEffect;
  66964. }());
  66965. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  66966. })(BABYLON || (BABYLON = {}));
  66967. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  66968. "use strict";
  66969. var BABYLON;
  66970. (function (BABYLON) {
  66971. var PostProcessRenderPipeline = /** @class */ (function () {
  66972. function PostProcessRenderPipeline(engine, name) {
  66973. this.engine = engine;
  66974. this._name = name;
  66975. this._renderEffects = {};
  66976. this._renderEffectsForIsolatedPass = new Array();
  66977. this._cameras = [];
  66978. }
  66979. PostProcessRenderPipeline.prototype.getClassName = function () {
  66980. return "PostProcessRenderPipeline";
  66981. };
  66982. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  66983. get: function () {
  66984. for (var renderEffectName in this._renderEffects) {
  66985. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66986. if (!this._renderEffects[renderEffectName].isSupported) {
  66987. return false;
  66988. }
  66989. }
  66990. }
  66991. return true;
  66992. },
  66993. enumerable: true,
  66994. configurable: true
  66995. });
  66996. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  66997. this._renderEffects[renderEffect._name] = renderEffect;
  66998. };
  66999. // private
  67000. PostProcessRenderPipeline.prototype._rebuild = function () {
  67001. };
  67002. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  67003. var renderEffects = this._renderEffects[renderEffectName];
  67004. if (!renderEffects) {
  67005. return;
  67006. }
  67007. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67008. };
  67009. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  67010. var renderEffects = this._renderEffects[renderEffectName];
  67011. if (!renderEffects) {
  67012. return;
  67013. }
  67014. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67015. };
  67016. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  67017. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67018. if (!cams) {
  67019. return;
  67020. }
  67021. var indicesToDelete = [];
  67022. var i;
  67023. for (i = 0; i < cams.length; i++) {
  67024. var camera = cams[i];
  67025. var cameraName = camera.name;
  67026. if (this._cameras.indexOf(camera) === -1) {
  67027. this._cameras[cameraName] = camera;
  67028. }
  67029. else if (unique) {
  67030. indicesToDelete.push(i);
  67031. }
  67032. }
  67033. for (i = 0; i < indicesToDelete.length; i++) {
  67034. cameras.splice(indicesToDelete[i], 1);
  67035. }
  67036. for (var renderEffectName in this._renderEffects) {
  67037. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67038. this._renderEffects[renderEffectName]._attachCameras(cams);
  67039. }
  67040. }
  67041. };
  67042. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  67043. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67044. if (!cams) {
  67045. return;
  67046. }
  67047. for (var renderEffectName in this._renderEffects) {
  67048. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67049. this._renderEffects[renderEffectName]._detachCameras(cams);
  67050. }
  67051. }
  67052. for (var i = 0; i < cams.length; i++) {
  67053. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  67054. }
  67055. };
  67056. PostProcessRenderPipeline.prototype._update = function () {
  67057. for (var renderEffectName in this._renderEffects) {
  67058. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67059. this._renderEffects[renderEffectName]._update();
  67060. }
  67061. }
  67062. for (var i = 0; i < this._cameras.length; i++) {
  67063. var cameraName = this._cameras[i].name;
  67064. if (this._renderEffectsForIsolatedPass[cameraName]) {
  67065. this._renderEffectsForIsolatedPass[cameraName]._update();
  67066. }
  67067. }
  67068. };
  67069. PostProcessRenderPipeline.prototype._reset = function () {
  67070. this._renderEffects = {};
  67071. this._renderEffectsForIsolatedPass = new Array();
  67072. };
  67073. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  67074. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  67075. var effectKeys = Object.keys(this._renderEffects);
  67076. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  67077. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  67078. if (postProcesses) {
  67079. postProcesses[0].samples = 4;
  67080. return true;
  67081. }
  67082. }
  67083. return false;
  67084. };
  67085. PostProcessRenderPipeline.prototype.dispose = function () {
  67086. // Must be implemented by children
  67087. };
  67088. __decorate([
  67089. BABYLON.serialize()
  67090. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  67091. return PostProcessRenderPipeline;
  67092. }());
  67093. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  67094. })(BABYLON || (BABYLON = {}));
  67095. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  67096. "use strict";
  67097. var BABYLON;
  67098. (function (BABYLON) {
  67099. /**
  67100. * This represents a depth renderer in Babylon.
  67101. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  67102. */
  67103. var DepthRenderer = /** @class */ (function () {
  67104. /**
  67105. * Instantiates a depth renderer
  67106. * @param scene The scene the renderer belongs to
  67107. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  67108. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  67109. */
  67110. function DepthRenderer(scene, type, camera) {
  67111. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67112. if (camera === void 0) { camera = null; }
  67113. var _this = this;
  67114. this._scene = scene;
  67115. this._camera = camera;
  67116. var engine = scene.getEngine();
  67117. // Render target
  67118. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  67119. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67120. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67121. this._depthMap.refreshRate = 1;
  67122. this._depthMap.renderParticles = false;
  67123. this._depthMap.renderList = null;
  67124. // Camera to get depth map from to support multiple concurrent cameras
  67125. this._depthMap.activeCamera = this._camera;
  67126. this._depthMap.ignoreCameraViewport = true;
  67127. this._depthMap.useCameraPostProcesses = false;
  67128. // set default depth value to 1.0 (far away)
  67129. this._depthMap.onClearObservable.add(function (engine) {
  67130. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  67131. });
  67132. // Custom render function
  67133. var renderSubMesh = function (subMesh) {
  67134. var mesh = subMesh.getRenderingMesh();
  67135. var scene = _this._scene;
  67136. var engine = scene.getEngine();
  67137. var material = subMesh.getMaterial();
  67138. if (!material) {
  67139. return;
  67140. }
  67141. // Culling and reverse (right handed system)
  67142. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67143. // Managing instances
  67144. var batch = mesh._getInstancesRenderList(subMesh._id);
  67145. if (batch.mustReturn) {
  67146. return;
  67147. }
  67148. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67149. var camera = _this._camera || scene.activeCamera;
  67150. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  67151. engine.enableEffect(_this._effect);
  67152. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67153. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67154. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  67155. // Alpha test
  67156. if (material && material.needAlphaTesting()) {
  67157. var alphaTexture = material.getAlphaTestTexture();
  67158. if (alphaTexture) {
  67159. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67160. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67161. }
  67162. }
  67163. // Bones
  67164. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67165. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67166. }
  67167. // Draw
  67168. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67169. }
  67170. };
  67171. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67172. var index;
  67173. if (depthOnlySubMeshes.length) {
  67174. engine.setColorWrite(false);
  67175. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67176. renderSubMesh(depthOnlySubMeshes.data[index]);
  67177. }
  67178. engine.setColorWrite(true);
  67179. }
  67180. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67181. renderSubMesh(opaqueSubMeshes.data[index]);
  67182. }
  67183. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67184. renderSubMesh(alphaTestSubMeshes.data[index]);
  67185. }
  67186. };
  67187. }
  67188. /**
  67189. * Creates the depth rendering effect and checks if the effect is ready.
  67190. * @param subMesh The submesh to be used to render the depth map of
  67191. * @param useInstances If multiple world instances should be used
  67192. * @returns if the depth renderer is ready to render the depth map
  67193. */
  67194. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  67195. var material = subMesh.getMaterial();
  67196. if (material.disableDepthWrite) {
  67197. return false;
  67198. }
  67199. var defines = [];
  67200. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67201. var mesh = subMesh.getMesh();
  67202. // Alpha test
  67203. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  67204. defines.push("#define ALPHATEST");
  67205. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67206. attribs.push(BABYLON.VertexBuffer.UVKind);
  67207. defines.push("#define UV1");
  67208. }
  67209. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67210. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67211. defines.push("#define UV2");
  67212. }
  67213. }
  67214. // Bones
  67215. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67216. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67217. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67218. if (mesh.numBoneInfluencers > 4) {
  67219. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67220. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67221. }
  67222. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67223. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67224. }
  67225. else {
  67226. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67227. }
  67228. // Instances
  67229. if (useInstances) {
  67230. defines.push("#define INSTANCES");
  67231. attribs.push("world0");
  67232. attribs.push("world1");
  67233. attribs.push("world2");
  67234. attribs.push("world3");
  67235. }
  67236. // Get correct effect
  67237. var join = defines.join("\n");
  67238. if (this._cachedDefines !== join) {
  67239. this._cachedDefines = join;
  67240. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  67241. }
  67242. return this._effect.isReady();
  67243. };
  67244. /**
  67245. * Gets the texture which the depth map will be written to.
  67246. * @returns The depth map texture
  67247. */
  67248. DepthRenderer.prototype.getDepthMap = function () {
  67249. return this._depthMap;
  67250. };
  67251. /**
  67252. * Disposes of the depth renderer.
  67253. */
  67254. DepthRenderer.prototype.dispose = function () {
  67255. this._depthMap.dispose();
  67256. };
  67257. return DepthRenderer;
  67258. }());
  67259. BABYLON.DepthRenderer = DepthRenderer;
  67260. })(BABYLON || (BABYLON = {}));
  67261. //# sourceMappingURL=babylon.depthRenderer.js.map
  67262. "use strict";
  67263. var BABYLON;
  67264. (function (BABYLON) {
  67265. var SSAORenderingPipeline = /** @class */ (function (_super) {
  67266. __extends(SSAORenderingPipeline, _super);
  67267. /**
  67268. * @constructor
  67269. * @param {string} name - The rendering pipeline name
  67270. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67271. * @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 }
  67272. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67273. */
  67274. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  67275. var _this = _super.call(this, scene.getEngine(), name) || this;
  67276. // Members
  67277. /**
  67278. * The PassPostProcess id in the pipeline that contains the original scene color
  67279. * @type {string}
  67280. */
  67281. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67282. /**
  67283. * The SSAO PostProcess id in the pipeline
  67284. * @type {string}
  67285. */
  67286. _this.SSAORenderEffect = "SSAORenderEffect";
  67287. /**
  67288. * The horizontal blur PostProcess id in the pipeline
  67289. * @type {string}
  67290. */
  67291. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67292. /**
  67293. * The vertical blur PostProcess id in the pipeline
  67294. * @type {string}
  67295. */
  67296. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67297. /**
  67298. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67299. * @type {string}
  67300. */
  67301. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67302. /**
  67303. * The output strength of the SSAO post-process. Default value is 1.0.
  67304. * @type {number}
  67305. */
  67306. _this.totalStrength = 1.0;
  67307. /**
  67308. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  67309. * @type {number}
  67310. */
  67311. _this.radius = 0.0001;
  67312. /**
  67313. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  67314. * Must not be equal to fallOff and superior to fallOff.
  67315. * Default value is 0.975
  67316. * @type {number}
  67317. */
  67318. _this.area = 0.0075;
  67319. /**
  67320. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  67321. * Must not be equal to area and inferior to area.
  67322. * Default value is 0.0
  67323. * @type {number}
  67324. */
  67325. _this.fallOff = 0.000001;
  67326. /**
  67327. * The base color of the SSAO post-process
  67328. * The final result is "base + ssao" between [0, 1]
  67329. * @type {number}
  67330. */
  67331. _this.base = 0.5;
  67332. _this._firstUpdate = true;
  67333. _this._scene = scene;
  67334. // Set up assets
  67335. _this._createRandomTexture();
  67336. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67337. var ssaoRatio = ratio.ssaoRatio || ratio;
  67338. var combineRatio = ratio.combineRatio || ratio;
  67339. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67340. _this._createSSAOPostProcess(ssaoRatio);
  67341. _this._createBlurPostProcess(ssaoRatio);
  67342. _this._createSSAOCombinePostProcess(combineRatio);
  67343. // Set up pipeline
  67344. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67345. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67346. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67347. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67348. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67349. // Finish
  67350. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67351. if (cameras)
  67352. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67353. return _this;
  67354. }
  67355. // Public Methods
  67356. /**
  67357. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67358. */
  67359. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67360. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67361. for (var i = 0; i < this._scene.cameras.length; i++) {
  67362. var camera = this._scene.cameras[i];
  67363. this._originalColorPostProcess.dispose(camera);
  67364. this._ssaoPostProcess.dispose(camera);
  67365. this._blurHPostProcess.dispose(camera);
  67366. this._blurVPostProcess.dispose(camera);
  67367. this._ssaoCombinePostProcess.dispose(camera);
  67368. }
  67369. this._randomTexture.dispose();
  67370. if (disableDepthRender)
  67371. this._scene.disableDepthRenderer();
  67372. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67373. _super.prototype.dispose.call(this);
  67374. };
  67375. // Private Methods
  67376. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  67377. var _this = this;
  67378. var size = 16;
  67379. 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);
  67380. 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);
  67381. this._blurHPostProcess.onActivateObservable.add(function () {
  67382. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  67383. _this._blurHPostProcess.kernel = size * dw;
  67384. });
  67385. this._blurVPostProcess.onActivateObservable.add(function () {
  67386. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  67387. _this._blurVPostProcess.kernel = size * dw;
  67388. });
  67389. };
  67390. SSAORenderingPipeline.prototype._rebuild = function () {
  67391. this._firstUpdate = true;
  67392. _super.prototype._rebuild.call(this);
  67393. };
  67394. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67395. var _this = this;
  67396. var numSamples = 16;
  67397. var sampleSphere = [
  67398. 0.5381, 0.1856, -0.4319,
  67399. 0.1379, 0.2486, 0.4430,
  67400. 0.3371, 0.5679, -0.0057,
  67401. -0.6999, -0.0451, -0.0019,
  67402. 0.0689, -0.1598, -0.8547,
  67403. 0.0560, 0.0069, -0.1843,
  67404. -0.0146, 0.1402, 0.0762,
  67405. 0.0100, -0.1924, -0.0344,
  67406. -0.3577, -0.5301, -0.4358,
  67407. -0.3169, 0.1063, 0.0158,
  67408. 0.0103, -0.5869, 0.0046,
  67409. -0.0897, -0.4940, 0.3287,
  67410. 0.7119, -0.0154, -0.0918,
  67411. -0.0533, 0.0596, -0.5411,
  67412. 0.0352, -0.0631, 0.5460,
  67413. -0.4776, 0.2847, -0.0271
  67414. ];
  67415. var samplesFactor = 1.0 / numSamples;
  67416. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  67417. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67418. "area", "fallOff", "base", "range", "viewport"
  67419. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67420. this._ssaoPostProcess.onApply = function (effect) {
  67421. if (_this._firstUpdate) {
  67422. effect.setArray3("sampleSphere", sampleSphere);
  67423. effect.setFloat("samplesFactor", samplesFactor);
  67424. effect.setFloat("randTextureTiles", 4.0);
  67425. }
  67426. effect.setFloat("totalStrength", _this.totalStrength);
  67427. effect.setFloat("radius", _this.radius);
  67428. effect.setFloat("area", _this.area);
  67429. effect.setFloat("fallOff", _this.fallOff);
  67430. effect.setFloat("base", _this.base);
  67431. effect.setTexture("textureSampler", _this._depthTexture);
  67432. effect.setTexture("randomSampler", _this._randomTexture);
  67433. };
  67434. };
  67435. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67436. var _this = this;
  67437. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67438. this._ssaoCombinePostProcess.onApply = function (effect) {
  67439. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67440. };
  67441. };
  67442. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  67443. var size = 512;
  67444. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67445. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67446. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67447. var context = this._randomTexture.getContext();
  67448. var rand = function (min, max) {
  67449. return Math.random() * (max - min) + min;
  67450. };
  67451. var randVector = BABYLON.Vector3.Zero();
  67452. for (var x = 0; x < size; x++) {
  67453. for (var y = 0; y < size; y++) {
  67454. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  67455. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  67456. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  67457. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67458. context.fillRect(x, y, 1, 1);
  67459. }
  67460. }
  67461. this._randomTexture.update(false);
  67462. };
  67463. __decorate([
  67464. BABYLON.serialize()
  67465. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  67466. __decorate([
  67467. BABYLON.serialize()
  67468. ], SSAORenderingPipeline.prototype, "radius", void 0);
  67469. __decorate([
  67470. BABYLON.serialize()
  67471. ], SSAORenderingPipeline.prototype, "area", void 0);
  67472. __decorate([
  67473. BABYLON.serialize()
  67474. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  67475. __decorate([
  67476. BABYLON.serialize()
  67477. ], SSAORenderingPipeline.prototype, "base", void 0);
  67478. return SSAORenderingPipeline;
  67479. }(BABYLON.PostProcessRenderPipeline));
  67480. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  67481. })(BABYLON || (BABYLON = {}));
  67482. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  67483. "use strict";
  67484. var BABYLON;
  67485. (function (BABYLON) {
  67486. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  67487. __extends(SSAO2RenderingPipeline, _super);
  67488. /**
  67489. * @constructor
  67490. * @param {string} name - The rendering pipeline name
  67491. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67492. * @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 }
  67493. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67494. */
  67495. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  67496. var _this = _super.call(this, scene.getEngine(), name) || this;
  67497. // Members
  67498. /**
  67499. * The PassPostProcess id in the pipeline that contains the original scene color
  67500. * @type {string}
  67501. */
  67502. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67503. /**
  67504. * The SSAO PostProcess id in the pipeline
  67505. * @type {string}
  67506. */
  67507. _this.SSAORenderEffect = "SSAORenderEffect";
  67508. /**
  67509. * The horizontal blur PostProcess id in the pipeline
  67510. * @type {string}
  67511. */
  67512. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67513. /**
  67514. * The vertical blur PostProcess id in the pipeline
  67515. * @type {string}
  67516. */
  67517. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67518. /**
  67519. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67520. * @type {string}
  67521. */
  67522. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67523. /**
  67524. * The output strength of the SSAO post-process. Default value is 1.0.
  67525. * @type {number}
  67526. */
  67527. _this.totalStrength = 1.0;
  67528. /**
  67529. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  67530. * @type {number}
  67531. */
  67532. _this.maxZ = 100.0;
  67533. /**
  67534. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  67535. * @type {number}
  67536. */
  67537. _this.minZAspect = 0.2;
  67538. /**
  67539. * Number of samples used for the SSAO calculations. Default value is 8
  67540. * @type {number}
  67541. */
  67542. _this._samples = 8;
  67543. /**
  67544. * Are we using bilateral blur ?
  67545. * @type {boolean}
  67546. */
  67547. _this._expensiveBlur = true;
  67548. /**
  67549. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  67550. * @type {number}
  67551. */
  67552. _this.radius = 2.0;
  67553. /**
  67554. * The base color of the SSAO post-process
  67555. * The final result is "base + ssao" between [0, 1]
  67556. * @type {number}
  67557. */
  67558. _this.base = 0.1;
  67559. _this._firstUpdate = true;
  67560. _this._scene = scene;
  67561. if (!_this.isSupported) {
  67562. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  67563. return _this;
  67564. }
  67565. var ssaoRatio = ratio.ssaoRatio || ratio;
  67566. var blurRatio = ratio.blurRatio || ratio;
  67567. // Set up assets
  67568. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  67569. _this._createRandomTexture();
  67570. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  67571. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  67572. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67573. _this._createSSAOPostProcess(1.0);
  67574. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  67575. _this._createSSAOCombinePostProcess(blurRatio);
  67576. // Set up pipeline
  67577. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67578. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67579. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67580. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67581. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67582. // Finish
  67583. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67584. if (cameras)
  67585. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67586. return _this;
  67587. }
  67588. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  67589. get: function () {
  67590. return this._samples;
  67591. },
  67592. set: function (n) {
  67593. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  67594. this._samples = n;
  67595. this._sampleSphere = this._generateHemisphere();
  67596. this._firstUpdate = true;
  67597. },
  67598. enumerable: true,
  67599. configurable: true
  67600. });
  67601. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  67602. get: function () {
  67603. return this._expensiveBlur;
  67604. },
  67605. set: function (b) {
  67606. 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"]);
  67607. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  67608. this._expensiveBlur = b;
  67609. this._firstUpdate = true;
  67610. },
  67611. enumerable: true,
  67612. configurable: true
  67613. });
  67614. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  67615. /**
  67616. * Support test.
  67617. * @type {boolean}
  67618. */
  67619. get: function () {
  67620. var engine = BABYLON.Engine.LastCreatedEngine;
  67621. if (!engine) {
  67622. return false;
  67623. }
  67624. return engine.getCaps().drawBuffersExtension;
  67625. },
  67626. enumerable: true,
  67627. configurable: true
  67628. });
  67629. // Public Methods
  67630. /**
  67631. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67632. */
  67633. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  67634. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  67635. for (var i = 0; i < this._scene.cameras.length; i++) {
  67636. var camera = this._scene.cameras[i];
  67637. this._originalColorPostProcess.dispose(camera);
  67638. this._ssaoPostProcess.dispose(camera);
  67639. this._blurHPostProcess.dispose(camera);
  67640. this._blurVPostProcess.dispose(camera);
  67641. this._ssaoCombinePostProcess.dispose(camera);
  67642. }
  67643. this._randomTexture.dispose();
  67644. if (disableGeometryBufferRenderer)
  67645. this._scene.disableGeometryBufferRenderer();
  67646. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67647. _super.prototype.dispose.call(this);
  67648. };
  67649. // Private Methods
  67650. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  67651. var _this = this;
  67652. this._samplerOffsets = [];
  67653. var expensive = this.expensiveBlur;
  67654. for (var i = -8; i < 8; i++) {
  67655. this._samplerOffsets.push(i * 2 + 0.5);
  67656. }
  67657. 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");
  67658. this._blurHPostProcess.onApply = function (effect) {
  67659. if (!_this._scene.activeCamera) {
  67660. return;
  67661. }
  67662. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  67663. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67664. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67665. effect.setFloat("radius", _this.radius);
  67666. effect.setTexture("depthSampler", _this._depthTexture);
  67667. if (_this._firstUpdate) {
  67668. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67669. }
  67670. };
  67671. 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");
  67672. this._blurVPostProcess.onApply = function (effect) {
  67673. if (!_this._scene.activeCamera) {
  67674. return;
  67675. }
  67676. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  67677. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67678. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67679. effect.setFloat("radius", _this.radius);
  67680. effect.setTexture("depthSampler", _this._depthTexture);
  67681. if (_this._firstUpdate) {
  67682. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67683. _this._firstUpdate = false;
  67684. }
  67685. };
  67686. };
  67687. SSAO2RenderingPipeline.prototype._rebuild = function () {
  67688. this._firstUpdate = true;
  67689. _super.prototype._rebuild.call(this);
  67690. };
  67691. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  67692. var numSamples = this.samples;
  67693. var result = [];
  67694. var vector, scale;
  67695. var rand = function (min, max) {
  67696. return Math.random() * (max - min) + min;
  67697. };
  67698. var i = 0;
  67699. while (i < numSamples) {
  67700. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  67701. vector.normalize();
  67702. scale = i / numSamples;
  67703. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  67704. vector.scaleInPlace(scale);
  67705. result.push(vector.x, vector.y, vector.z);
  67706. i++;
  67707. }
  67708. return result;
  67709. };
  67710. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67711. var _this = this;
  67712. var numSamples = this.samples;
  67713. this._sampleSphere = this._generateHemisphere();
  67714. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  67715. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67716. "base", "range", "projection", "near", "far", "texelSize",
  67717. "xViewport", "yViewport", "maxZ", "minZAspect"
  67718. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67719. this._ssaoPostProcess.onApply = function (effect) {
  67720. if (_this._firstUpdate) {
  67721. effect.setArray3("sampleSphere", _this._sampleSphere);
  67722. effect.setFloat("randTextureTiles", 4.0);
  67723. }
  67724. if (!_this._scene.activeCamera) {
  67725. return;
  67726. }
  67727. effect.setFloat("samplesFactor", 1 / _this.samples);
  67728. effect.setFloat("totalStrength", _this.totalStrength);
  67729. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  67730. effect.setFloat("radius", _this.radius);
  67731. effect.setFloat("maxZ", _this.maxZ);
  67732. effect.setFloat("minZAspect", _this.minZAspect);
  67733. effect.setFloat("base", _this.base);
  67734. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67735. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67736. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  67737. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  67738. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  67739. effect.setTexture("textureSampler", _this._depthTexture);
  67740. effect.setTexture("normalSampler", _this._normalTexture);
  67741. effect.setTexture("randomSampler", _this._randomTexture);
  67742. };
  67743. };
  67744. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67745. var _this = this;
  67746. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67747. this._ssaoCombinePostProcess.onApply = function (effect) {
  67748. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67749. };
  67750. };
  67751. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  67752. var size = 512;
  67753. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67754. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67755. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67756. var context = this._randomTexture.getContext();
  67757. var rand = function (min, max) {
  67758. return Math.random() * (max - min) + min;
  67759. };
  67760. var randVector = BABYLON.Vector3.Zero();
  67761. for (var x = 0; x < size; x++) {
  67762. for (var y = 0; y < size; y++) {
  67763. randVector.x = rand(0.0, 1.0);
  67764. randVector.y = rand(0.0, 1.0);
  67765. randVector.z = 0.0;
  67766. randVector.normalize();
  67767. randVector.scaleInPlace(255);
  67768. randVector.x = Math.floor(randVector.x);
  67769. randVector.y = Math.floor(randVector.y);
  67770. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67771. context.fillRect(x, y, 1, 1);
  67772. }
  67773. }
  67774. this._randomTexture.update(false);
  67775. };
  67776. __decorate([
  67777. BABYLON.serialize()
  67778. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  67779. __decorate([
  67780. BABYLON.serialize()
  67781. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  67782. __decorate([
  67783. BABYLON.serialize()
  67784. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  67785. __decorate([
  67786. BABYLON.serialize("samples")
  67787. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  67788. __decorate([
  67789. BABYLON.serialize("expensiveBlur")
  67790. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  67791. __decorate([
  67792. BABYLON.serialize()
  67793. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  67794. __decorate([
  67795. BABYLON.serialize()
  67796. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  67797. return SSAO2RenderingPipeline;
  67798. }(BABYLON.PostProcessRenderPipeline));
  67799. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  67800. })(BABYLON || (BABYLON = {}));
  67801. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  67802. "use strict";
  67803. // BABYLON.JS Chromatic Aberration GLSL Shader
  67804. // Author: Olivier Guyot
  67805. // Separates very slightly R, G and B colors on the edges of the screen
  67806. // Inspired by Francois Tarlier & Martins Upitis
  67807. var BABYLON;
  67808. (function (BABYLON) {
  67809. var LensRenderingPipeline = /** @class */ (function (_super) {
  67810. __extends(LensRenderingPipeline, _super);
  67811. /**
  67812. * @constructor
  67813. *
  67814. * Effect parameters are as follow:
  67815. * {
  67816. * chromatic_aberration: number; // from 0 to x (1 for realism)
  67817. * edge_blur: number; // from 0 to x (1 for realism)
  67818. * distortion: number; // from 0 to x (1 for realism)
  67819. * grain_amount: number; // from 0 to 1
  67820. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  67821. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  67822. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  67823. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  67824. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  67825. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  67826. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  67827. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  67828. * }
  67829. * Note: if an effect parameter is unset, effect is disabled
  67830. *
  67831. * @param {string} name - The rendering pipeline name
  67832. * @param {object} parameters - An object containing all parameters (see above)
  67833. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67834. * @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)
  67835. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67836. */
  67837. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  67838. if (ratio === void 0) { ratio = 1.0; }
  67839. var _this = _super.call(this, scene.getEngine(), name) || this;
  67840. // Lens effects can be of the following:
  67841. // - chromatic aberration (slight shift of RGB colors)
  67842. // - blur on the edge of the lens
  67843. // - lens distortion
  67844. // - depth-of-field blur & highlights enhancing
  67845. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  67846. // - grain effect (noise or custom texture)
  67847. // Two additional texture samplers are needed:
  67848. // - depth map (for depth-of-field)
  67849. // - grain texture
  67850. /**
  67851. * The chromatic aberration PostProcess id in the pipeline
  67852. * @type {string}
  67853. */
  67854. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  67855. /**
  67856. * The highlights enhancing PostProcess id in the pipeline
  67857. * @type {string}
  67858. */
  67859. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  67860. /**
  67861. * The depth-of-field PostProcess id in the pipeline
  67862. * @type {string}
  67863. */
  67864. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  67865. _this._scene = scene;
  67866. // Fetch texture samplers
  67867. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67868. if (parameters.grain_texture) {
  67869. _this._grainTexture = parameters.grain_texture;
  67870. }
  67871. else {
  67872. _this._createGrainTexture();
  67873. }
  67874. // save parameters
  67875. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  67876. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  67877. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  67878. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  67879. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  67880. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  67881. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  67882. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  67883. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  67884. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  67885. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  67886. // Create effects
  67887. _this._createChromaticAberrationPostProcess(ratio);
  67888. _this._createHighlightsPostProcess(ratio);
  67889. _this._createDepthOfFieldPostProcess(ratio / 4);
  67890. // Set up pipeline
  67891. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  67892. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  67893. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  67894. if (_this._highlightsGain === -1) {
  67895. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  67896. }
  67897. // Finish
  67898. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67899. if (cameras) {
  67900. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67901. }
  67902. return _this;
  67903. }
  67904. // public methods (self explanatory)
  67905. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  67906. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  67907. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  67908. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  67909. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  67910. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  67911. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  67912. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  67913. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  67914. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  67915. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  67916. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  67917. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  67918. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  67919. };
  67920. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  67921. this._highlightsPostProcess.updateEffect();
  67922. };
  67923. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  67924. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  67925. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  67926. this._highlightsGain = amount;
  67927. };
  67928. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  67929. if (this._highlightsGain === -1) {
  67930. this._highlightsGain = 1.0;
  67931. }
  67932. this._highlightsThreshold = amount;
  67933. };
  67934. LensRenderingPipeline.prototype.disableHighlights = function () {
  67935. this._highlightsGain = -1;
  67936. };
  67937. /**
  67938. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  67939. */
  67940. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67941. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67942. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67943. this._chromaticAberrationPostProcess = null;
  67944. this._highlightsPostProcess = null;
  67945. this._depthOfFieldPostProcess = null;
  67946. this._grainTexture.dispose();
  67947. if (disableDepthRender)
  67948. this._scene.disableDepthRenderer();
  67949. };
  67950. // colors shifting and distortion
  67951. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  67952. var _this = this;
  67953. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  67954. [], // samplers
  67955. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67956. this._chromaticAberrationPostProcess.onApply = function (effect) {
  67957. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  67958. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67959. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67960. effect.setFloat('radialIntensity', 1);
  67961. effect.setFloat2('direction', 17, 17);
  67962. effect.setFloat2('centerPosition', 0.5, 0.5);
  67963. };
  67964. };
  67965. // highlights enhancing
  67966. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  67967. var _this = this;
  67968. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  67969. [], // samplers
  67970. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  67971. this._highlightsPostProcess.onApply = function (effect) {
  67972. effect.setFloat('gain', _this._highlightsGain);
  67973. effect.setFloat('threshold', _this._highlightsThreshold);
  67974. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  67975. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67976. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67977. };
  67978. };
  67979. // colors shifting and distortion
  67980. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  67981. var _this = this;
  67982. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  67983. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  67984. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  67985. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67986. this._depthOfFieldPostProcess.onApply = function (effect) {
  67987. effect.setTexture("depthSampler", _this._depthTexture);
  67988. effect.setTexture("grainSampler", _this._grainTexture);
  67989. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  67990. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  67991. effect.setFloat('grain_amount', _this._grainAmount);
  67992. effect.setBool('blur_noise', _this._blurNoise);
  67993. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67994. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67995. effect.setFloat('distortion', _this._distortion);
  67996. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  67997. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  67998. effect.setFloat('aperture', _this._dofAperture);
  67999. effect.setFloat('darken', _this._dofDarken);
  68000. effect.setFloat('edge_blur', _this._edgeBlur);
  68001. effect.setBool('highlights', (_this._highlightsGain !== -1));
  68002. if (_this._scene.activeCamera) {
  68003. effect.setFloat('near', _this._scene.activeCamera.minZ);
  68004. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  68005. }
  68006. };
  68007. };
  68008. // creates a black and white random noise texture, 512x512
  68009. LensRenderingPipeline.prototype._createGrainTexture = function () {
  68010. var size = 512;
  68011. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68012. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68013. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68014. var context = this._grainTexture.getContext();
  68015. var rand = function (min, max) {
  68016. return Math.random() * (max - min) + min;
  68017. };
  68018. var value;
  68019. for (var x = 0; x < size; x++) {
  68020. for (var y = 0; y < size; y++) {
  68021. value = Math.floor(rand(0.42, 0.58) * 255);
  68022. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  68023. context.fillRect(x, y, 1, 1);
  68024. }
  68025. }
  68026. this._grainTexture.update(false);
  68027. };
  68028. return LensRenderingPipeline;
  68029. }(BABYLON.PostProcessRenderPipeline));
  68030. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  68031. })(BABYLON || (BABYLON = {}));
  68032. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  68033. "use strict";
  68034. var BABYLON;
  68035. (function (BABYLON) {
  68036. var StandardRenderingPipeline = /** @class */ (function (_super) {
  68037. __extends(StandardRenderingPipeline, _super);
  68038. /**
  68039. * @constructor
  68040. * @param {string} name - The rendering pipeline name
  68041. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68042. * @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)
  68043. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  68044. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68045. */
  68046. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  68047. if (originalPostProcess === void 0) { originalPostProcess = null; }
  68048. var _this = _super.call(this, scene.getEngine(), name) || this;
  68049. _this.downSampleX4PostProcess = null;
  68050. _this.brightPassPostProcess = null;
  68051. _this.blurHPostProcesses = [];
  68052. _this.blurVPostProcesses = [];
  68053. _this.textureAdderPostProcess = null;
  68054. _this.volumetricLightPostProcess = null;
  68055. _this.volumetricLightSmoothXPostProcess = null;
  68056. _this.volumetricLightSmoothYPostProcess = null;
  68057. _this.volumetricLightMergePostProces = null;
  68058. _this.volumetricLightFinalPostProcess = null;
  68059. _this.luminancePostProcess = null;
  68060. _this.luminanceDownSamplePostProcesses = [];
  68061. _this.hdrPostProcess = null;
  68062. _this.textureAdderFinalPostProcess = null;
  68063. _this.lensFlareFinalPostProcess = null;
  68064. _this.hdrFinalPostProcess = null;
  68065. _this.lensFlarePostProcess = null;
  68066. _this.lensFlareComposePostProcess = null;
  68067. _this.motionBlurPostProcess = null;
  68068. _this.depthOfFieldPostProcess = null;
  68069. // Values
  68070. _this.brightThreshold = 1.0;
  68071. _this.blurWidth = 512.0;
  68072. _this.horizontalBlur = false;
  68073. _this.exposure = 1.0;
  68074. _this.lensTexture = null;
  68075. _this.volumetricLightCoefficient = 0.2;
  68076. _this.volumetricLightPower = 4.0;
  68077. _this.volumetricLightBlurScale = 64.0;
  68078. _this.sourceLight = null;
  68079. _this.hdrMinimumLuminance = 1.0;
  68080. _this.hdrDecreaseRate = 0.5;
  68081. _this.hdrIncreaseRate = 0.5;
  68082. _this.lensColorTexture = null;
  68083. _this.lensFlareStrength = 20.0;
  68084. _this.lensFlareGhostDispersal = 1.4;
  68085. _this.lensFlareHaloWidth = 0.7;
  68086. _this.lensFlareDistortionStrength = 16.0;
  68087. _this.lensStarTexture = null;
  68088. _this.lensFlareDirtTexture = null;
  68089. _this.depthOfFieldDistance = 10.0;
  68090. _this.depthOfFieldBlurWidth = 64.0;
  68091. _this.motionStrength = 1.0;
  68092. // IAnimatable
  68093. _this.animations = [];
  68094. _this._currentDepthOfFieldSource = null;
  68095. _this._hdrCurrentLuminance = 1.0;
  68096. // Getters and setters
  68097. _this._bloomEnabled = true;
  68098. _this._depthOfFieldEnabled = false;
  68099. _this._vlsEnabled = false;
  68100. _this._lensFlareEnabled = false;
  68101. _this._hdrEnabled = false;
  68102. _this._motionBlurEnabled = false;
  68103. _this._motionBlurSamples = 64.0;
  68104. _this._volumetricLightStepsCount = 50.0;
  68105. _this._cameras = cameras || [];
  68106. // Initialize
  68107. _this._scene = scene;
  68108. _this._basePostProcess = originalPostProcess;
  68109. _this._ratio = ratio;
  68110. // Misc
  68111. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68112. // Finish
  68113. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68114. _this._buildPipeline();
  68115. return _this;
  68116. }
  68117. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  68118. get: function () {
  68119. return this._bloomEnabled;
  68120. },
  68121. set: function (enabled) {
  68122. if (this._bloomEnabled === enabled) {
  68123. return;
  68124. }
  68125. this._bloomEnabled = enabled;
  68126. this._buildPipeline();
  68127. },
  68128. enumerable: true,
  68129. configurable: true
  68130. });
  68131. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  68132. get: function () {
  68133. return this._depthOfFieldEnabled;
  68134. },
  68135. set: function (enabled) {
  68136. if (this._depthOfFieldEnabled === enabled) {
  68137. return;
  68138. }
  68139. this._depthOfFieldEnabled = enabled;
  68140. this._buildPipeline();
  68141. },
  68142. enumerable: true,
  68143. configurable: true
  68144. });
  68145. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  68146. get: function () {
  68147. return this._lensFlareEnabled;
  68148. },
  68149. set: function (enabled) {
  68150. if (this._lensFlareEnabled === enabled) {
  68151. return;
  68152. }
  68153. this._lensFlareEnabled = enabled;
  68154. this._buildPipeline();
  68155. },
  68156. enumerable: true,
  68157. configurable: true
  68158. });
  68159. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  68160. get: function () {
  68161. return this._hdrEnabled;
  68162. },
  68163. set: function (enabled) {
  68164. if (this._hdrEnabled === enabled) {
  68165. return;
  68166. }
  68167. this._hdrEnabled = enabled;
  68168. this._buildPipeline();
  68169. },
  68170. enumerable: true,
  68171. configurable: true
  68172. });
  68173. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  68174. get: function () {
  68175. return this._vlsEnabled;
  68176. },
  68177. set: function (enabled) {
  68178. if (this._vlsEnabled === enabled) {
  68179. return;
  68180. }
  68181. if (enabled) {
  68182. var geometry = this._scene.enableGeometryBufferRenderer();
  68183. if (!geometry) {
  68184. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  68185. return;
  68186. }
  68187. }
  68188. this._vlsEnabled = enabled;
  68189. this._buildPipeline();
  68190. },
  68191. enumerable: true,
  68192. configurable: true
  68193. });
  68194. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  68195. get: function () {
  68196. return this._motionBlurEnabled;
  68197. },
  68198. set: function (enabled) {
  68199. if (this._motionBlurEnabled === enabled) {
  68200. return;
  68201. }
  68202. this._motionBlurEnabled = enabled;
  68203. this._buildPipeline();
  68204. },
  68205. enumerable: true,
  68206. configurable: true
  68207. });
  68208. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  68209. get: function () {
  68210. return this._volumetricLightStepsCount;
  68211. },
  68212. set: function (count) {
  68213. if (this.volumetricLightPostProcess) {
  68214. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  68215. }
  68216. this._volumetricLightStepsCount = count;
  68217. },
  68218. enumerable: true,
  68219. configurable: true
  68220. });
  68221. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  68222. get: function () {
  68223. return this._motionBlurSamples;
  68224. },
  68225. set: function (samples) {
  68226. if (this.motionBlurPostProcess) {
  68227. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  68228. }
  68229. this._motionBlurSamples = samples;
  68230. },
  68231. enumerable: true,
  68232. configurable: true
  68233. });
  68234. StandardRenderingPipeline.prototype._buildPipeline = function () {
  68235. var _this = this;
  68236. var ratio = this._ratio;
  68237. var scene = this._scene;
  68238. this._disposePostProcesses();
  68239. this._reset();
  68240. // Create pass post-process
  68241. if (!this._basePostProcess) {
  68242. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  68243. this.originalPostProcess.onApply = function (effect) {
  68244. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  68245. };
  68246. }
  68247. else {
  68248. this.originalPostProcess = this._basePostProcess;
  68249. }
  68250. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  68251. this._currentDepthOfFieldSource = this.originalPostProcess;
  68252. if (this._vlsEnabled) {
  68253. // Create volumetric light
  68254. this._createVolumetricLightPostProcess(scene, ratio);
  68255. // Create volumetric light final post-process
  68256. 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);
  68257. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  68258. }
  68259. if (this._bloomEnabled) {
  68260. // Create down sample X4 post-process
  68261. this._createDownSampleX4PostProcess(scene, ratio / 2);
  68262. // Create bright pass post-process
  68263. this._createBrightPassPostProcess(scene, ratio / 2);
  68264. // Create gaussian blur post-processes (down sampling blurs)
  68265. this._createBlurPostProcesses(scene, ratio / 4, 1);
  68266. // Create texture adder post-process
  68267. this._createTextureAdderPostProcess(scene, ratio);
  68268. // Create depth-of-field source post-process
  68269. 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);
  68270. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  68271. }
  68272. if (this._lensFlareEnabled) {
  68273. // Create lens flare post-process
  68274. this._createLensFlarePostProcess(scene, ratio);
  68275. // Create depth-of-field source post-process post lens-flare and disable it now
  68276. 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);
  68277. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  68278. }
  68279. if (this._hdrEnabled) {
  68280. // Create luminance
  68281. this._createLuminancePostProcesses(scene, this._floatTextureType);
  68282. // Create HDR
  68283. this._createHdrPostProcess(scene, ratio);
  68284. // Create depth-of-field source post-process post hdr and disable it now
  68285. 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);
  68286. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  68287. }
  68288. if (this._depthOfFieldEnabled) {
  68289. // Create gaussian blur used by depth-of-field
  68290. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  68291. // Create depth-of-field post-process
  68292. this._createDepthOfFieldPostProcess(scene, ratio);
  68293. }
  68294. if (this._motionBlurEnabled) {
  68295. // Create motion blur post-process
  68296. this._createMotionBlurPostProcess(scene, ratio);
  68297. }
  68298. if (this._cameras !== null) {
  68299. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68300. }
  68301. };
  68302. // Down Sample X4 Post-Processs
  68303. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  68304. var _this = this;
  68305. var downSampleX4Offsets = new Array(32);
  68306. 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);
  68307. this.downSampleX4PostProcess.onApply = function (effect) {
  68308. var id = 0;
  68309. var width = _this.downSampleX4PostProcess.width;
  68310. var height = _this.downSampleX4PostProcess.height;
  68311. for (var i = -2; i < 2; i++) {
  68312. for (var j = -2; j < 2; j++) {
  68313. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  68314. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  68315. id += 2;
  68316. }
  68317. }
  68318. effect.setArray2("dsOffsets", downSampleX4Offsets);
  68319. };
  68320. // Add to pipeline
  68321. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  68322. };
  68323. // Brightpass Post-Process
  68324. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  68325. var _this = this;
  68326. var brightOffsets = new Array(8);
  68327. 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);
  68328. this.brightPassPostProcess.onApply = function (effect) {
  68329. var sU = (1.0 / _this.brightPassPostProcess.width);
  68330. var sV = (1.0 / _this.brightPassPostProcess.height);
  68331. brightOffsets[0] = -0.5 * sU;
  68332. brightOffsets[1] = 0.5 * sV;
  68333. brightOffsets[2] = 0.5 * sU;
  68334. brightOffsets[3] = 0.5 * sV;
  68335. brightOffsets[4] = -0.5 * sU;
  68336. brightOffsets[5] = -0.5 * sV;
  68337. brightOffsets[6] = 0.5 * sU;
  68338. brightOffsets[7] = -0.5 * sV;
  68339. effect.setArray2("dsOffsets", brightOffsets);
  68340. effect.setFloat("brightThreshold", _this.brightThreshold);
  68341. };
  68342. // Add to pipeline
  68343. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  68344. };
  68345. // Create blur H&V post-processes
  68346. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  68347. var _this = this;
  68348. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  68349. var engine = scene.getEngine();
  68350. 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);
  68351. 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);
  68352. blurX.onActivateObservable.add(function () {
  68353. var dw = blurX.width / engine.getRenderWidth();
  68354. blurX.kernel = _this[blurWidthKey] * dw;
  68355. });
  68356. blurY.onActivateObservable.add(function () {
  68357. var dw = blurY.height / engine.getRenderHeight();
  68358. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  68359. });
  68360. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  68361. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  68362. this.blurHPostProcesses.push(blurX);
  68363. this.blurVPostProcesses.push(blurY);
  68364. };
  68365. // Create texture adder post-process
  68366. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  68367. var _this = this;
  68368. 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);
  68369. this.textureAdderPostProcess.onApply = function (effect) {
  68370. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  68371. effect.setTexture("lensSampler", _this.lensTexture);
  68372. effect.setFloat("exposure", _this.exposure);
  68373. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  68374. };
  68375. // Add to pipeline
  68376. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  68377. };
  68378. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  68379. var _this = this;
  68380. var geometryRenderer = scene.enableGeometryBufferRenderer();
  68381. geometryRenderer.enablePosition = true;
  68382. var geometry = geometryRenderer.getGBuffer();
  68383. // Base post-process
  68384. 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));
  68385. var depthValues = BABYLON.Vector2.Zero();
  68386. this.volumetricLightPostProcess.onApply = function (effect) {
  68387. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  68388. var generator = _this.sourceLight.getShadowGenerator();
  68389. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  68390. effect.setTexture("positionSampler", geometry.textures[2]);
  68391. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  68392. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  68393. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  68394. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  68395. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  68396. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  68397. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  68398. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  68399. effect.setVector2("depthValues", depthValues);
  68400. }
  68401. };
  68402. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  68403. // Smooth
  68404. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  68405. // Merge
  68406. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  68407. this.volumetricLightMergePostProces.onApply = function (effect) {
  68408. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  68409. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  68410. };
  68411. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  68412. };
  68413. // Create luminance
  68414. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  68415. var _this = this;
  68416. // Create luminance
  68417. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  68418. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  68419. var offsets = [];
  68420. this.luminancePostProcess.onApply = function (effect) {
  68421. var sU = (1.0 / _this.luminancePostProcess.width);
  68422. var sV = (1.0 / _this.luminancePostProcess.height);
  68423. offsets[0] = -0.5 * sU;
  68424. offsets[1] = 0.5 * sV;
  68425. offsets[2] = 0.5 * sU;
  68426. offsets[3] = 0.5 * sV;
  68427. offsets[4] = -0.5 * sU;
  68428. offsets[5] = -0.5 * sV;
  68429. offsets[6] = 0.5 * sU;
  68430. offsets[7] = -0.5 * sV;
  68431. effect.setArray2("lumOffsets", offsets);
  68432. };
  68433. // Add to pipeline
  68434. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  68435. // Create down sample luminance
  68436. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  68437. var size = Math.pow(3, i);
  68438. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  68439. if (i === 0) {
  68440. defines += "#define FINAL_DOWN_SAMPLER";
  68441. }
  68442. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  68443. this.luminanceDownSamplePostProcesses.push(postProcess);
  68444. }
  68445. // Create callbacks and add effects
  68446. var lastLuminance = this.luminancePostProcess;
  68447. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  68448. var downSampleOffsets = new Array(18);
  68449. pp.onApply = function (effect) {
  68450. if (!lastLuminance) {
  68451. return;
  68452. }
  68453. var id = 0;
  68454. for (var x = -1; x < 2; x++) {
  68455. for (var y = -1; y < 2; y++) {
  68456. downSampleOffsets[id] = x / lastLuminance.width;
  68457. downSampleOffsets[id + 1] = y / lastLuminance.height;
  68458. id += 2;
  68459. }
  68460. }
  68461. effect.setArray2("dsOffsets", downSampleOffsets);
  68462. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  68463. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68464. lastLuminance = _this.luminancePostProcess;
  68465. }
  68466. else {
  68467. lastLuminance = pp;
  68468. }
  68469. };
  68470. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68471. pp.onAfterRender = function (effect) {
  68472. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  68473. 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);
  68474. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  68475. };
  68476. }
  68477. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  68478. });
  68479. };
  68480. // Create HDR post-process
  68481. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  68482. var _this = this;
  68483. 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);
  68484. var outputLiminance = 1;
  68485. var time = 0;
  68486. var lastTime = 0;
  68487. this.hdrPostProcess.onApply = function (effect) {
  68488. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  68489. time += scene.getEngine().getDeltaTime();
  68490. if (outputLiminance < 0) {
  68491. outputLiminance = _this._hdrCurrentLuminance;
  68492. }
  68493. else {
  68494. var dt = (lastTime - time) / 1000.0;
  68495. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  68496. outputLiminance += _this.hdrDecreaseRate * dt;
  68497. }
  68498. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  68499. outputLiminance -= _this.hdrIncreaseRate * dt;
  68500. }
  68501. else {
  68502. outputLiminance = _this._hdrCurrentLuminance;
  68503. }
  68504. }
  68505. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  68506. effect.setFloat("averageLuminance", outputLiminance);
  68507. lastTime = time;
  68508. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  68509. };
  68510. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  68511. };
  68512. // Create lens flare post-process
  68513. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  68514. var _this = this;
  68515. 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);
  68516. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  68517. this._createBlurPostProcesses(scene, ratio / 4, 2);
  68518. 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);
  68519. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  68520. var resolution = new BABYLON.Vector2(0, 0);
  68521. // Lens flare
  68522. this.lensFlarePostProcess.onApply = function (effect) {
  68523. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  68524. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  68525. effect.setFloat("strength", _this.lensFlareStrength);
  68526. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  68527. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  68528. // Shift
  68529. resolution.x = _this.lensFlarePostProcess.width;
  68530. resolution.y = _this.lensFlarePostProcess.height;
  68531. effect.setVector2("resolution", resolution);
  68532. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  68533. };
  68534. // Compose
  68535. 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);
  68536. 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);
  68537. this.lensFlareComposePostProcess.onApply = function (effect) {
  68538. if (!_this._scene.activeCamera) {
  68539. return;
  68540. }
  68541. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68542. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  68543. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  68544. // Lens start rotation matrix
  68545. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  68546. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  68547. 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));
  68548. camRot *= 4.0;
  68549. 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);
  68550. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  68551. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  68552. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  68553. };
  68554. };
  68555. // Create depth-of-field post-process
  68556. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  68557. var _this = this;
  68558. 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);
  68559. this.depthOfFieldPostProcess.onApply = function (effect) {
  68560. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68561. effect.setTexture("depthSampler", _this._getDepthTexture());
  68562. effect.setFloat("distance", _this.depthOfFieldDistance);
  68563. };
  68564. // Add to pipeline
  68565. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  68566. };
  68567. // Create motion blur post-process
  68568. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  68569. var _this = this;
  68570. 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);
  68571. var motionScale = 0;
  68572. var prevViewProjection = BABYLON.Matrix.Identity();
  68573. var invViewProjection = BABYLON.Matrix.Identity();
  68574. var viewProjection = BABYLON.Matrix.Identity();
  68575. var screenSize = BABYLON.Vector2.Zero();
  68576. this.motionBlurPostProcess.onApply = function (effect) {
  68577. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  68578. viewProjection.invertToRef(invViewProjection);
  68579. effect.setMatrix("inverseViewProjection", invViewProjection);
  68580. effect.setMatrix("prevViewProjection", prevViewProjection);
  68581. prevViewProjection = viewProjection;
  68582. screenSize.x = _this.motionBlurPostProcess.width;
  68583. screenSize.y = _this.motionBlurPostProcess.height;
  68584. effect.setVector2("screenSize", screenSize);
  68585. motionScale = scene.getEngine().getFps() / 60.0;
  68586. effect.setFloat("motionScale", motionScale);
  68587. effect.setFloat("motionStrength", _this.motionStrength);
  68588. effect.setTexture("depthSampler", _this._getDepthTexture());
  68589. };
  68590. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  68591. };
  68592. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  68593. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  68594. var renderer = this._scene.enableGeometryBufferRenderer();
  68595. return renderer.getGBuffer().textures[0];
  68596. }
  68597. return this._scene.enableDepthRenderer().getDepthMap();
  68598. };
  68599. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  68600. for (var i = 0; i < this._cameras.length; i++) {
  68601. var camera = this._cameras[i];
  68602. if (this.originalPostProcess) {
  68603. this.originalPostProcess.dispose(camera);
  68604. }
  68605. if (this.downSampleX4PostProcess) {
  68606. this.downSampleX4PostProcess.dispose(camera);
  68607. }
  68608. if (this.brightPassPostProcess) {
  68609. this.brightPassPostProcess.dispose(camera);
  68610. }
  68611. if (this.textureAdderPostProcess) {
  68612. this.textureAdderPostProcess.dispose(camera);
  68613. }
  68614. if (this.textureAdderFinalPostProcess) {
  68615. this.textureAdderFinalPostProcess.dispose(camera);
  68616. }
  68617. if (this.volumetricLightPostProcess) {
  68618. this.volumetricLightPostProcess.dispose(camera);
  68619. }
  68620. if (this.volumetricLightSmoothXPostProcess) {
  68621. this.volumetricLightSmoothXPostProcess.dispose(camera);
  68622. }
  68623. if (this.volumetricLightSmoothYPostProcess) {
  68624. this.volumetricLightSmoothYPostProcess.dispose(camera);
  68625. }
  68626. if (this.volumetricLightMergePostProces) {
  68627. this.volumetricLightMergePostProces.dispose(camera);
  68628. }
  68629. if (this.volumetricLightFinalPostProcess) {
  68630. this.volumetricLightFinalPostProcess.dispose(camera);
  68631. }
  68632. if (this.lensFlarePostProcess) {
  68633. this.lensFlarePostProcess.dispose(camera);
  68634. }
  68635. if (this.lensFlareComposePostProcess) {
  68636. this.lensFlareComposePostProcess.dispose(camera);
  68637. }
  68638. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  68639. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  68640. }
  68641. if (this.luminancePostProcess) {
  68642. this.luminancePostProcess.dispose(camera);
  68643. }
  68644. if (this.hdrPostProcess) {
  68645. this.hdrPostProcess.dispose(camera);
  68646. }
  68647. if (this.hdrFinalPostProcess) {
  68648. this.hdrFinalPostProcess.dispose(camera);
  68649. }
  68650. if (this.depthOfFieldPostProcess) {
  68651. this.depthOfFieldPostProcess.dispose(camera);
  68652. }
  68653. if (this.motionBlurPostProcess) {
  68654. this.motionBlurPostProcess.dispose(camera);
  68655. }
  68656. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  68657. this.blurHPostProcesses[j].dispose(camera);
  68658. }
  68659. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  68660. this.blurVPostProcesses[j].dispose(camera);
  68661. }
  68662. }
  68663. this.originalPostProcess = null;
  68664. this.downSampleX4PostProcess = null;
  68665. this.brightPassPostProcess = null;
  68666. this.textureAdderPostProcess = null;
  68667. this.textureAdderFinalPostProcess = null;
  68668. this.volumetricLightPostProcess = null;
  68669. this.volumetricLightSmoothXPostProcess = null;
  68670. this.volumetricLightSmoothYPostProcess = null;
  68671. this.volumetricLightMergePostProces = null;
  68672. this.volumetricLightFinalPostProcess = null;
  68673. this.lensFlarePostProcess = null;
  68674. this.lensFlareComposePostProcess = null;
  68675. this.luminancePostProcess = null;
  68676. this.hdrPostProcess = null;
  68677. this.hdrFinalPostProcess = null;
  68678. this.depthOfFieldPostProcess = null;
  68679. this.motionBlurPostProcess = null;
  68680. this.luminanceDownSamplePostProcesses = [];
  68681. this.blurHPostProcesses = [];
  68682. this.blurVPostProcesses = [];
  68683. };
  68684. // Dispose
  68685. StandardRenderingPipeline.prototype.dispose = function () {
  68686. this._disposePostProcesses();
  68687. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68688. _super.prototype.dispose.call(this);
  68689. };
  68690. // Serialize rendering pipeline
  68691. StandardRenderingPipeline.prototype.serialize = function () {
  68692. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68693. serializationObject.customType = "StandardRenderingPipeline";
  68694. return serializationObject;
  68695. };
  68696. /**
  68697. * Static members
  68698. */
  68699. // Parse serialized pipeline
  68700. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68701. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  68702. };
  68703. // Luminance steps
  68704. StandardRenderingPipeline.LuminanceSteps = 6;
  68705. __decorate([
  68706. BABYLON.serialize()
  68707. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  68708. __decorate([
  68709. BABYLON.serialize()
  68710. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  68711. __decorate([
  68712. BABYLON.serialize()
  68713. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  68714. __decorate([
  68715. BABYLON.serialize()
  68716. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  68717. __decorate([
  68718. BABYLON.serializeAsTexture("lensTexture")
  68719. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  68720. __decorate([
  68721. BABYLON.serialize()
  68722. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  68723. __decorate([
  68724. BABYLON.serialize()
  68725. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  68726. __decorate([
  68727. BABYLON.serialize()
  68728. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  68729. __decorate([
  68730. BABYLON.serialize()
  68731. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  68732. __decorate([
  68733. BABYLON.serialize()
  68734. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  68735. __decorate([
  68736. BABYLON.serialize()
  68737. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  68738. __decorate([
  68739. BABYLON.serializeAsTexture("lensColorTexture")
  68740. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  68741. __decorate([
  68742. BABYLON.serialize()
  68743. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  68744. __decorate([
  68745. BABYLON.serialize()
  68746. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  68747. __decorate([
  68748. BABYLON.serialize()
  68749. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  68750. __decorate([
  68751. BABYLON.serialize()
  68752. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  68753. __decorate([
  68754. BABYLON.serializeAsTexture("lensStarTexture")
  68755. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  68756. __decorate([
  68757. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  68758. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  68759. __decorate([
  68760. BABYLON.serialize()
  68761. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  68762. __decorate([
  68763. BABYLON.serialize()
  68764. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  68765. __decorate([
  68766. BABYLON.serialize()
  68767. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  68768. __decorate([
  68769. BABYLON.serialize()
  68770. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  68771. __decorate([
  68772. BABYLON.serialize()
  68773. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  68774. __decorate([
  68775. BABYLON.serialize()
  68776. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  68777. __decorate([
  68778. BABYLON.serialize()
  68779. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  68780. __decorate([
  68781. BABYLON.serialize()
  68782. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  68783. __decorate([
  68784. BABYLON.serialize()
  68785. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  68786. __decorate([
  68787. BABYLON.serialize()
  68788. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  68789. __decorate([
  68790. BABYLON.serialize()
  68791. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  68792. __decorate([
  68793. BABYLON.serialize()
  68794. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  68795. return StandardRenderingPipeline;
  68796. }(BABYLON.PostProcessRenderPipeline));
  68797. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  68798. })(BABYLON || (BABYLON = {}));
  68799. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  68800. "use strict";
  68801. var BABYLON;
  68802. (function (BABYLON) {
  68803. var FxaaPostProcess = /** @class */ (function (_super) {
  68804. __extends(FxaaPostProcess, _super);
  68805. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68806. if (camera === void 0) { camera = null; }
  68807. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68808. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  68809. _this.onApplyObservable.add(function (effect) {
  68810. var texelSize = _this.texelSize;
  68811. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  68812. });
  68813. return _this;
  68814. }
  68815. return FxaaPostProcess;
  68816. }(BABYLON.PostProcess));
  68817. BABYLON.FxaaPostProcess = FxaaPostProcess;
  68818. })(BABYLON || (BABYLON = {}));
  68819. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  68820. "use strict";
  68821. var BABYLON;
  68822. (function (BABYLON) {
  68823. /**
  68824. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  68825. */
  68826. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  68827. __extends(ChromaticAberrationPostProcess, _super);
  68828. /**
  68829. * Creates a new instance of @see ChromaticAberrationPostProcess
  68830. * @param name The name of the effect.
  68831. * @param screenWidth The width of the screen to apply the effect on.
  68832. * @param screenHeight The height of the screen to apply the effect on.
  68833. * @param options The required width/height ratio to downsize to before computing the render pass.
  68834. * @param camera The camera to apply the render pass to.
  68835. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68836. * @param engine The engine which the post process will be applied. (default: current engine)
  68837. * @param reusable If the post process can be reused on the same frame. (default: false)
  68838. * @param textureType Type of textures used when performing the post process. (default: 0)
  68839. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68840. */
  68841. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68842. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68843. if (blockCompilation === void 0) { blockCompilation = false; }
  68844. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  68845. /**
  68846. * The amount of seperation of rgb channels (default: 30)
  68847. */
  68848. _this.aberrationAmount = 30;
  68849. /**
  68850. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  68851. */
  68852. _this.radialIntensity = 0;
  68853. /**
  68854. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  68855. */
  68856. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  68857. /**
  68858. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  68859. */
  68860. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  68861. _this.onApplyObservable.add(function (effect) {
  68862. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  68863. effect.setFloat('screen_width', screenWidth);
  68864. effect.setFloat('screen_height', screenHeight);
  68865. effect.setFloat('radialIntensity', _this.radialIntensity);
  68866. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  68867. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  68868. });
  68869. return _this;
  68870. }
  68871. return ChromaticAberrationPostProcess;
  68872. }(BABYLON.PostProcess));
  68873. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  68874. })(BABYLON || (BABYLON = {}));
  68875. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  68876. "use strict";
  68877. var BABYLON;
  68878. (function (BABYLON) {
  68879. /**
  68880. * The SharpenPostProcess applies a sharpen kernel to every pixel
  68881. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68882. */
  68883. var SharpenPostProcess = /** @class */ (function (_super) {
  68884. __extends(SharpenPostProcess, _super);
  68885. /**
  68886. * Creates a new instance of @see ConvolutionPostProcess
  68887. * @param name The name of the effect.
  68888. * @param options The required width/height ratio to downsize to before computing the render pass.
  68889. * @param camera The camera to apply the render pass to.
  68890. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68891. * @param engine The engine which the post process will be applied. (default: current engine)
  68892. * @param reusable If the post process can be reused on the same frame. (default: false)
  68893. * @param textureType Type of textures used when performing the post process. (default: 0)
  68894. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68895. */
  68896. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68897. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68898. if (blockCompilation === void 0) { blockCompilation = false; }
  68899. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  68900. /**
  68901. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  68902. */
  68903. _this.colorAmount = 1.0;
  68904. /**
  68905. * How much sharpness should be applied (default: 0.3)
  68906. */
  68907. _this.edgeAmount = 0.3;
  68908. _this.onApply = function (effect) {
  68909. effect.setFloat2("screenSize", _this.width, _this.height);
  68910. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  68911. };
  68912. return _this;
  68913. }
  68914. return SharpenPostProcess;
  68915. }(BABYLON.PostProcess));
  68916. BABYLON.SharpenPostProcess = SharpenPostProcess;
  68917. })(BABYLON || (BABYLON = {}));
  68918. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  68919. "use strict";
  68920. var BABYLON;
  68921. (function (BABYLON) {
  68922. /**
  68923. * The Blur Post Process which blurs an image based on a kernel and direction.
  68924. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68925. */
  68926. var BlurPostProcess = /** @class */ (function (_super) {
  68927. __extends(BlurPostProcess, _super);
  68928. /**
  68929. * Creates a new instance of @see BlurPostProcess
  68930. * @param name The name of the effect.
  68931. * @param direction The direction in which to blur the image.
  68932. * @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.
  68933. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68934. * @param camera The camera to apply the render pass to.
  68935. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68936. * @param engine The engine which the post process will be applied. (default: current engine)
  68937. * @param reusable If the post process can be reused on the same frame. (default: false)
  68938. * @param textureType Type of textures used when performing the post process. (default: 0)
  68939. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68940. */
  68941. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  68942. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68943. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68944. if (defines === void 0) { defines = ""; }
  68945. if (blockCompilation === void 0) { blockCompilation = false; }
  68946. 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;
  68947. _this.direction = direction;
  68948. _this.blockCompilation = blockCompilation;
  68949. _this._packedFloat = false;
  68950. _this._staticDefines = "";
  68951. _this._staticDefines = defines;
  68952. _this.onApplyObservable.add(function (effect) {
  68953. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68954. });
  68955. _this.kernel = kernel;
  68956. return _this;
  68957. }
  68958. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68959. /**
  68960. * Gets the length in pixels of the blur sample region
  68961. */
  68962. get: function () {
  68963. return this._idealKernel;
  68964. },
  68965. /**
  68966. * Sets the length in pixels of the blur sample region
  68967. */
  68968. set: function (v) {
  68969. if (this._idealKernel === v) {
  68970. return;
  68971. }
  68972. v = Math.max(v, 1);
  68973. this._idealKernel = v;
  68974. this._kernel = this._nearestBestKernel(v);
  68975. if (!this.blockCompilation) {
  68976. this._updateParameters();
  68977. }
  68978. },
  68979. enumerable: true,
  68980. configurable: true
  68981. });
  68982. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68983. /**
  68984. * Gets wether or not the blur is unpacking/repacking floats
  68985. */
  68986. get: function () {
  68987. return this._packedFloat;
  68988. },
  68989. /**
  68990. * Sets wether or not the blur needs to unpack/repack floats
  68991. */
  68992. set: function (v) {
  68993. if (this._packedFloat === v) {
  68994. return;
  68995. }
  68996. this._packedFloat = v;
  68997. if (!this.blockCompilation) {
  68998. this._updateParameters();
  68999. }
  69000. },
  69001. enumerable: true,
  69002. configurable: true
  69003. });
  69004. /**
  69005. * Updates the effect with the current post process compile time values and recompiles the shader.
  69006. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69007. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69008. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69009. * @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
  69010. * @param onCompiled Called when the shader has been compiled.
  69011. * @param onError Called if there is an error when compiling a shader.
  69012. */
  69013. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69014. if (defines === void 0) { defines = null; }
  69015. if (uniforms === void 0) { uniforms = null; }
  69016. if (samplers === void 0) { samplers = null; }
  69017. this._updateParameters(onCompiled, onError);
  69018. };
  69019. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  69020. // Generate sampling offsets and weights
  69021. var N = this._kernel;
  69022. var centerIndex = (N - 1) / 2;
  69023. // Generate Gaussian sampling weights over kernel
  69024. var offsets = [];
  69025. var weights = [];
  69026. var totalWeight = 0;
  69027. for (var i = 0; i < N; i++) {
  69028. var u = i / (N - 1);
  69029. var w = this._gaussianWeight(u * 2.0 - 1);
  69030. offsets[i] = (i - centerIndex);
  69031. weights[i] = w;
  69032. totalWeight += w;
  69033. }
  69034. // Normalize weights
  69035. for (var i = 0; i < weights.length; i++) {
  69036. weights[i] /= totalWeight;
  69037. }
  69038. // Optimize: combine samples to take advantage of hardware linear sampling
  69039. // Walk from left to center, combining pairs (symmetrically)
  69040. var linearSamplingWeights = [];
  69041. var linearSamplingOffsets = [];
  69042. var linearSamplingMap = [];
  69043. for (var i = 0; i <= centerIndex; i += 2) {
  69044. var j = Math.min(i + 1, Math.floor(centerIndex));
  69045. var singleCenterSample = i === j;
  69046. if (singleCenterSample) {
  69047. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69048. }
  69049. else {
  69050. var sharedCell = j === centerIndex;
  69051. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69052. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69053. if (offsetLinear === 0) {
  69054. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69055. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69056. }
  69057. else {
  69058. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69059. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69060. }
  69061. }
  69062. }
  69063. for (var i = 0; i < linearSamplingMap.length; i++) {
  69064. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69065. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69066. }
  69067. // Replace with optimized
  69068. offsets = linearSamplingOffsets;
  69069. weights = linearSamplingWeights;
  69070. // Generate shaders
  69071. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69072. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69073. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69074. var defines = "";
  69075. defines += this._staticDefines;
  69076. for (var i = 0; i < varyingCount; i++) {
  69077. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69078. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69079. }
  69080. var depCount = 0;
  69081. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69082. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69083. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69084. depCount++;
  69085. }
  69086. if (this.packedFloat) {
  69087. defines += "#define PACKEDFLOAT 1";
  69088. }
  69089. _super.prototype.updateEffect.call(this, defines, null, null, {
  69090. varyingCount: varyingCount,
  69091. depCount: depCount
  69092. }, onCompiled, onError);
  69093. };
  69094. /**
  69095. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69096. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69097. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69098. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69099. * The gaps between physical kernels are compensated for in the weighting of the samples
  69100. * @param idealKernel Ideal blur kernel.
  69101. * @return Nearest best kernel.
  69102. */
  69103. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69104. var v = Math.round(idealKernel);
  69105. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69106. var k = _a[_i];
  69107. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69108. return Math.max(k, 3);
  69109. }
  69110. }
  69111. return Math.max(v, 3);
  69112. };
  69113. /**
  69114. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69115. * @param x The point on the Gaussian distribution to sample.
  69116. * @return the value of the Gaussian function at x.
  69117. */
  69118. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69119. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69120. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69121. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69122. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69123. // truncated at around 1.3% of peak strength.
  69124. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69125. var sigma = (1 / 3);
  69126. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69127. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69128. var weight = (1.0 / denominator) * Math.exp(exponent);
  69129. return weight;
  69130. };
  69131. /**
  69132. * Generates a string that can be used as a floating point number in GLSL.
  69133. * @param x Value to print.
  69134. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69135. * @return GLSL float string.
  69136. */
  69137. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69138. if (decimalFigures === void 0) { decimalFigures = 8; }
  69139. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69140. };
  69141. return BlurPostProcess;
  69142. }(BABYLON.PostProcess));
  69143. BABYLON.BlurPostProcess = BlurPostProcess;
  69144. })(BABYLON || (BABYLON = {}));
  69145. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69146. "use strict";
  69147. var BABYLON;
  69148. (function (BABYLON) {
  69149. /**
  69150. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  69151. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  69152. * based on samples that have a large difference in distance than the center pixel.
  69153. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69154. */
  69155. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  69156. __extends(DepthOfFieldBlurPostProcess, _super);
  69157. /**
  69158. * Creates a new instance of @see CircleOfConfusionPostProcess
  69159. * @param name The name of the effect.
  69160. * @param scene The scene the effect belongs to.
  69161. * @param direction The direction the blur should be applied.
  69162. * @param kernel The size of the kernel used to blur.
  69163. * @param options The required width/height ratio to downsize to before computing the render pass.
  69164. * @param camera The camera to apply the render pass to.
  69165. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  69166. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  69167. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69168. * @param engine The engine which the post process will be applied. (default: current engine)
  69169. * @param reusable If the post process can be reused on the same frame. (default: false)
  69170. * @param textureType Type of textures used when performing the post process. (default: 0)
  69171. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69172. */
  69173. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  69174. if (imageToBlur === void 0) { imageToBlur = null; }
  69175. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69176. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69177. if (blockCompilation === void 0) { blockCompilation = false; }
  69178. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  69179. _this.direction = direction;
  69180. _this.onApplyObservable.add(function (effect) {
  69181. if (imageToBlur != null) {
  69182. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  69183. }
  69184. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  69185. if (scene.activeCamera) {
  69186. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69187. }
  69188. });
  69189. return _this;
  69190. }
  69191. return DepthOfFieldBlurPostProcess;
  69192. }(BABYLON.BlurPostProcess));
  69193. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  69194. })(BABYLON || (BABYLON = {}));
  69195. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  69196. "use strict";
  69197. var BABYLON;
  69198. (function (BABYLON) {
  69199. /**
  69200. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  69201. */
  69202. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  69203. __extends(DepthOfFieldMergePostProcess, _super);
  69204. /**
  69205. * Creates a new instance of @see CircleOfConfusionPostProcess
  69206. * @param name The name of the effect.
  69207. * @param original The non-blurred image to be modified
  69208. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  69209. * @param blurSteps Incrimental bluring post processes.
  69210. * @param options The required width/height ratio to downsize to before computing the render pass.
  69211. * @param camera The camera to apply the render pass to.
  69212. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69213. * @param engine The engine which the post process will be applied. (default: current engine)
  69214. * @param reusable If the post process can be reused on the same frame. (default: false)
  69215. * @param textureType Type of textures used when performing the post process. (default: 0)
  69216. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69217. */
  69218. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69219. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69220. if (blockCompilation === void 0) { blockCompilation = false; }
  69221. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  69222. _this.blurSteps = blurSteps;
  69223. _this.onApplyObservable.add(function (effect) {
  69224. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  69225. effect.setTextureFromPostProcess("textureSampler", original);
  69226. blurSteps.forEach(function (step, index) {
  69227. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  69228. });
  69229. });
  69230. if (!blockCompilation) {
  69231. _this.updateEffect();
  69232. }
  69233. return _this;
  69234. }
  69235. /**
  69236. * Updates the effect with the current post process compile time values and recompiles the shader.
  69237. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69238. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69239. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69240. * @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
  69241. * @param onCompiled Called when the shader has been compiled.
  69242. * @param onError Called if there is an error when compiling a shader.
  69243. */
  69244. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69245. if (defines === void 0) { defines = null; }
  69246. if (uniforms === void 0) { uniforms = null; }
  69247. if (samplers === void 0) { samplers = null; }
  69248. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  69249. };
  69250. return DepthOfFieldMergePostProcess;
  69251. }(BABYLON.PostProcess));
  69252. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  69253. })(BABYLON || (BABYLON = {}));
  69254. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  69255. "use strict";
  69256. var BABYLON;
  69257. (function (BABYLON) {
  69258. /**
  69259. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  69260. */
  69261. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  69262. __extends(CircleOfConfusionPostProcess, _super);
  69263. /**
  69264. * Creates a new instance of @see CircleOfConfusionPostProcess
  69265. * @param name The name of the effect.
  69266. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  69267. * @param options The required width/height ratio to downsize to before computing the render pass.
  69268. * @param camera The camera to apply the render pass to.
  69269. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69270. * @param engine The engine which the post process will be applied. (default: current engine)
  69271. * @param reusable If the post process can be reused on the same frame. (default: false)
  69272. * @param textureType Type of textures used when performing the post process. (default: 0)
  69273. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69274. */
  69275. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69276. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69277. if (blockCompilation === void 0) { blockCompilation = false; }
  69278. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69279. /**
  69280. * 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.
  69281. */
  69282. _this.lensSize = 50;
  69283. /**
  69284. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69285. */
  69286. _this.fStop = 1.4;
  69287. /**
  69288. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69289. */
  69290. _this.focusDistance = 2000;
  69291. /**
  69292. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  69293. */
  69294. _this.focalLength = 50;
  69295. _this._depthTexture = null;
  69296. _this._depthTexture = depthTexture;
  69297. _this.onApplyObservable.add(function (effect) {
  69298. if (!_this._depthTexture) {
  69299. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  69300. return;
  69301. }
  69302. effect.setTexture("depthSampler", _this._depthTexture);
  69303. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  69304. var aperture = _this.lensSize / _this.fStop;
  69305. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  69306. effect.setFloat('focusDistance', _this.focusDistance);
  69307. effect.setFloat('cocPrecalculation', cocPrecalculation);
  69308. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  69309. });
  69310. return _this;
  69311. }
  69312. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  69313. /**
  69314. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  69315. */
  69316. set: function (value) {
  69317. this._depthTexture = value;
  69318. },
  69319. enumerable: true,
  69320. configurable: true
  69321. });
  69322. return CircleOfConfusionPostProcess;
  69323. }(BABYLON.PostProcess));
  69324. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  69325. })(BABYLON || (BABYLON = {}));
  69326. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  69327. "use strict";
  69328. var BABYLON;
  69329. (function (BABYLON) {
  69330. /**
  69331. * Specifies the level of max blur that should be applied when using the depth of field effect
  69332. */
  69333. var DepthOfFieldEffectBlurLevel;
  69334. (function (DepthOfFieldEffectBlurLevel) {
  69335. /**
  69336. * Subtle blur
  69337. */
  69338. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  69339. /**
  69340. * Medium blur
  69341. */
  69342. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  69343. /**
  69344. * Large blur
  69345. */
  69346. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  69347. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  69348. ;
  69349. /**
  69350. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  69351. */
  69352. var DepthOfFieldEffect = /** @class */ (function (_super) {
  69353. __extends(DepthOfFieldEffect, _super);
  69354. /**
  69355. * Creates a new instance of @see DepthOfFieldEffect
  69356. * @param scene The scene the effect belongs to.
  69357. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  69358. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  69359. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69360. */
  69361. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  69362. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  69363. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  69364. if (blockCompilation === void 0) { blockCompilation = false; }
  69365. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  69366. return _this._effects;
  69367. }, true) || this;
  69368. _this._effects = [];
  69369. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  69370. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69371. // 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)
  69372. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  69373. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69374. _this._depthOfFieldBlurY = [];
  69375. _this._depthOfFieldBlurX = [];
  69376. var blurCount = 1;
  69377. var kernelSize = 15;
  69378. switch (blurLevel) {
  69379. case DepthOfFieldEffectBlurLevel.High: {
  69380. blurCount = 3;
  69381. kernelSize = 51;
  69382. break;
  69383. }
  69384. case DepthOfFieldEffectBlurLevel.Medium: {
  69385. blurCount = 2;
  69386. kernelSize = 31;
  69387. break;
  69388. }
  69389. default: {
  69390. kernelSize = 15;
  69391. blurCount = 1;
  69392. break;
  69393. }
  69394. }
  69395. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  69396. for (var i = 0; i < blurCount; i++) {
  69397. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69398. blurY.autoClear = false;
  69399. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69400. blurX.autoClear = false;
  69401. _this._depthOfFieldBlurY.push(blurY);
  69402. _this._depthOfFieldBlurX.push(blurX);
  69403. }
  69404. // Merge blurred images with original image based on circleOfConfusion
  69405. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69406. _this._depthOfFieldMerge.autoClear = false;
  69407. // Set all post processes on the effect.
  69408. _this._effects = [_this._circleOfConfusion];
  69409. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  69410. _this._effects.push(_this._depthOfFieldBlurY[i]);
  69411. _this._effects.push(_this._depthOfFieldBlurX[i]);
  69412. }
  69413. _this._effects.push(_this._depthOfFieldMerge);
  69414. return _this;
  69415. }
  69416. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  69417. get: function () {
  69418. return this._circleOfConfusion.focalLength;
  69419. },
  69420. /**
  69421. * The focal the length of the camera used in the effect
  69422. */
  69423. set: function (value) {
  69424. this._circleOfConfusion.focalLength = value;
  69425. },
  69426. enumerable: true,
  69427. configurable: true
  69428. });
  69429. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  69430. get: function () {
  69431. return this._circleOfConfusion.fStop;
  69432. },
  69433. /**
  69434. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69435. */
  69436. set: function (value) {
  69437. this._circleOfConfusion.fStop = value;
  69438. },
  69439. enumerable: true,
  69440. configurable: true
  69441. });
  69442. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  69443. get: function () {
  69444. return this._circleOfConfusion.focusDistance;
  69445. },
  69446. /**
  69447. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69448. */
  69449. set: function (value) {
  69450. this._circleOfConfusion.focusDistance = value;
  69451. },
  69452. enumerable: true,
  69453. configurable: true
  69454. });
  69455. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  69456. get: function () {
  69457. return this._circleOfConfusion.lensSize;
  69458. },
  69459. /**
  69460. * 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.
  69461. */
  69462. set: function (value) {
  69463. this._circleOfConfusion.lensSize = value;
  69464. },
  69465. enumerable: true,
  69466. configurable: true
  69467. });
  69468. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  69469. /**
  69470. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  69471. */
  69472. set: function (value) {
  69473. this._circleOfConfusion.depthTexture = value;
  69474. },
  69475. enumerable: true,
  69476. configurable: true
  69477. });
  69478. /**
  69479. * Disposes each of the internal effects for a given camera.
  69480. * @param camera The camera to dispose the effect on.
  69481. */
  69482. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  69483. this._circleOfConfusion.dispose(camera);
  69484. this._depthOfFieldBlurX.forEach(function (element) {
  69485. element.dispose(camera);
  69486. });
  69487. this._depthOfFieldBlurY.forEach(function (element) {
  69488. element.dispose(camera);
  69489. });
  69490. this._depthOfFieldMerge.dispose(camera);
  69491. };
  69492. /**
  69493. * Internal
  69494. */
  69495. DepthOfFieldEffect.prototype._updateEffects = function () {
  69496. for (var effect in this._effects) {
  69497. this._effects[effect].updateEffect();
  69498. }
  69499. };
  69500. /**
  69501. * Internal
  69502. * @returns if all the contained post processes are ready.
  69503. */
  69504. DepthOfFieldEffect.prototype._isReady = function () {
  69505. for (var effect in this._effects) {
  69506. if (!this._effects[effect].isReady()) {
  69507. return false;
  69508. }
  69509. }
  69510. return true;
  69511. };
  69512. return DepthOfFieldEffect;
  69513. }(BABYLON.PostProcessRenderEffect));
  69514. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  69515. })(BABYLON || (BABYLON = {}));
  69516. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  69517. "use strict";
  69518. var BABYLON;
  69519. (function (BABYLON) {
  69520. /**
  69521. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  69522. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  69523. */
  69524. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  69525. __extends(DefaultRenderingPipeline, _super);
  69526. /**
  69527. * @constructor
  69528. * @param {string} name - The rendering pipeline name
  69529. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69530. * @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)
  69531. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69532. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  69533. */
  69534. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  69535. if (automaticBuild === void 0) { automaticBuild = true; }
  69536. var _this = _super.call(this, scene.getEngine(), name) || this;
  69537. _this._originalCameras = [];
  69538. /**
  69539. * ID of the sharpen post process,
  69540. */
  69541. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  69542. /**
  69543. * ID of the pass post process used for bloom,
  69544. */
  69545. _this.PassPostProcessId = "PassPostProcessEffect";
  69546. /**
  69547. * ID of the highlight post process used for bloom,
  69548. */
  69549. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  69550. /**
  69551. * ID of the blurX post process used for bloom,
  69552. */
  69553. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  69554. /**
  69555. * ID of the blurY post process used for bloom,
  69556. */
  69557. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  69558. /**
  69559. * ID of the copy back post process used for bloom,
  69560. */
  69561. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  69562. /**
  69563. * ID of the image processing post process;
  69564. */
  69565. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  69566. /**
  69567. * ID of the Fast Approximate Anti-Aliasing post process;
  69568. */
  69569. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  69570. /**
  69571. * ID of the final merge post process;
  69572. */
  69573. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  69574. /**
  69575. * ID of the chromatic aberration post process,
  69576. */
  69577. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  69578. /**
  69579. * Animations which can be used to tweak settings over a period of time
  69580. */
  69581. _this.animations = [];
  69582. // Values
  69583. _this._sharpenEnabled = false;
  69584. _this._bloomEnabled = false;
  69585. _this._depthOfFieldEnabled = false;
  69586. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  69587. _this._fxaaEnabled = false;
  69588. _this._msaaEnabled = false;
  69589. _this._imageProcessingEnabled = true;
  69590. _this._bloomScale = 0.6;
  69591. _this._chromaticAberrationEnabled = false;
  69592. _this._buildAllowed = true;
  69593. /**
  69594. * Specifies the size of the bloom blur kernel, relative to the final output size
  69595. */
  69596. _this.bloomKernel = 64;
  69597. /**
  69598. * Specifies the weight of the bloom in the final rendering
  69599. */
  69600. _this._bloomWeight = 0.15;
  69601. _this._prevPostProcess = null;
  69602. _this._prevPrevPostProcess = null;
  69603. _this._cameras = cameras || [];
  69604. _this._originalCameras = _this._cameras.slice();
  69605. _this._buildAllowed = automaticBuild;
  69606. // Initialize
  69607. _this._scene = scene;
  69608. var caps = _this._scene.getEngine().getCaps();
  69609. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  69610. // Misc
  69611. if (_this._hdr) {
  69612. if (caps.textureHalfFloatRender) {
  69613. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69614. }
  69615. else if (caps.textureFloatRender) {
  69616. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69617. }
  69618. }
  69619. else {
  69620. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69621. }
  69622. // Attach
  69623. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69624. var engine = _this._scene.getEngine();
  69625. // Create post processes before hand so they can be modified before enabled.
  69626. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  69627. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  69628. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  69629. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  69630. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  69631. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  69632. _this._buildPipeline();
  69633. return _this;
  69634. }
  69635. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  69636. get: function () {
  69637. return this._sharpenEnabled;
  69638. },
  69639. /**
  69640. * Enable or disable the sharpen process from the pipeline
  69641. */
  69642. set: function (enabled) {
  69643. if (this._sharpenEnabled === enabled) {
  69644. return;
  69645. }
  69646. this._sharpenEnabled = enabled;
  69647. this._buildPipeline();
  69648. },
  69649. enumerable: true,
  69650. configurable: true
  69651. });
  69652. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  69653. get: function () {
  69654. return this._bloomWeight;
  69655. },
  69656. /**
  69657. * The strength of the bloom.
  69658. */
  69659. set: function (value) {
  69660. if (this._bloomWeight === value) {
  69661. return;
  69662. }
  69663. this._bloomWeight = value;
  69664. if (this._hdr && this.copyBack) {
  69665. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  69666. }
  69667. },
  69668. enumerable: true,
  69669. configurable: true
  69670. });
  69671. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  69672. get: function () {
  69673. return this._bloomScale;
  69674. },
  69675. /**
  69676. * The scale of the bloom, lower value will provide better performance.
  69677. */
  69678. set: function (value) {
  69679. if (this._bloomScale === value) {
  69680. return;
  69681. }
  69682. this._bloomScale = value;
  69683. this._buildPipeline();
  69684. },
  69685. enumerable: true,
  69686. configurable: true
  69687. });
  69688. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  69689. get: function () {
  69690. return this._bloomEnabled;
  69691. },
  69692. /**
  69693. * Enable or disable the bloom from the pipeline
  69694. */
  69695. set: function (enabled) {
  69696. if (this._bloomEnabled === enabled) {
  69697. return;
  69698. }
  69699. this._bloomEnabled = enabled;
  69700. this._buildPipeline();
  69701. },
  69702. enumerable: true,
  69703. configurable: true
  69704. });
  69705. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  69706. /**
  69707. * If the depth of field is enabled.
  69708. */
  69709. get: function () {
  69710. return this._depthOfFieldEnabled;
  69711. },
  69712. set: function (enabled) {
  69713. if (this._depthOfFieldEnabled === enabled) {
  69714. return;
  69715. }
  69716. this._depthOfFieldEnabled = enabled;
  69717. this._buildPipeline();
  69718. },
  69719. enumerable: true,
  69720. configurable: true
  69721. });
  69722. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  69723. /**
  69724. * Blur level of the depth of field effect. (Higher blur will effect performance)
  69725. */
  69726. get: function () {
  69727. return this._depthOfFieldBlurLevel;
  69728. },
  69729. set: function (value) {
  69730. if (this._depthOfFieldBlurLevel === value) {
  69731. return;
  69732. }
  69733. this._depthOfFieldBlurLevel = value;
  69734. // recreate dof and dispose old as this setting is not dynamic
  69735. var oldDof = this.depthOfField;
  69736. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  69737. this.depthOfField.focalLength = oldDof.focalLength;
  69738. this.depthOfField.focusDistance = oldDof.focusDistance;
  69739. this.depthOfField.fStop = oldDof.fStop;
  69740. this.depthOfField.lensSize = oldDof.lensSize;
  69741. for (var i = 0; i < this._cameras.length; i++) {
  69742. oldDof.disposeEffects(this._cameras[i]);
  69743. }
  69744. this._buildPipeline();
  69745. },
  69746. enumerable: true,
  69747. configurable: true
  69748. });
  69749. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  69750. get: function () {
  69751. return this._fxaaEnabled;
  69752. },
  69753. /**
  69754. * If the anti aliasing is enabled.
  69755. */
  69756. set: function (enabled) {
  69757. if (this._fxaaEnabled === enabled) {
  69758. return;
  69759. }
  69760. this._fxaaEnabled = enabled;
  69761. this._buildPipeline();
  69762. },
  69763. enumerable: true,
  69764. configurable: true
  69765. });
  69766. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  69767. get: function () {
  69768. return this._msaaEnabled;
  69769. },
  69770. /**
  69771. * If the multisample anti-aliasing is enabled.
  69772. */
  69773. set: function (enabled) {
  69774. if (this._msaaEnabled === enabled) {
  69775. return;
  69776. }
  69777. this._msaaEnabled = enabled;
  69778. this._buildPipeline();
  69779. },
  69780. enumerable: true,
  69781. configurable: true
  69782. });
  69783. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  69784. get: function () {
  69785. return this._imageProcessingEnabled;
  69786. },
  69787. /**
  69788. * If image processing is enabled.
  69789. */
  69790. set: function (enabled) {
  69791. if (this._imageProcessingEnabled === enabled) {
  69792. return;
  69793. }
  69794. this._imageProcessingEnabled = enabled;
  69795. this._buildPipeline();
  69796. },
  69797. enumerable: true,
  69798. configurable: true
  69799. });
  69800. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  69801. get: function () {
  69802. return this._chromaticAberrationEnabled;
  69803. },
  69804. /**
  69805. * Enable or disable the chromaticAberration process from the pipeline
  69806. */
  69807. set: function (enabled) {
  69808. if (this._chromaticAberrationEnabled === enabled) {
  69809. return;
  69810. }
  69811. this._chromaticAberrationEnabled = enabled;
  69812. this._buildPipeline();
  69813. },
  69814. enumerable: true,
  69815. configurable: true
  69816. });
  69817. /**
  69818. * Force the compilation of the entire pipeline.
  69819. */
  69820. DefaultRenderingPipeline.prototype.prepare = function () {
  69821. var previousState = this._buildAllowed;
  69822. this._buildAllowed = true;
  69823. this._buildPipeline();
  69824. this._buildAllowed = previousState;
  69825. };
  69826. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  69827. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  69828. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  69829. postProcess.autoClear = false;
  69830. }
  69831. else {
  69832. postProcess.autoClear = true;
  69833. }
  69834. if (!skipTextureSharing) {
  69835. if (this._prevPrevPostProcess) {
  69836. postProcess.shareOutputWith(this._prevPrevPostProcess);
  69837. }
  69838. else {
  69839. postProcess.useOwnOutput();
  69840. }
  69841. if (this._prevPostProcess) {
  69842. this._prevPrevPostProcess = this._prevPostProcess;
  69843. }
  69844. this._prevPostProcess = postProcess;
  69845. }
  69846. };
  69847. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  69848. var _this = this;
  69849. if (!this._buildAllowed) {
  69850. return;
  69851. }
  69852. var engine = this._scene.getEngine();
  69853. this._disposePostProcesses();
  69854. if (this._cameras !== null) {
  69855. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69856. // get back cameras to be used to reattach pipeline
  69857. this._cameras = this._originalCameras.slice();
  69858. }
  69859. this._reset();
  69860. this._prevPostProcess = null;
  69861. this._prevPrevPostProcess = null;
  69862. if (this.sharpenEnabled) {
  69863. if (!this.sharpen.isReady()) {
  69864. this.sharpen.updateEffect();
  69865. }
  69866. this.addEffect(this._sharpenEffect);
  69867. this._setAutoClearAndTextureSharing(this.sharpen);
  69868. }
  69869. if (this.depthOfFieldEnabled) {
  69870. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  69871. this.depthOfField.depthTexture = depthTexture;
  69872. if (!this.depthOfField._isReady()) {
  69873. this.depthOfField._updateEffects();
  69874. }
  69875. this.addEffect(this.depthOfField);
  69876. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  69877. }
  69878. if (this.bloomEnabled) {
  69879. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69880. this._setAutoClearAndTextureSharing(this.pass, true);
  69881. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  69882. if (!this._hdr) {
  69883. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69884. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  69885. this.highlights.autoClear = false;
  69886. this.highlights.alwaysForcePOT = true;
  69887. }
  69888. 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);
  69889. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  69890. this.blurX.alwaysForcePOT = true;
  69891. this.blurX.autoClear = false;
  69892. this.blurX.onActivateObservable.add(function () {
  69893. var dw = _this.blurX.width / engine.getRenderWidth(true);
  69894. _this.blurX.kernel = _this.bloomKernel * dw;
  69895. });
  69896. 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);
  69897. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  69898. this.blurY.alwaysForcePOT = true;
  69899. this.blurY.autoClear = false;
  69900. this.blurY.onActivateObservable.add(function () {
  69901. var dh = _this.blurY.height / engine.getRenderHeight(true);
  69902. _this.blurY.kernel = _this.bloomKernel * dh;
  69903. });
  69904. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69905. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  69906. this.copyBack.alwaysForcePOT = true;
  69907. if (this._hdr) {
  69908. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  69909. var w = this.bloomWeight;
  69910. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  69911. }
  69912. else {
  69913. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  69914. }
  69915. this.copyBack.autoClear = false;
  69916. }
  69917. if (this._imageProcessingEnabled) {
  69918. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69919. if (this._hdr) {
  69920. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  69921. }
  69922. else {
  69923. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  69924. }
  69925. }
  69926. if (this._hdr && this.imageProcessing) {
  69927. this.finalMerge = this.imageProcessing;
  69928. }
  69929. else {
  69930. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69931. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  69932. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  69933. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  69934. }
  69935. if (this.bloomEnabled) {
  69936. if (this._hdr) {
  69937. this.copyBack.shareOutputWith(this.blurX);
  69938. if (this.imageProcessing) {
  69939. this.imageProcessing.shareOutputWith(this.pass);
  69940. this.imageProcessing.autoClear = false;
  69941. }
  69942. else {
  69943. this.finalMerge.shareOutputWith(this.pass);
  69944. }
  69945. }
  69946. else {
  69947. this.finalMerge.shareOutputWith(this.pass);
  69948. }
  69949. }
  69950. if (this.fxaaEnabled) {
  69951. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69952. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  69953. this._setAutoClearAndTextureSharing(this.fxaa);
  69954. }
  69955. if (this.chromaticAberrationEnabled) {
  69956. if (!this.chromaticAberration.isReady()) {
  69957. this.chromaticAberration.updateEffect();
  69958. }
  69959. this.addEffect(this._chromaticAberrationEffect);
  69960. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  69961. }
  69962. if (this._cameras !== null) {
  69963. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69964. }
  69965. if (this.msaaEnabled) {
  69966. if (!this._enableMSAAOnFirstPostProcess()) {
  69967. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  69968. }
  69969. }
  69970. };
  69971. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  69972. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  69973. for (var i = 0; i < this._cameras.length; i++) {
  69974. var camera = this._cameras[i];
  69975. if (this.pass) {
  69976. this.pass.dispose(camera);
  69977. }
  69978. if (this.highlights) {
  69979. this.highlights.dispose(camera);
  69980. }
  69981. if (this.blurX) {
  69982. this.blurX.dispose(camera);
  69983. }
  69984. if (this.blurY) {
  69985. this.blurY.dispose(camera);
  69986. }
  69987. if (this.copyBack) {
  69988. this.copyBack.dispose(camera);
  69989. }
  69990. if (this.imageProcessing) {
  69991. this.imageProcessing.dispose(camera);
  69992. }
  69993. if (this.fxaa) {
  69994. this.fxaa.dispose(camera);
  69995. }
  69996. if (this.finalMerge) {
  69997. this.finalMerge.dispose(camera);
  69998. }
  69999. // These are created in the constructor and should not be disposed on every pipeline change
  70000. if (disposeNonRecreated) {
  70001. if (this.sharpen) {
  70002. this.sharpen.dispose(camera);
  70003. }
  70004. if (this.depthOfField) {
  70005. this.depthOfField.disposeEffects(camera);
  70006. }
  70007. if (this.chromaticAberration) {
  70008. this.chromaticAberration.dispose(camera);
  70009. }
  70010. }
  70011. }
  70012. this.pass = null;
  70013. this.highlights = null;
  70014. this.blurX = null;
  70015. this.blurY = null;
  70016. this.copyBack = null;
  70017. this.imageProcessing = null;
  70018. this.fxaa = null;
  70019. this.finalMerge = null;
  70020. if (disposeNonRecreated) {
  70021. this.sharpen = null;
  70022. this.depthOfField = null;
  70023. this.chromaticAberration = null;
  70024. }
  70025. };
  70026. /**
  70027. * Dispose of the pipeline and stop all post processes
  70028. */
  70029. DefaultRenderingPipeline.prototype.dispose = function () {
  70030. this._disposePostProcesses(true);
  70031. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70032. _super.prototype.dispose.call(this);
  70033. };
  70034. /**
  70035. * Serialize the rendering pipeline (Used when exporting)
  70036. * @returns the serialized object
  70037. */
  70038. DefaultRenderingPipeline.prototype.serialize = function () {
  70039. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  70040. serializationObject.customType = "DefaultRenderingPipeline";
  70041. return serializationObject;
  70042. };
  70043. /**
  70044. * Parse the serialized pipeline
  70045. * @param source Source pipeline.
  70046. * @param scene The scene to load the pipeline to.
  70047. * @param rootUrl The URL of the serialized pipeline.
  70048. * @returns An instantiated pipeline from the serialized object.
  70049. */
  70050. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  70051. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  70052. };
  70053. __decorate([
  70054. BABYLON.serialize()
  70055. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  70056. __decorate([
  70057. BABYLON.serialize()
  70058. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  70059. __decorate([
  70060. BABYLON.serialize()
  70061. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  70062. __decorate([
  70063. BABYLON.serialize()
  70064. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  70065. __decorate([
  70066. BABYLON.serialize()
  70067. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  70068. __decorate([
  70069. BABYLON.serialize()
  70070. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  70071. __decorate([
  70072. BABYLON.serialize()
  70073. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  70074. __decorate([
  70075. BABYLON.serialize()
  70076. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  70077. __decorate([
  70078. BABYLON.serialize()
  70079. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  70080. __decorate([
  70081. BABYLON.serialize()
  70082. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  70083. __decorate([
  70084. BABYLON.serialize()
  70085. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  70086. __decorate([
  70087. BABYLON.serialize()
  70088. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  70089. __decorate([
  70090. BABYLON.serialize()
  70091. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  70092. return DefaultRenderingPipeline;
  70093. }(BABYLON.PostProcessRenderPipeline));
  70094. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  70095. })(BABYLON || (BABYLON = {}));
  70096. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  70097. "use strict";
  70098. var BABYLON;
  70099. (function (BABYLON) {
  70100. /**
  70101. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  70102. */
  70103. var GeometryBufferRenderer = /** @class */ (function () {
  70104. /**
  70105. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  70106. * @param scene The scene the buffer belongs to
  70107. * @param ratio How big is the buffer related to the main canvas.
  70108. */
  70109. function GeometryBufferRenderer(scene, ratio) {
  70110. if (ratio === void 0) { ratio = 1; }
  70111. this._enablePosition = false;
  70112. this._scene = scene;
  70113. this._ratio = ratio;
  70114. // Render target
  70115. this._createRenderTargets();
  70116. }
  70117. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  70118. /**
  70119. * Set the render list (meshes to be rendered) used in the G buffer.
  70120. */
  70121. set: function (meshes) {
  70122. this._multiRenderTarget.renderList = meshes;
  70123. },
  70124. enumerable: true,
  70125. configurable: true
  70126. });
  70127. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  70128. /**
  70129. * Gets wether or not G buffer are supported by the running hardware.
  70130. * This requires draw buffer supports
  70131. */
  70132. get: function () {
  70133. return this._multiRenderTarget.isSupported;
  70134. },
  70135. enumerable: true,
  70136. configurable: true
  70137. });
  70138. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  70139. /**
  70140. * Gets wether or not position are enabled for the G buffer.
  70141. */
  70142. get: function () {
  70143. return this._enablePosition;
  70144. },
  70145. /**
  70146. * Sets wether or not position are enabled for the G buffer.
  70147. */
  70148. set: function (enable) {
  70149. this._enablePosition = enable;
  70150. this.dispose();
  70151. this._createRenderTargets();
  70152. },
  70153. enumerable: true,
  70154. configurable: true
  70155. });
  70156. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  70157. /**
  70158. * Gets the scene associated with the buffer.
  70159. */
  70160. get: function () {
  70161. return this._scene;
  70162. },
  70163. enumerable: true,
  70164. configurable: true
  70165. });
  70166. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  70167. /**
  70168. * Gets the ratio used by the buffer during its creation.
  70169. * How big is the buffer related to the main canvas.
  70170. */
  70171. get: function () {
  70172. return this._ratio;
  70173. },
  70174. enumerable: true,
  70175. configurable: true
  70176. });
  70177. /**
  70178. * Checks wether everything is ready to render a submesh to the G buffer.
  70179. * @param subMesh the submesh to check readiness for
  70180. * @param useInstances is the mesh drawn using instance or not
  70181. * @returns true if ready otherwise false
  70182. */
  70183. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  70184. var material = subMesh.getMaterial();
  70185. if (material && material.disableDepthWrite) {
  70186. return false;
  70187. }
  70188. var defines = [];
  70189. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  70190. var mesh = subMesh.getMesh();
  70191. // Alpha test
  70192. if (material && material.needAlphaTesting()) {
  70193. defines.push("#define ALPHATEST");
  70194. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70195. attribs.push(BABYLON.VertexBuffer.UVKind);
  70196. defines.push("#define UV1");
  70197. }
  70198. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70199. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70200. defines.push("#define UV2");
  70201. }
  70202. }
  70203. // Buffers
  70204. if (this._enablePosition) {
  70205. defines.push("#define POSITION");
  70206. }
  70207. // Bones
  70208. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70209. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70210. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70211. if (mesh.numBoneInfluencers > 4) {
  70212. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70213. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70214. }
  70215. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70216. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  70217. }
  70218. else {
  70219. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70220. }
  70221. // Instances
  70222. if (useInstances) {
  70223. defines.push("#define INSTANCES");
  70224. attribs.push("world0");
  70225. attribs.push("world1");
  70226. attribs.push("world2");
  70227. attribs.push("world3");
  70228. }
  70229. // Get correct effect
  70230. var join = defines.join("\n");
  70231. if (this._cachedDefines !== join) {
  70232. this._cachedDefines = join;
  70233. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  70234. }
  70235. return this._effect.isReady();
  70236. };
  70237. /**
  70238. * Gets the current underlying G Buffer.
  70239. * @returns the buffer
  70240. */
  70241. GeometryBufferRenderer.prototype.getGBuffer = function () {
  70242. return this._multiRenderTarget;
  70243. };
  70244. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  70245. /**
  70246. * Gets the number of samples used to render the buffer (anti aliasing).
  70247. */
  70248. get: function () {
  70249. return this._multiRenderTarget.samples;
  70250. },
  70251. /**
  70252. * Sets the number of samples used to render the buffer (anti aliasing).
  70253. */
  70254. set: function (value) {
  70255. this._multiRenderTarget.samples = value;
  70256. },
  70257. enumerable: true,
  70258. configurable: true
  70259. });
  70260. /**
  70261. * Disposes the renderer and frees up associated resources.
  70262. */
  70263. GeometryBufferRenderer.prototype.dispose = function () {
  70264. this.getGBuffer().dispose();
  70265. };
  70266. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  70267. var _this = this;
  70268. var engine = this._scene.getEngine();
  70269. var count = this._enablePosition ? 3 : 2;
  70270. 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 });
  70271. if (!this.isSupported) {
  70272. return;
  70273. }
  70274. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70275. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70276. this._multiRenderTarget.refreshRate = 1;
  70277. this._multiRenderTarget.renderParticles = false;
  70278. this._multiRenderTarget.renderList = null;
  70279. // set default depth value to 1.0 (far away)
  70280. this._multiRenderTarget.onClearObservable.add(function (engine) {
  70281. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  70282. });
  70283. // Custom render function
  70284. var renderSubMesh = function (subMesh) {
  70285. var mesh = subMesh.getRenderingMesh();
  70286. var scene = _this._scene;
  70287. var engine = scene.getEngine();
  70288. var material = subMesh.getMaterial();
  70289. if (!material) {
  70290. return;
  70291. }
  70292. // Culling
  70293. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  70294. // Managing instances
  70295. var batch = mesh._getInstancesRenderList(subMesh._id);
  70296. if (batch.mustReturn) {
  70297. return;
  70298. }
  70299. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70300. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  70301. engine.enableEffect(_this._effect);
  70302. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  70303. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  70304. _this._effect.setMatrix("view", scene.getViewMatrix());
  70305. // Alpha test
  70306. if (material && material.needAlphaTesting()) {
  70307. var alphaTexture = material.getAlphaTestTexture();
  70308. if (alphaTexture) {
  70309. _this._effect.setTexture("diffuseSampler", alphaTexture);
  70310. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70311. }
  70312. }
  70313. // Bones
  70314. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70315. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70316. }
  70317. // Draw
  70318. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70319. }
  70320. };
  70321. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70322. var index;
  70323. if (depthOnlySubMeshes.length) {
  70324. engine.setColorWrite(false);
  70325. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70326. renderSubMesh(depthOnlySubMeshes.data[index]);
  70327. }
  70328. engine.setColorWrite(true);
  70329. }
  70330. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70331. renderSubMesh(opaqueSubMeshes.data[index]);
  70332. }
  70333. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70334. renderSubMesh(alphaTestSubMeshes.data[index]);
  70335. }
  70336. };
  70337. };
  70338. return GeometryBufferRenderer;
  70339. }());
  70340. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  70341. })(BABYLON || (BABYLON = {}));
  70342. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  70343. "use strict";
  70344. var BABYLON;
  70345. (function (BABYLON) {
  70346. var RefractionPostProcess = /** @class */ (function (_super) {
  70347. __extends(RefractionPostProcess, _super);
  70348. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  70349. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  70350. _this.color = color;
  70351. _this.depth = depth;
  70352. _this.colorLevel = colorLevel;
  70353. _this._ownRefractionTexture = true;
  70354. _this.onActivateObservable.add(function (cam) {
  70355. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  70356. });
  70357. _this.onApplyObservable.add(function (effect) {
  70358. effect.setColor3("baseColor", _this.color);
  70359. effect.setFloat("depth", _this.depth);
  70360. effect.setFloat("colorLevel", _this.colorLevel);
  70361. effect.setTexture("refractionSampler", _this._refTexture);
  70362. });
  70363. return _this;
  70364. }
  70365. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  70366. /**
  70367. * Gets or sets the refraction texture
  70368. * Please note that you are responsible for disposing the texture if you set it manually
  70369. */
  70370. get: function () {
  70371. return this._refTexture;
  70372. },
  70373. set: function (value) {
  70374. if (this._refTexture && this._ownRefractionTexture) {
  70375. this._refTexture.dispose();
  70376. }
  70377. this._refTexture = value;
  70378. this._ownRefractionTexture = false;
  70379. },
  70380. enumerable: true,
  70381. configurable: true
  70382. });
  70383. // Methods
  70384. RefractionPostProcess.prototype.dispose = function (camera) {
  70385. if (this._refTexture && this._ownRefractionTexture) {
  70386. this._refTexture.dispose();
  70387. this._refTexture = null;
  70388. }
  70389. _super.prototype.dispose.call(this, camera);
  70390. };
  70391. return RefractionPostProcess;
  70392. }(BABYLON.PostProcess));
  70393. BABYLON.RefractionPostProcess = RefractionPostProcess;
  70394. })(BABYLON || (BABYLON = {}));
  70395. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  70396. "use strict";
  70397. var BABYLON;
  70398. (function (BABYLON) {
  70399. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  70400. __extends(BlackAndWhitePostProcess, _super);
  70401. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  70402. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  70403. _this.degree = 1;
  70404. _this.onApplyObservable.add(function (effect) {
  70405. effect.setFloat("degree", _this.degree);
  70406. });
  70407. return _this;
  70408. }
  70409. return BlackAndWhitePostProcess;
  70410. }(BABYLON.PostProcess));
  70411. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  70412. })(BABYLON || (BABYLON = {}));
  70413. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  70414. "use strict";
  70415. var BABYLON;
  70416. (function (BABYLON) {
  70417. /**
  70418. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  70419. * input texture to perform effects such as edge detection or sharpening
  70420. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  70421. */
  70422. var ConvolutionPostProcess = /** @class */ (function (_super) {
  70423. __extends(ConvolutionPostProcess, _super);
  70424. /**
  70425. * Creates a new instance of @see ConvolutionPostProcess
  70426. * @param name The name of the effect.
  70427. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  70428. * @param options The required width/height ratio to downsize to before computing the render pass.
  70429. * @param camera The camera to apply the render pass to.
  70430. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70431. * @param engine The engine which the post process will be applied. (default: current engine)
  70432. * @param reusable If the post process can be reused on the same frame. (default: false)
  70433. * @param textureType Type of textures used when performing the post process. (default: 0)
  70434. */
  70435. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  70436. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70437. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70438. _this.kernel = kernel;
  70439. _this.onApply = function (effect) {
  70440. effect.setFloat2("screenSize", _this.width, _this.height);
  70441. effect.setArray("kernel", _this.kernel);
  70442. };
  70443. return _this;
  70444. }
  70445. // Statics
  70446. /**
  70447. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70448. */
  70449. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  70450. /**
  70451. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70452. */
  70453. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  70454. /**
  70455. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70456. */
  70457. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  70458. /**
  70459. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70460. */
  70461. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  70462. /**
  70463. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70464. */
  70465. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  70466. /**
  70467. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70468. */
  70469. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  70470. return ConvolutionPostProcess;
  70471. }(BABYLON.PostProcess));
  70472. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  70473. })(BABYLON || (BABYLON = {}));
  70474. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  70475. "use strict";
  70476. var BABYLON;
  70477. (function (BABYLON) {
  70478. var FilterPostProcess = /** @class */ (function (_super) {
  70479. __extends(FilterPostProcess, _super);
  70480. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  70481. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  70482. _this.kernelMatrix = kernelMatrix;
  70483. _this.onApply = function (effect) {
  70484. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  70485. };
  70486. return _this;
  70487. }
  70488. return FilterPostProcess;
  70489. }(BABYLON.PostProcess));
  70490. BABYLON.FilterPostProcess = FilterPostProcess;
  70491. })(BABYLON || (BABYLON = {}));
  70492. //# sourceMappingURL=babylon.filterPostProcess.js.map
  70493. "use strict";
  70494. var BABYLON;
  70495. (function (BABYLON) {
  70496. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  70497. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  70498. __extends(VolumetricLightScatteringPostProcess, _super);
  70499. /**
  70500. * @constructor
  70501. * @param {string} name - The post-process name
  70502. * @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)
  70503. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  70504. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  70505. * @param {number} samples - The post-process quality, default 100
  70506. * @param {number} samplingMode - The post-process filtering mode
  70507. * @param {BABYLON.Engine} engine - The babylon engine
  70508. * @param {boolean} reusable - If the post-process is reusable
  70509. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  70510. */
  70511. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  70512. if (samples === void 0) { samples = 100; }
  70513. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70514. 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;
  70515. _this._screenCoordinates = BABYLON.Vector2.Zero();
  70516. /**
  70517. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  70518. * @type {Vector3}
  70519. */
  70520. _this.customMeshPosition = BABYLON.Vector3.Zero();
  70521. /**
  70522. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  70523. * @type {boolean}
  70524. */
  70525. _this.useCustomMeshPosition = false;
  70526. /**
  70527. * If the post-process should inverse the light scattering direction
  70528. * @type {boolean}
  70529. */
  70530. _this.invert = true;
  70531. /**
  70532. * Array containing the excluded meshes not rendered in the internal pass
  70533. */
  70534. _this.excludedMeshes = new Array();
  70535. /**
  70536. * Controls the overall intensity of the post-process
  70537. * @type {number}
  70538. */
  70539. _this.exposure = 0.3;
  70540. /**
  70541. * Dissipates each sample's contribution in range [0, 1]
  70542. * @type {number}
  70543. */
  70544. _this.decay = 0.96815;
  70545. /**
  70546. * Controls the overall intensity of each sample
  70547. * @type {number}
  70548. */
  70549. _this.weight = 0.58767;
  70550. /**
  70551. * Controls the density of each sample
  70552. * @type {number}
  70553. */
  70554. _this.density = 0.926;
  70555. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  70556. engine = scene.getEngine();
  70557. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  70558. // Configure mesh
  70559. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  70560. // Configure
  70561. _this._createPass(scene, ratio.passRatio || ratio);
  70562. _this.onActivate = function (camera) {
  70563. if (!_this.isSupported) {
  70564. _this.dispose(camera);
  70565. }
  70566. _this.onActivate = null;
  70567. };
  70568. _this.onApplyObservable.add(function (effect) {
  70569. _this._updateMeshScreenCoordinates(scene);
  70570. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  70571. effect.setFloat("exposure", _this.exposure);
  70572. effect.setFloat("decay", _this.decay);
  70573. effect.setFloat("weight", _this.weight);
  70574. effect.setFloat("density", _this.density);
  70575. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  70576. });
  70577. return _this;
  70578. }
  70579. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  70580. get: function () {
  70581. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70582. return false;
  70583. },
  70584. set: function (useDiffuseColor) {
  70585. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70586. },
  70587. enumerable: true,
  70588. configurable: true
  70589. });
  70590. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  70591. return "VolumetricLightScatteringPostProcess";
  70592. };
  70593. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  70594. var mesh = subMesh.getMesh();
  70595. // Render this.mesh as default
  70596. if (mesh === this.mesh && mesh.material) {
  70597. return mesh.material.isReady(mesh);
  70598. }
  70599. var defines = [];
  70600. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70601. var material = subMesh.getMaterial();
  70602. // Alpha test
  70603. if (material) {
  70604. if (material.needAlphaTesting()) {
  70605. defines.push("#define ALPHATEST");
  70606. }
  70607. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70608. attribs.push(BABYLON.VertexBuffer.UVKind);
  70609. defines.push("#define UV1");
  70610. }
  70611. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70612. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70613. defines.push("#define UV2");
  70614. }
  70615. }
  70616. // Bones
  70617. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70618. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70619. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70620. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70621. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  70622. }
  70623. else {
  70624. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70625. }
  70626. // Instances
  70627. if (useInstances) {
  70628. defines.push("#define INSTANCES");
  70629. attribs.push("world0");
  70630. attribs.push("world1");
  70631. attribs.push("world2");
  70632. attribs.push("world3");
  70633. }
  70634. // Get correct effect
  70635. var join = defines.join("\n");
  70636. if (this._cachedDefines !== join) {
  70637. this._cachedDefines = join;
  70638. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  70639. }
  70640. return this._volumetricLightScatteringPass.isReady();
  70641. };
  70642. /**
  70643. * Sets the new light position for light scattering effect
  70644. * @param {BABYLON.Vector3} The new custom light position
  70645. */
  70646. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  70647. this.customMeshPosition = position;
  70648. };
  70649. /**
  70650. * Returns the light position for light scattering effect
  70651. * @return {BABYLON.Vector3} The custom light position
  70652. */
  70653. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  70654. return this.customMeshPosition;
  70655. };
  70656. /**
  70657. * Disposes the internal assets and detaches the post-process from the camera
  70658. */
  70659. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  70660. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  70661. if (rttIndex !== -1) {
  70662. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  70663. }
  70664. this._volumetricLightScatteringRTT.dispose();
  70665. _super.prototype.dispose.call(this, camera);
  70666. };
  70667. /**
  70668. * Returns the render target texture used by the post-process
  70669. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  70670. */
  70671. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  70672. return this._volumetricLightScatteringRTT;
  70673. };
  70674. // Private methods
  70675. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  70676. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  70677. return true;
  70678. }
  70679. return false;
  70680. };
  70681. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  70682. var _this = this;
  70683. var engine = scene.getEngine();
  70684. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70685. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70686. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70687. this._volumetricLightScatteringRTT.renderList = null;
  70688. this._volumetricLightScatteringRTT.renderParticles = false;
  70689. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  70690. var camera = this.getCamera();
  70691. if (camera) {
  70692. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70693. }
  70694. else {
  70695. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70696. }
  70697. // Custom render function for submeshes
  70698. var renderSubMesh = function (subMesh) {
  70699. var mesh = subMesh.getRenderingMesh();
  70700. if (_this._meshExcluded(mesh)) {
  70701. return;
  70702. }
  70703. var material = subMesh.getMaterial();
  70704. if (!material) {
  70705. return;
  70706. }
  70707. var scene = mesh.getScene();
  70708. var engine = scene.getEngine();
  70709. // Culling
  70710. engine.setState(material.backFaceCulling);
  70711. // Managing instances
  70712. var batch = mesh._getInstancesRenderList(subMesh._id);
  70713. if (batch.mustReturn) {
  70714. return;
  70715. }
  70716. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70717. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  70718. var effect = _this._volumetricLightScatteringPass;
  70719. if (mesh === _this.mesh) {
  70720. if (subMesh.effect) {
  70721. effect = subMesh.effect;
  70722. }
  70723. else {
  70724. effect = material.getEffect();
  70725. }
  70726. }
  70727. engine.enableEffect(effect);
  70728. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  70729. if (mesh === _this.mesh) {
  70730. material.bind(mesh.getWorldMatrix(), mesh);
  70731. }
  70732. else {
  70733. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  70734. // Alpha test
  70735. if (material && material.needAlphaTesting()) {
  70736. var alphaTexture = material.getAlphaTestTexture();
  70737. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  70738. if (alphaTexture) {
  70739. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70740. }
  70741. }
  70742. // Bones
  70743. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70744. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70745. }
  70746. }
  70747. // Draw
  70748. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  70749. }
  70750. };
  70751. // Render target texture callbacks
  70752. var savedSceneClearColor;
  70753. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  70754. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  70755. savedSceneClearColor = scene.clearColor;
  70756. scene.clearColor = sceneClearColor;
  70757. });
  70758. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  70759. scene.clearColor = savedSceneClearColor;
  70760. });
  70761. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70762. var engine = scene.getEngine();
  70763. var index;
  70764. if (depthOnlySubMeshes.length) {
  70765. engine.setColorWrite(false);
  70766. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70767. renderSubMesh(depthOnlySubMeshes.data[index]);
  70768. }
  70769. engine.setColorWrite(true);
  70770. }
  70771. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70772. renderSubMesh(opaqueSubMeshes.data[index]);
  70773. }
  70774. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70775. renderSubMesh(alphaTestSubMeshes.data[index]);
  70776. }
  70777. if (transparentSubMeshes.length) {
  70778. // Sort sub meshes
  70779. for (index = 0; index < transparentSubMeshes.length; index++) {
  70780. var submesh = transparentSubMeshes.data[index];
  70781. var boundingInfo = submesh.getBoundingInfo();
  70782. if (boundingInfo && scene.activeCamera) {
  70783. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  70784. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  70785. }
  70786. }
  70787. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  70788. sortedArray.sort(function (a, b) {
  70789. // Alpha index first
  70790. if (a._alphaIndex > b._alphaIndex) {
  70791. return 1;
  70792. }
  70793. if (a._alphaIndex < b._alphaIndex) {
  70794. return -1;
  70795. }
  70796. // Then distance to camera
  70797. if (a._distanceToCamera < b._distanceToCamera) {
  70798. return 1;
  70799. }
  70800. if (a._distanceToCamera > b._distanceToCamera) {
  70801. return -1;
  70802. }
  70803. return 0;
  70804. });
  70805. // Render sub meshes
  70806. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  70807. for (index = 0; index < sortedArray.length; index++) {
  70808. renderSubMesh(sortedArray[index]);
  70809. }
  70810. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70811. }
  70812. };
  70813. };
  70814. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  70815. var transform = scene.getTransformMatrix();
  70816. var meshPosition;
  70817. if (this.useCustomMeshPosition) {
  70818. meshPosition = this.customMeshPosition;
  70819. }
  70820. else if (this.attachedNode) {
  70821. meshPosition = this.attachedNode.position;
  70822. }
  70823. else {
  70824. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  70825. }
  70826. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  70827. this._screenCoordinates.x = pos.x / this._viewPort.width;
  70828. this._screenCoordinates.y = pos.y / this._viewPort.height;
  70829. if (this.invert)
  70830. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  70831. };
  70832. // Static methods
  70833. /**
  70834. * Creates a default mesh for the Volumeric Light Scattering post-process
  70835. * @param {string} The mesh name
  70836. * @param {BABYLON.Scene} The scene where to create the mesh
  70837. * @return {BABYLON.Mesh} the default mesh
  70838. */
  70839. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  70840. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  70841. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  70842. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  70843. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  70844. mesh.material = material;
  70845. return mesh;
  70846. };
  70847. __decorate([
  70848. BABYLON.serializeAsVector3()
  70849. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  70850. __decorate([
  70851. BABYLON.serialize()
  70852. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  70853. __decorate([
  70854. BABYLON.serialize()
  70855. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  70856. __decorate([
  70857. BABYLON.serializeAsMeshReference()
  70858. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  70859. __decorate([
  70860. BABYLON.serialize()
  70861. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  70862. __decorate([
  70863. BABYLON.serialize()
  70864. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  70865. __decorate([
  70866. BABYLON.serialize()
  70867. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  70868. __decorate([
  70869. BABYLON.serialize()
  70870. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  70871. __decorate([
  70872. BABYLON.serialize()
  70873. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  70874. return VolumetricLightScatteringPostProcess;
  70875. }(BABYLON.PostProcess));
  70876. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  70877. })(BABYLON || (BABYLON = {}));
  70878. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  70879. "use strict";
  70880. //
  70881. // This post-process allows the modification of rendered colors by using
  70882. // a 'look-up table' (LUT). This effect is also called Color Grading.
  70883. //
  70884. // The object needs to be provided an url to a texture containing the color
  70885. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  70886. // Use an image editing software to tweak the LUT to match your needs.
  70887. //
  70888. // For an example of a color LUT, see here:
  70889. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  70890. // For explanations on color grading, see here:
  70891. // http://udn.epicgames.com/Three/ColorGrading.html
  70892. //
  70893. var BABYLON;
  70894. (function (BABYLON) {
  70895. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  70896. __extends(ColorCorrectionPostProcess, _super);
  70897. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  70898. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  70899. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  70900. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  70901. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70902. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70903. _this.onApply = function (effect) {
  70904. effect.setTexture("colorTable", _this._colorTableTexture);
  70905. };
  70906. return _this;
  70907. }
  70908. return ColorCorrectionPostProcess;
  70909. }(BABYLON.PostProcess));
  70910. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  70911. })(BABYLON || (BABYLON = {}));
  70912. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  70913. "use strict";
  70914. var BABYLON;
  70915. (function (BABYLON) {
  70916. var TonemappingOperator;
  70917. (function (TonemappingOperator) {
  70918. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  70919. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  70920. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  70921. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  70922. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  70923. ;
  70924. var TonemapPostProcess = /** @class */ (function (_super) {
  70925. __extends(TonemapPostProcess, _super);
  70926. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  70927. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70928. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70929. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  70930. _this._operator = _operator;
  70931. _this.exposureAdjustment = exposureAdjustment;
  70932. var defines = "#define ";
  70933. if (_this._operator === TonemappingOperator.Hable)
  70934. defines += "HABLE_TONEMAPPING";
  70935. else if (_this._operator === TonemappingOperator.Reinhard)
  70936. defines += "REINHARD_TONEMAPPING";
  70937. else if (_this._operator === TonemappingOperator.HejiDawson)
  70938. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  70939. else if (_this._operator === TonemappingOperator.Photographic)
  70940. defines += "PHOTOGRAPHIC_TONEMAPPING";
  70941. //sadly a second call to create the effect.
  70942. _this.updateEffect(defines);
  70943. _this.onApply = function (effect) {
  70944. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  70945. };
  70946. return _this;
  70947. }
  70948. return TonemapPostProcess;
  70949. }(BABYLON.PostProcess));
  70950. BABYLON.TonemapPostProcess = TonemapPostProcess;
  70951. })(BABYLON || (BABYLON = {}));
  70952. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  70953. "use strict";
  70954. var BABYLON;
  70955. (function (BABYLON) {
  70956. var DisplayPassPostProcess = /** @class */ (function (_super) {
  70957. __extends(DisplayPassPostProcess, _super);
  70958. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  70959. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  70960. }
  70961. return DisplayPassPostProcess;
  70962. }(BABYLON.PostProcess));
  70963. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  70964. })(BABYLON || (BABYLON = {}));
  70965. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  70966. "use strict";
  70967. var BABYLON;
  70968. (function (BABYLON) {
  70969. var HighlightsPostProcess = /** @class */ (function (_super) {
  70970. __extends(HighlightsPostProcess, _super);
  70971. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  70972. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70973. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70974. }
  70975. return HighlightsPostProcess;
  70976. }(BABYLON.PostProcess));
  70977. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  70978. })(BABYLON || (BABYLON = {}));
  70979. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  70980. "use strict";
  70981. var BABYLON;
  70982. (function (BABYLON) {
  70983. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  70984. __extends(ImageProcessingPostProcess, _super);
  70985. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  70986. if (camera === void 0) { camera = null; }
  70987. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70988. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  70989. _this._fromLinearSpace = true;
  70990. /**
  70991. * Defines cache preventing GC.
  70992. */
  70993. _this._defines = {
  70994. IMAGEPROCESSING: false,
  70995. VIGNETTE: false,
  70996. VIGNETTEBLENDMODEMULTIPLY: false,
  70997. VIGNETTEBLENDMODEOPAQUE: false,
  70998. TONEMAPPING: false,
  70999. CONTRAST: false,
  71000. COLORCURVES: false,
  71001. COLORGRADING: false,
  71002. COLORGRADING3D: false,
  71003. FROMLINEARSPACE: false,
  71004. SAMPLER3DGREENDEPTH: false,
  71005. SAMPLER3DBGRMAP: false,
  71006. IMAGEPROCESSINGPOSTPROCESS: false,
  71007. EXPOSURE: false,
  71008. GRAIN: false,
  71009. };
  71010. // Setup the configuration as forced by the constructor. This would then not force the
  71011. // scene materials output in linear space and let untouched the default forward pass.
  71012. if (imageProcessingConfiguration) {
  71013. imageProcessingConfiguration.applyByPostProcess = true;
  71014. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  71015. // This will cause the shader to be compiled
  71016. _this.fromLinearSpace = false;
  71017. }
  71018. else {
  71019. _this._attachImageProcessingConfiguration(null, true);
  71020. _this.imageProcessingConfiguration.applyByPostProcess = true;
  71021. }
  71022. _this.onApply = function (effect) {
  71023. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  71024. };
  71025. return _this;
  71026. }
  71027. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  71028. /**
  71029. * Gets the image processing configuration used either in this material.
  71030. */
  71031. get: function () {
  71032. return this._imageProcessingConfiguration;
  71033. },
  71034. /**
  71035. * Sets the Default image processing configuration used either in the this material.
  71036. *
  71037. * If sets to null, the scene one is in use.
  71038. */
  71039. set: function (value) {
  71040. this._attachImageProcessingConfiguration(value);
  71041. },
  71042. enumerable: true,
  71043. configurable: true
  71044. });
  71045. /**
  71046. * Attaches a new image processing configuration to the PBR Material.
  71047. * @param configuration
  71048. */
  71049. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  71050. var _this = this;
  71051. if (doNotBuild === void 0) { doNotBuild = false; }
  71052. if (configuration === this._imageProcessingConfiguration) {
  71053. return;
  71054. }
  71055. // Detaches observer.
  71056. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71057. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71058. }
  71059. // Pick the scene configuration if needed.
  71060. if (!configuration) {
  71061. var scene = null;
  71062. var engine = this.getEngine();
  71063. var camera = this.getCamera();
  71064. if (camera) {
  71065. scene = camera.getScene();
  71066. }
  71067. else if (engine && engine.scenes) {
  71068. var scenes = engine.scenes;
  71069. scene = scenes[scenes.length - 1];
  71070. }
  71071. else {
  71072. scene = BABYLON.Engine.LastCreatedScene;
  71073. }
  71074. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  71075. }
  71076. else {
  71077. this._imageProcessingConfiguration = configuration;
  71078. }
  71079. // Attaches observer.
  71080. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  71081. _this._updateParameters();
  71082. });
  71083. // Ensure the effect will be rebuilt.
  71084. if (!doNotBuild) {
  71085. this._updateParameters();
  71086. }
  71087. };
  71088. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  71089. /**
  71090. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71091. */
  71092. get: function () {
  71093. return this.imageProcessingConfiguration.colorCurves;
  71094. },
  71095. /**
  71096. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71097. */
  71098. set: function (value) {
  71099. this.imageProcessingConfiguration.colorCurves = value;
  71100. },
  71101. enumerable: true,
  71102. configurable: true
  71103. });
  71104. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  71105. /**
  71106. * Gets wether the color curves effect is enabled.
  71107. */
  71108. get: function () {
  71109. return this.imageProcessingConfiguration.colorCurvesEnabled;
  71110. },
  71111. /**
  71112. * Sets wether the color curves effect is enabled.
  71113. */
  71114. set: function (value) {
  71115. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  71116. },
  71117. enumerable: true,
  71118. configurable: true
  71119. });
  71120. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  71121. /**
  71122. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71123. */
  71124. get: function () {
  71125. return this.imageProcessingConfiguration.colorGradingTexture;
  71126. },
  71127. /**
  71128. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71129. */
  71130. set: function (value) {
  71131. this.imageProcessingConfiguration.colorGradingTexture = value;
  71132. },
  71133. enumerable: true,
  71134. configurable: true
  71135. });
  71136. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  71137. /**
  71138. * Gets wether the color grading effect is enabled.
  71139. */
  71140. get: function () {
  71141. return this.imageProcessingConfiguration.colorGradingEnabled;
  71142. },
  71143. /**
  71144. * Gets wether the color grading effect is enabled.
  71145. */
  71146. set: function (value) {
  71147. this.imageProcessingConfiguration.colorGradingEnabled = value;
  71148. },
  71149. enumerable: true,
  71150. configurable: true
  71151. });
  71152. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  71153. /**
  71154. * Gets exposure used in the effect.
  71155. */
  71156. get: function () {
  71157. return this.imageProcessingConfiguration.exposure;
  71158. },
  71159. /**
  71160. * Sets exposure used in the effect.
  71161. */
  71162. set: function (value) {
  71163. this.imageProcessingConfiguration.exposure = value;
  71164. },
  71165. enumerable: true,
  71166. configurable: true
  71167. });
  71168. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  71169. /**
  71170. * Gets wether tonemapping is enabled or not.
  71171. */
  71172. get: function () {
  71173. return this._imageProcessingConfiguration.toneMappingEnabled;
  71174. },
  71175. /**
  71176. * Sets wether tonemapping is enabled or not
  71177. */
  71178. set: function (value) {
  71179. this._imageProcessingConfiguration.toneMappingEnabled = value;
  71180. },
  71181. enumerable: true,
  71182. configurable: true
  71183. });
  71184. ;
  71185. ;
  71186. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  71187. /**
  71188. * Gets contrast used in the effect.
  71189. */
  71190. get: function () {
  71191. return this.imageProcessingConfiguration.contrast;
  71192. },
  71193. /**
  71194. * Sets contrast used in the effect.
  71195. */
  71196. set: function (value) {
  71197. this.imageProcessingConfiguration.contrast = value;
  71198. },
  71199. enumerable: true,
  71200. configurable: true
  71201. });
  71202. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  71203. /**
  71204. * Gets Vignette stretch size.
  71205. */
  71206. get: function () {
  71207. return this.imageProcessingConfiguration.vignetteStretch;
  71208. },
  71209. /**
  71210. * Sets Vignette stretch size.
  71211. */
  71212. set: function (value) {
  71213. this.imageProcessingConfiguration.vignetteStretch = value;
  71214. },
  71215. enumerable: true,
  71216. configurable: true
  71217. });
  71218. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  71219. /**
  71220. * Gets Vignette centre X Offset.
  71221. */
  71222. get: function () {
  71223. return this.imageProcessingConfiguration.vignetteCentreX;
  71224. },
  71225. /**
  71226. * Sets Vignette centre X Offset.
  71227. */
  71228. set: function (value) {
  71229. this.imageProcessingConfiguration.vignetteCentreX = value;
  71230. },
  71231. enumerable: true,
  71232. configurable: true
  71233. });
  71234. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  71235. /**
  71236. * Gets Vignette centre Y Offset.
  71237. */
  71238. get: function () {
  71239. return this.imageProcessingConfiguration.vignetteCentreY;
  71240. },
  71241. /**
  71242. * Sets Vignette centre Y Offset.
  71243. */
  71244. set: function (value) {
  71245. this.imageProcessingConfiguration.vignetteCentreY = value;
  71246. },
  71247. enumerable: true,
  71248. configurable: true
  71249. });
  71250. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  71251. /**
  71252. * Gets Vignette weight or intensity of the vignette effect.
  71253. */
  71254. get: function () {
  71255. return this.imageProcessingConfiguration.vignetteWeight;
  71256. },
  71257. /**
  71258. * Sets Vignette weight or intensity of the vignette effect.
  71259. */
  71260. set: function (value) {
  71261. this.imageProcessingConfiguration.vignetteWeight = value;
  71262. },
  71263. enumerable: true,
  71264. configurable: true
  71265. });
  71266. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  71267. /**
  71268. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71269. * if vignetteEnabled is set to true.
  71270. */
  71271. get: function () {
  71272. return this.imageProcessingConfiguration.vignetteColor;
  71273. },
  71274. /**
  71275. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71276. * if vignetteEnabled is set to true.
  71277. */
  71278. set: function (value) {
  71279. this.imageProcessingConfiguration.vignetteColor = value;
  71280. },
  71281. enumerable: true,
  71282. configurable: true
  71283. });
  71284. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  71285. /**
  71286. * Gets Camera field of view used by the Vignette effect.
  71287. */
  71288. get: function () {
  71289. return this.imageProcessingConfiguration.vignetteCameraFov;
  71290. },
  71291. /**
  71292. * Sets Camera field of view used by the Vignette effect.
  71293. */
  71294. set: function (value) {
  71295. this.imageProcessingConfiguration.vignetteCameraFov = value;
  71296. },
  71297. enumerable: true,
  71298. configurable: true
  71299. });
  71300. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  71301. /**
  71302. * Gets the vignette blend mode allowing different kind of effect.
  71303. */
  71304. get: function () {
  71305. return this.imageProcessingConfiguration.vignetteBlendMode;
  71306. },
  71307. /**
  71308. * Sets the vignette blend mode allowing different kind of effect.
  71309. */
  71310. set: function (value) {
  71311. this.imageProcessingConfiguration.vignetteBlendMode = value;
  71312. },
  71313. enumerable: true,
  71314. configurable: true
  71315. });
  71316. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  71317. /**
  71318. * Gets wether the vignette effect is enabled.
  71319. */
  71320. get: function () {
  71321. return this.imageProcessingConfiguration.vignetteEnabled;
  71322. },
  71323. /**
  71324. * Sets wether the vignette effect is enabled.
  71325. */
  71326. set: function (value) {
  71327. this.imageProcessingConfiguration.vignetteEnabled = value;
  71328. },
  71329. enumerable: true,
  71330. configurable: true
  71331. });
  71332. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  71333. /**
  71334. * Gets wether the grain effect is enabled.
  71335. */
  71336. get: function () {
  71337. return this.imageProcessingConfiguration.grainEnabled;
  71338. },
  71339. /**
  71340. * Sets wether the grain effect is enabled.
  71341. */
  71342. set: function (value) {
  71343. this.imageProcessingConfiguration.grainEnabled = value;
  71344. },
  71345. enumerable: true,
  71346. configurable: true
  71347. });
  71348. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  71349. /**
  71350. * Gets the grain effect's intensity.
  71351. */
  71352. get: function () {
  71353. return this.imageProcessingConfiguration.grainIntensity;
  71354. },
  71355. /**
  71356. * Sets the grain effect's intensity.
  71357. */
  71358. set: function (value) {
  71359. this.imageProcessingConfiguration.grainIntensity = value;
  71360. },
  71361. enumerable: true,
  71362. configurable: true
  71363. });
  71364. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  71365. /**
  71366. * Gets wether the grain effect is animated.
  71367. */
  71368. get: function () {
  71369. return this.imageProcessingConfiguration.grainAnimated;
  71370. },
  71371. /**
  71372. * Sets wether the grain effect is animated.
  71373. */
  71374. set: function (value) {
  71375. this.imageProcessingConfiguration.grainAnimated = value;
  71376. },
  71377. enumerable: true,
  71378. configurable: true
  71379. });
  71380. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  71381. /**
  71382. * Gets wether the input of the processing is in Gamma or Linear Space.
  71383. */
  71384. get: function () {
  71385. return this._fromLinearSpace;
  71386. },
  71387. /**
  71388. * Sets wether the input of the processing is in Gamma or Linear Space.
  71389. */
  71390. set: function (value) {
  71391. if (this._fromLinearSpace === value) {
  71392. return;
  71393. }
  71394. this._fromLinearSpace = value;
  71395. this._updateParameters();
  71396. },
  71397. enumerable: true,
  71398. configurable: true
  71399. });
  71400. ImageProcessingPostProcess.prototype.getClassName = function () {
  71401. return "ImageProcessingPostProcess";
  71402. };
  71403. ImageProcessingPostProcess.prototype._updateParameters = function () {
  71404. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  71405. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  71406. var defines = "";
  71407. for (var define in this._defines) {
  71408. if (this._defines[define]) {
  71409. defines += "#define " + define + ";\r\n";
  71410. }
  71411. }
  71412. var samplers = ["textureSampler"];
  71413. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  71414. var uniforms = ["scale"];
  71415. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  71416. this.updateEffect(defines, uniforms, samplers);
  71417. };
  71418. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  71419. _super.prototype.dispose.call(this, camera);
  71420. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71421. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71422. }
  71423. this.imageProcessingConfiguration.applyByPostProcess = false;
  71424. };
  71425. __decorate([
  71426. BABYLON.serialize()
  71427. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  71428. return ImageProcessingPostProcess;
  71429. }(BABYLON.PostProcess));
  71430. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  71431. })(BABYLON || (BABYLON = {}));
  71432. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  71433. "use strict";
  71434. var BABYLON;
  71435. (function (BABYLON) {
  71436. var Bone = /** @class */ (function (_super) {
  71437. __extends(Bone, _super);
  71438. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  71439. if (parentBone === void 0) { parentBone = null; }
  71440. if (localMatrix === void 0) { localMatrix = null; }
  71441. if (restPose === void 0) { restPose = null; }
  71442. if (baseMatrix === void 0) { baseMatrix = null; }
  71443. if (index === void 0) { index = null; }
  71444. var _this = _super.call(this, name, skeleton.getScene()) || this;
  71445. _this.name = name;
  71446. _this.children = new Array();
  71447. _this.animations = new Array();
  71448. // Set this value to map this bone to a different index in the transform matrices.
  71449. // Set this value to -1 to exclude the bone from the transform matrices.
  71450. _this._index = null;
  71451. _this._worldTransform = new BABYLON.Matrix();
  71452. _this._absoluteTransform = new BABYLON.Matrix();
  71453. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  71454. _this._scaleMatrix = BABYLON.Matrix.Identity();
  71455. _this._scaleVector = BABYLON.Vector3.One();
  71456. _this._negateScaleChildren = BABYLON.Vector3.One();
  71457. _this._scalingDeterminant = 1;
  71458. _this._skeleton = skeleton;
  71459. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  71460. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  71461. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  71462. _this._index = index;
  71463. skeleton.bones.push(_this);
  71464. _this.setParent(parentBone, false);
  71465. _this._updateDifferenceMatrix();
  71466. return _this;
  71467. }
  71468. Object.defineProperty(Bone.prototype, "_matrix", {
  71469. get: function () {
  71470. return this._localMatrix;
  71471. },
  71472. set: function (val) {
  71473. if (this._localMatrix) {
  71474. this._localMatrix.copyFrom(val);
  71475. }
  71476. else {
  71477. this._localMatrix = val;
  71478. }
  71479. },
  71480. enumerable: true,
  71481. configurable: true
  71482. });
  71483. // Members
  71484. Bone.prototype.getSkeleton = function () {
  71485. return this._skeleton;
  71486. };
  71487. Bone.prototype.getParent = function () {
  71488. return this._parent;
  71489. };
  71490. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  71491. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71492. if (this._parent === parent) {
  71493. return;
  71494. }
  71495. if (this._parent) {
  71496. var index = this._parent.children.indexOf(this);
  71497. if (index !== -1) {
  71498. this._parent.children.splice(index, 1);
  71499. }
  71500. }
  71501. this._parent = parent;
  71502. if (this._parent) {
  71503. this._parent.children.push(this);
  71504. }
  71505. if (updateDifferenceMatrix) {
  71506. this._updateDifferenceMatrix();
  71507. }
  71508. };
  71509. Bone.prototype.getLocalMatrix = function () {
  71510. return this._localMatrix;
  71511. };
  71512. Bone.prototype.getBaseMatrix = function () {
  71513. return this._baseMatrix;
  71514. };
  71515. Bone.prototype.getRestPose = function () {
  71516. return this._restPose;
  71517. };
  71518. Bone.prototype.returnToRest = function () {
  71519. this.updateMatrix(this._restPose.clone());
  71520. };
  71521. Bone.prototype.getWorldMatrix = function () {
  71522. return this._worldTransform;
  71523. };
  71524. Bone.prototype.getInvertedAbsoluteTransform = function () {
  71525. return this._invertedAbsoluteTransform;
  71526. };
  71527. Bone.prototype.getAbsoluteTransform = function () {
  71528. return this._absoluteTransform;
  71529. };
  71530. Object.defineProperty(Bone.prototype, "position", {
  71531. // Properties (matches AbstractMesh properties)
  71532. get: function () {
  71533. return this.getPosition();
  71534. },
  71535. set: function (newPosition) {
  71536. this.setPosition(newPosition);
  71537. },
  71538. enumerable: true,
  71539. configurable: true
  71540. });
  71541. Object.defineProperty(Bone.prototype, "rotation", {
  71542. get: function () {
  71543. return this.getRotation();
  71544. },
  71545. set: function (newRotation) {
  71546. this.setRotation(newRotation);
  71547. },
  71548. enumerable: true,
  71549. configurable: true
  71550. });
  71551. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  71552. get: function () {
  71553. return this.getRotationQuaternion();
  71554. },
  71555. set: function (newRotation) {
  71556. this.setRotationQuaternion(newRotation);
  71557. },
  71558. enumerable: true,
  71559. configurable: true
  71560. });
  71561. Object.defineProperty(Bone.prototype, "scaling", {
  71562. get: function () {
  71563. return this.getScale();
  71564. },
  71565. set: function (newScaling) {
  71566. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  71567. },
  71568. enumerable: true,
  71569. configurable: true
  71570. });
  71571. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  71572. /**
  71573. * Gets the animation properties override
  71574. */
  71575. get: function () {
  71576. return this._skeleton.animationPropertiesOverride;
  71577. },
  71578. enumerable: true,
  71579. configurable: true
  71580. });
  71581. // Methods
  71582. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  71583. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71584. this._baseMatrix = matrix.clone();
  71585. this._localMatrix = matrix.clone();
  71586. this._skeleton._markAsDirty();
  71587. if (updateDifferenceMatrix) {
  71588. this._updateDifferenceMatrix();
  71589. }
  71590. };
  71591. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  71592. if (!rootMatrix) {
  71593. rootMatrix = this._baseMatrix;
  71594. }
  71595. if (this._parent) {
  71596. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71597. }
  71598. else {
  71599. this._absoluteTransform.copyFrom(rootMatrix);
  71600. }
  71601. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  71602. for (var index = 0; index < this.children.length; index++) {
  71603. this.children[index]._updateDifferenceMatrix();
  71604. }
  71605. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  71606. };
  71607. Bone.prototype.markAsDirty = function () {
  71608. this._currentRenderId++;
  71609. this._skeleton._markAsDirty();
  71610. };
  71611. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  71612. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71613. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  71614. // all animation may be coming from a library skeleton, so may need to create animation
  71615. if (this.animations.length === 0) {
  71616. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  71617. this.animations[0].setKeys([]);
  71618. }
  71619. // get animation info / verify there is such a range from the source bone
  71620. var sourceRange = source.animations[0].getRange(rangeName);
  71621. if (!sourceRange) {
  71622. return false;
  71623. }
  71624. var from = sourceRange.from;
  71625. var to = sourceRange.to;
  71626. var sourceKeys = source.animations[0].getKeys();
  71627. // rescaling prep
  71628. var sourceBoneLength = source.length;
  71629. var sourceParent = source.getParent();
  71630. var parent = this.getParent();
  71631. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  71632. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  71633. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  71634. var destKeys = this.animations[0].getKeys();
  71635. // loop vars declaration
  71636. var orig;
  71637. var origTranslation;
  71638. var mat;
  71639. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  71640. orig = sourceKeys[key];
  71641. if (orig.frame >= from && orig.frame <= to) {
  71642. if (rescaleAsRequired) {
  71643. mat = orig.value.clone();
  71644. // scale based on parent ratio, when bone has parent
  71645. if (parentScalingReqd) {
  71646. origTranslation = mat.getTranslation();
  71647. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  71648. // scale based on skeleton dimension ratio when root bone, and value is passed
  71649. }
  71650. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  71651. origTranslation = mat.getTranslation();
  71652. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  71653. // use original when root bone, and no data for skelDimensionsRatio
  71654. }
  71655. else {
  71656. mat = orig.value;
  71657. }
  71658. }
  71659. else {
  71660. mat = orig.value;
  71661. }
  71662. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  71663. }
  71664. }
  71665. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  71666. return true;
  71667. };
  71668. /**
  71669. * Translate the bone in local or world space.
  71670. * @param vec The amount to translate the bone.
  71671. * @param space The space that the translation is in.
  71672. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71673. */
  71674. Bone.prototype.translate = function (vec, space, mesh) {
  71675. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71676. var lm = this.getLocalMatrix();
  71677. if (space == BABYLON.Space.LOCAL) {
  71678. lm.m[12] += vec.x;
  71679. lm.m[13] += vec.y;
  71680. lm.m[14] += vec.z;
  71681. }
  71682. else {
  71683. var wm = null;
  71684. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71685. if (mesh) {
  71686. wm = mesh.getWorldMatrix();
  71687. }
  71688. this._skeleton.computeAbsoluteTransforms();
  71689. var tmat = Bone._tmpMats[0];
  71690. var tvec = Bone._tmpVecs[0];
  71691. if (this._parent) {
  71692. if (mesh && wm) {
  71693. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71694. tmat.multiplyToRef(wm, tmat);
  71695. }
  71696. else {
  71697. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71698. }
  71699. }
  71700. tmat.m[12] = 0;
  71701. tmat.m[13] = 0;
  71702. tmat.m[14] = 0;
  71703. tmat.invert();
  71704. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  71705. lm.m[12] += tvec.x;
  71706. lm.m[13] += tvec.y;
  71707. lm.m[14] += tvec.z;
  71708. }
  71709. this.markAsDirty();
  71710. };
  71711. /**
  71712. * Set the postion of the bone in local or world space.
  71713. * @param position The position to set the bone.
  71714. * @param space The space that the position is in.
  71715. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71716. */
  71717. Bone.prototype.setPosition = function (position, space, mesh) {
  71718. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71719. var lm = this.getLocalMatrix();
  71720. if (space == BABYLON.Space.LOCAL) {
  71721. lm.m[12] = position.x;
  71722. lm.m[13] = position.y;
  71723. lm.m[14] = position.z;
  71724. }
  71725. else {
  71726. var wm = null;
  71727. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71728. if (mesh) {
  71729. wm = mesh.getWorldMatrix();
  71730. }
  71731. this._skeleton.computeAbsoluteTransforms();
  71732. var tmat = Bone._tmpMats[0];
  71733. var vec = Bone._tmpVecs[0];
  71734. if (this._parent) {
  71735. if (mesh && wm) {
  71736. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71737. tmat.multiplyToRef(wm, tmat);
  71738. }
  71739. else {
  71740. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71741. }
  71742. }
  71743. tmat.invert();
  71744. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  71745. lm.m[12] = vec.x;
  71746. lm.m[13] = vec.y;
  71747. lm.m[14] = vec.z;
  71748. }
  71749. this.markAsDirty();
  71750. };
  71751. /**
  71752. * Set the absolute postion of the bone (world space).
  71753. * @param position The position to set the bone.
  71754. * @param mesh The mesh that this bone is attached to.
  71755. */
  71756. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  71757. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  71758. };
  71759. /**
  71760. * Set the scale of the bone on the x, y and z axes.
  71761. * @param x The scale of the bone on the x axis.
  71762. * @param x The scale of the bone on the y axis.
  71763. * @param z The scale of the bone on the z axis.
  71764. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71765. */
  71766. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  71767. if (scaleChildren === void 0) { scaleChildren = false; }
  71768. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  71769. if (!scaleChildren) {
  71770. this._negateScaleChildren.x = 1 / x;
  71771. this._negateScaleChildren.y = 1 / y;
  71772. this._negateScaleChildren.z = 1 / z;
  71773. }
  71774. this._syncScaleVector();
  71775. }
  71776. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  71777. };
  71778. /**
  71779. * Scale the bone on the x, y and z axes.
  71780. * @param x The amount to scale the bone on the x axis.
  71781. * @param x The amount to scale the bone on the y axis.
  71782. * @param z The amount to scale the bone on the z axis.
  71783. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71784. */
  71785. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  71786. if (scaleChildren === void 0) { scaleChildren = false; }
  71787. var locMat = this.getLocalMatrix();
  71788. var origLocMat = Bone._tmpMats[0];
  71789. origLocMat.copyFrom(locMat);
  71790. var origLocMatInv = Bone._tmpMats[1];
  71791. origLocMatInv.copyFrom(origLocMat);
  71792. origLocMatInv.invert();
  71793. var scaleMat = Bone._tmpMats[2];
  71794. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  71795. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  71796. this._scaleVector.x *= x;
  71797. this._scaleVector.y *= y;
  71798. this._scaleVector.z *= z;
  71799. locMat.multiplyToRef(origLocMatInv, locMat);
  71800. locMat.multiplyToRef(scaleMat, locMat);
  71801. locMat.multiplyToRef(origLocMat, locMat);
  71802. var parent = this.getParent();
  71803. if (parent) {
  71804. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  71805. }
  71806. else {
  71807. this.getAbsoluteTransform().copyFrom(locMat);
  71808. }
  71809. var len = this.children.length;
  71810. scaleMat.invert();
  71811. for (var i = 0; i < len; i++) {
  71812. var child = this.children[i];
  71813. var cm = child.getLocalMatrix();
  71814. cm.multiplyToRef(scaleMat, cm);
  71815. var lm = child.getLocalMatrix();
  71816. lm.m[12] *= x;
  71817. lm.m[13] *= y;
  71818. lm.m[14] *= z;
  71819. }
  71820. this.computeAbsoluteTransforms();
  71821. if (scaleChildren) {
  71822. for (var i = 0; i < len; i++) {
  71823. this.children[i].scale(x, y, z, scaleChildren);
  71824. }
  71825. }
  71826. this.markAsDirty();
  71827. };
  71828. /**
  71829. * Set the yaw, pitch, and roll of the bone in local or world space.
  71830. * @param yaw The rotation of the bone on the y axis.
  71831. * @param pitch The rotation of the bone on the x axis.
  71832. * @param roll The rotation of the bone on the z axis.
  71833. * @param space The space that the axes of rotation are in.
  71834. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71835. */
  71836. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  71837. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71838. var rotMat = Bone._tmpMats[0];
  71839. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  71840. var rotMatInv = Bone._tmpMats[1];
  71841. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71842. rotMatInv.multiplyToRef(rotMat, rotMat);
  71843. this._rotateWithMatrix(rotMat, space, mesh);
  71844. };
  71845. /**
  71846. * Rotate the bone on an axis in local or world space.
  71847. * @param axis The axis to rotate the bone on.
  71848. * @param amount The amount to rotate the bone.
  71849. * @param space The space that the axis is in.
  71850. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71851. */
  71852. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  71853. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71854. var rmat = Bone._tmpMats[0];
  71855. rmat.m[12] = 0;
  71856. rmat.m[13] = 0;
  71857. rmat.m[14] = 0;
  71858. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  71859. this._rotateWithMatrix(rmat, space, mesh);
  71860. };
  71861. /**
  71862. * Set the rotation of the bone to a particular axis angle in local or world space.
  71863. * @param axis The axis to rotate the bone on.
  71864. * @param angle The angle that the bone should be rotated to.
  71865. * @param space The space that the axis is in.
  71866. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71867. */
  71868. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  71869. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71870. var rotMat = Bone._tmpMats[0];
  71871. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  71872. var rotMatInv = Bone._tmpMats[1];
  71873. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71874. rotMatInv.multiplyToRef(rotMat, rotMat);
  71875. this._rotateWithMatrix(rotMat, space, mesh);
  71876. };
  71877. /**
  71878. * Set the euler rotation of the bone in local of world space.
  71879. * @param rotation The euler rotation that the bone should be set to.
  71880. * @param space The space that the rotation is in.
  71881. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71882. */
  71883. Bone.prototype.setRotation = function (rotation, space, mesh) {
  71884. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71885. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  71886. };
  71887. /**
  71888. * Set the quaternion rotation of the bone in local of world space.
  71889. * @param quat The quaternion rotation that the bone should be set to.
  71890. * @param space The space that the rotation is in.
  71891. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71892. */
  71893. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  71894. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71895. var rotMatInv = Bone._tmpMats[0];
  71896. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71897. var rotMat = Bone._tmpMats[1];
  71898. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  71899. rotMatInv.multiplyToRef(rotMat, rotMat);
  71900. this._rotateWithMatrix(rotMat, space, mesh);
  71901. };
  71902. /**
  71903. * Set the rotation matrix of the bone in local of world space.
  71904. * @param rotMat The rotation matrix that the bone should be set to.
  71905. * @param space The space that the rotation is in.
  71906. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71907. */
  71908. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  71909. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71910. var rotMatInv = Bone._tmpMats[0];
  71911. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71912. var rotMat2 = Bone._tmpMats[1];
  71913. rotMat2.copyFrom(rotMat);
  71914. rotMatInv.multiplyToRef(rotMat, rotMat2);
  71915. this._rotateWithMatrix(rotMat2, space, mesh);
  71916. };
  71917. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  71918. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71919. var lmat = this.getLocalMatrix();
  71920. var lx = lmat.m[12];
  71921. var ly = lmat.m[13];
  71922. var lz = lmat.m[14];
  71923. var parent = this.getParent();
  71924. var parentScale = Bone._tmpMats[3];
  71925. var parentScaleInv = Bone._tmpMats[4];
  71926. if (parent) {
  71927. if (space == BABYLON.Space.WORLD) {
  71928. if (mesh) {
  71929. parentScale.copyFrom(mesh.getWorldMatrix());
  71930. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  71931. }
  71932. else {
  71933. parentScale.copyFrom(parent.getAbsoluteTransform());
  71934. }
  71935. }
  71936. else {
  71937. parentScale = parent._scaleMatrix;
  71938. }
  71939. parentScaleInv.copyFrom(parentScale);
  71940. parentScaleInv.invert();
  71941. lmat.multiplyToRef(parentScale, lmat);
  71942. lmat.multiplyToRef(rmat, lmat);
  71943. lmat.multiplyToRef(parentScaleInv, lmat);
  71944. }
  71945. else {
  71946. if (space == BABYLON.Space.WORLD && mesh) {
  71947. parentScale.copyFrom(mesh.getWorldMatrix());
  71948. parentScaleInv.copyFrom(parentScale);
  71949. parentScaleInv.invert();
  71950. lmat.multiplyToRef(parentScale, lmat);
  71951. lmat.multiplyToRef(rmat, lmat);
  71952. lmat.multiplyToRef(parentScaleInv, lmat);
  71953. }
  71954. else {
  71955. lmat.multiplyToRef(rmat, lmat);
  71956. }
  71957. }
  71958. lmat.m[12] = lx;
  71959. lmat.m[13] = ly;
  71960. lmat.m[14] = lz;
  71961. this.computeAbsoluteTransforms();
  71962. this.markAsDirty();
  71963. };
  71964. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  71965. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71966. if (space == BABYLON.Space.WORLD) {
  71967. var scaleMatrix = Bone._tmpMats[2];
  71968. scaleMatrix.copyFrom(this._scaleMatrix);
  71969. rotMatInv.copyFrom(this.getAbsoluteTransform());
  71970. if (mesh) {
  71971. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  71972. var meshScale = Bone._tmpMats[3];
  71973. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  71974. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  71975. }
  71976. rotMatInv.invert();
  71977. scaleMatrix.m[0] *= this._scalingDeterminant;
  71978. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71979. }
  71980. else {
  71981. rotMatInv.copyFrom(this.getLocalMatrix());
  71982. rotMatInv.invert();
  71983. var scaleMatrix = Bone._tmpMats[2];
  71984. scaleMatrix.copyFrom(this._scaleMatrix);
  71985. if (this._parent) {
  71986. var pscaleMatrix = Bone._tmpMats[3];
  71987. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  71988. pscaleMatrix.invert();
  71989. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  71990. }
  71991. else {
  71992. scaleMatrix.m[0] *= this._scalingDeterminant;
  71993. }
  71994. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71995. }
  71996. };
  71997. /**
  71998. * Get the scale of the bone
  71999. * @returns the scale of the bone
  72000. */
  72001. Bone.prototype.getScale = function () {
  72002. return this._scaleVector.clone();
  72003. };
  72004. /**
  72005. * Copy the scale of the bone to a vector3.
  72006. * @param result The vector3 to copy the scale to
  72007. */
  72008. Bone.prototype.getScaleToRef = function (result) {
  72009. result.copyFrom(this._scaleVector);
  72010. };
  72011. /**
  72012. * Get the position of the bone in local or world space.
  72013. * @param space The space that the returned position is in.
  72014. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72015. * @returns The position of the bone
  72016. */
  72017. Bone.prototype.getPosition = function (space, mesh) {
  72018. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72019. if (mesh === void 0) { mesh = null; }
  72020. var pos = BABYLON.Vector3.Zero();
  72021. this.getPositionToRef(space, mesh, pos);
  72022. return pos;
  72023. };
  72024. /**
  72025. * Copy the position of the bone to a vector3 in local or world space.
  72026. * @param space The space that the returned position is in.
  72027. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72028. * @param result The vector3 to copy the position to.
  72029. */
  72030. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  72031. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72032. if (space == BABYLON.Space.LOCAL) {
  72033. var lm = this.getLocalMatrix();
  72034. result.x = lm.m[12];
  72035. result.y = lm.m[13];
  72036. result.z = lm.m[14];
  72037. }
  72038. else {
  72039. var wm = null;
  72040. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72041. if (mesh) {
  72042. wm = mesh.getWorldMatrix();
  72043. }
  72044. this._skeleton.computeAbsoluteTransforms();
  72045. var tmat = Bone._tmpMats[0];
  72046. if (mesh && wm) {
  72047. tmat.copyFrom(this.getAbsoluteTransform());
  72048. tmat.multiplyToRef(wm, tmat);
  72049. }
  72050. else {
  72051. tmat = this.getAbsoluteTransform();
  72052. }
  72053. result.x = tmat.m[12];
  72054. result.y = tmat.m[13];
  72055. result.z = tmat.m[14];
  72056. }
  72057. };
  72058. /**
  72059. * Get the absolute position of the bone (world space).
  72060. * @param mesh The mesh that this bone is attached to.
  72061. * @returns The absolute position of the bone
  72062. */
  72063. Bone.prototype.getAbsolutePosition = function (mesh) {
  72064. if (mesh === void 0) { mesh = null; }
  72065. var pos = BABYLON.Vector3.Zero();
  72066. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  72067. return pos;
  72068. };
  72069. /**
  72070. * Copy the absolute position of the bone (world space) to the result param.
  72071. * @param mesh The mesh that this bone is attached to.
  72072. * @param result The vector3 to copy the absolute position to.
  72073. */
  72074. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  72075. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  72076. };
  72077. /**
  72078. * Compute the absolute transforms of this bone and its children.
  72079. */
  72080. Bone.prototype.computeAbsoluteTransforms = function () {
  72081. if (this._parent) {
  72082. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72083. }
  72084. else {
  72085. this._absoluteTransform.copyFrom(this._localMatrix);
  72086. var poseMatrix = this._skeleton.getPoseMatrix();
  72087. if (poseMatrix) {
  72088. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  72089. }
  72090. }
  72091. var children = this.children;
  72092. var len = children.length;
  72093. for (var i = 0; i < len; i++) {
  72094. children[i].computeAbsoluteTransforms();
  72095. }
  72096. };
  72097. Bone.prototype._syncScaleVector = function () {
  72098. var lm = this.getLocalMatrix();
  72099. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  72100. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  72101. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  72102. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  72103. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  72104. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  72105. this._scaleVector.x = xs * Math.sqrt(xsq);
  72106. this._scaleVector.y = ys * Math.sqrt(ysq);
  72107. this._scaleVector.z = zs * Math.sqrt(zsq);
  72108. if (this._parent) {
  72109. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  72110. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  72111. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  72112. }
  72113. 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);
  72114. };
  72115. /**
  72116. * Get the world direction from an axis that is in the local space of the bone.
  72117. * @param localAxis The local direction that is used to compute the world direction.
  72118. * @param mesh The mesh that this bone is attached to.
  72119. * @returns The world direction
  72120. */
  72121. Bone.prototype.getDirection = function (localAxis, mesh) {
  72122. if (mesh === void 0) { mesh = null; }
  72123. var result = BABYLON.Vector3.Zero();
  72124. this.getDirectionToRef(localAxis, mesh, result);
  72125. return result;
  72126. };
  72127. /**
  72128. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  72129. * @param localAxis The local direction that is used to compute the world direction.
  72130. * @param mesh The mesh that this bone is attached to.
  72131. * @param result The vector3 that the world direction will be copied to.
  72132. */
  72133. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  72134. if (mesh === void 0) { mesh = null; }
  72135. var wm = null;
  72136. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72137. if (mesh) {
  72138. wm = mesh.getWorldMatrix();
  72139. }
  72140. this._skeleton.computeAbsoluteTransforms();
  72141. var mat = Bone._tmpMats[0];
  72142. mat.copyFrom(this.getAbsoluteTransform());
  72143. if (mesh && wm) {
  72144. mat.multiplyToRef(wm, mat);
  72145. }
  72146. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  72147. result.normalize();
  72148. };
  72149. /**
  72150. * Get the euler rotation of the bone in local or world space.
  72151. * @param space The space that the rotation should be in.
  72152. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72153. * @returns The euler rotation
  72154. */
  72155. Bone.prototype.getRotation = function (space, mesh) {
  72156. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72157. if (mesh === void 0) { mesh = null; }
  72158. var result = BABYLON.Vector3.Zero();
  72159. this.getRotationToRef(space, mesh, result);
  72160. return result;
  72161. };
  72162. /**
  72163. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  72164. * @param space The space that the rotation should be in.
  72165. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72166. * @param result The vector3 that the rotation should be copied to.
  72167. */
  72168. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  72169. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72170. if (mesh === void 0) { mesh = null; }
  72171. var quat = Bone._tmpQuat;
  72172. this.getRotationQuaternionToRef(space, mesh, quat);
  72173. quat.toEulerAnglesToRef(result);
  72174. };
  72175. /**
  72176. * Get the quaternion rotation of the bone in either local or world space.
  72177. * @param space The space that the rotation should be in.
  72178. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72179. * @returns The quaternion rotation
  72180. */
  72181. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  72182. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72183. if (mesh === void 0) { mesh = null; }
  72184. var result = BABYLON.Quaternion.Identity();
  72185. this.getRotationQuaternionToRef(space, mesh, result);
  72186. return result;
  72187. };
  72188. /**
  72189. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  72190. * @param space The space that the rotation should be in.
  72191. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72192. * @param result The quaternion that the rotation should be copied to.
  72193. */
  72194. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  72195. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72196. if (mesh === void 0) { mesh = null; }
  72197. if (space == BABYLON.Space.LOCAL) {
  72198. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72199. }
  72200. else {
  72201. var mat = Bone._tmpMats[0];
  72202. var amat = this.getAbsoluteTransform();
  72203. if (mesh) {
  72204. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72205. }
  72206. else {
  72207. mat.copyFrom(amat);
  72208. }
  72209. mat.m[0] *= this._scalingDeterminant;
  72210. mat.m[1] *= this._scalingDeterminant;
  72211. mat.m[2] *= this._scalingDeterminant;
  72212. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72213. }
  72214. };
  72215. /**
  72216. * Get the rotation matrix of the bone in local or world space.
  72217. * @param space The space that the rotation should be in.
  72218. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72219. * @returns The rotation matrix
  72220. */
  72221. Bone.prototype.getRotationMatrix = function (space, mesh) {
  72222. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72223. var result = BABYLON.Matrix.Identity();
  72224. this.getRotationMatrixToRef(space, mesh, result);
  72225. return result;
  72226. };
  72227. /**
  72228. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  72229. * @param space The space that the rotation should be in.
  72230. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72231. * @param result The quaternion that the rotation should be copied to.
  72232. */
  72233. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  72234. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72235. if (space == BABYLON.Space.LOCAL) {
  72236. this.getLocalMatrix().getRotationMatrixToRef(result);
  72237. }
  72238. else {
  72239. var mat = Bone._tmpMats[0];
  72240. var amat = this.getAbsoluteTransform();
  72241. if (mesh) {
  72242. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72243. }
  72244. else {
  72245. mat.copyFrom(amat);
  72246. }
  72247. mat.m[0] *= this._scalingDeterminant;
  72248. mat.m[1] *= this._scalingDeterminant;
  72249. mat.m[2] *= this._scalingDeterminant;
  72250. mat.getRotationMatrixToRef(result);
  72251. }
  72252. };
  72253. /**
  72254. * Get the world position of a point that is in the local space of the bone.
  72255. * @param position The local position
  72256. * @param mesh The mesh that this bone is attached to.
  72257. * @returns The world position
  72258. */
  72259. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  72260. if (mesh === void 0) { mesh = null; }
  72261. var result = BABYLON.Vector3.Zero();
  72262. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  72263. return result;
  72264. };
  72265. /**
  72266. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  72267. * @param position The local position
  72268. * @param mesh The mesh that this bone is attached to.
  72269. * @param result The vector3 that the world position should be copied to.
  72270. */
  72271. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  72272. if (mesh === void 0) { mesh = null; }
  72273. var wm = null;
  72274. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72275. if (mesh) {
  72276. wm = mesh.getWorldMatrix();
  72277. }
  72278. this._skeleton.computeAbsoluteTransforms();
  72279. var tmat = Bone._tmpMats[0];
  72280. if (mesh && wm) {
  72281. tmat.copyFrom(this.getAbsoluteTransform());
  72282. tmat.multiplyToRef(wm, tmat);
  72283. }
  72284. else {
  72285. tmat = this.getAbsoluteTransform();
  72286. }
  72287. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72288. };
  72289. /**
  72290. * Get the local position of a point that is in world space.
  72291. * @param position The world position
  72292. * @param mesh The mesh that this bone is attached to.
  72293. * @returns The local position
  72294. */
  72295. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  72296. if (mesh === void 0) { mesh = null; }
  72297. var result = BABYLON.Vector3.Zero();
  72298. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  72299. return result;
  72300. };
  72301. /**
  72302. * Get the local position of a point that is in world space and copy it to the result param.
  72303. * @param position The world position
  72304. * @param mesh The mesh that this bone is attached to.
  72305. * @param result The vector3 that the local position should be copied to.
  72306. */
  72307. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  72308. if (mesh === void 0) { mesh = null; }
  72309. var wm = null;
  72310. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72311. if (mesh) {
  72312. wm = mesh.getWorldMatrix();
  72313. }
  72314. this._skeleton.computeAbsoluteTransforms();
  72315. var tmat = Bone._tmpMats[0];
  72316. tmat.copyFrom(this.getAbsoluteTransform());
  72317. if (mesh && wm) {
  72318. tmat.multiplyToRef(wm, tmat);
  72319. }
  72320. tmat.invert();
  72321. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72322. };
  72323. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72324. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  72325. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72326. return Bone;
  72327. }(BABYLON.Node));
  72328. BABYLON.Bone = Bone;
  72329. })(BABYLON || (BABYLON = {}));
  72330. //# sourceMappingURL=babylon.bone.js.map
  72331. "use strict";
  72332. var BABYLON;
  72333. (function (BABYLON) {
  72334. var BoneIKController = /** @class */ (function () {
  72335. function BoneIKController(mesh, bone, options) {
  72336. this.targetPosition = BABYLON.Vector3.Zero();
  72337. this.poleTargetPosition = BABYLON.Vector3.Zero();
  72338. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  72339. this.poleAngle = 0;
  72340. this.slerpAmount = 1;
  72341. this._bone1Quat = BABYLON.Quaternion.Identity();
  72342. this._bone1Mat = BABYLON.Matrix.Identity();
  72343. this._bone2Ang = Math.PI;
  72344. this._maxAngle = Math.PI;
  72345. this._rightHandedSystem = false;
  72346. this._bendAxis = BABYLON.Vector3.Right();
  72347. this._slerping = false;
  72348. this._adjustRoll = 0;
  72349. this._bone2 = bone;
  72350. this._bone1 = bone.getParent();
  72351. if (!this._bone1) {
  72352. return;
  72353. }
  72354. this.mesh = mesh;
  72355. var bonePos = bone.getPosition();
  72356. if (bone.getAbsoluteTransform().determinant() > 0) {
  72357. this._rightHandedSystem = true;
  72358. this._bendAxis.x = 0;
  72359. this._bendAxis.y = 0;
  72360. this._bendAxis.z = -1;
  72361. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  72362. this._adjustRoll = Math.PI * .5;
  72363. this._bendAxis.z = 1;
  72364. }
  72365. }
  72366. if (this._bone1.length) {
  72367. var boneScale1 = this._bone1.getScale();
  72368. var boneScale2 = this._bone2.getScale();
  72369. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  72370. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  72371. }
  72372. else if (this._bone1.children[0]) {
  72373. mesh.computeWorldMatrix(true);
  72374. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  72375. var pos2 = this._bone2.getAbsolutePosition(mesh);
  72376. var pos3 = this._bone1.getAbsolutePosition(mesh);
  72377. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  72378. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  72379. }
  72380. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  72381. this.maxAngle = Math.PI;
  72382. if (options) {
  72383. if (options.targetMesh) {
  72384. this.targetMesh = options.targetMesh;
  72385. this.targetMesh.computeWorldMatrix(true);
  72386. }
  72387. if (options.poleTargetMesh) {
  72388. this.poleTargetMesh = options.poleTargetMesh;
  72389. this.poleTargetMesh.computeWorldMatrix(true);
  72390. }
  72391. else if (options.poleTargetBone) {
  72392. this.poleTargetBone = options.poleTargetBone;
  72393. }
  72394. else if (this._bone1.getParent()) {
  72395. this.poleTargetBone = this._bone1.getParent();
  72396. }
  72397. if (options.poleTargetLocalOffset) {
  72398. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  72399. }
  72400. if (options.poleAngle) {
  72401. this.poleAngle = options.poleAngle;
  72402. }
  72403. if (options.bendAxis) {
  72404. this._bendAxis.copyFrom(options.bendAxis);
  72405. }
  72406. if (options.maxAngle) {
  72407. this.maxAngle = options.maxAngle;
  72408. }
  72409. if (options.slerpAmount) {
  72410. this.slerpAmount = options.slerpAmount;
  72411. }
  72412. }
  72413. }
  72414. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  72415. get: function () {
  72416. return this._maxAngle;
  72417. },
  72418. set: function (value) {
  72419. this._setMaxAngle(value);
  72420. },
  72421. enumerable: true,
  72422. configurable: true
  72423. });
  72424. BoneIKController.prototype._setMaxAngle = function (ang) {
  72425. if (ang < 0) {
  72426. ang = 0;
  72427. }
  72428. if (ang > Math.PI || ang == undefined) {
  72429. ang = Math.PI;
  72430. }
  72431. this._maxAngle = ang;
  72432. var a = this._bone1Length;
  72433. var b = this._bone2Length;
  72434. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  72435. };
  72436. BoneIKController.prototype.update = function () {
  72437. var bone1 = this._bone1;
  72438. if (!bone1) {
  72439. return;
  72440. }
  72441. var target = this.targetPosition;
  72442. var poleTarget = this.poleTargetPosition;
  72443. var mat1 = BoneIKController._tmpMats[0];
  72444. var mat2 = BoneIKController._tmpMats[1];
  72445. if (this.targetMesh) {
  72446. target.copyFrom(this.targetMesh.getAbsolutePosition());
  72447. }
  72448. if (this.poleTargetBone) {
  72449. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  72450. }
  72451. else if (this.poleTargetMesh) {
  72452. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  72453. }
  72454. var bonePos = BoneIKController._tmpVecs[0];
  72455. var zaxis = BoneIKController._tmpVecs[1];
  72456. var xaxis = BoneIKController._tmpVecs[2];
  72457. var yaxis = BoneIKController._tmpVecs[3];
  72458. var upAxis = BoneIKController._tmpVecs[4];
  72459. var _tmpQuat = BoneIKController._tmpQuat;
  72460. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  72461. poleTarget.subtractToRef(bonePos, upAxis);
  72462. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  72463. upAxis.y = 1;
  72464. }
  72465. else {
  72466. upAxis.normalize();
  72467. }
  72468. target.subtractToRef(bonePos, yaxis);
  72469. yaxis.normalize();
  72470. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  72471. zaxis.normalize();
  72472. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  72473. xaxis.normalize();
  72474. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  72475. var a = this._bone1Length;
  72476. var b = this._bone2Length;
  72477. var c = BABYLON.Vector3.Distance(bonePos, target);
  72478. if (this._maxReach > 0) {
  72479. c = Math.min(this._maxReach, c);
  72480. }
  72481. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  72482. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  72483. if (acosa > 1) {
  72484. acosa = 1;
  72485. }
  72486. if (acosb > 1) {
  72487. acosb = 1;
  72488. }
  72489. if (acosa < -1) {
  72490. acosa = -1;
  72491. }
  72492. if (acosb < -1) {
  72493. acosb = -1;
  72494. }
  72495. var angA = Math.acos(acosa);
  72496. var angB = Math.acos(acosb);
  72497. var angC = -angA - angB;
  72498. if (this._rightHandedSystem) {
  72499. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  72500. mat2.multiplyToRef(mat1, mat1);
  72501. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  72502. mat2.multiplyToRef(mat1, mat1);
  72503. }
  72504. else {
  72505. var _tmpVec = BoneIKController._tmpVecs[5];
  72506. _tmpVec.copyFrom(this._bendAxis);
  72507. _tmpVec.x *= -1;
  72508. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  72509. mat2.multiplyToRef(mat1, mat1);
  72510. }
  72511. if (this.poleAngle) {
  72512. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  72513. mat1.multiplyToRef(mat2, mat1);
  72514. }
  72515. if (this._bone1) {
  72516. if (this.slerpAmount < 1) {
  72517. if (!this._slerping) {
  72518. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  72519. }
  72520. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  72521. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  72522. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  72523. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  72524. this._slerping = true;
  72525. }
  72526. else {
  72527. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  72528. this._bone1Mat.copyFrom(mat1);
  72529. this._slerping = false;
  72530. }
  72531. }
  72532. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  72533. this._bone2Ang = angC;
  72534. };
  72535. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72536. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  72537. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72538. return BoneIKController;
  72539. }());
  72540. BABYLON.BoneIKController = BoneIKController;
  72541. })(BABYLON || (BABYLON = {}));
  72542. //# sourceMappingURL=babylon.boneIKController.js.map
  72543. "use strict";
  72544. var BABYLON;
  72545. (function (BABYLON) {
  72546. var BoneLookController = /** @class */ (function () {
  72547. /**
  72548. * Create a BoneLookController
  72549. * @param mesh the mesh that the bone belongs to
  72550. * @param bone the bone that will be looking to the target
  72551. * @param target the target Vector3 to look at
  72552. * @param settings optional settings:
  72553. * - maxYaw: the maximum angle the bone will yaw to
  72554. * - minYaw: the minimum angle the bone will yaw to
  72555. * - maxPitch: the maximum angle the bone will pitch to
  72556. * - minPitch: the minimum angle the bone will yaw to
  72557. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  72558. * - upAxis: the up axis of the coordinate system
  72559. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72560. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  72561. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  72562. * - adjustYaw: used to make an adjustment to the yaw of the bone
  72563. * - adjustPitch: used to make an adjustment to the pitch of the bone
  72564. * - adjustRoll: used to make an adjustment to the roll of the bone
  72565. **/
  72566. function BoneLookController(mesh, bone, target, options) {
  72567. /**
  72568. * The up axis of the coordinate system that is used when the bone is rotated.
  72569. */
  72570. this.upAxis = BABYLON.Vector3.Up();
  72571. /**
  72572. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72573. */
  72574. this.upAxisSpace = BABYLON.Space.LOCAL;
  72575. /**
  72576. * Used to make an adjustment to the yaw of the bone.
  72577. */
  72578. this.adjustYaw = 0;
  72579. /**
  72580. * Used to make an adjustment to the pitch of the bone.
  72581. */
  72582. this.adjustPitch = 0;
  72583. /**
  72584. * Used to make an adjustment to the roll of the bone.
  72585. */
  72586. this.adjustRoll = 0;
  72587. /**
  72588. * 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).
  72589. */
  72590. this.slerpAmount = 1;
  72591. this._boneQuat = BABYLON.Quaternion.Identity();
  72592. this._slerping = false;
  72593. this._firstFrameSkipped = false;
  72594. this._fowardAxis = BABYLON.Vector3.Forward();
  72595. this.mesh = mesh;
  72596. this.bone = bone;
  72597. this.target = target;
  72598. if (options) {
  72599. if (options.adjustYaw) {
  72600. this.adjustYaw = options.adjustYaw;
  72601. }
  72602. if (options.adjustPitch) {
  72603. this.adjustPitch = options.adjustPitch;
  72604. }
  72605. if (options.adjustRoll) {
  72606. this.adjustRoll = options.adjustRoll;
  72607. }
  72608. if (options.maxYaw != null) {
  72609. this.maxYaw = options.maxYaw;
  72610. }
  72611. else {
  72612. this.maxYaw = Math.PI;
  72613. }
  72614. if (options.minYaw != null) {
  72615. this.minYaw = options.minYaw;
  72616. }
  72617. else {
  72618. this.minYaw = -Math.PI;
  72619. }
  72620. if (options.maxPitch != null) {
  72621. this.maxPitch = options.maxPitch;
  72622. }
  72623. else {
  72624. this.maxPitch = Math.PI;
  72625. }
  72626. if (options.minPitch != null) {
  72627. this.minPitch = options.minPitch;
  72628. }
  72629. else {
  72630. this.minPitch = -Math.PI;
  72631. }
  72632. if (options.slerpAmount != null) {
  72633. this.slerpAmount = options.slerpAmount;
  72634. }
  72635. if (options.upAxis != null) {
  72636. this.upAxis = options.upAxis;
  72637. }
  72638. if (options.upAxisSpace != null) {
  72639. this.upAxisSpace = options.upAxisSpace;
  72640. }
  72641. if (options.yawAxis != null || options.pitchAxis != null) {
  72642. var newYawAxis = BABYLON.Axis.Y;
  72643. var newPitchAxis = BABYLON.Axis.X;
  72644. if (options.yawAxis != null) {
  72645. newYawAxis = options.yawAxis.clone();
  72646. newYawAxis.normalize();
  72647. }
  72648. if (options.pitchAxis != null) {
  72649. newPitchAxis = options.pitchAxis.clone();
  72650. newPitchAxis.normalize();
  72651. }
  72652. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  72653. this._transformYawPitch = BABYLON.Matrix.Identity();
  72654. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  72655. this._transformYawPitchInv = this._transformYawPitch.clone();
  72656. this._transformYawPitch.invert();
  72657. }
  72658. }
  72659. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  72660. this.upAxisSpace = BABYLON.Space.LOCAL;
  72661. }
  72662. }
  72663. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  72664. /**
  72665. * Get/set the minimum yaw angle that the bone can look to.
  72666. */
  72667. get: function () {
  72668. return this._minYaw;
  72669. },
  72670. set: function (value) {
  72671. this._minYaw = value;
  72672. this._minYawSin = Math.sin(value);
  72673. this._minYawCos = Math.cos(value);
  72674. if (this._maxYaw != null) {
  72675. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72676. this._yawRange = this._maxYaw - this._minYaw;
  72677. }
  72678. },
  72679. enumerable: true,
  72680. configurable: true
  72681. });
  72682. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  72683. /**
  72684. * Get/set the maximum yaw angle that the bone can look to.
  72685. */
  72686. get: function () {
  72687. return this._maxYaw;
  72688. },
  72689. set: function (value) {
  72690. this._maxYaw = value;
  72691. this._maxYawSin = Math.sin(value);
  72692. this._maxYawCos = Math.cos(value);
  72693. if (this._minYaw != null) {
  72694. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72695. this._yawRange = this._maxYaw - this._minYaw;
  72696. }
  72697. },
  72698. enumerable: true,
  72699. configurable: true
  72700. });
  72701. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  72702. /**
  72703. * Get/set the minimum pitch angle that the bone can look to.
  72704. */
  72705. get: function () {
  72706. return this._minPitch;
  72707. },
  72708. set: function (value) {
  72709. this._minPitch = value;
  72710. this._minPitchTan = Math.tan(value);
  72711. },
  72712. enumerable: true,
  72713. configurable: true
  72714. });
  72715. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  72716. /**
  72717. * Get/set the maximum pitch angle that the bone can look to.
  72718. */
  72719. get: function () {
  72720. return this._maxPitch;
  72721. },
  72722. set: function (value) {
  72723. this._maxPitch = value;
  72724. this._maxPitchTan = Math.tan(value);
  72725. },
  72726. enumerable: true,
  72727. configurable: true
  72728. });
  72729. /**
  72730. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  72731. */
  72732. BoneLookController.prototype.update = function () {
  72733. //skip the first frame when slerping so that the mesh rotation is correct
  72734. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  72735. this._firstFrameSkipped = true;
  72736. return;
  72737. }
  72738. var bone = this.bone;
  72739. var bonePos = BoneLookController._tmpVecs[0];
  72740. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  72741. var target = this.target;
  72742. var _tmpMat1 = BoneLookController._tmpMats[0];
  72743. var _tmpMat2 = BoneLookController._tmpMats[1];
  72744. var mesh = this.mesh;
  72745. var parentBone = bone.getParent();
  72746. var upAxis = BoneLookController._tmpVecs[1];
  72747. upAxis.copyFrom(this.upAxis);
  72748. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  72749. if (this._transformYawPitch) {
  72750. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  72751. }
  72752. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  72753. }
  72754. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  72755. mesh.getDirectionToRef(upAxis, upAxis);
  72756. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  72757. upAxis.normalize();
  72758. }
  72759. }
  72760. var checkYaw = false;
  72761. var checkPitch = false;
  72762. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  72763. checkYaw = true;
  72764. }
  72765. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  72766. checkPitch = true;
  72767. }
  72768. if (checkYaw || checkPitch) {
  72769. var spaceMat = BoneLookController._tmpMats[2];
  72770. var spaceMatInv = BoneLookController._tmpMats[3];
  72771. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  72772. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  72773. }
  72774. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  72775. spaceMat.copyFrom(mesh.getWorldMatrix());
  72776. }
  72777. else {
  72778. var forwardAxis = BoneLookController._tmpVecs[2];
  72779. forwardAxis.copyFrom(this._fowardAxis);
  72780. if (this._transformYawPitch) {
  72781. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  72782. }
  72783. if (parentBone) {
  72784. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  72785. }
  72786. else {
  72787. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  72788. }
  72789. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  72790. rightAxis.normalize();
  72791. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  72792. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  72793. }
  72794. spaceMat.invertToRef(spaceMatInv);
  72795. var xzlen = null;
  72796. if (checkPitch) {
  72797. var localTarget = BoneLookController._tmpVecs[3];
  72798. target.subtractToRef(bonePos, localTarget);
  72799. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72800. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72801. var pitch = Math.atan2(localTarget.y, xzlen);
  72802. var newPitch = pitch;
  72803. if (pitch > this._maxPitch) {
  72804. localTarget.y = this._maxPitchTan * xzlen;
  72805. newPitch = this._maxPitch;
  72806. }
  72807. else if (pitch < this._minPitch) {
  72808. localTarget.y = this._minPitchTan * xzlen;
  72809. newPitch = this._minPitch;
  72810. }
  72811. if (pitch != newPitch) {
  72812. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72813. localTarget.addInPlace(bonePos);
  72814. target = localTarget;
  72815. }
  72816. }
  72817. if (checkYaw) {
  72818. var localTarget = BoneLookController._tmpVecs[4];
  72819. target.subtractToRef(bonePos, localTarget);
  72820. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72821. var yaw = Math.atan2(localTarget.x, localTarget.z);
  72822. var newYaw = yaw;
  72823. if (yaw > this._maxYaw || yaw < this._minYaw) {
  72824. if (xzlen == null) {
  72825. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72826. }
  72827. if (this._yawRange > Math.PI) {
  72828. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  72829. localTarget.z = this._maxYawCos * xzlen;
  72830. localTarget.x = this._maxYawSin * xzlen;
  72831. newYaw = this._maxYaw;
  72832. }
  72833. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  72834. localTarget.z = this._minYawCos * xzlen;
  72835. localTarget.x = this._minYawSin * xzlen;
  72836. newYaw = this._minYaw;
  72837. }
  72838. }
  72839. else {
  72840. if (yaw > this._maxYaw) {
  72841. localTarget.z = this._maxYawCos * xzlen;
  72842. localTarget.x = this._maxYawSin * xzlen;
  72843. newYaw = this._maxYaw;
  72844. }
  72845. else if (yaw < this._minYaw) {
  72846. localTarget.z = this._minYawCos * xzlen;
  72847. localTarget.x = this._minYawSin * xzlen;
  72848. newYaw = this._minYaw;
  72849. }
  72850. }
  72851. }
  72852. if (this._slerping && this._yawRange > Math.PI) {
  72853. //are we going to be crossing into the min/max region?
  72854. var boneFwd = BoneLookController._tmpVecs[8];
  72855. boneFwd.copyFrom(BABYLON.Axis.Z);
  72856. if (this._transformYawPitch) {
  72857. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  72858. }
  72859. var boneRotMat = BoneLookController._tmpMats[4];
  72860. this._boneQuat.toRotationMatrix(boneRotMat);
  72861. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  72862. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  72863. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  72864. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  72865. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  72866. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  72867. if (angBtwTar > angBtwMidYaw) {
  72868. if (xzlen == null) {
  72869. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72870. }
  72871. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  72872. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  72873. if (angBtwMin < angBtwMax) {
  72874. newYaw = boneYaw + Math.PI * .75;
  72875. localTarget.z = Math.cos(newYaw) * xzlen;
  72876. localTarget.x = Math.sin(newYaw) * xzlen;
  72877. }
  72878. else {
  72879. newYaw = boneYaw - Math.PI * .75;
  72880. localTarget.z = Math.cos(newYaw) * xzlen;
  72881. localTarget.x = Math.sin(newYaw) * xzlen;
  72882. }
  72883. }
  72884. }
  72885. if (yaw != newYaw) {
  72886. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72887. localTarget.addInPlace(bonePos);
  72888. target = localTarget;
  72889. }
  72890. }
  72891. }
  72892. var zaxis = BoneLookController._tmpVecs[5];
  72893. var xaxis = BoneLookController._tmpVecs[6];
  72894. var yaxis = BoneLookController._tmpVecs[7];
  72895. var _tmpQuat = BoneLookController._tmpQuat;
  72896. target.subtractToRef(bonePos, zaxis);
  72897. zaxis.normalize();
  72898. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  72899. xaxis.normalize();
  72900. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  72901. yaxis.normalize();
  72902. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  72903. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  72904. return;
  72905. }
  72906. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  72907. return;
  72908. }
  72909. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  72910. return;
  72911. }
  72912. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  72913. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  72914. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  72915. }
  72916. if (this.slerpAmount < 1) {
  72917. if (!this._slerping) {
  72918. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  72919. }
  72920. if (this._transformYawPitch) {
  72921. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72922. }
  72923. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  72924. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  72925. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  72926. this._slerping = true;
  72927. }
  72928. else {
  72929. if (this._transformYawPitch) {
  72930. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72931. }
  72932. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  72933. this._slerping = false;
  72934. }
  72935. };
  72936. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  72937. var angDiff = ang2 - ang1;
  72938. angDiff %= Math.PI * 2;
  72939. if (angDiff > Math.PI) {
  72940. angDiff -= Math.PI * 2;
  72941. }
  72942. else if (angDiff < -Math.PI) {
  72943. angDiff += Math.PI * 2;
  72944. }
  72945. return angDiff;
  72946. };
  72947. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  72948. ang1 %= (2 * Math.PI);
  72949. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72950. ang2 %= (2 * Math.PI);
  72951. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72952. var ab = 0;
  72953. if (ang1 < ang2) {
  72954. ab = ang2 - ang1;
  72955. }
  72956. else {
  72957. ab = ang1 - ang2;
  72958. }
  72959. if (ab > Math.PI) {
  72960. ab = Math.PI * 2 - ab;
  72961. }
  72962. return ab;
  72963. };
  72964. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  72965. ang %= (2 * Math.PI);
  72966. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  72967. ang1 %= (2 * Math.PI);
  72968. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72969. ang2 %= (2 * Math.PI);
  72970. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72971. if (ang1 < ang2) {
  72972. if (ang > ang1 && ang < ang2) {
  72973. return true;
  72974. }
  72975. }
  72976. else {
  72977. if (ang > ang2 && ang < ang1) {
  72978. return true;
  72979. }
  72980. }
  72981. return false;
  72982. };
  72983. 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()];
  72984. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  72985. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72986. return BoneLookController;
  72987. }());
  72988. BABYLON.BoneLookController = BoneLookController;
  72989. })(BABYLON || (BABYLON = {}));
  72990. //# sourceMappingURL=babylon.boneLookController.js.map
  72991. "use strict";
  72992. var BABYLON;
  72993. (function (BABYLON) {
  72994. var Skeleton = /** @class */ (function () {
  72995. function Skeleton(name, id, scene) {
  72996. this.name = name;
  72997. this.id = id;
  72998. this.bones = new Array();
  72999. this.needInitialSkinMatrix = false;
  73000. this._isDirty = true;
  73001. this._meshesWithPoseMatrix = new Array();
  73002. this._identity = BABYLON.Matrix.Identity();
  73003. this._ranges = {};
  73004. this._lastAbsoluteTransformsUpdateId = -1;
  73005. /**
  73006. * Specifies if the skeleton should be serialized.
  73007. */
  73008. this.doNotSerialize = false;
  73009. // Events
  73010. /**
  73011. * An event triggered before computing the skeleton's matrices
  73012. * @type {BABYLON.Observable}
  73013. */
  73014. this.onBeforeComputeObservable = new BABYLON.Observable();
  73015. this.bones = [];
  73016. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73017. scene.skeletons.push(this);
  73018. //make sure it will recalculate the matrix next time prepare is called.
  73019. this._isDirty = true;
  73020. }
  73021. // Members
  73022. Skeleton.prototype.getTransformMatrices = function (mesh) {
  73023. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  73024. return mesh._bonesTransformMatrices;
  73025. }
  73026. if (!this._transformMatrices) {
  73027. this.prepare();
  73028. }
  73029. return this._transformMatrices;
  73030. };
  73031. Skeleton.prototype.getScene = function () {
  73032. return this._scene;
  73033. };
  73034. // Methods
  73035. /**
  73036. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  73037. */
  73038. Skeleton.prototype.toString = function (fullDetails) {
  73039. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  73040. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  73041. if (fullDetails) {
  73042. ret += ", Ranges: {";
  73043. var first = true;
  73044. for (var name_1 in this._ranges) {
  73045. if (first) {
  73046. ret += ", ";
  73047. first = false;
  73048. }
  73049. ret += name_1;
  73050. }
  73051. ret += "}";
  73052. }
  73053. return ret;
  73054. };
  73055. /**
  73056. * Get bone's index searching by name
  73057. * @param {string} name is bone's name to search for
  73058. * @return {number} Indice of the bone. Returns -1 if not found
  73059. */
  73060. Skeleton.prototype.getBoneIndexByName = function (name) {
  73061. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  73062. if (this.bones[boneIndex].name === name) {
  73063. return boneIndex;
  73064. }
  73065. }
  73066. return -1;
  73067. };
  73068. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  73069. // check name not already in use
  73070. if (!this._ranges[name]) {
  73071. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  73072. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73073. if (this.bones[i].animations[0]) {
  73074. this.bones[i].animations[0].createRange(name, from, to);
  73075. }
  73076. }
  73077. }
  73078. };
  73079. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  73080. if (deleteFrames === void 0) { deleteFrames = true; }
  73081. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73082. if (this.bones[i].animations[0]) {
  73083. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  73084. }
  73085. }
  73086. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  73087. };
  73088. Skeleton.prototype.getAnimationRange = function (name) {
  73089. return this._ranges[name];
  73090. };
  73091. /**
  73092. * Returns as an Array, all AnimationRanges defined on this skeleton
  73093. */
  73094. Skeleton.prototype.getAnimationRanges = function () {
  73095. var animationRanges = [];
  73096. var name;
  73097. var i = 0;
  73098. for (name in this._ranges) {
  73099. animationRanges[i] = this._ranges[name];
  73100. i++;
  73101. }
  73102. return animationRanges;
  73103. };
  73104. /**
  73105. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  73106. */
  73107. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  73108. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  73109. if (this._ranges[name] || !source.getAnimationRange(name)) {
  73110. return false;
  73111. }
  73112. var ret = true;
  73113. var frameOffset = this._getHighestAnimationFrame() + 1;
  73114. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  73115. var boneDict = {};
  73116. var sourceBones = source.bones;
  73117. var nBones;
  73118. var i;
  73119. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  73120. boneDict[sourceBones[i].name] = sourceBones[i];
  73121. }
  73122. if (this.bones.length !== sourceBones.length) {
  73123. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  73124. ret = false;
  73125. }
  73126. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  73127. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  73128. var boneName = this.bones[i].name;
  73129. var sourceBone = boneDict[boneName];
  73130. if (sourceBone) {
  73131. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  73132. }
  73133. else {
  73134. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  73135. ret = false;
  73136. }
  73137. }
  73138. // do not call createAnimationRange(), since it also is done to bones, which was already done
  73139. var range = source.getAnimationRange(name);
  73140. if (range) {
  73141. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  73142. }
  73143. return ret;
  73144. };
  73145. Skeleton.prototype.returnToRest = function () {
  73146. for (var index = 0; index < this.bones.length; index++) {
  73147. this.bones[index].returnToRest();
  73148. }
  73149. };
  73150. Skeleton.prototype._getHighestAnimationFrame = function () {
  73151. var ret = 0;
  73152. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73153. if (this.bones[i].animations[0]) {
  73154. var highest = this.bones[i].animations[0].getHighestFrame();
  73155. if (ret < highest) {
  73156. ret = highest;
  73157. }
  73158. }
  73159. }
  73160. return ret;
  73161. };
  73162. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  73163. var range = this.getAnimationRange(name);
  73164. if (!range) {
  73165. return null;
  73166. }
  73167. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  73168. };
  73169. Skeleton.prototype._markAsDirty = function () {
  73170. this._isDirty = true;
  73171. };
  73172. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  73173. this._meshesWithPoseMatrix.push(mesh);
  73174. };
  73175. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  73176. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  73177. if (index > -1) {
  73178. this._meshesWithPoseMatrix.splice(index, 1);
  73179. }
  73180. };
  73181. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  73182. this.onBeforeComputeObservable.notifyObservers(this);
  73183. for (var index = 0; index < this.bones.length; index++) {
  73184. var bone = this.bones[index];
  73185. var parentBone = bone.getParent();
  73186. if (parentBone) {
  73187. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  73188. }
  73189. else {
  73190. if (initialSkinMatrix) {
  73191. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  73192. }
  73193. else {
  73194. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  73195. }
  73196. }
  73197. if (bone._index !== -1) {
  73198. var mappedIndex = bone._index === null ? index : bone._index;
  73199. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  73200. }
  73201. }
  73202. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  73203. };
  73204. Skeleton.prototype.prepare = function () {
  73205. if (!this._isDirty) {
  73206. return;
  73207. }
  73208. if (this.needInitialSkinMatrix) {
  73209. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  73210. var mesh = this._meshesWithPoseMatrix[index];
  73211. var poseMatrix = mesh.getPoseMatrix();
  73212. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  73213. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73214. }
  73215. if (this._synchronizedWithMesh !== mesh) {
  73216. this._synchronizedWithMesh = mesh;
  73217. // Prepare bones
  73218. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  73219. var bone = this.bones[boneIndex];
  73220. if (!bone.getParent()) {
  73221. var matrix = bone.getBaseMatrix();
  73222. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  73223. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  73224. }
  73225. }
  73226. }
  73227. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  73228. }
  73229. }
  73230. else {
  73231. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  73232. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73233. }
  73234. this._computeTransformMatrices(this._transformMatrices, null);
  73235. }
  73236. this._isDirty = false;
  73237. this._scene._activeBones.addCount(this.bones.length, false);
  73238. };
  73239. Skeleton.prototype.getAnimatables = function () {
  73240. if (!this._animatables || this._animatables.length !== this.bones.length) {
  73241. this._animatables = [];
  73242. for (var index = 0; index < this.bones.length; index++) {
  73243. this._animatables.push(this.bones[index]);
  73244. }
  73245. }
  73246. return this._animatables;
  73247. };
  73248. Skeleton.prototype.clone = function (name, id) {
  73249. var result = new Skeleton(name, id || name, this._scene);
  73250. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73251. for (var index = 0; index < this.bones.length; index++) {
  73252. var source = this.bones[index];
  73253. var parentBone = null;
  73254. var parent_1 = source.getParent();
  73255. if (parent_1) {
  73256. var parentIndex = this.bones.indexOf(parent_1);
  73257. parentBone = result.bones[parentIndex];
  73258. }
  73259. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  73260. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  73261. }
  73262. if (this._ranges) {
  73263. result._ranges = {};
  73264. for (var rangeName in this._ranges) {
  73265. var range = this._ranges[rangeName];
  73266. if (range) {
  73267. result._ranges[rangeName] = range.clone();
  73268. }
  73269. }
  73270. }
  73271. this._isDirty = true;
  73272. return result;
  73273. };
  73274. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  73275. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  73276. this.bones.forEach(function (bone) {
  73277. bone.animations.forEach(function (animation) {
  73278. animation.enableBlending = true;
  73279. animation.blendingSpeed = blendingSpeed;
  73280. });
  73281. });
  73282. };
  73283. Skeleton.prototype.dispose = function () {
  73284. this._meshesWithPoseMatrix = [];
  73285. // Animations
  73286. this.getScene().stopAnimation(this);
  73287. // Remove from scene
  73288. this.getScene().removeSkeleton(this);
  73289. };
  73290. Skeleton.prototype.serialize = function () {
  73291. var serializationObject = {};
  73292. serializationObject.name = this.name;
  73293. serializationObject.id = this.id;
  73294. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  73295. serializationObject.bones = [];
  73296. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73297. for (var index = 0; index < this.bones.length; index++) {
  73298. var bone = this.bones[index];
  73299. var parent_2 = bone.getParent();
  73300. var serializedBone = {
  73301. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  73302. name: bone.name,
  73303. matrix: bone.getBaseMatrix().toArray(),
  73304. rest: bone.getRestPose().toArray()
  73305. };
  73306. serializationObject.bones.push(serializedBone);
  73307. if (bone.length) {
  73308. serializedBone.length = bone.length;
  73309. }
  73310. if (bone.animations && bone.animations.length > 0) {
  73311. serializedBone.animation = bone.animations[0].serialize();
  73312. }
  73313. serializationObject.ranges = [];
  73314. for (var name in this._ranges) {
  73315. var source = this._ranges[name];
  73316. if (!source) {
  73317. continue;
  73318. }
  73319. var range = {};
  73320. range.name = name;
  73321. range.from = source.from;
  73322. range.to = source.to;
  73323. serializationObject.ranges.push(range);
  73324. }
  73325. }
  73326. return serializationObject;
  73327. };
  73328. Skeleton.Parse = function (parsedSkeleton, scene) {
  73329. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  73330. if (parsedSkeleton.dimensionsAtRest) {
  73331. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  73332. }
  73333. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  73334. var index;
  73335. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  73336. var parsedBone = parsedSkeleton.bones[index];
  73337. var parentBone = null;
  73338. if (parsedBone.parentBoneIndex > -1) {
  73339. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  73340. }
  73341. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  73342. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  73343. if (parsedBone.length) {
  73344. bone.length = parsedBone.length;
  73345. }
  73346. if (parsedBone.animation) {
  73347. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  73348. }
  73349. }
  73350. // placed after bones, so createAnimationRange can cascade down
  73351. if (parsedSkeleton.ranges) {
  73352. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  73353. var data = parsedSkeleton.ranges[index];
  73354. skeleton.createAnimationRange(data.name, data.from, data.to);
  73355. }
  73356. }
  73357. return skeleton;
  73358. };
  73359. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  73360. if (forceUpdate === void 0) { forceUpdate = false; }
  73361. var renderId = this._scene.getRenderId();
  73362. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  73363. this.bones[0].computeAbsoluteTransforms();
  73364. this._lastAbsoluteTransformsUpdateId = renderId;
  73365. }
  73366. };
  73367. Skeleton.prototype.getPoseMatrix = function () {
  73368. var poseMatrix = null;
  73369. if (this._meshesWithPoseMatrix.length > 0) {
  73370. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  73371. }
  73372. return poseMatrix;
  73373. };
  73374. Skeleton.prototype.sortBones = function () {
  73375. var bones = new Array();
  73376. var visited = new Array(this.bones.length);
  73377. for (var index = 0; index < this.bones.length; index++) {
  73378. this._sortBones(index, bones, visited);
  73379. }
  73380. this.bones = bones;
  73381. };
  73382. Skeleton.prototype._sortBones = function (index, bones, visited) {
  73383. if (visited[index]) {
  73384. return;
  73385. }
  73386. visited[index] = true;
  73387. var bone = this.bones[index];
  73388. if (bone._index === undefined) {
  73389. bone._index = index;
  73390. }
  73391. var parentBone = bone.getParent();
  73392. if (parentBone) {
  73393. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  73394. }
  73395. bones.push(bone);
  73396. };
  73397. return Skeleton;
  73398. }());
  73399. BABYLON.Skeleton = Skeleton;
  73400. })(BABYLON || (BABYLON = {}));
  73401. //# sourceMappingURL=babylon.skeleton.js.map
  73402. "use strict";
  73403. var BABYLON;
  73404. (function (BABYLON) {
  73405. var SphericalPolynomial = /** @class */ (function () {
  73406. function SphericalPolynomial() {
  73407. this.x = BABYLON.Vector3.Zero();
  73408. this.y = BABYLON.Vector3.Zero();
  73409. this.z = BABYLON.Vector3.Zero();
  73410. this.xx = BABYLON.Vector3.Zero();
  73411. this.yy = BABYLON.Vector3.Zero();
  73412. this.zz = BABYLON.Vector3.Zero();
  73413. this.xy = BABYLON.Vector3.Zero();
  73414. this.yz = BABYLON.Vector3.Zero();
  73415. this.zx = BABYLON.Vector3.Zero();
  73416. }
  73417. SphericalPolynomial.prototype.addAmbient = function (color) {
  73418. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73419. this.xx = this.xx.add(colorVector);
  73420. this.yy = this.yy.add(colorVector);
  73421. this.zz = this.zz.add(colorVector);
  73422. };
  73423. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  73424. var result = new SphericalPolynomial();
  73425. result.x = harmonics.L11.scale(1.02333);
  73426. result.y = harmonics.L1_1.scale(1.02333);
  73427. result.z = harmonics.L10.scale(1.02333);
  73428. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  73429. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  73430. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  73431. result.yz = harmonics.L2_1.scale(0.858086);
  73432. result.zx = harmonics.L21.scale(0.858086);
  73433. result.xy = harmonics.L2_2.scale(0.858086);
  73434. result.scale(1.0 / Math.PI);
  73435. return result;
  73436. };
  73437. SphericalPolynomial.prototype.scale = function (scale) {
  73438. this.x = this.x.scale(scale);
  73439. this.y = this.y.scale(scale);
  73440. this.z = this.z.scale(scale);
  73441. this.xx = this.xx.scale(scale);
  73442. this.yy = this.yy.scale(scale);
  73443. this.zz = this.zz.scale(scale);
  73444. this.yz = this.yz.scale(scale);
  73445. this.zx = this.zx.scale(scale);
  73446. this.xy = this.xy.scale(scale);
  73447. };
  73448. return SphericalPolynomial;
  73449. }());
  73450. BABYLON.SphericalPolynomial = SphericalPolynomial;
  73451. var SphericalHarmonics = /** @class */ (function () {
  73452. function SphericalHarmonics() {
  73453. this.L00 = BABYLON.Vector3.Zero();
  73454. this.L1_1 = BABYLON.Vector3.Zero();
  73455. this.L10 = BABYLON.Vector3.Zero();
  73456. this.L11 = BABYLON.Vector3.Zero();
  73457. this.L2_2 = BABYLON.Vector3.Zero();
  73458. this.L2_1 = BABYLON.Vector3.Zero();
  73459. this.L20 = BABYLON.Vector3.Zero();
  73460. this.L21 = BABYLON.Vector3.Zero();
  73461. this.L22 = BABYLON.Vector3.Zero();
  73462. }
  73463. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  73464. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73465. var c = colorVector.scale(deltaSolidAngle);
  73466. this.L00 = this.L00.add(c.scale(0.282095));
  73467. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  73468. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  73469. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  73470. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  73471. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  73472. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  73473. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  73474. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  73475. };
  73476. SphericalHarmonics.prototype.scale = function (scale) {
  73477. this.L00 = this.L00.scale(scale);
  73478. this.L1_1 = this.L1_1.scale(scale);
  73479. this.L10 = this.L10.scale(scale);
  73480. this.L11 = this.L11.scale(scale);
  73481. this.L2_2 = this.L2_2.scale(scale);
  73482. this.L2_1 = this.L2_1.scale(scale);
  73483. this.L20 = this.L20.scale(scale);
  73484. this.L21 = this.L21.scale(scale);
  73485. this.L22 = this.L22.scale(scale);
  73486. };
  73487. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  73488. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  73489. //
  73490. // E_lm = A_l * L_lm
  73491. //
  73492. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  73493. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  73494. // the scaling factors are given in equation 9.
  73495. // Constant (Band 0)
  73496. this.L00 = this.L00.scale(3.141593);
  73497. // Linear (Band 1)
  73498. this.L1_1 = this.L1_1.scale(2.094395);
  73499. this.L10 = this.L10.scale(2.094395);
  73500. this.L11 = this.L11.scale(2.094395);
  73501. // Quadratic (Band 2)
  73502. this.L2_2 = this.L2_2.scale(0.785398);
  73503. this.L2_1 = this.L2_1.scale(0.785398);
  73504. this.L20 = this.L20.scale(0.785398);
  73505. this.L21 = this.L21.scale(0.785398);
  73506. this.L22 = this.L22.scale(0.785398);
  73507. };
  73508. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  73509. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  73510. // L = (1/pi) * E * rho
  73511. //
  73512. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  73513. this.scale(1.0 / Math.PI);
  73514. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  73515. // (The pixel shader must apply albedo after texture fetches, etc).
  73516. };
  73517. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  73518. var result = new SphericalHarmonics();
  73519. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  73520. result.L1_1 = polynomial.y.scale(0.977204);
  73521. result.L10 = polynomial.z.scale(0.977204);
  73522. result.L11 = polynomial.x.scale(0.977204);
  73523. result.L2_2 = polynomial.xy.scale(1.16538);
  73524. result.L2_1 = polynomial.yz.scale(1.16538);
  73525. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  73526. result.L21 = polynomial.zx.scale(1.16538);
  73527. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  73528. result.scale(Math.PI);
  73529. return result;
  73530. };
  73531. return SphericalHarmonics;
  73532. }());
  73533. BABYLON.SphericalHarmonics = SphericalHarmonics;
  73534. })(BABYLON || (BABYLON = {}));
  73535. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  73536. "use strict";
  73537. var BABYLON;
  73538. (function (BABYLON) {
  73539. var FileFaceOrientation = /** @class */ (function () {
  73540. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  73541. this.name = name;
  73542. this.worldAxisForNormal = worldAxisForNormal;
  73543. this.worldAxisForFileX = worldAxisForFileX;
  73544. this.worldAxisForFileY = worldAxisForFileY;
  73545. }
  73546. return FileFaceOrientation;
  73547. }());
  73548. ;
  73549. /**
  73550. * Helper class dealing with the extraction of spherical polynomial dataArray
  73551. * from a cube map.
  73552. */
  73553. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  73554. function CubeMapToSphericalPolynomialTools() {
  73555. }
  73556. /**
  73557. * Converts a texture to the according Spherical Polynomial data.
  73558. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73559. *
  73560. * @param texture The texture to extract the information from.
  73561. * @return The Spherical Polynomial data.
  73562. */
  73563. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  73564. if (!texture.isCube) {
  73565. // Only supports cube Textures currently.
  73566. return null;
  73567. }
  73568. var size = texture.getSize().width;
  73569. var right = texture.readPixels(0);
  73570. var left = texture.readPixels(1);
  73571. var up;
  73572. var down;
  73573. if (texture.isRenderTarget) {
  73574. up = texture.readPixels(3);
  73575. down = texture.readPixels(2);
  73576. }
  73577. else {
  73578. up = texture.readPixels(2);
  73579. down = texture.readPixels(3);
  73580. }
  73581. var front = texture.readPixels(4);
  73582. var back = texture.readPixels(5);
  73583. var gammaSpace = texture.gammaSpace;
  73584. // Always read as RGBA.
  73585. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  73586. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73587. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73588. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73589. }
  73590. var cubeInfo = {
  73591. size: size,
  73592. right: right,
  73593. left: left,
  73594. up: up,
  73595. down: down,
  73596. front: front,
  73597. back: back,
  73598. format: format,
  73599. type: type,
  73600. gammaSpace: gammaSpace,
  73601. };
  73602. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  73603. };
  73604. /**
  73605. * Converts a cubemap to the according Spherical Polynomial data.
  73606. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73607. *
  73608. * @param cubeInfo The Cube map to extract the information from.
  73609. * @return The Spherical Polynomial data.
  73610. */
  73611. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  73612. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  73613. var totalSolidAngle = 0.0;
  73614. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  73615. var du = 2.0 / cubeInfo.size;
  73616. var dv = du;
  73617. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  73618. var minUV = du * 0.5 - 1.0;
  73619. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73620. var fileFace = this.FileFaces[faceIndex];
  73621. var dataArray = cubeInfo[fileFace.name];
  73622. var v = minUV;
  73623. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  73624. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  73625. // Because SP is still linear, so summation is fine in that basis.
  73626. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  73627. for (var y = 0; y < cubeInfo.size; y++) {
  73628. var u = minUV;
  73629. for (var x = 0; x < cubeInfo.size; x++) {
  73630. // World direction (not normalised)
  73631. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  73632. worldDirection.normalize();
  73633. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  73634. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  73635. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  73636. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  73637. // Handle Integer types.
  73638. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73639. r /= 255;
  73640. g /= 255;
  73641. b /= 255;
  73642. }
  73643. // Handle Gamma space textures.
  73644. if (cubeInfo.gammaSpace) {
  73645. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  73646. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  73647. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  73648. }
  73649. var color = new BABYLON.Color3(r, g, b);
  73650. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  73651. totalSolidAngle += deltaSolidAngle;
  73652. u += du;
  73653. }
  73654. v += dv;
  73655. }
  73656. }
  73657. // Solid angle for entire sphere is 4*pi
  73658. var sphereSolidAngle = 4.0 * Math.PI;
  73659. // Adjust the solid angle to allow for how many faces we processed.
  73660. var facesProcessed = 6.0;
  73661. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  73662. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  73663. // This is needed because the numerical integration over the cube uses a
  73664. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  73665. // and also to compensate for accumulative error due to float precision in the summation.
  73666. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  73667. sphericalHarmonics.scale(correctionFactor);
  73668. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  73669. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  73670. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  73671. };
  73672. CubeMapToSphericalPolynomialTools.FileFaces = [
  73673. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  73674. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  73675. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  73676. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  73677. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  73678. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  73679. ];
  73680. return CubeMapToSphericalPolynomialTools;
  73681. }());
  73682. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  73683. })(BABYLON || (BABYLON = {}));
  73684. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  73685. "use strict";
  73686. var BABYLON;
  73687. (function (BABYLON) {
  73688. /**
  73689. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  73690. */
  73691. var PanoramaToCubeMapTools = /** @class */ (function () {
  73692. function PanoramaToCubeMapTools() {
  73693. }
  73694. /**
  73695. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  73696. *
  73697. * @param float32Array The source data.
  73698. * @param inputWidth The width of the input panorama.
  73699. * @param inputhHeight The height of the input panorama.
  73700. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  73701. * @return The cubemap data
  73702. */
  73703. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  73704. if (!float32Array) {
  73705. throw "ConvertPanoramaToCubemap: input cannot be null";
  73706. }
  73707. if (float32Array.length != inputWidth * inputHeight * 3) {
  73708. throw "ConvertPanoramaToCubemap: input size is wrong";
  73709. }
  73710. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  73711. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  73712. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  73713. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  73714. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  73715. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  73716. return {
  73717. front: textureFront,
  73718. back: textureBack,
  73719. left: textureLeft,
  73720. right: textureRight,
  73721. up: textureUp,
  73722. down: textureDown,
  73723. size: size,
  73724. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  73725. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  73726. gammaSpace: false,
  73727. };
  73728. };
  73729. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  73730. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  73731. var textureArray = new Float32Array(buffer);
  73732. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  73733. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  73734. var dy = 1 / texSize;
  73735. var fy = 0;
  73736. for (var y = 0; y < texSize; y++) {
  73737. var xv1 = faceData[0];
  73738. var xv2 = faceData[2];
  73739. for (var x = 0; x < texSize; x++) {
  73740. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  73741. v.normalize();
  73742. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  73743. // 3 channels per pixels
  73744. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  73745. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  73746. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  73747. xv1 = xv1.add(rotDX1);
  73748. xv2 = xv2.add(rotDX2);
  73749. }
  73750. fy += dy;
  73751. }
  73752. return textureArray;
  73753. };
  73754. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  73755. var theta = Math.atan2(vDir.z, vDir.x);
  73756. var phi = Math.acos(vDir.y);
  73757. while (theta < -Math.PI)
  73758. theta += 2 * Math.PI;
  73759. while (theta > Math.PI)
  73760. theta -= 2 * Math.PI;
  73761. var dx = theta / Math.PI;
  73762. var dy = phi / Math.PI;
  73763. // recenter.
  73764. dx = dx * 0.5 + 0.5;
  73765. var px = Math.round(dx * inputWidth);
  73766. if (px < 0)
  73767. px = 0;
  73768. else if (px >= inputWidth)
  73769. px = inputWidth - 1;
  73770. var py = Math.round(dy * inputHeight);
  73771. if (py < 0)
  73772. py = 0;
  73773. else if (py >= inputHeight)
  73774. py = inputHeight - 1;
  73775. var inputY = (inputHeight - py - 1);
  73776. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  73777. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  73778. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  73779. return {
  73780. r: r,
  73781. g: g,
  73782. b: b
  73783. };
  73784. };
  73785. PanoramaToCubeMapTools.FACE_FRONT = [
  73786. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73787. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73788. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73789. new BABYLON.Vector3(1.0, 1.0, -1.0)
  73790. ];
  73791. PanoramaToCubeMapTools.FACE_BACK = [
  73792. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73793. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73794. new BABYLON.Vector3(1.0, 1.0, 1.0),
  73795. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  73796. ];
  73797. PanoramaToCubeMapTools.FACE_RIGHT = [
  73798. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73799. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73800. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73801. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73802. ];
  73803. PanoramaToCubeMapTools.FACE_LEFT = [
  73804. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73805. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73806. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73807. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  73808. ];
  73809. PanoramaToCubeMapTools.FACE_DOWN = [
  73810. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73811. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73812. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73813. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73814. ];
  73815. PanoramaToCubeMapTools.FACE_UP = [
  73816. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73817. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73818. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73819. new BABYLON.Vector3(1.0, -1.0, -1.0)
  73820. ];
  73821. return PanoramaToCubeMapTools;
  73822. }());
  73823. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  73824. })(BABYLON || (BABYLON = {}));
  73825. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  73826. "use strict";
  73827. var BABYLON;
  73828. (function (BABYLON) {
  73829. ;
  73830. /**
  73831. * This groups tools to convert HDR texture to native colors array.
  73832. */
  73833. var HDRTools = /** @class */ (function () {
  73834. function HDRTools() {
  73835. }
  73836. HDRTools.Ldexp = function (mantissa, exponent) {
  73837. if (exponent > 1023) {
  73838. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  73839. }
  73840. if (exponent < -1074) {
  73841. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  73842. }
  73843. return mantissa * Math.pow(2, exponent);
  73844. };
  73845. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  73846. if (exponent > 0) {
  73847. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  73848. float32array[index + 0] = red * exponent;
  73849. float32array[index + 1] = green * exponent;
  73850. float32array[index + 2] = blue * exponent;
  73851. }
  73852. else {
  73853. float32array[index + 0] = 0;
  73854. float32array[index + 1] = 0;
  73855. float32array[index + 2] = 0;
  73856. }
  73857. };
  73858. HDRTools.readStringLine = function (uint8array, startIndex) {
  73859. var line = "";
  73860. var character = "";
  73861. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  73862. character = String.fromCharCode(uint8array[i]);
  73863. if (character == "\n") {
  73864. break;
  73865. }
  73866. line += character;
  73867. }
  73868. return line;
  73869. };
  73870. /**
  73871. * Reads header information from an RGBE texture stored in a native array.
  73872. * More information on this format are available here:
  73873. * https://en.wikipedia.org/wiki/RGBE_image_format
  73874. *
  73875. * @param uint8array The binary file stored in native array.
  73876. * @return The header information.
  73877. */
  73878. HDRTools.RGBE_ReadHeader = function (uint8array) {
  73879. var height = 0;
  73880. var width = 0;
  73881. var line = this.readStringLine(uint8array, 0);
  73882. if (line[0] != '#' || line[1] != '?') {
  73883. throw "Bad HDR Format.";
  73884. }
  73885. var endOfHeader = false;
  73886. var findFormat = false;
  73887. var lineIndex = 0;
  73888. do {
  73889. lineIndex += (line.length + 1);
  73890. line = this.readStringLine(uint8array, lineIndex);
  73891. if (line == "FORMAT=32-bit_rle_rgbe") {
  73892. findFormat = true;
  73893. }
  73894. else if (line.length == 0) {
  73895. endOfHeader = true;
  73896. }
  73897. } while (!endOfHeader);
  73898. if (!findFormat) {
  73899. throw "HDR Bad header format, unsupported FORMAT";
  73900. }
  73901. lineIndex += (line.length + 1);
  73902. line = this.readStringLine(uint8array, lineIndex);
  73903. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  73904. var match = sizeRegexp.exec(line);
  73905. // TODO. Support +Y and -X if needed.
  73906. if (!match || match.length < 3) {
  73907. throw "HDR Bad header format, no size";
  73908. }
  73909. width = parseInt(match[2]);
  73910. height = parseInt(match[1]);
  73911. if (width < 8 || width > 0x7fff) {
  73912. throw "HDR Bad header format, unsupported size";
  73913. }
  73914. lineIndex += (line.length + 1);
  73915. return {
  73916. height: height,
  73917. width: width,
  73918. dataPosition: lineIndex
  73919. };
  73920. };
  73921. /**
  73922. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  73923. * This RGBE texture needs to store the information as a panorama.
  73924. *
  73925. * More information on this format are available here:
  73926. * https://en.wikipedia.org/wiki/RGBE_image_format
  73927. *
  73928. * @param buffer The binary file stored in an array buffer.
  73929. * @param size The expected size of the extracted cubemap.
  73930. * @return The Cube Map information.
  73931. */
  73932. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  73933. var uint8array = new Uint8Array(buffer);
  73934. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  73935. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73936. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  73937. return cubeMapData;
  73938. };
  73939. /**
  73940. * Returns the pixels data extracted from an RGBE texture.
  73941. * This pixels will be stored left to right up to down in the R G B order in one array.
  73942. *
  73943. * More information on this format are available here:
  73944. * https://en.wikipedia.org/wiki/RGBE_image_format
  73945. *
  73946. * @param uint8array The binary file stored in an array buffer.
  73947. * @param hdrInfo The header information of the file.
  73948. * @return The pixels data in RGB right to left up to down order.
  73949. */
  73950. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  73951. // Keep for multi format supports.
  73952. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73953. };
  73954. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  73955. var num_scanlines = hdrInfo.height;
  73956. var scanline_width = hdrInfo.width;
  73957. var a, b, c, d, count;
  73958. var dataIndex = hdrInfo.dataPosition;
  73959. var index = 0, endIndex = 0, i = 0;
  73960. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  73961. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  73962. // 3 channels of 4 bytes per pixel in float.
  73963. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  73964. var resultArray = new Float32Array(resultBuffer);
  73965. // read in each successive scanline
  73966. while (num_scanlines > 0) {
  73967. a = uint8array[dataIndex++];
  73968. b = uint8array[dataIndex++];
  73969. c = uint8array[dataIndex++];
  73970. d = uint8array[dataIndex++];
  73971. if (a != 2 || b != 2 || (c & 0x80)) {
  73972. // this file is not run length encoded
  73973. throw "HDR Bad header format, not RLE";
  73974. }
  73975. if (((c << 8) | d) != scanline_width) {
  73976. throw "HDR Bad header format, wrong scan line width";
  73977. }
  73978. index = 0;
  73979. // read each of the four channels for the scanline into the buffer
  73980. for (i = 0; i < 4; i++) {
  73981. endIndex = (i + 1) * scanline_width;
  73982. while (index < endIndex) {
  73983. a = uint8array[dataIndex++];
  73984. b = uint8array[dataIndex++];
  73985. if (a > 128) {
  73986. // a run of the same value
  73987. count = a - 128;
  73988. if ((count == 0) || (count > endIndex - index)) {
  73989. throw "HDR Bad Format, bad scanline data (run)";
  73990. }
  73991. while (count-- > 0) {
  73992. scanLineArray[index++] = b;
  73993. }
  73994. }
  73995. else {
  73996. // a non-run
  73997. count = a;
  73998. if ((count == 0) || (count > endIndex - index)) {
  73999. throw "HDR Bad Format, bad scanline data (non-run)";
  74000. }
  74001. scanLineArray[index++] = b;
  74002. if (--count > 0) {
  74003. for (var j = 0; j < count; j++) {
  74004. scanLineArray[index++] = uint8array[dataIndex++];
  74005. }
  74006. }
  74007. }
  74008. }
  74009. }
  74010. // now convert data from buffer into floats
  74011. for (i = 0; i < scanline_width; i++) {
  74012. a = scanLineArray[i];
  74013. b = scanLineArray[i + scanline_width];
  74014. c = scanLineArray[i + 2 * scanline_width];
  74015. d = scanLineArray[i + 3 * scanline_width];
  74016. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  74017. }
  74018. num_scanlines--;
  74019. }
  74020. return resultArray;
  74021. };
  74022. return HDRTools;
  74023. }());
  74024. BABYLON.HDRTools = HDRTools;
  74025. })(BABYLON || (BABYLON = {}));
  74026. //# sourceMappingURL=babylon.hdr.js.map
  74027. "use strict";
  74028. var BABYLON;
  74029. (function (BABYLON) {
  74030. /**
  74031. * This represents a texture coming from an HDR input.
  74032. *
  74033. * The only supported format is currently panorama picture stored in RGBE format.
  74034. * Example of such files can be found on HDRLib: http://hdrlib.com/
  74035. */
  74036. var HDRCubeTexture = /** @class */ (function (_super) {
  74037. __extends(HDRCubeTexture, _super);
  74038. /**
  74039. * Instantiates an HDRTexture from the following parameters.
  74040. *
  74041. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  74042. * @param scene The scene the texture will be used in
  74043. * @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.
  74044. * @param noMipmap Forces to not generate the mipmap if true
  74045. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  74046. * @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)
  74047. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  74048. */
  74049. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  74050. if (noMipmap === void 0) { noMipmap = false; }
  74051. if (generateHarmonics === void 0) { generateHarmonics = true; }
  74052. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  74053. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  74054. if (onLoad === void 0) { onLoad = null; }
  74055. if (onError === void 0) { onError = null; }
  74056. var _this = _super.call(this, scene) || this;
  74057. _this._useInGammaSpace = false;
  74058. _this._generateHarmonics = true;
  74059. _this._isBABYLONPreprocessed = false;
  74060. _this._onLoad = null;
  74061. _this._onError = null;
  74062. /**
  74063. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  74064. */
  74065. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  74066. /**
  74067. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  74068. * This is usefull at run time to apply the good shader.
  74069. */
  74070. _this.isPMREM = false;
  74071. _this._isBlocking = true;
  74072. /**
  74073. * Gets or sets the center of the bounding box associated with the cube texture
  74074. * It must define where the camera used to render the texture was set
  74075. */
  74076. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  74077. if (!url) {
  74078. return _this;
  74079. }
  74080. _this.name = url;
  74081. _this.url = url;
  74082. _this.hasAlpha = false;
  74083. _this.isCube = true;
  74084. _this._textureMatrix = BABYLON.Matrix.Identity();
  74085. _this._onLoad = onLoad;
  74086. _this._onError = onError;
  74087. _this.gammaSpace = false;
  74088. var caps = scene.getEngine().getCaps();
  74089. if (size) {
  74090. _this._isBABYLONPreprocessed = false;
  74091. _this._noMipmap = noMipmap;
  74092. _this._size = size;
  74093. _this._useInGammaSpace = useInGammaSpace;
  74094. _this._usePMREMGenerator = usePMREMGenerator &&
  74095. caps.textureLOD &&
  74096. caps.textureFloat &&
  74097. !_this._useInGammaSpace;
  74098. }
  74099. else {
  74100. _this._isBABYLONPreprocessed = true;
  74101. _this._noMipmap = false;
  74102. _this._useInGammaSpace = false;
  74103. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  74104. !_this._useInGammaSpace;
  74105. }
  74106. _this.isPMREM = _this._usePMREMGenerator;
  74107. _this._texture = _this._getFromCache(url, _this._noMipmap);
  74108. if (!_this._texture) {
  74109. if (!scene.useDelayedTextureLoading) {
  74110. _this.loadTexture();
  74111. }
  74112. else {
  74113. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  74114. }
  74115. }
  74116. return _this;
  74117. }
  74118. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  74119. /**
  74120. * Gets wether or not the texture is blocking during loading.
  74121. */
  74122. get: function () {
  74123. return this._isBlocking;
  74124. },
  74125. /**
  74126. * Sets wether or not the texture is blocking during loading.
  74127. */
  74128. set: function (value) {
  74129. this._isBlocking = value;
  74130. },
  74131. enumerable: true,
  74132. configurable: true
  74133. });
  74134. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  74135. get: function () {
  74136. return this._boundingBoxSize;
  74137. },
  74138. /**
  74139. * Gets or sets the size of the bounding box associated with the cube texture
  74140. * When defined, the cubemap will switch to local mode
  74141. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  74142. * @example https://www.babylonjs-playground.com/#RNASML
  74143. */
  74144. set: function (value) {
  74145. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  74146. return;
  74147. }
  74148. this._boundingBoxSize = value;
  74149. var scene = this.getScene();
  74150. if (scene) {
  74151. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  74152. }
  74153. },
  74154. enumerable: true,
  74155. configurable: true
  74156. });
  74157. /**
  74158. * Occurs when the file is a preprocessed .babylon.hdr file.
  74159. */
  74160. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  74161. var _this = this;
  74162. var mipLevels = 0;
  74163. var floatArrayView = null;
  74164. var scene = this.getScene();
  74165. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  74166. var mips = new Array();
  74167. if (!floatArrayView) {
  74168. return mips;
  74169. }
  74170. var startIndex = 30;
  74171. for (var level = 0; level < mipLevels; level++) {
  74172. mips.push([]);
  74173. // Fill each pixel of the mip level.
  74174. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  74175. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74176. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  74177. mips[level].push(faceData);
  74178. startIndex += faceSize;
  74179. }
  74180. }
  74181. return mips;
  74182. } : null;
  74183. var callback = function (buffer) {
  74184. var scene = _this.getScene();
  74185. if (!scene) {
  74186. return null;
  74187. }
  74188. // Create Native Array Views
  74189. var intArrayView = new Int32Array(buffer);
  74190. floatArrayView = new Float32Array(buffer);
  74191. // Fill header.
  74192. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  74193. _this._size = intArrayView[1]; // CubeMap max mip face size.
  74194. // Update Texture Information.
  74195. if (!_this._texture) {
  74196. return null;
  74197. }
  74198. _this._texture.updateSize(_this._size, _this._size);
  74199. // Fill polynomial information.
  74200. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  74201. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  74202. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  74203. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  74204. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  74205. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  74206. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  74207. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  74208. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  74209. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  74210. _this.sphericalPolynomial = sphericalPolynomial;
  74211. // Fill pixel data.
  74212. mipLevels = intArrayView[29]; // Number of mip levels.
  74213. var startIndex = 30;
  74214. var data = [];
  74215. var faceSize = Math.pow(_this._size, 2) * 3;
  74216. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74217. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  74218. startIndex += faceSize;
  74219. }
  74220. var results = [];
  74221. var byteArray = null;
  74222. // Push each faces.
  74223. for (var k = 0; k < 6; k++) {
  74224. var dataFace = null;
  74225. // To be deprecated.
  74226. if (version === 1) {
  74227. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  74228. dataFace = data[j];
  74229. }
  74230. // If special cases.
  74231. if (!mipmapGenerator && dataFace) {
  74232. if (!scene.getEngine().getCaps().textureFloat) {
  74233. // 3 channels of 1 bytes per pixel in bytes.
  74234. var byteBuffer = new ArrayBuffer(faceSize);
  74235. byteArray = new Uint8Array(byteBuffer);
  74236. }
  74237. for (var i = 0; i < _this._size * _this._size; i++) {
  74238. // Put in gamma space if requested.
  74239. if (_this._useInGammaSpace) {
  74240. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74241. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74242. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74243. }
  74244. // Convert to int texture for fallback.
  74245. if (byteArray) {
  74246. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74247. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74248. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74249. // May use luminance instead if the result is not accurate.
  74250. var max = Math.max(Math.max(r, g), b);
  74251. if (max > 255) {
  74252. var scale = 255 / max;
  74253. r *= scale;
  74254. g *= scale;
  74255. b *= scale;
  74256. }
  74257. byteArray[(i * 3) + 0] = r;
  74258. byteArray[(i * 3) + 1] = g;
  74259. byteArray[(i * 3) + 2] = b;
  74260. }
  74261. }
  74262. }
  74263. // Fill the array accordingly.
  74264. if (byteArray) {
  74265. results.push(byteArray);
  74266. }
  74267. else {
  74268. results.push(dataFace);
  74269. }
  74270. }
  74271. return results;
  74272. };
  74273. if (scene) {
  74274. 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);
  74275. }
  74276. };
  74277. /**
  74278. * Occurs when the file is raw .hdr file.
  74279. */
  74280. HDRCubeTexture.prototype.loadHDRTexture = function () {
  74281. var _this = this;
  74282. var callback = function (buffer) {
  74283. var scene = _this.getScene();
  74284. if (!scene) {
  74285. return null;
  74286. }
  74287. // Extract the raw linear data.
  74288. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  74289. // Generate harmonics if needed.
  74290. if (_this._generateHarmonics) {
  74291. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  74292. _this.sphericalPolynomial = sphericalPolynomial;
  74293. }
  74294. var results = [];
  74295. var byteArray = null;
  74296. // Push each faces.
  74297. for (var j = 0; j < 6; j++) {
  74298. // Create uintarray fallback.
  74299. if (!scene.getEngine().getCaps().textureFloat) {
  74300. // 3 channels of 1 bytes per pixel in bytes.
  74301. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  74302. byteArray = new Uint8Array(byteBuffer);
  74303. }
  74304. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  74305. // If special cases.
  74306. if (_this._useInGammaSpace || byteArray) {
  74307. for (var i = 0; i < _this._size * _this._size; i++) {
  74308. // Put in gamma space if requested.
  74309. if (_this._useInGammaSpace) {
  74310. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74311. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74312. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74313. }
  74314. // Convert to int texture for fallback.
  74315. if (byteArray) {
  74316. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74317. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74318. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74319. // May use luminance instead if the result is not accurate.
  74320. var max = Math.max(Math.max(r, g), b);
  74321. if (max > 255) {
  74322. var scale = 255 / max;
  74323. r *= scale;
  74324. g *= scale;
  74325. b *= scale;
  74326. }
  74327. byteArray[(i * 3) + 0] = r;
  74328. byteArray[(i * 3) + 1] = g;
  74329. byteArray[(i * 3) + 2] = b;
  74330. }
  74331. }
  74332. }
  74333. if (byteArray) {
  74334. results.push(byteArray);
  74335. }
  74336. else {
  74337. results.push(dataFace);
  74338. }
  74339. }
  74340. return results;
  74341. };
  74342. var mipmapGenerator = null;
  74343. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  74344. // if (!this._noMipmap &&
  74345. // this._usePMREMGenerator) {
  74346. // mipmapGenerator = (data: ArrayBufferView[]) => {
  74347. // // Custom setup of the generator matching with the PBR shader values.
  74348. // var generator = new BABYLON.PMREMGenerator(data,
  74349. // this._size,
  74350. // this._size,
  74351. // 0,
  74352. // 3,
  74353. // this.getScene().getEngine().getCaps().textureFloat,
  74354. // 2048,
  74355. // 0.25,
  74356. // false,
  74357. // true);
  74358. // return generator.filterCubeMap();
  74359. // };
  74360. // }
  74361. var scene = this.getScene();
  74362. if (scene) {
  74363. 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);
  74364. }
  74365. };
  74366. /**
  74367. * Starts the loading process of the texture.
  74368. */
  74369. HDRCubeTexture.prototype.loadTexture = function () {
  74370. if (this._isBABYLONPreprocessed) {
  74371. this.loadBabylonTexture();
  74372. }
  74373. else {
  74374. this.loadHDRTexture();
  74375. }
  74376. };
  74377. HDRCubeTexture.prototype.clone = function () {
  74378. var scene = this.getScene();
  74379. if (!scene) {
  74380. return this;
  74381. }
  74382. var size = (this._isBABYLONPreprocessed ? null : this._size);
  74383. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  74384. // Base texture
  74385. newTexture.level = this.level;
  74386. newTexture.wrapU = this.wrapU;
  74387. newTexture.wrapV = this.wrapV;
  74388. newTexture.coordinatesIndex = this.coordinatesIndex;
  74389. newTexture.coordinatesMode = this.coordinatesMode;
  74390. return newTexture;
  74391. };
  74392. // Methods
  74393. HDRCubeTexture.prototype.delayLoad = function () {
  74394. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  74395. return;
  74396. }
  74397. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  74398. this._texture = this._getFromCache(this.url, this._noMipmap);
  74399. if (!this._texture) {
  74400. this.loadTexture();
  74401. }
  74402. };
  74403. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  74404. return this._textureMatrix;
  74405. };
  74406. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  74407. this._textureMatrix = value;
  74408. };
  74409. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  74410. var texture = null;
  74411. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  74412. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  74413. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  74414. texture.name = parsedTexture.name;
  74415. texture.hasAlpha = parsedTexture.hasAlpha;
  74416. texture.level = parsedTexture.level;
  74417. texture.coordinatesMode = parsedTexture.coordinatesMode;
  74418. texture.isBlocking = parsedTexture.isBlocking;
  74419. }
  74420. if (texture) {
  74421. if (parsedTexture.boundingBoxPosition) {
  74422. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  74423. }
  74424. if (parsedTexture.boundingBoxSize) {
  74425. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  74426. }
  74427. }
  74428. return texture;
  74429. };
  74430. HDRCubeTexture.prototype.serialize = function () {
  74431. if (!this.name) {
  74432. return null;
  74433. }
  74434. var serializationObject = {};
  74435. serializationObject.name = this.name;
  74436. serializationObject.hasAlpha = this.hasAlpha;
  74437. serializationObject.isCube = true;
  74438. serializationObject.level = this.level;
  74439. serializationObject.size = this._size;
  74440. serializationObject.coordinatesMode = this.coordinatesMode;
  74441. serializationObject.useInGammaSpace = this._useInGammaSpace;
  74442. serializationObject.generateHarmonics = this._generateHarmonics;
  74443. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  74444. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  74445. serializationObject.customType = "BABYLON.HDRCubeTexture";
  74446. serializationObject.noMipmap = this._noMipmap;
  74447. serializationObject.isBlocking = this._isBlocking;
  74448. return serializationObject;
  74449. };
  74450. /**
  74451. * Saves as a file the data contained in the texture in a binary format.
  74452. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74453. * as the spherical used in the lighting.
  74454. * @param url The HDR file url.
  74455. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74456. * @param onError Method called if any error happens during download.
  74457. * @return The packed binary data.
  74458. */
  74459. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  74460. if (onError === void 0) { onError = null; }
  74461. var callback = function (buffer) {
  74462. var data = new Blob([buffer], { type: 'application/octet-stream' });
  74463. // Returns a URL you can use as a href.
  74464. var objUrl = window.URL.createObjectURL(data);
  74465. // Simulates a link to it and click to dowload.
  74466. var a = document.createElement("a");
  74467. document.body.appendChild(a);
  74468. a.style.display = "none";
  74469. a.href = objUrl;
  74470. a.download = "envmap.babylon.hdr";
  74471. a.click();
  74472. };
  74473. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  74474. };
  74475. /**
  74476. * Serializes the data contained in the texture in a binary format.
  74477. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74478. * as the spherical used in the lighting.
  74479. * @param url The HDR file url.
  74480. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74481. * @param onError Method called if any error happens during download.
  74482. * @return The packed binary data.
  74483. */
  74484. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  74485. if (onError === void 0) { onError = null; }
  74486. // Needs the url tho create the texture.
  74487. if (!url) {
  74488. return;
  74489. }
  74490. // Check Power of two size.
  74491. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  74492. return;
  74493. }
  74494. // Coming Back in 3.x.
  74495. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  74496. };
  74497. HDRCubeTexture._facesMapping = [
  74498. "right",
  74499. "left",
  74500. "up",
  74501. "down",
  74502. "front",
  74503. "back"
  74504. ];
  74505. return HDRCubeTexture;
  74506. }(BABYLON.BaseTexture));
  74507. BABYLON.HDRCubeTexture = HDRCubeTexture;
  74508. })(BABYLON || (BABYLON = {}));
  74509. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  74510. "use strict";
  74511. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  74512. // Huge respect for a such great lib.
  74513. // Earcut license:
  74514. // Copyright (c) 2016, Mapbox
  74515. //
  74516. // Permission to use, copy, modify, and/or distribute this software for any purpose
  74517. // with or without fee is hereby granted, provided that the above copyright notice
  74518. // and this permission notice appear in all copies.
  74519. //
  74520. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  74521. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  74522. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  74523. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  74524. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  74525. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  74526. // THIS SOFTWARE.
  74527. var Earcut;
  74528. (function (Earcut) {
  74529. /**
  74530. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  74531. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  74532. * @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).
  74533. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  74534. */
  74535. function earcut(data, holeIndices, dim) {
  74536. dim = dim || 2;
  74537. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  74538. if (!outerNode)
  74539. return triangles;
  74540. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  74541. if (hasHoles)
  74542. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  74543. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  74544. if (data.length > 80 * dim) {
  74545. minX = maxX = data[0];
  74546. minY = maxY = data[1];
  74547. for (var i = dim; i < outerLen; i += dim) {
  74548. x = data[i];
  74549. y = data[i + 1];
  74550. if (x < minX)
  74551. minX = x;
  74552. if (y < minY)
  74553. minY = y;
  74554. if (x > maxX)
  74555. maxX = x;
  74556. if (y > maxY)
  74557. maxY = y;
  74558. }
  74559. // minX, minY and size are later used to transform coords into integers for z-order calculation
  74560. size = Math.max(maxX - minX, maxY - minY);
  74561. }
  74562. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  74563. return triangles;
  74564. }
  74565. Earcut.earcut = earcut;
  74566. var Node = /** @class */ (function () {
  74567. function Node(i, x, y) {
  74568. this.i = i;
  74569. this.x = x;
  74570. this.y = y;
  74571. this.prev = null;
  74572. this.next = null;
  74573. this.z = null;
  74574. this.prevZ = null;
  74575. this.nextZ = null;
  74576. this.steiner = false;
  74577. }
  74578. return Node;
  74579. }());
  74580. // create a circular doubly linked list from polygon points in the specified winding order
  74581. function linkedList(data, start, end, dim, clockwise) {
  74582. var i, last = null;
  74583. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  74584. for (i = start; i < end; i += dim)
  74585. last = insertNode(i, data[i], data[i + 1], last);
  74586. }
  74587. else {
  74588. for (i = end - dim; i >= start; i -= dim)
  74589. last = insertNode(i, data[i], data[i + 1], last);
  74590. }
  74591. if (last && equals(last, last.next)) {
  74592. removeNode(last);
  74593. last = last.next;
  74594. }
  74595. return last;
  74596. }
  74597. // eliminate colinear or duplicate points
  74598. function filterPoints(start, end) {
  74599. if (!start)
  74600. return start;
  74601. if (!end)
  74602. end = start;
  74603. var p = start, again;
  74604. do {
  74605. again = false;
  74606. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  74607. removeNode(p);
  74608. p = end = p.prev;
  74609. if (p === p.next)
  74610. return undefined;
  74611. again = true;
  74612. }
  74613. else {
  74614. p = p.next;
  74615. }
  74616. } while (again || p !== end);
  74617. return end;
  74618. }
  74619. // main ear slicing loop which triangulates a polygon (given as a linked list)
  74620. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  74621. if (!ear)
  74622. return;
  74623. // interlink polygon nodes in z-order
  74624. if (!pass && size)
  74625. indexCurve(ear, minX, minY, size);
  74626. var stop = ear, prev, next;
  74627. // iterate through ears, slicing them one by one
  74628. while (ear.prev !== ear.next) {
  74629. prev = ear.prev;
  74630. next = ear.next;
  74631. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  74632. // cut off the triangle
  74633. triangles.push(prev.i / dim);
  74634. triangles.push(ear.i / dim);
  74635. triangles.push(next.i / dim);
  74636. removeNode(ear);
  74637. // skipping the next vertice leads to less sliver triangles
  74638. ear = next.next;
  74639. stop = next.next;
  74640. continue;
  74641. }
  74642. ear = next;
  74643. // if we looped through the whole remaining polygon and can't find any more ears
  74644. if (ear === stop) {
  74645. // try filtering points and slicing again
  74646. if (!pass) {
  74647. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  74648. // if this didn't work, try curing all small self-intersections locally
  74649. }
  74650. else if (pass === 1) {
  74651. ear = cureLocalIntersections(ear, triangles, dim);
  74652. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  74653. // as a last resort, try splitting the remaining polygon into two
  74654. }
  74655. else if (pass === 2) {
  74656. splitEarcut(ear, triangles, dim, minX, minY, size);
  74657. }
  74658. break;
  74659. }
  74660. }
  74661. }
  74662. // check whether a polygon node forms a valid ear with adjacent nodes
  74663. function isEar(ear) {
  74664. var a = ear.prev, b = ear, c = ear.next;
  74665. if (area(a, b, c) >= 0)
  74666. return false; // reflex, can't be an ear
  74667. // now make sure we don't have other points inside the potential ear
  74668. var p = ear.next.next;
  74669. while (p !== ear.prev) {
  74670. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74671. area(p.prev, p, p.next) >= 0)
  74672. return false;
  74673. p = p.next;
  74674. }
  74675. return true;
  74676. }
  74677. function isEarHashed(ear, minX, minY, size) {
  74678. var a = ear.prev, b = ear, c = ear.next;
  74679. if (area(a, b, c) >= 0)
  74680. return false; // reflex, can't be an ear
  74681. // triangle bbox; min & max are calculated like this for speed
  74682. 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);
  74683. // z-order range for the current triangle bbox;
  74684. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  74685. // first look for points inside the triangle in increasing z-order
  74686. var p = ear.nextZ;
  74687. while (p && p.z <= maxZ) {
  74688. if (p !== ear.prev &&
  74689. p !== ear.next &&
  74690. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74691. area(p.prev, p, p.next) >= 0)
  74692. return false;
  74693. p = p.nextZ;
  74694. }
  74695. // then look for points in decreasing z-order
  74696. p = ear.prevZ;
  74697. while (p && p.z >= minZ) {
  74698. if (p !== ear.prev &&
  74699. p !== ear.next &&
  74700. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74701. area(p.prev, p, p.next) >= 0)
  74702. return false;
  74703. p = p.prevZ;
  74704. }
  74705. return true;
  74706. }
  74707. // go through all polygon nodes and cure small local self-intersections
  74708. function cureLocalIntersections(start, triangles, dim) {
  74709. var p = start;
  74710. do {
  74711. var a = p.prev, b = p.next.next;
  74712. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  74713. triangles.push(a.i / dim);
  74714. triangles.push(p.i / dim);
  74715. triangles.push(b.i / dim);
  74716. // remove two nodes involved
  74717. removeNode(p);
  74718. removeNode(p.next);
  74719. p = start = b;
  74720. }
  74721. p = p.next;
  74722. } while (p !== start);
  74723. return p;
  74724. }
  74725. // try splitting polygon into two and triangulate them independently
  74726. function splitEarcut(start, triangles, dim, minX, minY, size) {
  74727. // look for a valid diagonal that divides the polygon into two
  74728. var a = start;
  74729. do {
  74730. var b = a.next.next;
  74731. while (b !== a.prev) {
  74732. if (a.i !== b.i && isValidDiagonal(a, b)) {
  74733. // split the polygon in two by the diagonal
  74734. var c = splitPolygon(a, b);
  74735. // filter colinear points around the cuts
  74736. a = filterPoints(a, a.next);
  74737. c = filterPoints(c, c.next);
  74738. // run earcut on each half
  74739. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  74740. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  74741. return;
  74742. }
  74743. b = b.next;
  74744. }
  74745. a = a.next;
  74746. } while (a !== start);
  74747. }
  74748. // link every hole into the outer loop, producing a single-ring polygon without holes
  74749. function eliminateHoles(data, holeIndices, outerNode, dim) {
  74750. var queue = [], i, len, start, end, list;
  74751. for (i = 0, len = holeIndices.length; i < len; i++) {
  74752. start = holeIndices[i] * dim;
  74753. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74754. list = linkedList(data, start, end, dim, false);
  74755. if (list === list.next)
  74756. list.steiner = true;
  74757. queue.push(getLeftmost(list));
  74758. }
  74759. queue.sort(compareX);
  74760. // process holes from left to right
  74761. for (i = 0; i < queue.length; i++) {
  74762. eliminateHole(queue[i], outerNode);
  74763. outerNode = filterPoints(outerNode, outerNode.next);
  74764. }
  74765. return outerNode;
  74766. }
  74767. function compareX(a, b) {
  74768. return a.x - b.x;
  74769. }
  74770. // find a bridge between vertices that connects hole with an outer ring and and link it
  74771. function eliminateHole(hole, outerNode) {
  74772. outerNode = findHoleBridge(hole, outerNode);
  74773. if (outerNode) {
  74774. var b = splitPolygon(outerNode, hole);
  74775. filterPoints(b, b.next);
  74776. }
  74777. }
  74778. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  74779. function findHoleBridge(hole, outerNode) {
  74780. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  74781. // find a segment intersected by a ray from the hole's leftmost point to the left;
  74782. // segment's endpoint with lesser x will be potential connection point
  74783. do {
  74784. if (hy <= p.y && hy >= p.next.y) {
  74785. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  74786. if (x <= hx && x > qx) {
  74787. qx = x;
  74788. if (x === hx) {
  74789. if (hy === p.y)
  74790. return p;
  74791. if (hy === p.next.y)
  74792. return p.next;
  74793. }
  74794. m = p.x < p.next.x ? p : p.next;
  74795. }
  74796. }
  74797. p = p.next;
  74798. } while (p !== outerNode);
  74799. if (!m)
  74800. return null;
  74801. if (hx === qx)
  74802. return m.prev; // hole touches outer segment; pick lower endpoint
  74803. // look for points inside the triangle of hole point, segment intersection and endpoint;
  74804. // if there are no points found, we have a valid connection;
  74805. // otherwise choose the point of the minimum angle with the ray as connection point
  74806. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  74807. p = m.next;
  74808. while (p !== stop) {
  74809. if (hx >= p.x &&
  74810. p.x >= mx &&
  74811. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  74812. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  74813. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  74814. m = p;
  74815. tanMin = tan;
  74816. }
  74817. }
  74818. p = p.next;
  74819. }
  74820. return m;
  74821. }
  74822. // interlink polygon nodes in z-order
  74823. function indexCurve(start, minX, minY, size) {
  74824. var p = start;
  74825. do {
  74826. if (p.z === null)
  74827. p.z = zOrder(p.x, p.y, minX, minY, size);
  74828. p.prevZ = p.prev;
  74829. p.nextZ = p.next;
  74830. p = p.next;
  74831. } while (p !== start);
  74832. p.prevZ.nextZ = null;
  74833. p.prevZ = null;
  74834. sortLinked(p);
  74835. }
  74836. // Simon Tatham's linked list merge sort algorithm
  74837. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  74838. function sortLinked(list) {
  74839. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  74840. do {
  74841. p = list;
  74842. list = null;
  74843. tail = null;
  74844. numMerges = 0;
  74845. while (p) {
  74846. numMerges++;
  74847. q = p;
  74848. pSize = 0;
  74849. for (i = 0; i < inSize; i++) {
  74850. pSize++;
  74851. q = q.nextZ;
  74852. if (!q)
  74853. break;
  74854. }
  74855. qSize = inSize;
  74856. while (pSize > 0 || (qSize > 0 && q)) {
  74857. if (pSize === 0) {
  74858. e = q;
  74859. q = q.nextZ;
  74860. qSize--;
  74861. }
  74862. else if (qSize === 0 || !q) {
  74863. e = p;
  74864. p = p.nextZ;
  74865. pSize--;
  74866. }
  74867. else if (p.z <= q.z) {
  74868. e = p;
  74869. p = p.nextZ;
  74870. pSize--;
  74871. }
  74872. else {
  74873. e = q;
  74874. q = q.nextZ;
  74875. qSize--;
  74876. }
  74877. if (tail)
  74878. tail.nextZ = e;
  74879. else
  74880. list = e;
  74881. e.prevZ = tail;
  74882. tail = e;
  74883. }
  74884. p = q;
  74885. }
  74886. tail.nextZ = null;
  74887. inSize *= 2;
  74888. } while (numMerges > 1);
  74889. return list;
  74890. }
  74891. // z-order of a point given coords and size of the data bounding box
  74892. function zOrder(x, y, minX, minY, size) {
  74893. // coords are transformed into non-negative 15-bit integer range
  74894. x = 32767 * (x - minX) / size;
  74895. y = 32767 * (y - minY) / size;
  74896. x = (x | (x << 8)) & 0x00FF00FF;
  74897. x = (x | (x << 4)) & 0x0F0F0F0F;
  74898. x = (x | (x << 2)) & 0x33333333;
  74899. x = (x | (x << 1)) & 0x55555555;
  74900. y = (y | (y << 8)) & 0x00FF00FF;
  74901. y = (y | (y << 4)) & 0x0F0F0F0F;
  74902. y = (y | (y << 2)) & 0x33333333;
  74903. y = (y | (y << 1)) & 0x55555555;
  74904. return x | (y << 1);
  74905. }
  74906. // find the leftmost node of a polygon ring
  74907. function getLeftmost(start) {
  74908. var p = start, leftmost = start;
  74909. do {
  74910. if (p.x < leftmost.x)
  74911. leftmost = p;
  74912. p = p.next;
  74913. } while (p !== start);
  74914. return leftmost;
  74915. }
  74916. // check if a point lies within a convex triangle
  74917. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  74918. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  74919. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  74920. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  74921. }
  74922. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  74923. function isValidDiagonal(a, b) {
  74924. return a.next.i !== b.i &&
  74925. a.prev.i !== b.i &&
  74926. !intersectsPolygon(a, b) &&
  74927. locallyInside(a, b) &&
  74928. locallyInside(b, a) &&
  74929. middleInside(a, b);
  74930. }
  74931. // signed area of a triangle
  74932. function area(p, q, r) {
  74933. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  74934. }
  74935. // check if two points are equal
  74936. function equals(p1, p2) {
  74937. return p1.x === p2.x && p1.y === p2.y;
  74938. }
  74939. // check if two segments intersect
  74940. function intersects(p1, q1, p2, q2) {
  74941. if ((equals(p1, q1) && equals(p2, q2)) ||
  74942. (equals(p1, q2) && equals(p2, q1)))
  74943. return true;
  74944. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  74945. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  74946. }
  74947. // check if a polygon diagonal intersects any polygon segments
  74948. function intersectsPolygon(a, b) {
  74949. var p = a;
  74950. do {
  74951. if (p.i !== a.i &&
  74952. p.next.i !== a.i &&
  74953. p.i !== b.i &&
  74954. p.next.i !== b.i &&
  74955. intersects(p, p.next, a, b))
  74956. return true;
  74957. p = p.next;
  74958. } while (p !== a);
  74959. return false;
  74960. }
  74961. // check if a polygon diagonal is locally inside the polygon
  74962. function locallyInside(a, b) {
  74963. return area(a.prev, a, a.next) < 0
  74964. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  74965. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  74966. }
  74967. // check if the middle point of a polygon diagonal is inside the polygon
  74968. function middleInside(a, b) {
  74969. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  74970. do {
  74971. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  74972. inside = !inside;
  74973. p = p.next;
  74974. } while (p !== a);
  74975. return inside;
  74976. }
  74977. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  74978. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  74979. function splitPolygon(a, b) {
  74980. 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;
  74981. a.next = b;
  74982. b.prev = a;
  74983. a2.next = an;
  74984. an.prev = a2;
  74985. b2.next = a2;
  74986. a2.prev = b2;
  74987. bp.next = b2;
  74988. b2.prev = bp;
  74989. return b2;
  74990. }
  74991. // create a node and optionally link it with previous one (in a circular doubly linked list)
  74992. function insertNode(i, x, y, last) {
  74993. var p = new Node(i, x, y);
  74994. if (!last) {
  74995. p.prev = p;
  74996. p.next = p;
  74997. }
  74998. else {
  74999. p.next = last.next;
  75000. p.prev = last;
  75001. last.next.prev = p;
  75002. last.next = p;
  75003. }
  75004. return p;
  75005. }
  75006. function removeNode(p) {
  75007. p.next.prev = p.prev;
  75008. p.prev.next = p.next;
  75009. if (p.prevZ)
  75010. p.prevZ.nextZ = p.nextZ;
  75011. if (p.nextZ)
  75012. p.nextZ.prevZ = p.prevZ;
  75013. }
  75014. /**
  75015. * return a percentage difference between the polygon area and its triangulation area;
  75016. * used to verify correctness of triangulation
  75017. */
  75018. function deviation(data, holeIndices, dim, triangles) {
  75019. var hasHoles = holeIndices && holeIndices.length;
  75020. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  75021. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  75022. if (hasHoles) {
  75023. for (var i = 0, len = holeIndices.length; i < len; i++) {
  75024. var start = holeIndices[i] * dim;
  75025. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75026. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  75027. }
  75028. }
  75029. var trianglesArea = 0;
  75030. for (i = 0; i < triangles.length; i += 3) {
  75031. var a = triangles[i] * dim;
  75032. var b = triangles[i + 1] * dim;
  75033. var c = triangles[i + 2] * dim;
  75034. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  75035. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  75036. }
  75037. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  75038. }
  75039. Earcut.deviation = deviation;
  75040. ;
  75041. function signedArea(data, start, end, dim) {
  75042. var sum = 0;
  75043. for (var i = start, j = end - dim; i < end; i += dim) {
  75044. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  75045. j = i;
  75046. }
  75047. return sum;
  75048. }
  75049. /**
  75050. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  75051. */
  75052. function flatten(data) {
  75053. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  75054. for (var i = 0; i < data.length; i++) {
  75055. for (var j = 0; j < data[i].length; j++) {
  75056. for (var d = 0; d < dim; d++)
  75057. result.vertices.push(data[i][j][d]);
  75058. }
  75059. if (i > 0) {
  75060. holeIndex += data[i - 1].length;
  75061. result.holes.push(holeIndex);
  75062. }
  75063. }
  75064. return result;
  75065. }
  75066. Earcut.flatten = flatten;
  75067. ;
  75068. })(Earcut || (Earcut = {}));
  75069. //# sourceMappingURL=babylon.earcut.js.map
  75070. "use strict";
  75071. var BABYLON;
  75072. (function (BABYLON) {
  75073. var IndexedVector2 = /** @class */ (function (_super) {
  75074. __extends(IndexedVector2, _super);
  75075. function IndexedVector2(original, index) {
  75076. var _this = _super.call(this, original.x, original.y) || this;
  75077. _this.index = index;
  75078. return _this;
  75079. }
  75080. return IndexedVector2;
  75081. }(BABYLON.Vector2));
  75082. var PolygonPoints = /** @class */ (function () {
  75083. function PolygonPoints() {
  75084. this.elements = new Array();
  75085. }
  75086. PolygonPoints.prototype.add = function (originalPoints) {
  75087. var _this = this;
  75088. var result = new Array();
  75089. originalPoints.forEach(function (point) {
  75090. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  75091. var newPoint = new IndexedVector2(point, _this.elements.length);
  75092. result.push(newPoint);
  75093. _this.elements.push(newPoint);
  75094. }
  75095. });
  75096. return result;
  75097. };
  75098. PolygonPoints.prototype.computeBounds = function () {
  75099. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75100. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75101. this.elements.forEach(function (point) {
  75102. // x
  75103. if (point.x < lmin.x) {
  75104. lmin.x = point.x;
  75105. }
  75106. else if (point.x > lmax.x) {
  75107. lmax.x = point.x;
  75108. }
  75109. // y
  75110. if (point.y < lmin.y) {
  75111. lmin.y = point.y;
  75112. }
  75113. else if (point.y > lmax.y) {
  75114. lmax.y = point.y;
  75115. }
  75116. });
  75117. return {
  75118. min: lmin,
  75119. max: lmax,
  75120. width: lmax.x - lmin.x,
  75121. height: lmax.y - lmin.y
  75122. };
  75123. };
  75124. return PolygonPoints;
  75125. }());
  75126. var Polygon = /** @class */ (function () {
  75127. function Polygon() {
  75128. }
  75129. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  75130. return [
  75131. new BABYLON.Vector2(xmin, ymin),
  75132. new BABYLON.Vector2(xmax, ymin),
  75133. new BABYLON.Vector2(xmax, ymax),
  75134. new BABYLON.Vector2(xmin, ymax)
  75135. ];
  75136. };
  75137. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  75138. if (cx === void 0) { cx = 0; }
  75139. if (cy === void 0) { cy = 0; }
  75140. if (numberOfSides === void 0) { numberOfSides = 32; }
  75141. var result = new Array();
  75142. var angle = 0;
  75143. var increment = (Math.PI * 2) / numberOfSides;
  75144. for (var i = 0; i < numberOfSides; i++) {
  75145. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  75146. angle -= increment;
  75147. }
  75148. return result;
  75149. };
  75150. Polygon.Parse = function (input) {
  75151. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  75152. var i, result = [];
  75153. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  75154. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  75155. }
  75156. return result;
  75157. };
  75158. Polygon.StartingAt = function (x, y) {
  75159. return BABYLON.Path2.StartingAt(x, y);
  75160. };
  75161. return Polygon;
  75162. }());
  75163. BABYLON.Polygon = Polygon;
  75164. var PolygonMeshBuilder = /** @class */ (function () {
  75165. function PolygonMeshBuilder(name, contours, scene) {
  75166. this._points = new PolygonPoints();
  75167. this._outlinepoints = new PolygonPoints();
  75168. this._holes = new Array();
  75169. this._epoints = new Array();
  75170. this._eholes = new Array();
  75171. this._name = name;
  75172. this._scene = scene;
  75173. var points;
  75174. if (contours instanceof BABYLON.Path2) {
  75175. points = contours.getPoints();
  75176. }
  75177. else {
  75178. points = contours;
  75179. }
  75180. this._addToepoint(points);
  75181. this._points.add(points);
  75182. this._outlinepoints.add(points);
  75183. }
  75184. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  75185. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  75186. var p = points_1[_i];
  75187. this._epoints.push(p.x, p.y);
  75188. }
  75189. };
  75190. PolygonMeshBuilder.prototype.addHole = function (hole) {
  75191. this._points.add(hole);
  75192. var holepoints = new PolygonPoints();
  75193. holepoints.add(hole);
  75194. this._holes.push(holepoints);
  75195. this._eholes.push(this._epoints.length / 2);
  75196. this._addToepoint(hole);
  75197. return this;
  75198. };
  75199. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  75200. var _this = this;
  75201. if (updatable === void 0) { updatable = false; }
  75202. if (depth === void 0) { depth = 0; }
  75203. var result = new BABYLON.Mesh(this._name, this._scene);
  75204. var normals = new Array();
  75205. var positions = new Array();
  75206. var uvs = new Array();
  75207. var bounds = this._points.computeBounds();
  75208. this._points.elements.forEach(function (p) {
  75209. normals.push(0, 1.0, 0);
  75210. positions.push(p.x, 0, p.y);
  75211. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  75212. });
  75213. var indices = new Array();
  75214. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  75215. for (var i = 0; i < res.length; i++) {
  75216. indices.push(res[i]);
  75217. }
  75218. if (depth > 0) {
  75219. var positionscount = (positions.length / 3); //get the current pointcount
  75220. this._points.elements.forEach(function (p) {
  75221. normals.push(0, -1.0, 0);
  75222. positions.push(p.x, -depth, p.y);
  75223. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  75224. });
  75225. var totalCount = indices.length;
  75226. for (var i = 0; i < totalCount; i += 3) {
  75227. var i0 = indices[i + 0];
  75228. var i1 = indices[i + 1];
  75229. var i2 = indices[i + 2];
  75230. indices.push(i2 + positionscount);
  75231. indices.push(i1 + positionscount);
  75232. indices.push(i0 + positionscount);
  75233. }
  75234. //Add the sides
  75235. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  75236. this._holes.forEach(function (hole) {
  75237. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  75238. });
  75239. }
  75240. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  75241. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  75242. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  75243. result.setIndices(indices);
  75244. return result;
  75245. };
  75246. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  75247. var StartIndex = positions.length / 3;
  75248. var ulength = 0;
  75249. for (var i = 0; i < points.elements.length; i++) {
  75250. var p = points.elements[i];
  75251. var p1;
  75252. if ((i + 1) > points.elements.length - 1) {
  75253. p1 = points.elements[0];
  75254. }
  75255. else {
  75256. p1 = points.elements[i + 1];
  75257. }
  75258. positions.push(p.x, 0, p.y);
  75259. positions.push(p.x, -depth, p.y);
  75260. positions.push(p1.x, 0, p1.y);
  75261. positions.push(p1.x, -depth, p1.y);
  75262. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  75263. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  75264. var v3 = v2.subtract(v1);
  75265. var v4 = new BABYLON.Vector3(0, 1, 0);
  75266. var vn = BABYLON.Vector3.Cross(v3, v4);
  75267. vn = vn.normalize();
  75268. uvs.push(ulength / bounds.width, 0);
  75269. uvs.push(ulength / bounds.width, 1);
  75270. ulength += v3.length();
  75271. uvs.push((ulength / bounds.width), 0);
  75272. uvs.push((ulength / bounds.width), 1);
  75273. if (!flip) {
  75274. normals.push(-vn.x, -vn.y, -vn.z);
  75275. normals.push(-vn.x, -vn.y, -vn.z);
  75276. normals.push(-vn.x, -vn.y, -vn.z);
  75277. normals.push(-vn.x, -vn.y, -vn.z);
  75278. indices.push(StartIndex);
  75279. indices.push(StartIndex + 1);
  75280. indices.push(StartIndex + 2);
  75281. indices.push(StartIndex + 1);
  75282. indices.push(StartIndex + 3);
  75283. indices.push(StartIndex + 2);
  75284. }
  75285. else {
  75286. normals.push(vn.x, vn.y, vn.z);
  75287. normals.push(vn.x, vn.y, vn.z);
  75288. normals.push(vn.x, vn.y, vn.z);
  75289. normals.push(vn.x, vn.y, vn.z);
  75290. indices.push(StartIndex);
  75291. indices.push(StartIndex + 2);
  75292. indices.push(StartIndex + 1);
  75293. indices.push(StartIndex + 1);
  75294. indices.push(StartIndex + 2);
  75295. indices.push(StartIndex + 3);
  75296. }
  75297. StartIndex += 4;
  75298. }
  75299. ;
  75300. };
  75301. return PolygonMeshBuilder;
  75302. }());
  75303. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  75304. })(BABYLON || (BABYLON = {}));
  75305. //# sourceMappingURL=babylon.polygonMesh.js.map
  75306. "use strict";
  75307. var BABYLON;
  75308. (function (BABYLON) {
  75309. // Unique ID when we import meshes from Babylon to CSG
  75310. var currentCSGMeshId = 0;
  75311. // # class Vertex
  75312. // Represents a vertex of a polygon. Use your own vertex class instead of this
  75313. // one to provide additional features like texture coordinates and vertex
  75314. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  75315. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  75316. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  75317. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  75318. // is not used anywhere else.
  75319. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  75320. var Vertex = /** @class */ (function () {
  75321. function Vertex(pos, normal, uv) {
  75322. this.pos = pos;
  75323. this.normal = normal;
  75324. this.uv = uv;
  75325. }
  75326. Vertex.prototype.clone = function () {
  75327. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  75328. };
  75329. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  75330. // orientation of a polygon is flipped.
  75331. Vertex.prototype.flip = function () {
  75332. this.normal = this.normal.scale(-1);
  75333. };
  75334. // Create a new vertex between this vertex and `other` by linearly
  75335. // interpolating all properties using a parameter of `t`. Subclasses should
  75336. // override this to interpolate additional properties.
  75337. Vertex.prototype.interpolate = function (other, t) {
  75338. 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));
  75339. };
  75340. return Vertex;
  75341. }());
  75342. // # class Plane
  75343. // Represents a plane in 3D space.
  75344. var Plane = /** @class */ (function () {
  75345. function Plane(normal, w) {
  75346. this.normal = normal;
  75347. this.w = w;
  75348. }
  75349. Plane.FromPoints = function (a, b, c) {
  75350. var v0 = c.subtract(a);
  75351. var v1 = b.subtract(a);
  75352. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  75353. return null;
  75354. }
  75355. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  75356. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  75357. };
  75358. Plane.prototype.clone = function () {
  75359. return new Plane(this.normal.clone(), this.w);
  75360. };
  75361. Plane.prototype.flip = function () {
  75362. this.normal.scaleInPlace(-1);
  75363. this.w = -this.w;
  75364. };
  75365. // Split `polygon` by this plane if needed, then put the polygon or polygon
  75366. // fragments in the appropriate lists. Coplanar polygons go into either
  75367. // `coplanarFront` or `coplanarBack` depending on their orientation with
  75368. // respect to this plane. Polygons in front or in back of this plane go into
  75369. // either `front` or `back`.
  75370. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  75371. var COPLANAR = 0;
  75372. var FRONT = 1;
  75373. var BACK = 2;
  75374. var SPANNING = 3;
  75375. // Classify each point as well as the entire polygon into one of the above
  75376. // four classes.
  75377. var polygonType = 0;
  75378. var types = [];
  75379. var i;
  75380. var t;
  75381. for (i = 0; i < polygon.vertices.length; i++) {
  75382. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  75383. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  75384. polygonType |= type;
  75385. types.push(type);
  75386. }
  75387. // Put the polygon in the correct list, splitting it when necessary.
  75388. switch (polygonType) {
  75389. case COPLANAR:
  75390. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  75391. break;
  75392. case FRONT:
  75393. front.push(polygon);
  75394. break;
  75395. case BACK:
  75396. back.push(polygon);
  75397. break;
  75398. case SPANNING:
  75399. var f = [], b = [];
  75400. for (i = 0; i < polygon.vertices.length; i++) {
  75401. var j = (i + 1) % polygon.vertices.length;
  75402. var ti = types[i], tj = types[j];
  75403. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  75404. if (ti !== BACK)
  75405. f.push(vi);
  75406. if (ti !== FRONT)
  75407. b.push(ti !== BACK ? vi.clone() : vi);
  75408. if ((ti | tj) === SPANNING) {
  75409. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  75410. var v = vi.interpolate(vj, t);
  75411. f.push(v);
  75412. b.push(v.clone());
  75413. }
  75414. }
  75415. var poly;
  75416. if (f.length >= 3) {
  75417. poly = new Polygon(f, polygon.shared);
  75418. if (poly.plane)
  75419. front.push(poly);
  75420. }
  75421. if (b.length >= 3) {
  75422. poly = new Polygon(b, polygon.shared);
  75423. if (poly.plane)
  75424. back.push(poly);
  75425. }
  75426. break;
  75427. }
  75428. };
  75429. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  75430. // point is on the plane.
  75431. Plane.EPSILON = 1e-5;
  75432. return Plane;
  75433. }());
  75434. // # class Polygon
  75435. // Represents a convex polygon. The vertices used to initialize a polygon must
  75436. // be coplanar and form a convex loop.
  75437. //
  75438. // Each convex polygon has a `shared` property, which is shared between all
  75439. // polygons that are clones of each other or were split from the same polygon.
  75440. // This can be used to define per-polygon properties (such as surface color).
  75441. var Polygon = /** @class */ (function () {
  75442. function Polygon(vertices, shared) {
  75443. this.vertices = vertices;
  75444. this.shared = shared;
  75445. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  75446. }
  75447. Polygon.prototype.clone = function () {
  75448. var vertices = this.vertices.map(function (v) { return v.clone(); });
  75449. return new Polygon(vertices, this.shared);
  75450. };
  75451. Polygon.prototype.flip = function () {
  75452. this.vertices.reverse().map(function (v) { v.flip(); });
  75453. this.plane.flip();
  75454. };
  75455. return Polygon;
  75456. }());
  75457. // # class Node
  75458. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  75459. // by picking a polygon to split along. That polygon (and all other coplanar
  75460. // polygons) are added directly to that node and the other polygons are added to
  75461. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  75462. // no distinction between internal and leaf nodes.
  75463. var Node = /** @class */ (function () {
  75464. function Node(polygons) {
  75465. this.plane = null;
  75466. this.front = null;
  75467. this.back = null;
  75468. this.polygons = new Array();
  75469. if (polygons) {
  75470. this.build(polygons);
  75471. }
  75472. }
  75473. Node.prototype.clone = function () {
  75474. var node = new Node();
  75475. node.plane = this.plane && this.plane.clone();
  75476. node.front = this.front && this.front.clone();
  75477. node.back = this.back && this.back.clone();
  75478. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  75479. return node;
  75480. };
  75481. // Convert solid space to empty space and empty space to solid space.
  75482. Node.prototype.invert = function () {
  75483. for (var i = 0; i < this.polygons.length; i++) {
  75484. this.polygons[i].flip();
  75485. }
  75486. if (this.plane) {
  75487. this.plane.flip();
  75488. }
  75489. if (this.front) {
  75490. this.front.invert();
  75491. }
  75492. if (this.back) {
  75493. this.back.invert();
  75494. }
  75495. var temp = this.front;
  75496. this.front = this.back;
  75497. this.back = temp;
  75498. };
  75499. // Recursively remove all polygons in `polygons` that are inside this BSP
  75500. // tree.
  75501. Node.prototype.clipPolygons = function (polygons) {
  75502. if (!this.plane)
  75503. return polygons.slice();
  75504. var front = new Array(), back = new Array();
  75505. for (var i = 0; i < polygons.length; i++) {
  75506. this.plane.splitPolygon(polygons[i], front, back, front, back);
  75507. }
  75508. if (this.front) {
  75509. front = this.front.clipPolygons(front);
  75510. }
  75511. if (this.back) {
  75512. back = this.back.clipPolygons(back);
  75513. }
  75514. else {
  75515. back = [];
  75516. }
  75517. return front.concat(back);
  75518. };
  75519. // Remove all polygons in this BSP tree that are inside the other BSP tree
  75520. // `bsp`.
  75521. Node.prototype.clipTo = function (bsp) {
  75522. this.polygons = bsp.clipPolygons(this.polygons);
  75523. if (this.front)
  75524. this.front.clipTo(bsp);
  75525. if (this.back)
  75526. this.back.clipTo(bsp);
  75527. };
  75528. // Return a list of all polygons in this BSP tree.
  75529. Node.prototype.allPolygons = function () {
  75530. var polygons = this.polygons.slice();
  75531. if (this.front)
  75532. polygons = polygons.concat(this.front.allPolygons());
  75533. if (this.back)
  75534. polygons = polygons.concat(this.back.allPolygons());
  75535. return polygons;
  75536. };
  75537. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  75538. // new polygons are filtered down to the bottom of the tree and become new
  75539. // nodes there. Each set of polygons is partitioned using the first polygon
  75540. // (no heuristic is used to pick a good split).
  75541. Node.prototype.build = function (polygons) {
  75542. if (!polygons.length)
  75543. return;
  75544. if (!this.plane)
  75545. this.plane = polygons[0].plane.clone();
  75546. var front = new Array(), back = new Array();
  75547. for (var i = 0; i < polygons.length; i++) {
  75548. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  75549. }
  75550. if (front.length) {
  75551. if (!this.front)
  75552. this.front = new Node();
  75553. this.front.build(front);
  75554. }
  75555. if (back.length) {
  75556. if (!this.back)
  75557. this.back = new Node();
  75558. this.back.build(back);
  75559. }
  75560. };
  75561. return Node;
  75562. }());
  75563. var CSG = /** @class */ (function () {
  75564. function CSG() {
  75565. this.polygons = new Array();
  75566. }
  75567. // Convert BABYLON.Mesh to BABYLON.CSG
  75568. CSG.FromMesh = function (mesh) {
  75569. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  75570. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  75571. if (mesh instanceof BABYLON.Mesh) {
  75572. mesh.computeWorldMatrix(true);
  75573. matrix = mesh.getWorldMatrix();
  75574. meshPosition = mesh.position.clone();
  75575. meshRotation = mesh.rotation.clone();
  75576. if (mesh.rotationQuaternion) {
  75577. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  75578. }
  75579. meshScaling = mesh.scaling.clone();
  75580. }
  75581. else {
  75582. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  75583. }
  75584. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75585. var subMeshes = mesh.subMeshes;
  75586. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  75587. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  75588. vertices = [];
  75589. for (var j = 0; j < 3; j++) {
  75590. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  75591. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  75592. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  75593. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  75594. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  75595. vertex = new Vertex(position, normal, uv);
  75596. vertices.push(vertex);
  75597. }
  75598. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  75599. // To handle the case of degenerated triangle
  75600. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  75601. if (polygon.plane)
  75602. polygons.push(polygon);
  75603. }
  75604. }
  75605. var csg = CSG.FromPolygons(polygons);
  75606. csg.matrix = matrix;
  75607. csg.position = meshPosition;
  75608. csg.rotation = meshRotation;
  75609. csg.scaling = meshScaling;
  75610. csg.rotationQuaternion = meshRotationQuaternion;
  75611. currentCSGMeshId++;
  75612. return csg;
  75613. };
  75614. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  75615. CSG.FromPolygons = function (polygons) {
  75616. var csg = new CSG();
  75617. csg.polygons = polygons;
  75618. return csg;
  75619. };
  75620. CSG.prototype.clone = function () {
  75621. var csg = new CSG();
  75622. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  75623. csg.copyTransformAttributes(this);
  75624. return csg;
  75625. };
  75626. CSG.prototype.union = function (csg) {
  75627. var a = new Node(this.clone().polygons);
  75628. var b = new Node(csg.clone().polygons);
  75629. a.clipTo(b);
  75630. b.clipTo(a);
  75631. b.invert();
  75632. b.clipTo(a);
  75633. b.invert();
  75634. a.build(b.allPolygons());
  75635. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75636. };
  75637. CSG.prototype.unionInPlace = function (csg) {
  75638. var a = new Node(this.polygons);
  75639. var b = new Node(csg.polygons);
  75640. a.clipTo(b);
  75641. b.clipTo(a);
  75642. b.invert();
  75643. b.clipTo(a);
  75644. b.invert();
  75645. a.build(b.allPolygons());
  75646. this.polygons = a.allPolygons();
  75647. };
  75648. CSG.prototype.subtract = function (csg) {
  75649. var a = new Node(this.clone().polygons);
  75650. var b = new Node(csg.clone().polygons);
  75651. a.invert();
  75652. a.clipTo(b);
  75653. b.clipTo(a);
  75654. b.invert();
  75655. b.clipTo(a);
  75656. b.invert();
  75657. a.build(b.allPolygons());
  75658. a.invert();
  75659. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75660. };
  75661. CSG.prototype.subtractInPlace = function (csg) {
  75662. var a = new Node(this.polygons);
  75663. var b = new Node(csg.polygons);
  75664. a.invert();
  75665. a.clipTo(b);
  75666. b.clipTo(a);
  75667. b.invert();
  75668. b.clipTo(a);
  75669. b.invert();
  75670. a.build(b.allPolygons());
  75671. a.invert();
  75672. this.polygons = a.allPolygons();
  75673. };
  75674. CSG.prototype.intersect = function (csg) {
  75675. var a = new Node(this.clone().polygons);
  75676. var b = new Node(csg.clone().polygons);
  75677. a.invert();
  75678. b.clipTo(a);
  75679. b.invert();
  75680. a.clipTo(b);
  75681. b.clipTo(a);
  75682. a.build(b.allPolygons());
  75683. a.invert();
  75684. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75685. };
  75686. CSG.prototype.intersectInPlace = function (csg) {
  75687. var a = new Node(this.polygons);
  75688. var b = new Node(csg.polygons);
  75689. a.invert();
  75690. b.clipTo(a);
  75691. b.invert();
  75692. a.clipTo(b);
  75693. b.clipTo(a);
  75694. a.build(b.allPolygons());
  75695. a.invert();
  75696. this.polygons = a.allPolygons();
  75697. };
  75698. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  75699. // not modified.
  75700. CSG.prototype.inverse = function () {
  75701. var csg = this.clone();
  75702. csg.inverseInPlace();
  75703. return csg;
  75704. };
  75705. CSG.prototype.inverseInPlace = function () {
  75706. this.polygons.map(function (p) { p.flip(); });
  75707. };
  75708. // This is used to keep meshes transformations so they can be restored
  75709. // when we build back a Babylon Mesh
  75710. // NB : All CSG operations are performed in world coordinates
  75711. CSG.prototype.copyTransformAttributes = function (csg) {
  75712. this.matrix = csg.matrix;
  75713. this.position = csg.position;
  75714. this.rotation = csg.rotation;
  75715. this.scaling = csg.scaling;
  75716. this.rotationQuaternion = csg.rotationQuaternion;
  75717. return this;
  75718. };
  75719. // Build Raw mesh from CSG
  75720. // Coordinates here are in world space
  75721. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  75722. var matrix = this.matrix.clone();
  75723. matrix.invert();
  75724. 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;
  75725. if (keepSubMeshes) {
  75726. // Sort Polygons, since subMeshes are indices range
  75727. polygons.sort(function (a, b) {
  75728. if (a.shared.meshId === b.shared.meshId) {
  75729. return a.shared.subMeshId - b.shared.subMeshId;
  75730. }
  75731. else {
  75732. return a.shared.meshId - b.shared.meshId;
  75733. }
  75734. });
  75735. }
  75736. for (var i = 0, il = polygons.length; i < il; i++) {
  75737. polygon = polygons[i];
  75738. // Building SubMeshes
  75739. if (!subMesh_dict[polygon.shared.meshId]) {
  75740. subMesh_dict[polygon.shared.meshId] = {};
  75741. }
  75742. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  75743. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  75744. indexStart: +Infinity,
  75745. indexEnd: -Infinity,
  75746. materialIndex: polygon.shared.materialIndex
  75747. };
  75748. }
  75749. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  75750. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  75751. polygonIndices[0] = 0;
  75752. polygonIndices[1] = j - 1;
  75753. polygonIndices[2] = j;
  75754. for (var k = 0; k < 3; k++) {
  75755. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  75756. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  75757. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  75758. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  75759. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  75760. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  75761. // Check if 2 points can be merged
  75762. if (!(typeof vertex_idx !== 'undefined' &&
  75763. normals[vertex_idx * 3] === localNormal.x &&
  75764. normals[vertex_idx * 3 + 1] === localNormal.y &&
  75765. normals[vertex_idx * 3 + 2] === localNormal.z &&
  75766. uvs[vertex_idx * 2] === uv.x &&
  75767. uvs[vertex_idx * 2 + 1] === uv.y)) {
  75768. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  75769. uvs.push(uv.x, uv.y);
  75770. normals.push(normal.x, normal.y, normal.z);
  75771. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  75772. }
  75773. indices.push(vertex_idx);
  75774. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  75775. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  75776. currentIndex++;
  75777. }
  75778. }
  75779. }
  75780. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  75781. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  75782. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  75783. mesh.setIndices(indices, null);
  75784. if (keepSubMeshes) {
  75785. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  75786. var materialIndexOffset = 0, materialMaxIndex;
  75787. mesh.subMeshes = new Array();
  75788. for (var m in subMesh_dict) {
  75789. materialMaxIndex = -1;
  75790. for (var sm in subMesh_dict[m]) {
  75791. subMesh_obj = subMesh_dict[m][sm];
  75792. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  75793. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  75794. }
  75795. materialIndexOffset += ++materialMaxIndex;
  75796. }
  75797. }
  75798. return mesh;
  75799. };
  75800. // Build Mesh from CSG taking material and transforms into account
  75801. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  75802. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  75803. mesh.material = material;
  75804. mesh.position.copyFrom(this.position);
  75805. mesh.rotation.copyFrom(this.rotation);
  75806. if (this.rotationQuaternion) {
  75807. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  75808. }
  75809. mesh.scaling.copyFrom(this.scaling);
  75810. mesh.computeWorldMatrix(true);
  75811. return mesh;
  75812. };
  75813. return CSG;
  75814. }());
  75815. BABYLON.CSG = CSG;
  75816. })(BABYLON || (BABYLON = {}));
  75817. //# sourceMappingURL=babylon.csg.js.map
  75818. "use strict";
  75819. var BABYLON;
  75820. (function (BABYLON) {
  75821. var LensFlare = /** @class */ (function () {
  75822. function LensFlare(size, position, color, imgUrl, system) {
  75823. this.size = size;
  75824. this.position = position;
  75825. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  75826. this.color = color || new BABYLON.Color3(1, 1, 1);
  75827. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  75828. this._system = system;
  75829. system.lensFlares.push(this);
  75830. }
  75831. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  75832. return new LensFlare(size, position, color, imgUrl, system);
  75833. };
  75834. LensFlare.prototype.dispose = function () {
  75835. if (this.texture) {
  75836. this.texture.dispose();
  75837. }
  75838. // Remove from scene
  75839. var index = this._system.lensFlares.indexOf(this);
  75840. this._system.lensFlares.splice(index, 1);
  75841. };
  75842. ;
  75843. return LensFlare;
  75844. }());
  75845. BABYLON.LensFlare = LensFlare;
  75846. })(BABYLON || (BABYLON = {}));
  75847. //# sourceMappingURL=babylon.lensFlare.js.map
  75848. "use strict";
  75849. var BABYLON;
  75850. (function (BABYLON) {
  75851. var LensFlareSystem = /** @class */ (function () {
  75852. function LensFlareSystem(name, emitter, scene) {
  75853. this.name = name;
  75854. this.lensFlares = new Array();
  75855. this.borderLimit = 300;
  75856. this.viewportBorder = 0;
  75857. this.layerMask = 0x0FFFFFFF;
  75858. this._vertexBuffers = {};
  75859. this._isEnabled = true;
  75860. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75861. this._emitter = emitter;
  75862. this.id = name;
  75863. scene.lensFlareSystems.push(this);
  75864. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  75865. var engine = scene.getEngine();
  75866. // VBO
  75867. var vertices = [];
  75868. vertices.push(1, 1);
  75869. vertices.push(-1, 1);
  75870. vertices.push(-1, -1);
  75871. vertices.push(1, -1);
  75872. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75873. // Indices
  75874. var indices = [];
  75875. indices.push(0);
  75876. indices.push(1);
  75877. indices.push(2);
  75878. indices.push(0);
  75879. indices.push(2);
  75880. indices.push(3);
  75881. this._indexBuffer = engine.createIndexBuffer(indices);
  75882. // Effects
  75883. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  75884. }
  75885. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  75886. get: function () {
  75887. return this._isEnabled;
  75888. },
  75889. set: function (value) {
  75890. this._isEnabled = value;
  75891. },
  75892. enumerable: true,
  75893. configurable: true
  75894. });
  75895. LensFlareSystem.prototype.getScene = function () {
  75896. return this._scene;
  75897. };
  75898. LensFlareSystem.prototype.getEmitter = function () {
  75899. return this._emitter;
  75900. };
  75901. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  75902. this._emitter = newEmitter;
  75903. };
  75904. LensFlareSystem.prototype.getEmitterPosition = function () {
  75905. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  75906. };
  75907. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  75908. var position = this.getEmitterPosition();
  75909. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  75910. this._positionX = position.x;
  75911. this._positionY = position.y;
  75912. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  75913. if (this.viewportBorder > 0) {
  75914. globalViewport.x -= this.viewportBorder;
  75915. globalViewport.y -= this.viewportBorder;
  75916. globalViewport.width += this.viewportBorder * 2;
  75917. globalViewport.height += this.viewportBorder * 2;
  75918. position.x += this.viewportBorder;
  75919. position.y += this.viewportBorder;
  75920. this._positionX += this.viewportBorder;
  75921. this._positionY += this.viewportBorder;
  75922. }
  75923. if (position.z > 0) {
  75924. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  75925. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  75926. return true;
  75927. }
  75928. return true;
  75929. }
  75930. return false;
  75931. };
  75932. LensFlareSystem.prototype._isVisible = function () {
  75933. if (!this._isEnabled || !this._scene.activeCamera) {
  75934. return false;
  75935. }
  75936. var emitterPosition = this.getEmitterPosition();
  75937. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  75938. var distance = direction.length();
  75939. direction.normalize();
  75940. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  75941. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  75942. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  75943. };
  75944. LensFlareSystem.prototype.render = function () {
  75945. if (!this._effect.isReady() || !this._scene.activeCamera)
  75946. return false;
  75947. var engine = this._scene.getEngine();
  75948. var viewport = this._scene.activeCamera.viewport;
  75949. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  75950. // Position
  75951. if (!this.computeEffectivePosition(globalViewport)) {
  75952. return false;
  75953. }
  75954. // Visibility
  75955. if (!this._isVisible()) {
  75956. return false;
  75957. }
  75958. // Intensity
  75959. var awayX;
  75960. var awayY;
  75961. if (this._positionX < this.borderLimit + globalViewport.x) {
  75962. awayX = this.borderLimit + globalViewport.x - this._positionX;
  75963. }
  75964. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  75965. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  75966. }
  75967. else {
  75968. awayX = 0;
  75969. }
  75970. if (this._positionY < this.borderLimit + globalViewport.y) {
  75971. awayY = this.borderLimit + globalViewport.y - this._positionY;
  75972. }
  75973. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  75974. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  75975. }
  75976. else {
  75977. awayY = 0;
  75978. }
  75979. var away = (awayX > awayY) ? awayX : awayY;
  75980. away -= this.viewportBorder;
  75981. if (away > this.borderLimit) {
  75982. away = this.borderLimit;
  75983. }
  75984. var intensity = 1.0 - (away / this.borderLimit);
  75985. if (intensity < 0) {
  75986. return false;
  75987. }
  75988. if (intensity > 1.0) {
  75989. intensity = 1.0;
  75990. }
  75991. if (this.viewportBorder > 0) {
  75992. globalViewport.x += this.viewportBorder;
  75993. globalViewport.y += this.viewportBorder;
  75994. globalViewport.width -= this.viewportBorder * 2;
  75995. globalViewport.height -= this.viewportBorder * 2;
  75996. this._positionX -= this.viewportBorder;
  75997. this._positionY -= this.viewportBorder;
  75998. }
  75999. // Position
  76000. var centerX = globalViewport.x + globalViewport.width / 2;
  76001. var centerY = globalViewport.y + globalViewport.height / 2;
  76002. var distX = centerX - this._positionX;
  76003. var distY = centerY - this._positionY;
  76004. // Effects
  76005. engine.enableEffect(this._effect);
  76006. engine.setState(false);
  76007. engine.setDepthBuffer(false);
  76008. // VBOs
  76009. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76010. // Flares
  76011. for (var index = 0; index < this.lensFlares.length; index++) {
  76012. var flare = this.lensFlares[index];
  76013. engine.setAlphaMode(flare.alphaMode);
  76014. var x = centerX - (distX * flare.position);
  76015. var y = centerY - (distY * flare.position);
  76016. var cw = flare.size;
  76017. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  76018. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  76019. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  76020. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  76021. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  76022. // Texture
  76023. this._effect.setTexture("textureSampler", flare.texture);
  76024. // Color
  76025. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  76026. // Draw order
  76027. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76028. }
  76029. engine.setDepthBuffer(true);
  76030. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76031. return true;
  76032. };
  76033. LensFlareSystem.prototype.dispose = function () {
  76034. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76035. if (vertexBuffer) {
  76036. vertexBuffer.dispose();
  76037. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76038. }
  76039. if (this._indexBuffer) {
  76040. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76041. this._indexBuffer = null;
  76042. }
  76043. while (this.lensFlares.length) {
  76044. this.lensFlares[0].dispose();
  76045. }
  76046. // Remove from scene
  76047. var index = this._scene.lensFlareSystems.indexOf(this);
  76048. this._scene.lensFlareSystems.splice(index, 1);
  76049. };
  76050. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  76051. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  76052. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  76053. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  76054. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  76055. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  76056. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  76057. var parsedFlare = parsedLensFlareSystem.flares[index];
  76058. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  76059. }
  76060. return lensFlareSystem;
  76061. };
  76062. LensFlareSystem.prototype.serialize = function () {
  76063. var serializationObject = {};
  76064. serializationObject.id = this.id;
  76065. serializationObject.name = this.name;
  76066. serializationObject.emitterId = this.getEmitter().id;
  76067. serializationObject.borderLimit = this.borderLimit;
  76068. serializationObject.flares = [];
  76069. for (var index = 0; index < this.lensFlares.length; index++) {
  76070. var flare = this.lensFlares[index];
  76071. serializationObject.flares.push({
  76072. size: flare.size,
  76073. position: flare.position,
  76074. color: flare.color.asArray(),
  76075. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  76076. });
  76077. }
  76078. return serializationObject;
  76079. };
  76080. return LensFlareSystem;
  76081. }());
  76082. BABYLON.LensFlareSystem = LensFlareSystem;
  76083. })(BABYLON || (BABYLON = {}));
  76084. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  76085. "use strict";
  76086. var BABYLON;
  76087. (function (BABYLON) {
  76088. /**
  76089. * This is a holder class for the physics joint created by the physics plugin.
  76090. * It holds a set of functions to control the underlying joint.
  76091. */
  76092. var PhysicsJoint = /** @class */ (function () {
  76093. function PhysicsJoint(type, jointData) {
  76094. this.type = type;
  76095. this.jointData = jointData;
  76096. jointData.nativeParams = jointData.nativeParams || {};
  76097. }
  76098. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  76099. get: function () {
  76100. return this._physicsJoint;
  76101. },
  76102. set: function (newJoint) {
  76103. if (this._physicsJoint) {
  76104. //remove from the wolrd
  76105. }
  76106. this._physicsJoint = newJoint;
  76107. },
  76108. enumerable: true,
  76109. configurable: true
  76110. });
  76111. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  76112. set: function (physicsPlugin) {
  76113. this._physicsPlugin = physicsPlugin;
  76114. },
  76115. enumerable: true,
  76116. configurable: true
  76117. });
  76118. /**
  76119. * Execute a function that is physics-plugin specific.
  76120. * @param {Function} func the function that will be executed.
  76121. * It accepts two parameters: the physics world and the physics joint.
  76122. */
  76123. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  76124. func(this._physicsPlugin.world, this._physicsJoint);
  76125. };
  76126. //TODO check if the native joints are the same
  76127. //Joint Types
  76128. PhysicsJoint.DistanceJoint = 0;
  76129. PhysicsJoint.HingeJoint = 1;
  76130. PhysicsJoint.BallAndSocketJoint = 2;
  76131. PhysicsJoint.WheelJoint = 3;
  76132. PhysicsJoint.SliderJoint = 4;
  76133. //OIMO
  76134. PhysicsJoint.PrismaticJoint = 5;
  76135. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  76136. PhysicsJoint.UniversalJoint = 6;
  76137. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  76138. //Cannon
  76139. //Similar to a Ball-Joint. Different in params
  76140. PhysicsJoint.PointToPointJoint = 8;
  76141. //Cannon only at the moment
  76142. PhysicsJoint.SpringJoint = 9;
  76143. PhysicsJoint.LockJoint = 10;
  76144. return PhysicsJoint;
  76145. }());
  76146. BABYLON.PhysicsJoint = PhysicsJoint;
  76147. /**
  76148. * A class representing a physics distance joint.
  76149. */
  76150. var DistanceJoint = /** @class */ (function (_super) {
  76151. __extends(DistanceJoint, _super);
  76152. function DistanceJoint(jointData) {
  76153. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  76154. }
  76155. /**
  76156. * Update the predefined distance.
  76157. */
  76158. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  76159. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  76160. };
  76161. return DistanceJoint;
  76162. }(PhysicsJoint));
  76163. BABYLON.DistanceJoint = DistanceJoint;
  76164. var MotorEnabledJoint = /** @class */ (function (_super) {
  76165. __extends(MotorEnabledJoint, _super);
  76166. function MotorEnabledJoint(type, jointData) {
  76167. return _super.call(this, type, jointData) || this;
  76168. }
  76169. /**
  76170. * Set the motor values.
  76171. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76172. * @param {number} force the force to apply
  76173. * @param {number} maxForce max force for this motor.
  76174. */
  76175. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  76176. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76177. };
  76178. /**
  76179. * Set the motor's limits.
  76180. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76181. */
  76182. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76183. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76184. };
  76185. return MotorEnabledJoint;
  76186. }(PhysicsJoint));
  76187. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  76188. /**
  76189. * This class represents a single hinge physics joint
  76190. */
  76191. var HingeJoint = /** @class */ (function (_super) {
  76192. __extends(HingeJoint, _super);
  76193. function HingeJoint(jointData) {
  76194. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  76195. }
  76196. /**
  76197. * Set the motor values.
  76198. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76199. * @param {number} force the force to apply
  76200. * @param {number} maxForce max force for this motor.
  76201. */
  76202. HingeJoint.prototype.setMotor = function (force, maxForce) {
  76203. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76204. };
  76205. /**
  76206. * Set the motor's limits.
  76207. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76208. */
  76209. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76210. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76211. };
  76212. return HingeJoint;
  76213. }(MotorEnabledJoint));
  76214. BABYLON.HingeJoint = HingeJoint;
  76215. /**
  76216. * This class represents a dual hinge physics joint (same as wheel joint)
  76217. */
  76218. var Hinge2Joint = /** @class */ (function (_super) {
  76219. __extends(Hinge2Joint, _super);
  76220. function Hinge2Joint(jointData) {
  76221. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  76222. }
  76223. /**
  76224. * Set the motor values.
  76225. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76226. * @param {number} force the force to apply
  76227. * @param {number} maxForce max force for this motor.
  76228. * @param {motorIndex} the motor's index, 0 or 1.
  76229. */
  76230. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  76231. if (motorIndex === void 0) { motorIndex = 0; }
  76232. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  76233. };
  76234. /**
  76235. * Set the motor limits.
  76236. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76237. * @param {number} upperLimit the upper limit
  76238. * @param {number} lowerLimit lower limit
  76239. * @param {motorIndex} the motor's index, 0 or 1.
  76240. */
  76241. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  76242. if (motorIndex === void 0) { motorIndex = 0; }
  76243. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  76244. };
  76245. return Hinge2Joint;
  76246. }(MotorEnabledJoint));
  76247. BABYLON.Hinge2Joint = Hinge2Joint;
  76248. })(BABYLON || (BABYLON = {}));
  76249. //# sourceMappingURL=babylon.physicsJoint.js.map
  76250. "use strict";
  76251. var BABYLON;
  76252. (function (BABYLON) {
  76253. var PhysicsImpostor = /** @class */ (function () {
  76254. function PhysicsImpostor(object, type, _options, _scene) {
  76255. if (_options === void 0) { _options = { mass: 0 }; }
  76256. var _this = this;
  76257. this.object = object;
  76258. this.type = type;
  76259. this._options = _options;
  76260. this._scene = _scene;
  76261. this._bodyUpdateRequired = false;
  76262. this._onBeforePhysicsStepCallbacks = new Array();
  76263. this._onAfterPhysicsStepCallbacks = new Array();
  76264. this._onPhysicsCollideCallbacks = [];
  76265. this._deltaPosition = BABYLON.Vector3.Zero();
  76266. this._isDisposed = false;
  76267. //temp variables for parent rotation calculations
  76268. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  76269. this._tmpQuat = new BABYLON.Quaternion();
  76270. this._tmpQuat2 = new BABYLON.Quaternion();
  76271. /**
  76272. * this function is executed by the physics engine.
  76273. */
  76274. this.beforeStep = function () {
  76275. if (!_this._physicsEngine) {
  76276. return;
  76277. }
  76278. _this.object.translate(_this._deltaPosition, -1);
  76279. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  76280. _this.object.computeWorldMatrix(false);
  76281. if (_this.object.parent && _this.object.rotationQuaternion) {
  76282. _this.getParentsRotation();
  76283. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  76284. }
  76285. else {
  76286. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  76287. }
  76288. if (!_this._options.disableBidirectionalTransformation) {
  76289. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  76290. }
  76291. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  76292. func(_this);
  76293. });
  76294. };
  76295. /**
  76296. * this function is executed by the physics engine.
  76297. */
  76298. this.afterStep = function () {
  76299. if (!_this._physicsEngine) {
  76300. return;
  76301. }
  76302. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  76303. func(_this);
  76304. });
  76305. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  76306. // object has now its world rotation. needs to be converted to local.
  76307. if (_this.object.parent && _this.object.rotationQuaternion) {
  76308. _this.getParentsRotation();
  76309. _this._tmpQuat.conjugateInPlace();
  76310. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  76311. }
  76312. // take the position set and make it the absolute position of this object.
  76313. _this.object.setAbsolutePosition(_this.object.position);
  76314. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  76315. _this.object.translate(_this._deltaPosition, 1);
  76316. };
  76317. /**
  76318. * Legacy collision detection event support
  76319. */
  76320. this.onCollideEvent = null;
  76321. //event and body object due to cannon's event-based architecture.
  76322. this.onCollide = function (e) {
  76323. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  76324. return;
  76325. }
  76326. if (!_this._physicsEngine) {
  76327. return;
  76328. }
  76329. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  76330. if (otherImpostor) {
  76331. // Legacy collision detection event support
  76332. if (_this.onCollideEvent) {
  76333. _this.onCollideEvent(_this, otherImpostor);
  76334. }
  76335. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  76336. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  76337. }).forEach(function (obj) {
  76338. obj.callback(_this, otherImpostor);
  76339. });
  76340. }
  76341. };
  76342. //sanity check!
  76343. if (!this.object) {
  76344. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  76345. return;
  76346. }
  76347. //legacy support for old syntax.
  76348. if (!this._scene && object.getScene) {
  76349. this._scene = object.getScene();
  76350. }
  76351. if (!this._scene) {
  76352. return;
  76353. }
  76354. this._physicsEngine = this._scene.getPhysicsEngine();
  76355. if (!this._physicsEngine) {
  76356. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  76357. }
  76358. else {
  76359. //set the object's quaternion, if not set
  76360. if (!this.object.rotationQuaternion) {
  76361. if (this.object.rotation) {
  76362. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  76363. }
  76364. else {
  76365. this.object.rotationQuaternion = new BABYLON.Quaternion();
  76366. }
  76367. }
  76368. //default options params
  76369. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  76370. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  76371. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  76372. this._joints = [];
  76373. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  76374. if (!this.object.parent || this._options.ignoreParent) {
  76375. this._init();
  76376. }
  76377. else if (this.object.parent.physicsImpostor) {
  76378. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  76379. }
  76380. }
  76381. }
  76382. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  76383. get: function () {
  76384. return this._isDisposed;
  76385. },
  76386. enumerable: true,
  76387. configurable: true
  76388. });
  76389. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  76390. get: function () {
  76391. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  76392. },
  76393. set: function (value) {
  76394. this.setMass(value);
  76395. },
  76396. enumerable: true,
  76397. configurable: true
  76398. });
  76399. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  76400. get: function () {
  76401. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  76402. },
  76403. set: function (value) {
  76404. if (!this._physicsEngine) {
  76405. return;
  76406. }
  76407. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  76408. },
  76409. enumerable: true,
  76410. configurable: true
  76411. });
  76412. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  76413. get: function () {
  76414. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  76415. },
  76416. set: function (value) {
  76417. if (!this._physicsEngine) {
  76418. return;
  76419. }
  76420. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  76421. },
  76422. enumerable: true,
  76423. configurable: true
  76424. });
  76425. /**
  76426. * This function will completly initialize this impostor.
  76427. * It will create a new body - but only if this mesh has no parent.
  76428. * If it has, this impostor will not be used other than to define the impostor
  76429. * of the child mesh.
  76430. */
  76431. PhysicsImpostor.prototype._init = function () {
  76432. if (!this._physicsEngine) {
  76433. return;
  76434. }
  76435. this._physicsEngine.removeImpostor(this);
  76436. this.physicsBody = null;
  76437. this._parent = this._parent || this._getPhysicsParent();
  76438. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  76439. this._physicsEngine.addImpostor(this);
  76440. }
  76441. };
  76442. PhysicsImpostor.prototype._getPhysicsParent = function () {
  76443. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  76444. var parentMesh = this.object.parent;
  76445. return parentMesh.physicsImpostor;
  76446. }
  76447. return null;
  76448. };
  76449. /**
  76450. * Should a new body be generated.
  76451. */
  76452. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  76453. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  76454. };
  76455. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  76456. this.forceUpdate();
  76457. };
  76458. /**
  76459. * Force a regeneration of this or the parent's impostor's body.
  76460. * Use under cautious - This will remove all joints already implemented.
  76461. */
  76462. PhysicsImpostor.prototype.forceUpdate = function () {
  76463. this._init();
  76464. if (this.parent && !this._options.ignoreParent) {
  76465. this.parent.forceUpdate();
  76466. }
  76467. };
  76468. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  76469. /*public get mesh(): AbstractMesh {
  76470. return this._mesh;
  76471. }*/
  76472. /**
  76473. * Gets the body that holds this impostor. Either its own, or its parent.
  76474. */
  76475. get: function () {
  76476. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  76477. },
  76478. /**
  76479. * Set the physics body. Used mainly by the physics engine/plugin
  76480. */
  76481. set: function (physicsBody) {
  76482. if (this._physicsBody && this._physicsEngine) {
  76483. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  76484. }
  76485. this._physicsBody = physicsBody;
  76486. this.resetUpdateFlags();
  76487. },
  76488. enumerable: true,
  76489. configurable: true
  76490. });
  76491. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  76492. get: function () {
  76493. return !this._options.ignoreParent && this._parent ? this._parent : null;
  76494. },
  76495. set: function (value) {
  76496. this._parent = value;
  76497. },
  76498. enumerable: true,
  76499. configurable: true
  76500. });
  76501. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  76502. this._bodyUpdateRequired = false;
  76503. };
  76504. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  76505. if (this.object.getBoundingInfo) {
  76506. var q = this.object.rotationQuaternion;
  76507. //reset rotation
  76508. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  76509. //calculate the world matrix with no rotation
  76510. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76511. var boundingInfo = this.object.getBoundingInfo();
  76512. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  76513. //bring back the rotation
  76514. this.object.rotationQuaternion = q;
  76515. //calculate the world matrix with the new rotation
  76516. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76517. return size;
  76518. }
  76519. else {
  76520. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  76521. }
  76522. };
  76523. PhysicsImpostor.prototype.getObjectCenter = function () {
  76524. if (this.object.getBoundingInfo) {
  76525. var boundingInfo = this.object.getBoundingInfo();
  76526. return boundingInfo.boundingBox.centerWorld;
  76527. }
  76528. else {
  76529. return this.object.position;
  76530. }
  76531. };
  76532. /**
  76533. * Get a specific parametes from the options parameter.
  76534. */
  76535. PhysicsImpostor.prototype.getParam = function (paramName) {
  76536. return this._options[paramName];
  76537. };
  76538. /**
  76539. * Sets a specific parameter in the options given to the physics plugin
  76540. */
  76541. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  76542. this._options[paramName] = value;
  76543. this._bodyUpdateRequired = true;
  76544. };
  76545. /**
  76546. * Specifically change the body's mass option. Won't recreate the physics body object
  76547. */
  76548. PhysicsImpostor.prototype.setMass = function (mass) {
  76549. if (this.getParam("mass") !== mass) {
  76550. this.setParam("mass", mass);
  76551. }
  76552. if (this._physicsEngine) {
  76553. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  76554. }
  76555. };
  76556. PhysicsImpostor.prototype.getLinearVelocity = function () {
  76557. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  76558. };
  76559. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  76560. if (this._physicsEngine) {
  76561. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  76562. }
  76563. };
  76564. PhysicsImpostor.prototype.getAngularVelocity = function () {
  76565. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  76566. };
  76567. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  76568. if (this._physicsEngine) {
  76569. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  76570. }
  76571. };
  76572. /**
  76573. * Execute a function with the physics plugin native code.
  76574. * Provide a function the will have two variables - the world object and the physics body object.
  76575. */
  76576. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  76577. if (this._physicsEngine) {
  76578. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  76579. }
  76580. };
  76581. /**
  76582. * Register a function that will be executed before the physics world is stepping forward.
  76583. */
  76584. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  76585. this._onBeforePhysicsStepCallbacks.push(func);
  76586. };
  76587. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  76588. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  76589. if (index > -1) {
  76590. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  76591. }
  76592. else {
  76593. BABYLON.Tools.Warn("Function to remove was not found");
  76594. }
  76595. };
  76596. /**
  76597. * Register a function that will be executed after the physics step
  76598. */
  76599. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  76600. this._onAfterPhysicsStepCallbacks.push(func);
  76601. };
  76602. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  76603. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  76604. if (index > -1) {
  76605. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  76606. }
  76607. else {
  76608. BABYLON.Tools.Warn("Function to remove was not found");
  76609. }
  76610. };
  76611. /**
  76612. * register a function that will be executed when this impostor collides against a different body.
  76613. */
  76614. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  76615. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76616. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  76617. };
  76618. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  76619. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76620. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  76621. if (index > -1) {
  76622. this._onPhysicsCollideCallbacks.splice(index, 1);
  76623. }
  76624. else {
  76625. BABYLON.Tools.Warn("Function to remove was not found");
  76626. }
  76627. };
  76628. PhysicsImpostor.prototype.getParentsRotation = function () {
  76629. var parent = this.object.parent;
  76630. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  76631. while (parent) {
  76632. if (parent.rotationQuaternion) {
  76633. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  76634. }
  76635. else {
  76636. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  76637. }
  76638. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  76639. parent = parent.parent;
  76640. }
  76641. return this._tmpQuat;
  76642. };
  76643. /**
  76644. * Apply a force
  76645. */
  76646. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  76647. if (this._physicsEngine) {
  76648. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  76649. }
  76650. return this;
  76651. };
  76652. /**
  76653. * Apply an impulse
  76654. */
  76655. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  76656. if (this._physicsEngine) {
  76657. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  76658. }
  76659. return this;
  76660. };
  76661. /**
  76662. * A help function to create a joint.
  76663. */
  76664. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  76665. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  76666. this.addJoint(otherImpostor, joint);
  76667. return this;
  76668. };
  76669. /**
  76670. * Add a joint to this impostor with a different impostor.
  76671. */
  76672. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  76673. this._joints.push({
  76674. otherImpostor: otherImpostor,
  76675. joint: joint
  76676. });
  76677. if (this._physicsEngine) {
  76678. this._physicsEngine.addJoint(this, otherImpostor, joint);
  76679. }
  76680. return this;
  76681. };
  76682. /**
  76683. * Will keep this body still, in a sleep mode.
  76684. */
  76685. PhysicsImpostor.prototype.sleep = function () {
  76686. if (this._physicsEngine) {
  76687. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  76688. }
  76689. return this;
  76690. };
  76691. /**
  76692. * Wake the body up.
  76693. */
  76694. PhysicsImpostor.prototype.wakeUp = function () {
  76695. if (this._physicsEngine) {
  76696. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  76697. }
  76698. return this;
  76699. };
  76700. PhysicsImpostor.prototype.clone = function (newObject) {
  76701. if (!newObject)
  76702. return null;
  76703. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  76704. };
  76705. PhysicsImpostor.prototype.dispose = function () {
  76706. var _this = this;
  76707. //no dispose if no physics engine is available.
  76708. if (!this._physicsEngine) {
  76709. return;
  76710. }
  76711. this._joints.forEach(function (j) {
  76712. if (_this._physicsEngine) {
  76713. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  76714. }
  76715. });
  76716. //dispose the physics body
  76717. this._physicsEngine.removeImpostor(this);
  76718. if (this.parent) {
  76719. this.parent.forceUpdate();
  76720. }
  76721. else {
  76722. /*this._object.getChildMeshes().forEach(function(mesh) {
  76723. if (mesh.physicsImpostor) {
  76724. if (disposeChildren) {
  76725. mesh.physicsImpostor.dispose();
  76726. mesh.physicsImpostor = null;
  76727. }
  76728. }
  76729. })*/
  76730. }
  76731. this._isDisposed = true;
  76732. };
  76733. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  76734. this._deltaPosition.copyFrom(position);
  76735. };
  76736. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  76737. if (!this._deltaRotation) {
  76738. this._deltaRotation = new BABYLON.Quaternion();
  76739. }
  76740. this._deltaRotation.copyFrom(rotation);
  76741. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  76742. };
  76743. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  76744. if (this._physicsEngine) {
  76745. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  76746. }
  76747. return this;
  76748. };
  76749. PhysicsImpostor.prototype.getRadius = function () {
  76750. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  76751. };
  76752. /**
  76753. * Sync a bone with this impostor
  76754. * @param bone The bone to sync to the impostor.
  76755. * @param boneMesh The mesh that the bone is influencing.
  76756. * @param jointPivot The pivot of the joint / bone in local space.
  76757. * @param distToJoint Optional distance from the impostor to the joint.
  76758. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76759. */
  76760. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  76761. var tempVec = PhysicsImpostor._tmpVecs[0];
  76762. var mesh = this.object;
  76763. if (mesh.rotationQuaternion) {
  76764. if (adjustRotation) {
  76765. var tempQuat = PhysicsImpostor._tmpQuat;
  76766. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  76767. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  76768. }
  76769. else {
  76770. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  76771. }
  76772. }
  76773. tempVec.x = 0;
  76774. tempVec.y = 0;
  76775. tempVec.z = 0;
  76776. if (jointPivot) {
  76777. tempVec.x = jointPivot.x;
  76778. tempVec.y = jointPivot.y;
  76779. tempVec.z = jointPivot.z;
  76780. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  76781. if (distToJoint === undefined || distToJoint === null) {
  76782. distToJoint = jointPivot.length();
  76783. }
  76784. tempVec.x *= distToJoint;
  76785. tempVec.y *= distToJoint;
  76786. tempVec.z *= distToJoint;
  76787. }
  76788. if (bone.getParent()) {
  76789. tempVec.addInPlace(mesh.getAbsolutePosition());
  76790. bone.setAbsolutePosition(tempVec, boneMesh);
  76791. }
  76792. else {
  76793. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  76794. boneMesh.position.x -= tempVec.x;
  76795. boneMesh.position.y -= tempVec.y;
  76796. boneMesh.position.z -= tempVec.z;
  76797. }
  76798. };
  76799. /**
  76800. * Sync impostor to a bone
  76801. * @param bone The bone that the impostor will be synced to.
  76802. * @param boneMesh The mesh that the bone is influencing.
  76803. * @param jointPivot The pivot of the joint / bone in local space.
  76804. * @param distToJoint Optional distance from the impostor to the joint.
  76805. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76806. * @param boneAxis Optional vector3 axis the bone is aligned with
  76807. */
  76808. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  76809. var mesh = this.object;
  76810. if (mesh.rotationQuaternion) {
  76811. if (adjustRotation) {
  76812. var tempQuat = PhysicsImpostor._tmpQuat;
  76813. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  76814. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  76815. }
  76816. else {
  76817. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  76818. }
  76819. }
  76820. var pos = PhysicsImpostor._tmpVecs[0];
  76821. var boneDir = PhysicsImpostor._tmpVecs[1];
  76822. if (!boneAxis) {
  76823. boneAxis = PhysicsImpostor._tmpVecs[2];
  76824. boneAxis.x = 0;
  76825. boneAxis.y = 1;
  76826. boneAxis.z = 0;
  76827. }
  76828. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  76829. bone.getAbsolutePositionToRef(boneMesh, pos);
  76830. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  76831. distToJoint = jointPivot.length();
  76832. }
  76833. if (distToJoint !== undefined && distToJoint !== null) {
  76834. pos.x += boneDir.x * distToJoint;
  76835. pos.y += boneDir.y * distToJoint;
  76836. pos.z += boneDir.z * distToJoint;
  76837. }
  76838. mesh.setAbsolutePosition(pos);
  76839. };
  76840. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  76841. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  76842. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76843. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  76844. //Impostor types
  76845. PhysicsImpostor.NoImpostor = 0;
  76846. PhysicsImpostor.SphereImpostor = 1;
  76847. PhysicsImpostor.BoxImpostor = 2;
  76848. PhysicsImpostor.PlaneImpostor = 3;
  76849. PhysicsImpostor.MeshImpostor = 4;
  76850. PhysicsImpostor.CylinderImpostor = 7;
  76851. PhysicsImpostor.ParticleImpostor = 8;
  76852. PhysicsImpostor.HeightmapImpostor = 9;
  76853. return PhysicsImpostor;
  76854. }());
  76855. BABYLON.PhysicsImpostor = PhysicsImpostor;
  76856. })(BABYLON || (BABYLON = {}));
  76857. //# sourceMappingURL=babylon.physicsImpostor.js.map
  76858. "use strict";
  76859. var BABYLON;
  76860. (function (BABYLON) {
  76861. var PhysicsEngine = /** @class */ (function () {
  76862. function PhysicsEngine(gravity, _physicsPlugin) {
  76863. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  76864. this._physicsPlugin = _physicsPlugin;
  76865. //new methods and parameters
  76866. this._impostors = [];
  76867. this._joints = [];
  76868. if (!this._physicsPlugin.isSupported()) {
  76869. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  76870. + "Please make sure it is included.");
  76871. }
  76872. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  76873. this.setGravity(gravity);
  76874. this.setTimeStep();
  76875. }
  76876. PhysicsEngine.prototype.setGravity = function (gravity) {
  76877. this.gravity = gravity;
  76878. this._physicsPlugin.setGravity(this.gravity);
  76879. };
  76880. /**
  76881. * Set the time step of the physics engine.
  76882. * default is 1/60.
  76883. * To slow it down, enter 1/600 for example.
  76884. * To speed it up, 1/30
  76885. * @param {number} newTimeStep the new timestep to apply to this world.
  76886. */
  76887. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  76888. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  76889. this._physicsPlugin.setTimeStep(newTimeStep);
  76890. };
  76891. /**
  76892. * Get the time step of the physics engine.
  76893. */
  76894. PhysicsEngine.prototype.getTimeStep = function () {
  76895. return this._physicsPlugin.getTimeStep();
  76896. };
  76897. PhysicsEngine.prototype.dispose = function () {
  76898. this._impostors.forEach(function (impostor) {
  76899. impostor.dispose();
  76900. });
  76901. this._physicsPlugin.dispose();
  76902. };
  76903. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  76904. return this._physicsPlugin.name;
  76905. };
  76906. /**
  76907. * Adding a new impostor for the impostor tracking.
  76908. * This will be done by the impostor itself.
  76909. * @param {PhysicsImpostor} impostor the impostor to add
  76910. */
  76911. PhysicsEngine.prototype.addImpostor = function (impostor) {
  76912. impostor.uniqueId = this._impostors.push(impostor);
  76913. //if no parent, generate the body
  76914. if (!impostor.parent) {
  76915. this._physicsPlugin.generatePhysicsBody(impostor);
  76916. }
  76917. };
  76918. /**
  76919. * Remove an impostor from the engine.
  76920. * This impostor and its mesh will not longer be updated by the physics engine.
  76921. * @param {PhysicsImpostor} impostor the impostor to remove
  76922. */
  76923. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  76924. var index = this._impostors.indexOf(impostor);
  76925. if (index > -1) {
  76926. var removed = this._impostors.splice(index, 1);
  76927. //Is it needed?
  76928. if (removed.length) {
  76929. //this will also remove it from the world.
  76930. removed[0].physicsBody = null;
  76931. }
  76932. }
  76933. };
  76934. /**
  76935. * Add a joint to the physics engine
  76936. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  76937. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  76938. * @param {PhysicsJoint} the joint that will connect both impostors.
  76939. */
  76940. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  76941. var impostorJoint = {
  76942. mainImpostor: mainImpostor,
  76943. connectedImpostor: connectedImpostor,
  76944. joint: joint
  76945. };
  76946. joint.physicsPlugin = this._physicsPlugin;
  76947. this._joints.push(impostorJoint);
  76948. this._physicsPlugin.generateJoint(impostorJoint);
  76949. };
  76950. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  76951. var matchingJoints = this._joints.filter(function (impostorJoint) {
  76952. return (impostorJoint.connectedImpostor === connectedImpostor
  76953. && impostorJoint.joint === joint
  76954. && impostorJoint.mainImpostor === mainImpostor);
  76955. });
  76956. if (matchingJoints.length) {
  76957. this._physicsPlugin.removeJoint(matchingJoints[0]);
  76958. //TODO remove it from the list as well
  76959. }
  76960. };
  76961. /**
  76962. * Called by the scene. no need to call it.
  76963. */
  76964. PhysicsEngine.prototype._step = function (delta) {
  76965. var _this = this;
  76966. //check if any mesh has no body / requires an update
  76967. this._impostors.forEach(function (impostor) {
  76968. if (impostor.isBodyInitRequired()) {
  76969. _this._physicsPlugin.generatePhysicsBody(impostor);
  76970. }
  76971. });
  76972. if (delta > 0.1) {
  76973. delta = 0.1;
  76974. }
  76975. else if (delta <= 0) {
  76976. delta = 1.0 / 60.0;
  76977. }
  76978. this._physicsPlugin.executeStep(delta, this._impostors);
  76979. };
  76980. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  76981. return this._physicsPlugin;
  76982. };
  76983. PhysicsEngine.prototype.getImpostors = function () {
  76984. return this._impostors;
  76985. };
  76986. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  76987. for (var i = 0; i < this._impostors.length; ++i) {
  76988. if (this._impostors[i].object === object) {
  76989. return this._impostors[i];
  76990. }
  76991. }
  76992. return null;
  76993. };
  76994. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  76995. for (var i = 0; i < this._impostors.length; ++i) {
  76996. if (this._impostors[i].physicsBody === body) {
  76997. return this._impostors[i];
  76998. }
  76999. }
  77000. return null;
  77001. };
  77002. // Statics
  77003. PhysicsEngine.Epsilon = 0.001;
  77004. return PhysicsEngine;
  77005. }());
  77006. BABYLON.PhysicsEngine = PhysicsEngine;
  77007. })(BABYLON || (BABYLON = {}));
  77008. //# sourceMappingURL=babylon.physicsEngine.js.map
  77009. "use strict";
  77010. var BABYLON;
  77011. (function (BABYLON) {
  77012. var PhysicsHelper = /** @class */ (function () {
  77013. function PhysicsHelper(scene) {
  77014. this._scene = scene;
  77015. this._physicsEngine = this._scene.getPhysicsEngine();
  77016. if (!this._physicsEngine) {
  77017. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  77018. }
  77019. }
  77020. /**
  77021. * @param {Vector3} origin the origin of the explosion
  77022. * @param {number} radius the explosion radius
  77023. * @param {number} strength the explosion strength
  77024. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77025. */
  77026. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  77027. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77028. if (!this._physicsEngine) {
  77029. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  77030. return null;
  77031. }
  77032. var impostors = this._physicsEngine.getImpostors();
  77033. if (impostors.length === 0) {
  77034. return null;
  77035. }
  77036. var event = new PhysicsRadialExplosionEvent(this._scene);
  77037. impostors.forEach(function (impostor) {
  77038. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77039. if (!impostorForceAndContactPoint) {
  77040. return;
  77041. }
  77042. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77043. });
  77044. event.dispose(false);
  77045. return event;
  77046. };
  77047. /**
  77048. * @param {Vector3} origin the origin of the explosion
  77049. * @param {number} radius the explosion radius
  77050. * @param {number} strength the explosion strength
  77051. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77052. */
  77053. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  77054. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77055. if (!this._physicsEngine) {
  77056. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77057. return null;
  77058. }
  77059. var impostors = this._physicsEngine.getImpostors();
  77060. if (impostors.length === 0) {
  77061. return null;
  77062. }
  77063. var event = new PhysicsRadialExplosionEvent(this._scene);
  77064. impostors.forEach(function (impostor) {
  77065. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77066. if (!impostorForceAndContactPoint) {
  77067. return;
  77068. }
  77069. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77070. });
  77071. event.dispose(false);
  77072. return event;
  77073. };
  77074. /**
  77075. * @param {Vector3} origin the origin of the explosion
  77076. * @param {number} radius the explosion radius
  77077. * @param {number} strength the explosion strength
  77078. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77079. */
  77080. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  77081. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77082. if (!this._physicsEngine) {
  77083. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77084. return null;
  77085. }
  77086. var impostors = this._physicsEngine.getImpostors();
  77087. if (impostors.length === 0) {
  77088. return null;
  77089. }
  77090. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  77091. event.dispose(false);
  77092. return event;
  77093. };
  77094. /**
  77095. * @param {Vector3} origin the origin of the updraft
  77096. * @param {number} radius the radius of the updraft
  77097. * @param {number} strength the strength of the updraft
  77098. * @param {number} height the height of the updraft
  77099. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  77100. */
  77101. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  77102. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  77103. if (!this._physicsEngine) {
  77104. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77105. return null;
  77106. }
  77107. if (this._physicsEngine.getImpostors().length === 0) {
  77108. return null;
  77109. }
  77110. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  77111. event.dispose(false);
  77112. return event;
  77113. };
  77114. /**
  77115. * @param {Vector3} origin the of the vortex
  77116. * @param {number} radius the radius of the vortex
  77117. * @param {number} strength the strength of the vortex
  77118. * @param {number} height the height of the vortex
  77119. */
  77120. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  77121. if (!this._physicsEngine) {
  77122. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77123. return null;
  77124. }
  77125. if (this._physicsEngine.getImpostors().length === 0) {
  77126. return null;
  77127. }
  77128. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  77129. event.dispose(false);
  77130. return event;
  77131. };
  77132. return PhysicsHelper;
  77133. }());
  77134. BABYLON.PhysicsHelper = PhysicsHelper;
  77135. /***** Radial explosion *****/
  77136. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  77137. function PhysicsRadialExplosionEvent(scene) {
  77138. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  77139. this._rays = [];
  77140. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  77141. this._scene = scene;
  77142. }
  77143. /**
  77144. * Returns the data related to the radial explosion event (sphere & rays).
  77145. * @returns {PhysicsRadialExplosionEventData}
  77146. */
  77147. PhysicsRadialExplosionEvent.prototype.getData = function () {
  77148. this._dataFetched = true;
  77149. return {
  77150. sphere: this._sphere,
  77151. rays: this._rays,
  77152. };
  77153. };
  77154. /**
  77155. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  77156. * @param impostor
  77157. * @param {Vector3} origin the origin of the explosion
  77158. * @param {number} radius the explosion radius
  77159. * @param {number} strength the explosion strength
  77160. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  77161. * @returns {Nullable<PhysicsForceAndContactPoint>}
  77162. */
  77163. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  77164. if (impostor.mass === 0) {
  77165. return null;
  77166. }
  77167. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  77168. return null;
  77169. }
  77170. if (impostor.object.getClassName() !== 'Mesh') {
  77171. return null;
  77172. }
  77173. var impostorObject = impostor.object;
  77174. var impostorObjectCenter = impostor.getObjectCenter();
  77175. var direction = impostorObjectCenter.subtract(origin);
  77176. var ray = new BABYLON.Ray(origin, direction, radius);
  77177. this._rays.push(ray);
  77178. var hit = ray.intersectsMesh(impostorObject);
  77179. var contactPoint = hit.pickedPoint;
  77180. if (!contactPoint) {
  77181. return null;
  77182. }
  77183. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  77184. if (distanceFromOrigin > radius) {
  77185. return null;
  77186. }
  77187. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  77188. ? strength
  77189. : strength * (1 - (distanceFromOrigin / radius));
  77190. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77191. return { force: force, contactPoint: contactPoint };
  77192. };
  77193. /**
  77194. * Disposes the sphere.
  77195. * @param {bolean} force
  77196. */
  77197. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  77198. var _this = this;
  77199. if (force === void 0) { force = true; }
  77200. if (force) {
  77201. this._sphere.dispose();
  77202. }
  77203. else {
  77204. setTimeout(function () {
  77205. if (!_this._dataFetched) {
  77206. _this._sphere.dispose();
  77207. }
  77208. }, 0);
  77209. }
  77210. };
  77211. /*** Helpers ***/
  77212. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  77213. if (!this._sphere) {
  77214. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  77215. this._sphere.isVisible = false;
  77216. }
  77217. };
  77218. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  77219. var impostorObject = impostor.object;
  77220. this._prepareSphere();
  77221. this._sphere.position = origin;
  77222. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  77223. this._sphere._updateBoundingInfo();
  77224. this._sphere.computeWorldMatrix(true);
  77225. return this._sphere.intersectsMesh(impostorObject, true);
  77226. };
  77227. return PhysicsRadialExplosionEvent;
  77228. }());
  77229. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  77230. /***** Gravitational Field *****/
  77231. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  77232. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  77233. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77234. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77235. this._physicsHelper = physicsHelper;
  77236. this._scene = scene;
  77237. this._origin = origin;
  77238. this._radius = radius;
  77239. this._strength = strength;
  77240. this._falloff = falloff;
  77241. this._tickCallback = this._tick.bind(this);
  77242. }
  77243. /**
  77244. * Returns the data related to the gravitational field event (sphere).
  77245. * @returns {PhysicsGravitationalFieldEventData}
  77246. */
  77247. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  77248. this._dataFetched = true;
  77249. return {
  77250. sphere: this._sphere,
  77251. };
  77252. };
  77253. /**
  77254. * Enables the gravitational field.
  77255. */
  77256. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  77257. this._tickCallback.call(this);
  77258. this._scene.registerBeforeRender(this._tickCallback);
  77259. };
  77260. /**
  77261. * Disables the gravitational field.
  77262. */
  77263. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  77264. this._scene.unregisterBeforeRender(this._tickCallback);
  77265. };
  77266. /**
  77267. * Disposes the sphere.
  77268. * @param {bolean} force
  77269. */
  77270. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  77271. var _this = this;
  77272. if (force === void 0) { force = true; }
  77273. if (force) {
  77274. this._sphere.dispose();
  77275. }
  77276. else {
  77277. setTimeout(function () {
  77278. if (!_this._dataFetched) {
  77279. _this._sphere.dispose();
  77280. }
  77281. }, 0);
  77282. }
  77283. };
  77284. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  77285. // Since the params won't change, we fetch the event only once
  77286. if (this._sphere) {
  77287. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77288. }
  77289. else {
  77290. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77291. if (radialExplosionEvent) {
  77292. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  77293. }
  77294. }
  77295. };
  77296. return PhysicsGravitationalFieldEvent;
  77297. }());
  77298. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  77299. /***** Updraft *****/
  77300. var PhysicsUpdraftEvent = /** @class */ (function () {
  77301. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  77302. this._scene = _scene;
  77303. this._origin = _origin;
  77304. this._radius = _radius;
  77305. this._strength = _strength;
  77306. this._height = _height;
  77307. this._updraftMode = _updraftMode;
  77308. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77309. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  77310. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77311. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77312. this._physicsEngine = this._scene.getPhysicsEngine();
  77313. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77314. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77315. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77316. this._originDirection = this._origin.subtract(this._originTop).normalize();
  77317. }
  77318. this._tickCallback = this._tick.bind(this);
  77319. }
  77320. /**
  77321. * Returns the data related to the updraft event (cylinder).
  77322. * @returns {PhysicsUpdraftEventData}
  77323. */
  77324. PhysicsUpdraftEvent.prototype.getData = function () {
  77325. this._dataFetched = true;
  77326. return {
  77327. cylinder: this._cylinder,
  77328. };
  77329. };
  77330. /**
  77331. * Enables the updraft.
  77332. */
  77333. PhysicsUpdraftEvent.prototype.enable = function () {
  77334. this._tickCallback.call(this);
  77335. this._scene.registerBeforeRender(this._tickCallback);
  77336. };
  77337. /**
  77338. * Disables the cortex.
  77339. */
  77340. PhysicsUpdraftEvent.prototype.disable = function () {
  77341. this._scene.unregisterBeforeRender(this._tickCallback);
  77342. };
  77343. /**
  77344. * Disposes the sphere.
  77345. * @param {bolean} force
  77346. */
  77347. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  77348. var _this = this;
  77349. if (force === void 0) { force = true; }
  77350. if (force) {
  77351. this._cylinder.dispose();
  77352. }
  77353. else {
  77354. setTimeout(function () {
  77355. if (!_this._dataFetched) {
  77356. _this._cylinder.dispose();
  77357. }
  77358. }, 0);
  77359. }
  77360. };
  77361. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77362. if (impostor.mass === 0) {
  77363. return null;
  77364. }
  77365. if (!this._intersectsWithCylinder(impostor)) {
  77366. return null;
  77367. }
  77368. var impostorObjectCenter = impostor.getObjectCenter();
  77369. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77370. var direction = this._originDirection;
  77371. }
  77372. else {
  77373. var direction = impostorObjectCenter.subtract(this._originTop);
  77374. }
  77375. var multiplier = this._strength * -1;
  77376. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77377. return { force: force, contactPoint: impostorObjectCenter };
  77378. };
  77379. PhysicsUpdraftEvent.prototype._tick = function () {
  77380. var _this = this;
  77381. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77382. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77383. if (!impostorForceAndContactPoint) {
  77384. return;
  77385. }
  77386. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77387. });
  77388. };
  77389. /*** Helpers ***/
  77390. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  77391. if (!this._cylinder) {
  77392. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  77393. height: this._height,
  77394. diameter: this._radius * 2,
  77395. }, this._scene);
  77396. this._cylinder.isVisible = false;
  77397. }
  77398. };
  77399. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  77400. var impostorObject = impostor.object;
  77401. this._prepareCylinder();
  77402. this._cylinder.position = this._cylinderPosition;
  77403. return this._cylinder.intersectsMesh(impostorObject, true);
  77404. };
  77405. return PhysicsUpdraftEvent;
  77406. }());
  77407. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  77408. /***** Vortex *****/
  77409. var PhysicsVortexEvent = /** @class */ (function () {
  77410. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  77411. this._scene = _scene;
  77412. this._origin = _origin;
  77413. this._radius = _radius;
  77414. this._strength = _strength;
  77415. this._height = _height;
  77416. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77417. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  77418. this._updraftMultiplier = 0.02;
  77419. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77420. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77421. this._physicsEngine = this._scene.getPhysicsEngine();
  77422. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77423. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77424. this._tickCallback = this._tick.bind(this);
  77425. }
  77426. /**
  77427. * Returns the data related to the vortex event (cylinder).
  77428. * @returns {PhysicsVortexEventData}
  77429. */
  77430. PhysicsVortexEvent.prototype.getData = function () {
  77431. this._dataFetched = true;
  77432. return {
  77433. cylinder: this._cylinder,
  77434. };
  77435. };
  77436. /**
  77437. * Enables the vortex.
  77438. */
  77439. PhysicsVortexEvent.prototype.enable = function () {
  77440. this._tickCallback.call(this);
  77441. this._scene.registerBeforeRender(this._tickCallback);
  77442. };
  77443. /**
  77444. * Disables the cortex.
  77445. */
  77446. PhysicsVortexEvent.prototype.disable = function () {
  77447. this._scene.unregisterBeforeRender(this._tickCallback);
  77448. };
  77449. /**
  77450. * Disposes the sphere.
  77451. * @param {bolean} force
  77452. */
  77453. PhysicsVortexEvent.prototype.dispose = function (force) {
  77454. var _this = this;
  77455. if (force === void 0) { force = true; }
  77456. if (force) {
  77457. this._cylinder.dispose();
  77458. }
  77459. else {
  77460. setTimeout(function () {
  77461. if (!_this._dataFetched) {
  77462. _this._cylinder.dispose();
  77463. }
  77464. }, 0);
  77465. }
  77466. };
  77467. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77468. if (impostor.mass === 0) {
  77469. return null;
  77470. }
  77471. if (!this._intersectsWithCylinder(impostor)) {
  77472. return null;
  77473. }
  77474. if (impostor.object.getClassName() !== 'Mesh') {
  77475. return null;
  77476. }
  77477. var impostorObject = impostor.object;
  77478. var impostorObjectCenter = impostor.getObjectCenter();
  77479. 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)
  77480. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  77481. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  77482. var hit = ray.intersectsMesh(impostorObject);
  77483. var contactPoint = hit.pickedPoint;
  77484. if (!contactPoint) {
  77485. return null;
  77486. }
  77487. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  77488. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  77489. var directionToOrigin = contactPoint.normalize();
  77490. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77491. directionToOrigin = directionToOrigin.negate();
  77492. }
  77493. // TODO: find a more physically based solution
  77494. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77495. var forceX = directionToOrigin.x * this._strength / 8;
  77496. var forceY = directionToOrigin.y * this._updraftMultiplier;
  77497. var forceZ = directionToOrigin.z * this._strength / 8;
  77498. }
  77499. else {
  77500. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  77501. var forceY = this._originTop.y * this._updraftMultiplier;
  77502. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  77503. }
  77504. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  77505. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  77506. return { force: force, contactPoint: impostorObjectCenter };
  77507. };
  77508. PhysicsVortexEvent.prototype._tick = function () {
  77509. var _this = this;
  77510. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77511. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77512. if (!impostorForceAndContactPoint) {
  77513. return;
  77514. }
  77515. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77516. });
  77517. };
  77518. /*** Helpers ***/
  77519. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  77520. if (!this._cylinder) {
  77521. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  77522. height: this._height,
  77523. diameter: this._radius * 2,
  77524. }, this._scene);
  77525. this._cylinder.isVisible = false;
  77526. }
  77527. };
  77528. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  77529. var impostorObject = impostor.object;
  77530. this._prepareCylinder();
  77531. this._cylinder.position = this._cylinderPosition;
  77532. return this._cylinder.intersectsMesh(impostorObject, true);
  77533. };
  77534. return PhysicsVortexEvent;
  77535. }());
  77536. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  77537. /***** Enums *****/
  77538. /**
  77539. * The strenght of the force in correspondence to the distance of the affected object
  77540. */
  77541. var PhysicsRadialImpulseFalloff;
  77542. (function (PhysicsRadialImpulseFalloff) {
  77543. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  77544. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  77545. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  77546. /**
  77547. * The strenght of the force in correspondence to the distance of the affected object
  77548. */
  77549. var PhysicsUpdraftMode;
  77550. (function (PhysicsUpdraftMode) {
  77551. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  77552. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  77553. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  77554. })(BABYLON || (BABYLON = {}));
  77555. //# sourceMappingURL=babylon.physicsHelper.js.map
  77556. "use strict";
  77557. var BABYLON;
  77558. (function (BABYLON) {
  77559. var CannonJSPlugin = /** @class */ (function () {
  77560. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  77561. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  77562. if (iterations === void 0) { iterations = 10; }
  77563. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  77564. this.name = "CannonJSPlugin";
  77565. this._physicsMaterials = new Array();
  77566. this._fixedTimeStep = 1 / 60;
  77567. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  77568. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  77569. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  77570. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  77571. this._tmpPosition = BABYLON.Vector3.Zero();
  77572. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  77573. this._tmpUnityRotation = new BABYLON.Quaternion();
  77574. if (!this.isSupported()) {
  77575. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  77576. return;
  77577. }
  77578. this._extendNamespace();
  77579. this.world = new this.BJSCANNON.World();
  77580. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  77581. this.world.solver.iterations = iterations;
  77582. }
  77583. CannonJSPlugin.prototype.setGravity = function (gravity) {
  77584. this.world.gravity.copy(gravity);
  77585. };
  77586. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  77587. this._fixedTimeStep = timeStep;
  77588. };
  77589. CannonJSPlugin.prototype.getTimeStep = function () {
  77590. return this._fixedTimeStep;
  77591. };
  77592. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  77593. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  77594. };
  77595. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77596. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77597. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77598. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  77599. };
  77600. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77601. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77602. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77603. impostor.physicsBody.applyForce(impulse, worldPoint);
  77604. };
  77605. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77606. //parent-child relationship. Does this impostor has a parent impostor?
  77607. if (impostor.parent) {
  77608. if (impostor.physicsBody) {
  77609. this.removePhysicsBody(impostor);
  77610. //TODO is that needed?
  77611. impostor.forceUpdate();
  77612. }
  77613. return;
  77614. }
  77615. //should a new body be created for this impostor?
  77616. if (impostor.isBodyInitRequired()) {
  77617. var shape = this._createShape(impostor);
  77618. //unregister events, if body is being changed
  77619. var oldBody = impostor.physicsBody;
  77620. if (oldBody) {
  77621. this.removePhysicsBody(impostor);
  77622. }
  77623. //create the body and material
  77624. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  77625. var bodyCreationObject = {
  77626. mass: impostor.getParam("mass"),
  77627. material: material
  77628. };
  77629. // A simple extend, in case native options were used.
  77630. var nativeOptions = impostor.getParam("nativeOptions");
  77631. for (var key in nativeOptions) {
  77632. if (nativeOptions.hasOwnProperty(key)) {
  77633. bodyCreationObject[key] = nativeOptions[key];
  77634. }
  77635. }
  77636. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  77637. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  77638. this.world.addEventListener("preStep", impostor.beforeStep);
  77639. this.world.addEventListener("postStep", impostor.afterStep);
  77640. impostor.physicsBody.addShape(shape);
  77641. this.world.add(impostor.physicsBody);
  77642. //try to keep the body moving in the right direction by taking old properties.
  77643. //Should be tested!
  77644. if (oldBody) {
  77645. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  77646. impostor.physicsBody[param].copy(oldBody[param]);
  77647. });
  77648. }
  77649. this._processChildMeshes(impostor);
  77650. }
  77651. //now update the body's transformation
  77652. this._updatePhysicsBodyTransformation(impostor);
  77653. };
  77654. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  77655. var _this = this;
  77656. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  77657. var currentRotation = mainImpostor.object.rotationQuaternion;
  77658. if (meshChildren.length) {
  77659. var processMesh = function (localPosition, mesh) {
  77660. if (!currentRotation || !mesh.rotationQuaternion) {
  77661. return;
  77662. }
  77663. var childImpostor = mesh.getPhysicsImpostor();
  77664. if (childImpostor) {
  77665. var parent = childImpostor.parent;
  77666. if (parent !== mainImpostor) {
  77667. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  77668. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  77669. if (childImpostor.physicsBody) {
  77670. _this.removePhysicsBody(childImpostor);
  77671. childImpostor.physicsBody = null;
  77672. }
  77673. childImpostor.parent = mainImpostor;
  77674. childImpostor.resetUpdateFlags();
  77675. 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));
  77676. //Add the mass of the children.
  77677. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  77678. }
  77679. }
  77680. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  77681. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  77682. };
  77683. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  77684. }
  77685. };
  77686. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77687. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  77688. this.world.removeEventListener("preStep", impostor.beforeStep);
  77689. this.world.removeEventListener("postStep", impostor.afterStep);
  77690. this.world.remove(impostor.physicsBody);
  77691. };
  77692. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77693. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77694. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77695. if (!mainBody || !connectedBody) {
  77696. return;
  77697. }
  77698. var constraint;
  77699. var jointData = impostorJoint.joint.jointData;
  77700. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  77701. var constraintData = {
  77702. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  77703. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  77704. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  77705. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  77706. maxForce: jointData.nativeParams.maxForce,
  77707. collideConnected: !!jointData.collision
  77708. };
  77709. switch (impostorJoint.joint.type) {
  77710. case BABYLON.PhysicsJoint.HingeJoint:
  77711. case BABYLON.PhysicsJoint.Hinge2Joint:
  77712. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  77713. break;
  77714. case BABYLON.PhysicsJoint.DistanceJoint:
  77715. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  77716. break;
  77717. case BABYLON.PhysicsJoint.SpringJoint:
  77718. var springData = jointData;
  77719. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  77720. restLength: springData.length,
  77721. stiffness: springData.stiffness,
  77722. damping: springData.damping,
  77723. localAnchorA: constraintData.pivotA,
  77724. localAnchorB: constraintData.pivotB
  77725. });
  77726. break;
  77727. case BABYLON.PhysicsJoint.LockJoint:
  77728. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  77729. break;
  77730. case BABYLON.PhysicsJoint.PointToPointJoint:
  77731. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77732. default:
  77733. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  77734. break;
  77735. }
  77736. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  77737. constraint.collideConnected = !!jointData.collision;
  77738. impostorJoint.joint.physicsJoint = constraint;
  77739. //don't add spring as constraint, as it is not one.
  77740. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  77741. this.world.addConstraint(constraint);
  77742. }
  77743. else {
  77744. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  77745. constraint.applyForce();
  77746. });
  77747. }
  77748. };
  77749. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77750. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  77751. };
  77752. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  77753. var index;
  77754. var mat;
  77755. for (index = 0; index < this._physicsMaterials.length; index++) {
  77756. mat = this._physicsMaterials[index];
  77757. if (mat.friction === friction && mat.restitution === restitution) {
  77758. return mat;
  77759. }
  77760. }
  77761. var currentMat = new this.BJSCANNON.Material(name);
  77762. currentMat.friction = friction;
  77763. currentMat.restitution = restitution;
  77764. this._physicsMaterials.push(currentMat);
  77765. return currentMat;
  77766. };
  77767. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  77768. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  77769. };
  77770. CannonJSPlugin.prototype._createShape = function (impostor) {
  77771. var object = impostor.object;
  77772. var returnValue;
  77773. var extendSize = impostor.getObjectExtendSize();
  77774. switch (impostor.type) {
  77775. case BABYLON.PhysicsImpostor.SphereImpostor:
  77776. var radiusX = extendSize.x;
  77777. var radiusY = extendSize.y;
  77778. var radiusZ = extendSize.z;
  77779. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  77780. break;
  77781. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  77782. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77783. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  77784. break;
  77785. case BABYLON.PhysicsImpostor.BoxImpostor:
  77786. var box = extendSize.scale(0.5);
  77787. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  77788. break;
  77789. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77790. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  77791. returnValue = new this.BJSCANNON.Plane();
  77792. break;
  77793. case BABYLON.PhysicsImpostor.MeshImpostor:
  77794. // should transform the vertex data to world coordinates!!
  77795. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  77796. var rawFaces = object.getIndices ? object.getIndices() : [];
  77797. if (!rawVerts)
  77798. return;
  77799. // get only scale! so the object could transform correctly.
  77800. var oldPosition = object.position.clone();
  77801. var oldRotation = object.rotation && object.rotation.clone();
  77802. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  77803. object.position.copyFromFloats(0, 0, 0);
  77804. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77805. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77806. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77807. var transform = object.computeWorldMatrix(true);
  77808. // convert rawVerts to object space
  77809. var temp = new Array();
  77810. var index;
  77811. for (index = 0; index < rawVerts.length; index += 3) {
  77812. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  77813. }
  77814. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  77815. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  77816. //now set back the transformation!
  77817. object.position.copyFrom(oldPosition);
  77818. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  77819. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  77820. break;
  77821. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  77822. var oldPosition2 = object.position.clone();
  77823. var oldRotation2 = object.rotation && object.rotation.clone();
  77824. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  77825. object.position.copyFromFloats(0, 0, 0);
  77826. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77827. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77828. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77829. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  77830. returnValue = this._createHeightmap(object);
  77831. object.position.copyFrom(oldPosition2);
  77832. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  77833. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  77834. object.computeWorldMatrix(true);
  77835. break;
  77836. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77837. returnValue = new this.BJSCANNON.Particle();
  77838. break;
  77839. }
  77840. return returnValue;
  77841. };
  77842. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  77843. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77844. var transform = object.computeWorldMatrix(true);
  77845. // convert rawVerts to object space
  77846. var temp = new Array();
  77847. var index;
  77848. for (index = 0; index < pos.length; index += 3) {
  77849. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  77850. }
  77851. pos = temp;
  77852. var matrix = new Array();
  77853. //For now pointDepth will not be used and will be automatically calculated.
  77854. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  77855. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  77856. var boundingInfo = object.getBoundingInfo();
  77857. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  77858. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  77859. var elementSize = dim * 2 / arraySize;
  77860. for (var i = 0; i < pos.length; i = i + 3) {
  77861. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  77862. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  77863. var y = -pos[i + 2] + minY;
  77864. if (!matrix[x]) {
  77865. matrix[x] = [];
  77866. }
  77867. if (!matrix[x][z]) {
  77868. matrix[x][z] = y;
  77869. }
  77870. matrix[x][z] = Math.max(y, matrix[x][z]);
  77871. }
  77872. for (var x = 0; x <= arraySize; ++x) {
  77873. if (!matrix[x]) {
  77874. var loc = 1;
  77875. while (!matrix[(x + loc) % arraySize]) {
  77876. loc++;
  77877. }
  77878. matrix[x] = matrix[(x + loc) % arraySize].slice();
  77879. //console.log("missing x", x);
  77880. }
  77881. for (var z = 0; z <= arraySize; ++z) {
  77882. if (!matrix[x][z]) {
  77883. var loc = 1;
  77884. var newValue;
  77885. while (newValue === undefined) {
  77886. newValue = matrix[x][(z + loc++) % arraySize];
  77887. }
  77888. matrix[x][z] = newValue;
  77889. }
  77890. }
  77891. }
  77892. var shape = new this.BJSCANNON.Heightfield(matrix, {
  77893. elementSize: elementSize
  77894. });
  77895. //For future reference, needed for body transformation
  77896. shape.minY = minY;
  77897. return shape;
  77898. };
  77899. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  77900. var object = impostor.object;
  77901. //make sure it is updated...
  77902. object.computeWorldMatrix && object.computeWorldMatrix(true);
  77903. // The delta between the mesh position and the mesh bounding box center
  77904. var bInfo = object.getBoundingInfo();
  77905. if (!bInfo)
  77906. return;
  77907. var center = impostor.getObjectCenter();
  77908. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  77909. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  77910. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  77911. this._tmpPosition.copyFrom(center);
  77912. var quaternion = object.rotationQuaternion;
  77913. if (!quaternion) {
  77914. return;
  77915. }
  77916. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  77917. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  77918. //-90 DEG in X, precalculated
  77919. quaternion = quaternion.multiply(this._minus90X);
  77920. //Invert! (Precalculated, 90 deg in X)
  77921. //No need to clone. this will never change.
  77922. impostor.setDeltaRotation(this._plus90X);
  77923. }
  77924. //If it is a heightfield, if should be centered.
  77925. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  77926. var mesh = object;
  77927. var boundingInfo = mesh.getBoundingInfo();
  77928. //calculate the correct body position:
  77929. var rotationQuaternion = mesh.rotationQuaternion;
  77930. mesh.rotationQuaternion = this._tmpUnityRotation;
  77931. mesh.computeWorldMatrix(true);
  77932. //get original center with no rotation
  77933. var c = center.clone();
  77934. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  77935. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  77936. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  77937. mesh.setPreTransformMatrix(p);
  77938. mesh.computeWorldMatrix(true);
  77939. //calculate the translation
  77940. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  77941. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  77942. //add it inverted to the delta
  77943. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  77944. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  77945. //rotation is back
  77946. mesh.rotationQuaternion = rotationQuaternion;
  77947. mesh.setPreTransformMatrix(oldPivot);
  77948. mesh.computeWorldMatrix(true);
  77949. }
  77950. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  77951. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  77952. //this._tmpPosition.copyFrom(object.position);
  77953. }
  77954. impostor.setDeltaPosition(this._tmpDeltaPosition);
  77955. //Now update the impostor object
  77956. impostor.physicsBody.position.copy(this._tmpPosition);
  77957. impostor.physicsBody.quaternion.copy(quaternion);
  77958. };
  77959. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77960. impostor.object.position.copyFrom(impostor.physicsBody.position);
  77961. if (impostor.object.rotationQuaternion) {
  77962. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  77963. }
  77964. };
  77965. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77966. impostor.physicsBody.position.copy(newPosition);
  77967. impostor.physicsBody.quaternion.copy(newRotation);
  77968. };
  77969. CannonJSPlugin.prototype.isSupported = function () {
  77970. return this.BJSCANNON !== undefined;
  77971. };
  77972. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77973. impostor.physicsBody.velocity.copy(velocity);
  77974. };
  77975. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77976. impostor.physicsBody.angularVelocity.copy(velocity);
  77977. };
  77978. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77979. var v = impostor.physicsBody.velocity;
  77980. if (!v) {
  77981. return null;
  77982. }
  77983. return new BABYLON.Vector3(v.x, v.y, v.z);
  77984. };
  77985. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77986. var v = impostor.physicsBody.angularVelocity;
  77987. if (!v) {
  77988. return null;
  77989. }
  77990. return new BABYLON.Vector3(v.x, v.y, v.z);
  77991. };
  77992. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77993. impostor.physicsBody.mass = mass;
  77994. impostor.physicsBody.updateMassProperties();
  77995. };
  77996. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  77997. return impostor.physicsBody.mass;
  77998. };
  77999. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  78000. return impostor.physicsBody.material.friction;
  78001. };
  78002. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78003. impostor.physicsBody.material.friction = friction;
  78004. };
  78005. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78006. return impostor.physicsBody.material.restitution;
  78007. };
  78008. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78009. impostor.physicsBody.material.restitution = restitution;
  78010. };
  78011. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  78012. impostor.physicsBody.sleep();
  78013. };
  78014. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  78015. impostor.physicsBody.wakeUp();
  78016. };
  78017. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78018. joint.physicsJoint.distance = maxDistance;
  78019. };
  78020. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78021. // if (!motorIndex) {
  78022. // joint.physicsJoint.enableMotor();
  78023. // }
  78024. // }
  78025. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78026. // if (!motorIndex) {
  78027. // joint.physicsJoint.disableMotor();
  78028. // }
  78029. // }
  78030. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78031. if (!motorIndex) {
  78032. joint.physicsJoint.enableMotor();
  78033. joint.physicsJoint.setMotorSpeed(speed);
  78034. if (maxForce) {
  78035. this.setLimit(joint, maxForce);
  78036. }
  78037. }
  78038. };
  78039. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  78040. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  78041. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  78042. };
  78043. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78044. var body = impostor.physicsBody;
  78045. mesh.position.x = body.position.x;
  78046. mesh.position.y = body.position.y;
  78047. mesh.position.z = body.position.z;
  78048. if (mesh.rotationQuaternion) {
  78049. mesh.rotationQuaternion.x = body.quaternion.x;
  78050. mesh.rotationQuaternion.y = body.quaternion.y;
  78051. mesh.rotationQuaternion.z = body.quaternion.z;
  78052. mesh.rotationQuaternion.w = body.quaternion.w;
  78053. }
  78054. };
  78055. CannonJSPlugin.prototype.getRadius = function (impostor) {
  78056. var shape = impostor.physicsBody.shapes[0];
  78057. return shape.boundingSphereRadius;
  78058. };
  78059. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78060. var shape = impostor.physicsBody.shapes[0];
  78061. result.x = shape.halfExtents.x * 2;
  78062. result.y = shape.halfExtents.y * 2;
  78063. result.z = shape.halfExtents.z * 2;
  78064. };
  78065. CannonJSPlugin.prototype.dispose = function () {
  78066. };
  78067. CannonJSPlugin.prototype._extendNamespace = function () {
  78068. //this will force cannon to execute at least one step when using interpolation
  78069. var step_tmp1 = new this.BJSCANNON.Vec3();
  78070. var Engine = this.BJSCANNON;
  78071. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  78072. maxSubSteps = maxSubSteps || 10;
  78073. timeSinceLastCalled = timeSinceLastCalled || 0;
  78074. if (timeSinceLastCalled === 0) {
  78075. this.internalStep(dt);
  78076. this.time += dt;
  78077. }
  78078. else {
  78079. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  78080. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  78081. var t0 = performance.now();
  78082. for (var i = 0; i !== internalSteps; i++) {
  78083. this.internalStep(dt);
  78084. if (performance.now() - t0 > dt * 1000) {
  78085. break;
  78086. }
  78087. }
  78088. this.time += timeSinceLastCalled;
  78089. var h = this.time % dt;
  78090. var h_div_dt = h / dt;
  78091. var interpvelo = step_tmp1;
  78092. var bodies = this.bodies;
  78093. for (var j = 0; j !== bodies.length; j++) {
  78094. var b = bodies[j];
  78095. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  78096. b.position.vsub(b.previousPosition, interpvelo);
  78097. interpvelo.scale(h_div_dt, interpvelo);
  78098. b.position.vadd(interpvelo, b.interpolatedPosition);
  78099. }
  78100. else {
  78101. b.interpolatedPosition.copy(b.position);
  78102. b.interpolatedQuaternion.copy(b.quaternion);
  78103. }
  78104. }
  78105. }
  78106. };
  78107. };
  78108. return CannonJSPlugin;
  78109. }());
  78110. BABYLON.CannonJSPlugin = CannonJSPlugin;
  78111. })(BABYLON || (BABYLON = {}));
  78112. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  78113. "use strict";
  78114. var BABYLON;
  78115. (function (BABYLON) {
  78116. var OimoJSPlugin = /** @class */ (function () {
  78117. function OimoJSPlugin(iterations) {
  78118. this.name = "OimoJSPlugin";
  78119. this._tmpImpostorsArray = [];
  78120. this._tmpPositionVector = BABYLON.Vector3.Zero();
  78121. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  78122. this.world = new this.BJSOIMO.World({
  78123. iterations: iterations
  78124. });
  78125. this.world.clear();
  78126. }
  78127. OimoJSPlugin.prototype.setGravity = function (gravity) {
  78128. this.world.gravity.copy(gravity);
  78129. };
  78130. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  78131. this.world.timeStep = timeStep;
  78132. };
  78133. OimoJSPlugin.prototype.getTimeStep = function () {
  78134. return this.world.timeStep;
  78135. };
  78136. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  78137. var _this = this;
  78138. impostors.forEach(function (impostor) {
  78139. impostor.beforeStep();
  78140. });
  78141. this.world.step();
  78142. impostors.forEach(function (impostor) {
  78143. impostor.afterStep();
  78144. //update the ordered impostors array
  78145. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  78146. });
  78147. //check for collisions
  78148. var contact = this.world.contacts;
  78149. while (contact !== null) {
  78150. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  78151. contact = contact.next;
  78152. continue;
  78153. }
  78154. //is this body colliding with any other? get the impostor
  78155. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  78156. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  78157. if (!mainImpostor || !collidingImpostor) {
  78158. contact = contact.next;
  78159. continue;
  78160. }
  78161. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  78162. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  78163. contact = contact.next;
  78164. }
  78165. };
  78166. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78167. var mass = impostor.physicsBody.mass;
  78168. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  78169. };
  78170. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78171. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  78172. this.applyImpulse(impostor, force, contactPoint);
  78173. };
  78174. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78175. var _this = this;
  78176. //parent-child relationship. Does this impostor has a parent impostor?
  78177. if (impostor.parent) {
  78178. if (impostor.physicsBody) {
  78179. this.removePhysicsBody(impostor);
  78180. //TODO is that needed?
  78181. impostor.forceUpdate();
  78182. }
  78183. return;
  78184. }
  78185. if (impostor.isBodyInitRequired()) {
  78186. var bodyConfig = {
  78187. name: impostor.uniqueId,
  78188. //Oimo must have mass, also for static objects.
  78189. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  78190. size: [],
  78191. type: [],
  78192. pos: [],
  78193. posShape: [],
  78194. rot: [],
  78195. rotShape: [],
  78196. move: impostor.getParam("mass") !== 0,
  78197. density: impostor.getParam("mass"),
  78198. friction: impostor.getParam("friction"),
  78199. restitution: impostor.getParam("restitution"),
  78200. //Supporting older versions of Oimo
  78201. world: this.world
  78202. };
  78203. var impostors = [impostor];
  78204. var addToArray = function (parent) {
  78205. if (!parent.getChildMeshes)
  78206. return;
  78207. parent.getChildMeshes().forEach(function (m) {
  78208. if (m.physicsImpostor) {
  78209. impostors.push(m.physicsImpostor);
  78210. //m.physicsImpostor._init();
  78211. }
  78212. });
  78213. };
  78214. addToArray(impostor.object);
  78215. var checkWithEpsilon_1 = function (value) {
  78216. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  78217. };
  78218. impostors.forEach(function (i) {
  78219. if (!i.object.rotationQuaternion) {
  78220. return;
  78221. }
  78222. //get the correct bounding box
  78223. var oldQuaternion = i.object.rotationQuaternion;
  78224. var rot = oldQuaternion.toEulerAngles();
  78225. var extendSize = i.getObjectExtendSize();
  78226. var radToDeg = 57.295779513082320876;
  78227. if (i === impostor) {
  78228. var center = impostor.getObjectCenter();
  78229. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  78230. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  78231. //Can also use Array.prototype.push.apply
  78232. bodyConfig.pos.push(center.x);
  78233. bodyConfig.pos.push(center.y);
  78234. bodyConfig.pos.push(center.z);
  78235. bodyConfig.posShape.push(0, 0, 0);
  78236. //tmp solution
  78237. bodyConfig.rot.push(rot.x * radToDeg);
  78238. bodyConfig.rot.push(rot.y * radToDeg);
  78239. bodyConfig.rot.push(rot.z * radToDeg);
  78240. bodyConfig.rotShape.push(0, 0, 0);
  78241. }
  78242. else {
  78243. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  78244. bodyConfig.posShape.push(localPosition.x);
  78245. bodyConfig.posShape.push(localPosition.y);
  78246. bodyConfig.posShape.push(localPosition.z);
  78247. bodyConfig.pos.push(0, 0, 0);
  78248. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  78249. bodyConfig.rot.push(0);
  78250. bodyConfig.rot.push(0);
  78251. bodyConfig.rot.push(0);
  78252. bodyConfig.rotShape.push(rot.x * radToDeg);
  78253. bodyConfig.rotShape.push(rot.y * radToDeg);
  78254. bodyConfig.rotShape.push(rot.z * radToDeg);
  78255. }
  78256. // register mesh
  78257. switch (i.type) {
  78258. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78259. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  78260. case BABYLON.PhysicsImpostor.SphereImpostor:
  78261. var radiusX = extendSize.x;
  78262. var radiusY = extendSize.y;
  78263. var radiusZ = extendSize.z;
  78264. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  78265. bodyConfig.type.push('sphere');
  78266. //due to the way oimo works with compounds, add 3 times
  78267. bodyConfig.size.push(size);
  78268. bodyConfig.size.push(size);
  78269. bodyConfig.size.push(size);
  78270. break;
  78271. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78272. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  78273. var sizeY = checkWithEpsilon_1(extendSize.y);
  78274. bodyConfig.type.push('cylinder');
  78275. bodyConfig.size.push(sizeX);
  78276. bodyConfig.size.push(sizeY);
  78277. //due to the way oimo works with compounds, add one more value.
  78278. bodyConfig.size.push(sizeY);
  78279. break;
  78280. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78281. case BABYLON.PhysicsImpostor.BoxImpostor:
  78282. default:
  78283. var sizeX = checkWithEpsilon_1(extendSize.x);
  78284. var sizeY = checkWithEpsilon_1(extendSize.y);
  78285. var sizeZ = checkWithEpsilon_1(extendSize.z);
  78286. bodyConfig.type.push('box');
  78287. //if (i === impostor) {
  78288. bodyConfig.size.push(sizeX);
  78289. bodyConfig.size.push(sizeY);
  78290. bodyConfig.size.push(sizeZ);
  78291. //} else {
  78292. // bodyConfig.size.push(0,0,0);
  78293. //}
  78294. break;
  78295. }
  78296. //actually not needed, but hey...
  78297. i.object.rotationQuaternion = oldQuaternion;
  78298. });
  78299. impostor.physicsBody = this.world.add(bodyConfig);
  78300. }
  78301. else {
  78302. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  78303. }
  78304. impostor.setDeltaPosition(this._tmpPositionVector);
  78305. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  78306. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  78307. };
  78308. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78309. //impostor.physicsBody.dispose();
  78310. //Same as : (older oimo versions)
  78311. this.world.removeRigidBody(impostor.physicsBody);
  78312. };
  78313. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78314. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78315. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78316. if (!mainBody || !connectedBody) {
  78317. return;
  78318. }
  78319. var jointData = impostorJoint.joint.jointData;
  78320. var options = jointData.nativeParams || {};
  78321. var type;
  78322. var nativeJointData = {
  78323. body1: mainBody,
  78324. body2: connectedBody,
  78325. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  78326. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  78327. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  78328. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  78329. min: options.min,
  78330. max: options.max,
  78331. collision: options.collision || jointData.collision,
  78332. spring: options.spring,
  78333. //supporting older version of Oimo
  78334. world: this.world
  78335. };
  78336. switch (impostorJoint.joint.type) {
  78337. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78338. type = "jointBall";
  78339. break;
  78340. case BABYLON.PhysicsJoint.SpringJoint:
  78341. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  78342. var springData = jointData;
  78343. nativeJointData.min = springData.length || nativeJointData.min;
  78344. //Max should also be set, just make sure it is at least min
  78345. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  78346. case BABYLON.PhysicsJoint.DistanceJoint:
  78347. type = "jointDistance";
  78348. nativeJointData.max = jointData.maxDistance;
  78349. break;
  78350. case BABYLON.PhysicsJoint.PrismaticJoint:
  78351. type = "jointPrisme";
  78352. break;
  78353. case BABYLON.PhysicsJoint.SliderJoint:
  78354. type = "jointSlide";
  78355. break;
  78356. case BABYLON.PhysicsJoint.WheelJoint:
  78357. type = "jointWheel";
  78358. break;
  78359. case BABYLON.PhysicsJoint.HingeJoint:
  78360. default:
  78361. type = "jointHinge";
  78362. break;
  78363. }
  78364. nativeJointData.type = type;
  78365. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  78366. };
  78367. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78368. //Bug in Oimo prevents us from disposing a joint in the playground
  78369. //joint.joint.physicsJoint.dispose();
  78370. //So we will bruteforce it!
  78371. try {
  78372. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  78373. }
  78374. catch (e) {
  78375. BABYLON.Tools.Warn(e);
  78376. }
  78377. };
  78378. OimoJSPlugin.prototype.isSupported = function () {
  78379. return this.BJSOIMO !== undefined;
  78380. };
  78381. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78382. if (!impostor.physicsBody.sleeping) {
  78383. //TODO check that
  78384. /*if (impostor.physicsBody.shapes.next) {
  78385. var parentShape = this._getLastShape(impostor.physicsBody);
  78386. impostor.object.position.copyFrom(parentShape.position);
  78387. console.log(parentShape.position);
  78388. } else {*/
  78389. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  78390. //}
  78391. if (impostor.object.rotationQuaternion) {
  78392. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  78393. }
  78394. }
  78395. };
  78396. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78397. var body = impostor.physicsBody;
  78398. body.position.copy(newPosition);
  78399. body.orientation.copy(newRotation);
  78400. body.syncShapes();
  78401. body.awake();
  78402. };
  78403. /*private _getLastShape(body: any): any {
  78404. var lastShape = body.shapes;
  78405. while (lastShape.next) {
  78406. lastShape = lastShape.next;
  78407. }
  78408. return lastShape;
  78409. }*/
  78410. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78411. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  78412. };
  78413. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78414. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  78415. };
  78416. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78417. var v = impostor.physicsBody.linearVelocity;
  78418. if (!v) {
  78419. return null;
  78420. }
  78421. return new BABYLON.Vector3(v.x, v.y, v.z);
  78422. };
  78423. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78424. var v = impostor.physicsBody.angularVelocity;
  78425. if (!v) {
  78426. return null;
  78427. }
  78428. return new BABYLON.Vector3(v.x, v.y, v.z);
  78429. };
  78430. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78431. var staticBody = mass === 0;
  78432. //this will actually set the body's density and not its mass.
  78433. //But this is how oimo treats the mass variable.
  78434. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  78435. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  78436. };
  78437. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  78438. return impostor.physicsBody.shapes.density;
  78439. };
  78440. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  78441. return impostor.physicsBody.shapes.friction;
  78442. };
  78443. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78444. impostor.physicsBody.shapes.friction = friction;
  78445. };
  78446. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78447. return impostor.physicsBody.shapes.restitution;
  78448. };
  78449. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78450. impostor.physicsBody.shapes.restitution = restitution;
  78451. };
  78452. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  78453. impostor.physicsBody.sleep();
  78454. };
  78455. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  78456. impostor.physicsBody.awake();
  78457. };
  78458. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78459. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  78460. if (minDistance !== void 0) {
  78461. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  78462. }
  78463. };
  78464. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78465. //TODO separate rotational and transational motors.
  78466. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78467. if (motor) {
  78468. motor.setMotor(speed, maxForce);
  78469. }
  78470. };
  78471. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  78472. //TODO separate rotational and transational motors.
  78473. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78474. if (motor) {
  78475. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  78476. }
  78477. };
  78478. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78479. var body = impostor.physicsBody;
  78480. mesh.position.x = body.position.x;
  78481. mesh.position.y = body.position.y;
  78482. mesh.position.z = body.position.z;
  78483. if (mesh.rotationQuaternion) {
  78484. mesh.rotationQuaternion.x = body.orientation.x;
  78485. mesh.rotationQuaternion.y = body.orientation.y;
  78486. mesh.rotationQuaternion.z = body.orientation.z;
  78487. mesh.rotationQuaternion.w = body.orientation.s;
  78488. }
  78489. };
  78490. OimoJSPlugin.prototype.getRadius = function (impostor) {
  78491. return impostor.physicsBody.shapes.radius;
  78492. };
  78493. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78494. var shape = impostor.physicsBody.shapes;
  78495. result.x = shape.halfWidth * 2;
  78496. result.y = shape.halfHeight * 2;
  78497. result.z = shape.halfDepth * 2;
  78498. };
  78499. OimoJSPlugin.prototype.dispose = function () {
  78500. this.world.clear();
  78501. };
  78502. return OimoJSPlugin;
  78503. }());
  78504. BABYLON.OimoJSPlugin = OimoJSPlugin;
  78505. })(BABYLON || (BABYLON = {}));
  78506. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  78507. "use strict";
  78508. var BABYLON;
  78509. (function (BABYLON) {
  78510. /*
  78511. * Based on jsTGALoader - Javascript loader for TGA file
  78512. * By Vincent Thibault
  78513. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  78514. */
  78515. var TGATools = /** @class */ (function () {
  78516. function TGATools() {
  78517. }
  78518. TGATools.GetTGAHeader = function (data) {
  78519. var offset = 0;
  78520. var header = {
  78521. id_length: data[offset++],
  78522. colormap_type: data[offset++],
  78523. image_type: data[offset++],
  78524. colormap_index: data[offset++] | data[offset++] << 8,
  78525. colormap_length: data[offset++] | data[offset++] << 8,
  78526. colormap_size: data[offset++],
  78527. origin: [
  78528. data[offset++] | data[offset++] << 8,
  78529. data[offset++] | data[offset++] << 8
  78530. ],
  78531. width: data[offset++] | data[offset++] << 8,
  78532. height: data[offset++] | data[offset++] << 8,
  78533. pixel_size: data[offset++],
  78534. flags: data[offset++]
  78535. };
  78536. return header;
  78537. };
  78538. TGATools.UploadContent = function (gl, data) {
  78539. // Not enough data to contain header ?
  78540. if (data.length < 19) {
  78541. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  78542. return;
  78543. }
  78544. // Read Header
  78545. var offset = 18;
  78546. var header = TGATools.GetTGAHeader(data);
  78547. // Assume it's a valid Targa file.
  78548. if (header.id_length + offset > data.length) {
  78549. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  78550. return;
  78551. }
  78552. // Skip not needed data
  78553. offset += header.id_length;
  78554. var use_rle = false;
  78555. var use_pal = false;
  78556. var use_grey = false;
  78557. // Get some informations.
  78558. switch (header.image_type) {
  78559. case TGATools._TYPE_RLE_INDEXED:
  78560. use_rle = true;
  78561. case TGATools._TYPE_INDEXED:
  78562. use_pal = true;
  78563. break;
  78564. case TGATools._TYPE_RLE_RGB:
  78565. use_rle = true;
  78566. case TGATools._TYPE_RGB:
  78567. // use_rgb = true;
  78568. break;
  78569. case TGATools._TYPE_RLE_GREY:
  78570. use_rle = true;
  78571. case TGATools._TYPE_GREY:
  78572. use_grey = true;
  78573. break;
  78574. }
  78575. var pixel_data;
  78576. // var numAlphaBits = header.flags & 0xf;
  78577. var pixel_size = header.pixel_size >> 3;
  78578. var pixel_total = header.width * header.height * pixel_size;
  78579. // Read palettes
  78580. var palettes;
  78581. if (use_pal) {
  78582. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  78583. }
  78584. // Read LRE
  78585. if (use_rle) {
  78586. pixel_data = new Uint8Array(pixel_total);
  78587. var c, count, i;
  78588. var localOffset = 0;
  78589. var pixels = new Uint8Array(pixel_size);
  78590. while (offset < pixel_total && localOffset < pixel_total) {
  78591. c = data[offset++];
  78592. count = (c & 0x7f) + 1;
  78593. // RLE pixels
  78594. if (c & 0x80) {
  78595. // Bind pixel tmp array
  78596. for (i = 0; i < pixel_size; ++i) {
  78597. pixels[i] = data[offset++];
  78598. }
  78599. // Copy pixel array
  78600. for (i = 0; i < count; ++i) {
  78601. pixel_data.set(pixels, localOffset + i * pixel_size);
  78602. }
  78603. localOffset += pixel_size * count;
  78604. }
  78605. else {
  78606. count *= pixel_size;
  78607. for (i = 0; i < count; ++i) {
  78608. pixel_data[localOffset + i] = data[offset++];
  78609. }
  78610. localOffset += count;
  78611. }
  78612. }
  78613. }
  78614. else {
  78615. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  78616. }
  78617. // Load to texture
  78618. var x_start, y_start, x_step, y_step, y_end, x_end;
  78619. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  78620. default:
  78621. case TGATools._ORIGIN_UL:
  78622. x_start = 0;
  78623. x_step = 1;
  78624. x_end = header.width;
  78625. y_start = 0;
  78626. y_step = 1;
  78627. y_end = header.height;
  78628. break;
  78629. case TGATools._ORIGIN_BL:
  78630. x_start = 0;
  78631. x_step = 1;
  78632. x_end = header.width;
  78633. y_start = header.height - 1;
  78634. y_step = -1;
  78635. y_end = -1;
  78636. break;
  78637. case TGATools._ORIGIN_UR:
  78638. x_start = header.width - 1;
  78639. x_step = -1;
  78640. x_end = -1;
  78641. y_start = 0;
  78642. y_step = 1;
  78643. y_end = header.height;
  78644. break;
  78645. case TGATools._ORIGIN_BR:
  78646. x_start = header.width - 1;
  78647. x_step = -1;
  78648. x_end = -1;
  78649. y_start = header.height - 1;
  78650. y_step = -1;
  78651. y_end = -1;
  78652. break;
  78653. }
  78654. // Load the specify method
  78655. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  78656. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  78657. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  78658. };
  78659. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78660. var image = pixel_data, colormap = palettes;
  78661. var width = header.width, height = header.height;
  78662. var color, i = 0, x, y;
  78663. var imageData = new Uint8Array(width * height * 4);
  78664. for (y = y_start; y !== y_end; y += y_step) {
  78665. for (x = x_start; x !== x_end; x += x_step, i++) {
  78666. color = image[i];
  78667. imageData[(x + width * y) * 4 + 3] = 255;
  78668. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  78669. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  78670. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  78671. }
  78672. }
  78673. return imageData;
  78674. };
  78675. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78676. var image = pixel_data;
  78677. var width = header.width, height = header.height;
  78678. var color, i = 0, x, y;
  78679. var imageData = new Uint8Array(width * height * 4);
  78680. for (y = y_start; y !== y_end; y += y_step) {
  78681. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78682. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  78683. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  78684. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  78685. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  78686. imageData[(x + width * y) * 4 + 0] = r;
  78687. imageData[(x + width * y) * 4 + 1] = g;
  78688. imageData[(x + width * y) * 4 + 2] = b;
  78689. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  78690. }
  78691. }
  78692. return imageData;
  78693. };
  78694. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78695. var image = pixel_data;
  78696. var width = header.width, height = header.height;
  78697. var i = 0, x, y;
  78698. var imageData = new Uint8Array(width * height * 4);
  78699. for (y = y_start; y !== y_end; y += y_step) {
  78700. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  78701. imageData[(x + width * y) * 4 + 3] = 255;
  78702. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78703. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78704. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78705. }
  78706. }
  78707. return imageData;
  78708. };
  78709. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78710. var image = pixel_data;
  78711. var width = header.width, height = header.height;
  78712. var i = 0, x, y;
  78713. var imageData = new Uint8Array(width * height * 4);
  78714. for (y = y_start; y !== y_end; y += y_step) {
  78715. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  78716. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78717. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78718. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78719. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  78720. }
  78721. }
  78722. return imageData;
  78723. };
  78724. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78725. var image = pixel_data;
  78726. var width = header.width, height = header.height;
  78727. var color, i = 0, x, y;
  78728. var imageData = new Uint8Array(width * height * 4);
  78729. for (y = y_start; y !== y_end; y += y_step) {
  78730. for (x = x_start; x !== x_end; x += x_step, i++) {
  78731. color = image[i];
  78732. imageData[(x + width * y) * 4 + 0] = color;
  78733. imageData[(x + width * y) * 4 + 1] = color;
  78734. imageData[(x + width * y) * 4 + 2] = color;
  78735. imageData[(x + width * y) * 4 + 3] = 255;
  78736. }
  78737. }
  78738. return imageData;
  78739. };
  78740. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78741. var image = pixel_data;
  78742. var width = header.width, height = header.height;
  78743. var i = 0, x, y;
  78744. var imageData = new Uint8Array(width * height * 4);
  78745. for (y = y_start; y !== y_end; y += y_step) {
  78746. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78747. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  78748. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  78749. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78750. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  78751. }
  78752. }
  78753. return imageData;
  78754. };
  78755. //private static _TYPE_NO_DATA = 0;
  78756. TGATools._TYPE_INDEXED = 1;
  78757. TGATools._TYPE_RGB = 2;
  78758. TGATools._TYPE_GREY = 3;
  78759. TGATools._TYPE_RLE_INDEXED = 9;
  78760. TGATools._TYPE_RLE_RGB = 10;
  78761. TGATools._TYPE_RLE_GREY = 11;
  78762. TGATools._ORIGIN_MASK = 0x30;
  78763. TGATools._ORIGIN_SHIFT = 0x04;
  78764. TGATools._ORIGIN_BL = 0x00;
  78765. TGATools._ORIGIN_BR = 0x01;
  78766. TGATools._ORIGIN_UL = 0x02;
  78767. TGATools._ORIGIN_UR = 0x03;
  78768. return TGATools;
  78769. }());
  78770. BABYLON.TGATools = TGATools;
  78771. })(BABYLON || (BABYLON = {}));
  78772. //# sourceMappingURL=babylon.tga.js.map
  78773. "use strict";
  78774. var BABYLON;
  78775. (function (BABYLON) {
  78776. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  78777. // All values and structures referenced from:
  78778. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  78779. var DDS_MAGIC = 0x20534444;
  78780. var
  78781. //DDSD_CAPS = 0x1,
  78782. //DDSD_HEIGHT = 0x2,
  78783. //DDSD_WIDTH = 0x4,
  78784. //DDSD_PITCH = 0x8,
  78785. //DDSD_PIXELFORMAT = 0x1000,
  78786. DDSD_MIPMAPCOUNT = 0x20000;
  78787. //DDSD_LINEARSIZE = 0x80000,
  78788. //DDSD_DEPTH = 0x800000;
  78789. // var DDSCAPS_COMPLEX = 0x8,
  78790. // DDSCAPS_MIPMAP = 0x400000,
  78791. // DDSCAPS_TEXTURE = 0x1000;
  78792. var DDSCAPS2_CUBEMAP = 0x200;
  78793. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  78794. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  78795. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  78796. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  78797. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  78798. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  78799. // DDSCAPS2_VOLUME = 0x200000;
  78800. var
  78801. //DDPF_ALPHAPIXELS = 0x1,
  78802. //DDPF_ALPHA = 0x2,
  78803. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  78804. //DDPF_YUV = 0x200,
  78805. DDPF_LUMINANCE = 0x20000;
  78806. function FourCCToInt32(value) {
  78807. return value.charCodeAt(0) +
  78808. (value.charCodeAt(1) << 8) +
  78809. (value.charCodeAt(2) << 16) +
  78810. (value.charCodeAt(3) << 24);
  78811. }
  78812. function Int32ToFourCC(value) {
  78813. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  78814. }
  78815. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  78816. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  78817. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  78818. var FOURCC_DX10 = FourCCToInt32("DX10");
  78819. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  78820. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  78821. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  78822. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  78823. var headerLengthInt = 31; // The header length in 32 bit ints
  78824. // Offsets into the header array
  78825. var off_magic = 0;
  78826. var off_size = 1;
  78827. var off_flags = 2;
  78828. var off_height = 3;
  78829. var off_width = 4;
  78830. var off_mipmapCount = 7;
  78831. var off_pfFlags = 20;
  78832. var off_pfFourCC = 21;
  78833. var off_RGBbpp = 22;
  78834. var off_RMask = 23;
  78835. var off_GMask = 24;
  78836. var off_BMask = 25;
  78837. var off_AMask = 26;
  78838. // var off_caps1 = 27;
  78839. var off_caps2 = 28;
  78840. // var off_caps3 = 29;
  78841. // var off_caps4 = 30;
  78842. var off_dxgiFormat = 32;
  78843. ;
  78844. var DDSTools = /** @class */ (function () {
  78845. function DDSTools() {
  78846. }
  78847. DDSTools.GetDDSInfo = function (arrayBuffer) {
  78848. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78849. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  78850. var mipmapCount = 1;
  78851. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  78852. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78853. }
  78854. var fourCC = header[off_pfFourCC];
  78855. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  78856. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78857. switch (fourCC) {
  78858. case FOURCC_D3DFMT_R16G16B16A16F:
  78859. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78860. break;
  78861. case FOURCC_D3DFMT_R32G32B32A32F:
  78862. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78863. break;
  78864. case FOURCC_DX10:
  78865. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  78866. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78867. break;
  78868. }
  78869. }
  78870. return {
  78871. width: header[off_width],
  78872. height: header[off_height],
  78873. mipmapCount: mipmapCount,
  78874. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  78875. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  78876. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  78877. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  78878. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  78879. dxgiFormat: dxgiFormat,
  78880. textureType: textureType
  78881. };
  78882. };
  78883. DDSTools._ToHalfFloat = function (value) {
  78884. if (!DDSTools._FloatView) {
  78885. DDSTools._FloatView = new Float32Array(1);
  78886. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  78887. }
  78888. DDSTools._FloatView[0] = value;
  78889. var x = DDSTools._Int32View[0];
  78890. var bits = (x >> 16) & 0x8000; /* Get the sign */
  78891. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  78892. var e = (x >> 23) & 0xff; /* Using int is faster here */
  78893. /* If zero, or denormal, or exponent underflows too much for a denormal
  78894. * half, return signed zero. */
  78895. if (e < 103) {
  78896. return bits;
  78897. }
  78898. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  78899. if (e > 142) {
  78900. bits |= 0x7c00;
  78901. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  78902. * not Inf, so make sure we set one mantissa bit too. */
  78903. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  78904. return bits;
  78905. }
  78906. /* If exponent underflows but not too much, return a denormal */
  78907. if (e < 113) {
  78908. m |= 0x0800;
  78909. /* Extra rounding may overflow and set mantissa to 0 and exponent
  78910. * to 1, which is OK. */
  78911. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  78912. return bits;
  78913. }
  78914. bits |= ((e - 112) << 10) | (m >> 1);
  78915. bits += m & 1;
  78916. return bits;
  78917. };
  78918. DDSTools._FromHalfFloat = function (value) {
  78919. var s = (value & 0x8000) >> 15;
  78920. var e = (value & 0x7C00) >> 10;
  78921. var f = value & 0x03FF;
  78922. if (e === 0) {
  78923. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  78924. }
  78925. else if (e == 0x1F) {
  78926. return f ? NaN : ((s ? -1 : 1) * Infinity);
  78927. }
  78928. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  78929. };
  78930. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78931. var destArray = new Float32Array(dataLength);
  78932. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78933. var index = 0;
  78934. for (var y = 0; y < height; y++) {
  78935. for (var x = 0; x < width; x++) {
  78936. var srcPos = (x + y * width) * 4;
  78937. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  78938. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  78939. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  78940. if (DDSTools.StoreLODInAlphaChannel) {
  78941. destArray[index + 3] = lod;
  78942. }
  78943. else {
  78944. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  78945. }
  78946. index += 4;
  78947. }
  78948. }
  78949. return destArray;
  78950. };
  78951. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78952. if (DDSTools.StoreLODInAlphaChannel) {
  78953. var destArray = new Uint16Array(dataLength);
  78954. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78955. var index = 0;
  78956. for (var y = 0; y < height; y++) {
  78957. for (var x = 0; x < width; x++) {
  78958. var srcPos = (x + y * width) * 4;
  78959. destArray[index] = srcData[srcPos];
  78960. destArray[index + 1] = srcData[srcPos + 1];
  78961. destArray[index + 2] = srcData[srcPos + 2];
  78962. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  78963. index += 4;
  78964. }
  78965. }
  78966. return destArray;
  78967. }
  78968. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  78969. };
  78970. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78971. if (DDSTools.StoreLODInAlphaChannel) {
  78972. var destArray = new Float32Array(dataLength);
  78973. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78974. var index = 0;
  78975. for (var y = 0; y < height; y++) {
  78976. for (var x = 0; x < width; x++) {
  78977. var srcPos = (x + y * width) * 4;
  78978. destArray[index] = srcData[srcPos];
  78979. destArray[index + 1] = srcData[srcPos + 1];
  78980. destArray[index + 2] = srcData[srcPos + 2];
  78981. destArray[index + 3] = lod;
  78982. index += 4;
  78983. }
  78984. }
  78985. return destArray;
  78986. }
  78987. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  78988. };
  78989. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78990. var destArray = new Uint8Array(dataLength);
  78991. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78992. var index = 0;
  78993. for (var y = 0; y < height; y++) {
  78994. for (var x = 0; x < width; x++) {
  78995. var srcPos = (x + y * width) * 4;
  78996. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  78997. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  78998. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  78999. if (DDSTools.StoreLODInAlphaChannel) {
  79000. destArray[index + 3] = lod;
  79001. }
  79002. else {
  79003. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  79004. }
  79005. index += 4;
  79006. }
  79007. }
  79008. return destArray;
  79009. };
  79010. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79011. var destArray = new Uint8Array(dataLength);
  79012. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79013. var index = 0;
  79014. for (var y = 0; y < height; y++) {
  79015. for (var x = 0; x < width; x++) {
  79016. var srcPos = (x + y * width) * 4;
  79017. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  79018. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  79019. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  79020. if (DDSTools.StoreLODInAlphaChannel) {
  79021. destArray[index + 3] = lod;
  79022. }
  79023. else {
  79024. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  79025. }
  79026. index += 4;
  79027. }
  79028. }
  79029. return destArray;
  79030. };
  79031. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  79032. var byteArray = new Uint8Array(dataLength);
  79033. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79034. var index = 0;
  79035. for (var y = 0; y < height; y++) {
  79036. for (var x = 0; x < width; x++) {
  79037. var srcPos = (x + y * width) * 4;
  79038. byteArray[index] = srcData[srcPos + rOffset];
  79039. byteArray[index + 1] = srcData[srcPos + gOffset];
  79040. byteArray[index + 2] = srcData[srcPos + bOffset];
  79041. byteArray[index + 3] = srcData[srcPos + aOffset];
  79042. index += 4;
  79043. }
  79044. }
  79045. return byteArray;
  79046. };
  79047. DDSTools._ExtractLongWordOrder = function (value) {
  79048. if (value === 0 || value === 255 || value === -16777216) {
  79049. return 0;
  79050. }
  79051. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  79052. };
  79053. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  79054. var byteArray = new Uint8Array(dataLength);
  79055. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79056. var index = 0;
  79057. for (var y = 0; y < height; y++) {
  79058. for (var x = 0; x < width; x++) {
  79059. var srcPos = (x + y * width) * 3;
  79060. byteArray[index] = srcData[srcPos + rOffset];
  79061. byteArray[index + 1] = srcData[srcPos + gOffset];
  79062. byteArray[index + 2] = srcData[srcPos + bOffset];
  79063. index += 3;
  79064. }
  79065. }
  79066. return byteArray;
  79067. };
  79068. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  79069. var byteArray = new Uint8Array(dataLength);
  79070. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79071. var index = 0;
  79072. for (var y = 0; y < height; y++) {
  79073. for (var x = 0; x < width; x++) {
  79074. var srcPos = (x + y * width);
  79075. byteArray[index] = srcData[srcPos];
  79076. index++;
  79077. }
  79078. }
  79079. return byteArray;
  79080. };
  79081. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  79082. if (lodIndex === void 0) { lodIndex = -1; }
  79083. var ext = engine.getCaps().s3tc;
  79084. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79085. var fourCC, width, height, dataLength = 0, dataOffset;
  79086. var byteArray, mipmapCount, mip;
  79087. var internalFormat = 0;
  79088. var format = 0;
  79089. var blockBytes = 1;
  79090. if (header[off_magic] !== DDS_MAGIC) {
  79091. BABYLON.Tools.Error("Invalid magic number in DDS header");
  79092. return;
  79093. }
  79094. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  79095. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  79096. return;
  79097. }
  79098. if (info.isCompressed && !ext) {
  79099. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  79100. return;
  79101. }
  79102. var bpp = header[off_RGBbpp];
  79103. dataOffset = header[off_size] + 4;
  79104. var computeFormats = false;
  79105. if (info.isFourCC) {
  79106. fourCC = header[off_pfFourCC];
  79107. switch (fourCC) {
  79108. case FOURCC_DXT1:
  79109. blockBytes = 8;
  79110. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  79111. break;
  79112. case FOURCC_DXT3:
  79113. blockBytes = 16;
  79114. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  79115. break;
  79116. case FOURCC_DXT5:
  79117. blockBytes = 16;
  79118. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  79119. break;
  79120. case FOURCC_D3DFMT_R16G16B16A16F:
  79121. computeFormats = true;
  79122. break;
  79123. case FOURCC_D3DFMT_R32G32B32A32F:
  79124. computeFormats = true;
  79125. break;
  79126. case FOURCC_DX10:
  79127. // There is an additionnal header so dataOffset need to be changed
  79128. dataOffset += 5 * 4; // 5 uints
  79129. var supported = false;
  79130. switch (info.dxgiFormat) {
  79131. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  79132. computeFormats = true;
  79133. supported = true;
  79134. break;
  79135. case DXGI_FORMAT_B8G8R8X8_UNORM:
  79136. info.isRGB = true;
  79137. info.isFourCC = false;
  79138. bpp = 32;
  79139. supported = true;
  79140. break;
  79141. }
  79142. if (supported) {
  79143. break;
  79144. }
  79145. default:
  79146. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  79147. return;
  79148. }
  79149. }
  79150. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  79151. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  79152. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  79153. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  79154. if (computeFormats) {
  79155. format = engine._getWebGLTextureType(info.textureType);
  79156. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79157. }
  79158. mipmapCount = 1;
  79159. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  79160. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79161. }
  79162. for (var face = 0; face < faces; face++) {
  79163. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  79164. width = header[off_width];
  79165. height = header[off_height];
  79166. for (mip = 0; mip < mipmapCount; ++mip) {
  79167. if (lodIndex === -1 || lodIndex === mip) {
  79168. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  79169. var i = (lodIndex === -1) ? mip : 0;
  79170. if (!info.isCompressed && info.isFourCC) {
  79171. dataLength = width * height * 4;
  79172. var floatArray = null;
  79173. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  79174. if (bpp === 128) {
  79175. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79176. }
  79177. else if (bpp === 64) {
  79178. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79179. }
  79180. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79181. format = engine._getWebGLTextureType(info.textureType);
  79182. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79183. }
  79184. else {
  79185. if (bpp === 128) {
  79186. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79187. }
  79188. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  79189. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79190. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79191. format = engine._getWebGLTextureType(info.textureType);
  79192. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79193. }
  79194. else {
  79195. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79196. }
  79197. }
  79198. if (floatArray) {
  79199. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  79200. }
  79201. }
  79202. else if (info.isRGB) {
  79203. if (bpp === 24) {
  79204. dataLength = width * height * 3;
  79205. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  79206. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  79207. }
  79208. else {
  79209. dataLength = width * height * 4;
  79210. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  79211. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  79212. }
  79213. }
  79214. else if (info.isLuminance) {
  79215. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  79216. var unpaddedRowSize = width;
  79217. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  79218. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  79219. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  79220. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  79221. }
  79222. else {
  79223. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  79224. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  79225. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  79226. }
  79227. }
  79228. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  79229. width *= 0.5;
  79230. height *= 0.5;
  79231. width = Math.max(1.0, width);
  79232. height = Math.max(1.0, height);
  79233. }
  79234. if (currentFace !== undefined) {
  79235. // Loading a single face
  79236. break;
  79237. }
  79238. }
  79239. };
  79240. DDSTools.StoreLODInAlphaChannel = false;
  79241. return DDSTools;
  79242. }());
  79243. BABYLON.DDSTools = DDSTools;
  79244. })(BABYLON || (BABYLON = {}));
  79245. //# sourceMappingURL=babylon.dds.js.map
  79246. "use strict";
  79247. var BABYLON;
  79248. (function (BABYLON) {
  79249. /**
  79250. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  79251. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  79252. */
  79253. var KhronosTextureContainer = /** @class */ (function () {
  79254. /**
  79255. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  79256. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  79257. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  79258. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  79259. */
  79260. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  79261. this.arrayBuffer = arrayBuffer;
  79262. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  79263. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  79264. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  79265. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  79266. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  79267. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  79268. BABYLON.Tools.Error("texture missing KTX identifier");
  79269. return;
  79270. }
  79271. // load the reset of the header in native 32 bit int
  79272. var header = new Int32Array(this.arrayBuffer, 12, 13);
  79273. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  79274. var oppositeEndianess = header[0] === 0x01020304;
  79275. // read all the header elements in order they exist in the file, without modification (sans endainness)
  79276. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  79277. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  79278. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  79279. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  79280. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  79281. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  79282. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  79283. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  79284. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  79285. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  79286. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  79287. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  79288. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  79289. if (this.glType !== 0) {
  79290. BABYLON.Tools.Error("only compressed formats currently supported");
  79291. return;
  79292. }
  79293. else {
  79294. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  79295. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  79296. }
  79297. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  79298. BABYLON.Tools.Error("only 2D textures currently supported");
  79299. return;
  79300. }
  79301. if (this.numberOfArrayElements !== 0) {
  79302. BABYLON.Tools.Error("texture arrays not currently supported");
  79303. return;
  79304. }
  79305. if (this.numberOfFaces !== facesExpected) {
  79306. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  79307. return;
  79308. }
  79309. // we now have a completely validated file, so could use existence of loadType as success
  79310. // would need to make this more elaborate & adjust checks above to support more than one load type
  79311. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  79312. }
  79313. // not as fast hardware based, but will probably never need to use
  79314. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  79315. return ((val & 0xFF) << 24)
  79316. | ((val & 0xFF00) << 8)
  79317. | ((val >> 8) & 0xFF00)
  79318. | ((val >> 24) & 0xFF);
  79319. };
  79320. /**
  79321. * It is assumed that the texture has already been created & is currently bound
  79322. */
  79323. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  79324. switch (this.loadType) {
  79325. case KhronosTextureContainer.COMPRESSED_2D:
  79326. this._upload2DCompressedLevels(gl, loadMipmaps);
  79327. break;
  79328. case KhronosTextureContainer.TEX_2D:
  79329. case KhronosTextureContainer.COMPRESSED_3D:
  79330. case KhronosTextureContainer.TEX_3D:
  79331. }
  79332. };
  79333. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  79334. // initialize width & height for level 1
  79335. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  79336. var width = this.pixelWidth;
  79337. var height = this.pixelHeight;
  79338. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  79339. for (var level = 0; level < mipmapCount; level++) {
  79340. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  79341. for (var face = 0; face < this.numberOfFaces; face++) {
  79342. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  79343. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  79344. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  79345. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  79346. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  79347. }
  79348. width = Math.max(1.0, width * 0.5);
  79349. height = Math.max(1.0, height * 0.5);
  79350. }
  79351. };
  79352. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  79353. // load types
  79354. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  79355. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  79356. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  79357. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  79358. return KhronosTextureContainer;
  79359. }());
  79360. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  79361. })(BABYLON || (BABYLON = {}));
  79362. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  79363. "use strict";
  79364. var BABYLON;
  79365. (function (BABYLON) {
  79366. var Debug = /** @class */ (function () {
  79367. function Debug() {
  79368. }
  79369. Debug.AxesViewer = /** @class */ (function () {
  79370. function AxesViewer(scene, scaleLines) {
  79371. if (scaleLines === void 0) { scaleLines = 1; }
  79372. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79373. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79374. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79375. this.scaleLines = 1;
  79376. this.scaleLines = scaleLines;
  79377. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  79378. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  79379. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  79380. this._xmesh.renderingGroupId = 2;
  79381. this._ymesh.renderingGroupId = 2;
  79382. this._zmesh.renderingGroupId = 2;
  79383. this._xmesh.material.checkReadyOnlyOnce = true;
  79384. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  79385. this._ymesh.material.checkReadyOnlyOnce = true;
  79386. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  79387. this._zmesh.material.checkReadyOnlyOnce = true;
  79388. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  79389. this.scene = scene;
  79390. }
  79391. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  79392. var scaleLines = this.scaleLines;
  79393. if (this._xmesh) {
  79394. this._xmesh.position.copyFrom(position);
  79395. }
  79396. if (this._ymesh) {
  79397. this._ymesh.position.copyFrom(position);
  79398. }
  79399. if (this._zmesh) {
  79400. this._zmesh.position.copyFrom(position);
  79401. }
  79402. var point2 = this._xline[1];
  79403. point2.x = xaxis.x * scaleLines;
  79404. point2.y = xaxis.y * scaleLines;
  79405. point2.z = xaxis.z * scaleLines;
  79406. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  79407. point2 = this._yline[1];
  79408. point2.x = yaxis.x * scaleLines;
  79409. point2.y = yaxis.y * scaleLines;
  79410. point2.z = yaxis.z * scaleLines;
  79411. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  79412. point2 = this._zline[1];
  79413. point2.x = zaxis.x * scaleLines;
  79414. point2.y = zaxis.y * scaleLines;
  79415. point2.z = zaxis.z * scaleLines;
  79416. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  79417. };
  79418. AxesViewer.prototype.dispose = function () {
  79419. if (this._xmesh) {
  79420. this._xmesh.dispose();
  79421. }
  79422. if (this._ymesh) {
  79423. this._ymesh.dispose();
  79424. }
  79425. if (this._zmesh) {
  79426. this._zmesh.dispose();
  79427. }
  79428. this._xmesh = null;
  79429. this._ymesh = null;
  79430. this._zmesh = null;
  79431. this.scene = null;
  79432. };
  79433. return AxesViewer;
  79434. }());
  79435. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  79436. __extends(BoneAxesViewer, _super);
  79437. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  79438. if (scaleLines === void 0) { scaleLines = 1; }
  79439. var _this = _super.call(this, scene, scaleLines) || this;
  79440. _this.pos = BABYLON.Vector3.Zero();
  79441. _this.xaxis = BABYLON.Vector3.Zero();
  79442. _this.yaxis = BABYLON.Vector3.Zero();
  79443. _this.zaxis = BABYLON.Vector3.Zero();
  79444. _this.mesh = mesh;
  79445. _this.bone = bone;
  79446. return _this;
  79447. }
  79448. BoneAxesViewer.prototype.update = function () {
  79449. if (!this.mesh || !this.bone) {
  79450. return;
  79451. }
  79452. var bone = this.bone;
  79453. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  79454. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  79455. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  79456. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  79457. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  79458. };
  79459. BoneAxesViewer.prototype.dispose = function () {
  79460. if (this.mesh) {
  79461. this.mesh = null;
  79462. this.bone = null;
  79463. _super.prototype.dispose.call(this);
  79464. }
  79465. };
  79466. return BoneAxesViewer;
  79467. }(Debug.AxesViewer));
  79468. Debug.PhysicsViewer = /** @class */ (function () {
  79469. function PhysicsViewer(scene) {
  79470. this._impostors = [];
  79471. this._meshes = [];
  79472. this._numMeshes = 0;
  79473. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79474. var physicEngine = this._scene.getPhysicsEngine();
  79475. if (physicEngine) {
  79476. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  79477. }
  79478. }
  79479. PhysicsViewer.prototype._updateDebugMeshes = function () {
  79480. var plugin = this._physicsEnginePlugin;
  79481. for (var i = 0; i < this._numMeshes; i++) {
  79482. var impostor = this._impostors[i];
  79483. if (!impostor) {
  79484. continue;
  79485. }
  79486. if (impostor.isDisposed) {
  79487. this.hideImpostor(this._impostors[i--]);
  79488. }
  79489. else {
  79490. var mesh = this._meshes[i];
  79491. if (mesh && plugin) {
  79492. plugin.syncMeshWithImpostor(mesh, impostor);
  79493. }
  79494. }
  79495. }
  79496. };
  79497. PhysicsViewer.prototype.showImpostor = function (impostor) {
  79498. if (!this._scene) {
  79499. return;
  79500. }
  79501. for (var i = 0; i < this._numMeshes; i++) {
  79502. if (this._impostors[i] == impostor) {
  79503. return;
  79504. }
  79505. }
  79506. var debugMesh = this._getDebugMesh(impostor, this._scene);
  79507. if (debugMesh) {
  79508. this._impostors[this._numMeshes] = impostor;
  79509. this._meshes[this._numMeshes] = debugMesh;
  79510. if (this._numMeshes === 0) {
  79511. this._renderFunction = this._updateDebugMeshes.bind(this);
  79512. this._scene.registerBeforeRender(this._renderFunction);
  79513. }
  79514. this._numMeshes++;
  79515. }
  79516. };
  79517. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  79518. if (!impostor || !this._scene) {
  79519. return;
  79520. }
  79521. var removed = false;
  79522. for (var i = 0; i < this._numMeshes; i++) {
  79523. if (this._impostors[i] == impostor) {
  79524. var mesh = this._meshes[i];
  79525. if (!mesh) {
  79526. continue;
  79527. }
  79528. this._scene.removeMesh(mesh);
  79529. mesh.dispose();
  79530. this._numMeshes--;
  79531. if (this._numMeshes > 0) {
  79532. this._meshes[i] = this._meshes[this._numMeshes];
  79533. this._impostors[i] = this._impostors[this._numMeshes];
  79534. this._meshes[this._numMeshes] = null;
  79535. this._impostors[this._numMeshes] = null;
  79536. }
  79537. else {
  79538. this._meshes[0] = null;
  79539. this._impostors[0] = null;
  79540. }
  79541. removed = true;
  79542. break;
  79543. }
  79544. }
  79545. if (removed && this._numMeshes === 0) {
  79546. this._scene.unregisterBeforeRender(this._renderFunction);
  79547. }
  79548. };
  79549. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  79550. if (!this._debugMaterial) {
  79551. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  79552. this._debugMaterial.wireframe = true;
  79553. }
  79554. return this._debugMaterial;
  79555. };
  79556. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  79557. if (!this._debugBoxMesh) {
  79558. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  79559. this._debugBoxMesh.renderingGroupId = 1;
  79560. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79561. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  79562. scene.removeMesh(this._debugBoxMesh);
  79563. }
  79564. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  79565. };
  79566. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  79567. if (!this._debugSphereMesh) {
  79568. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  79569. this._debugSphereMesh.renderingGroupId = 1;
  79570. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79571. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  79572. scene.removeMesh(this._debugSphereMesh);
  79573. }
  79574. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  79575. };
  79576. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  79577. var mesh = null;
  79578. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  79579. mesh = this._getDebugBoxMesh(scene);
  79580. impostor.getBoxSizeToRef(mesh.scaling);
  79581. }
  79582. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  79583. mesh = this._getDebugSphereMesh(scene);
  79584. var radius = impostor.getRadius();
  79585. mesh.scaling.x = radius * 2;
  79586. mesh.scaling.y = radius * 2;
  79587. mesh.scaling.z = radius * 2;
  79588. }
  79589. return mesh;
  79590. };
  79591. PhysicsViewer.prototype.dispose = function () {
  79592. for (var i = 0; i < this._numMeshes; i++) {
  79593. this.hideImpostor(this._impostors[i]);
  79594. }
  79595. if (this._debugBoxMesh) {
  79596. this._debugBoxMesh.dispose();
  79597. }
  79598. if (this._debugSphereMesh) {
  79599. this._debugSphereMesh.dispose();
  79600. }
  79601. if (this._debugMaterial) {
  79602. this._debugMaterial.dispose();
  79603. }
  79604. this._impostors.length = 0;
  79605. this._scene = null;
  79606. this._physicsEnginePlugin = null;
  79607. };
  79608. return PhysicsViewer;
  79609. }());
  79610. Debug.SkeletonViewer = /** @class */ (function () {
  79611. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  79612. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  79613. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  79614. this.skeleton = skeleton;
  79615. this.mesh = mesh;
  79616. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  79617. this.renderingGroupId = renderingGroupId;
  79618. this.color = BABYLON.Color3.White();
  79619. this._debugLines = new Array();
  79620. this._isEnabled = false;
  79621. this._scene = scene;
  79622. this.update();
  79623. this._renderFunction = this.update.bind(this);
  79624. }
  79625. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  79626. get: function () {
  79627. return this._isEnabled;
  79628. },
  79629. set: function (value) {
  79630. if (this._isEnabled === value) {
  79631. return;
  79632. }
  79633. this._isEnabled = value;
  79634. if (value) {
  79635. this._scene.registerBeforeRender(this._renderFunction);
  79636. }
  79637. else {
  79638. this._scene.unregisterBeforeRender(this._renderFunction);
  79639. }
  79640. },
  79641. enumerable: true,
  79642. configurable: true
  79643. });
  79644. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  79645. if (x === void 0) { x = 0; }
  79646. if (y === void 0) { y = 0; }
  79647. if (z === void 0) { z = 0; }
  79648. var tmat = BABYLON.Tmp.Matrix[0];
  79649. var parentBone = bone.getParent();
  79650. tmat.copyFrom(bone.getLocalMatrix());
  79651. if (x !== 0 || y !== 0 || z !== 0) {
  79652. var tmat2 = BABYLON.Tmp.Matrix[1];
  79653. BABYLON.Matrix.IdentityToRef(tmat2);
  79654. tmat2.m[12] = x;
  79655. tmat2.m[13] = y;
  79656. tmat2.m[14] = z;
  79657. tmat2.multiplyToRef(tmat, tmat);
  79658. }
  79659. if (parentBone) {
  79660. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  79661. }
  79662. tmat.multiplyToRef(meshMat, tmat);
  79663. position.x = tmat.m[12];
  79664. position.y = tmat.m[13];
  79665. position.z = tmat.m[14];
  79666. };
  79667. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  79668. var len = bones.length;
  79669. var meshPos = this.mesh.position;
  79670. for (var i = 0; i < len; i++) {
  79671. var bone = bones[i];
  79672. var points = this._debugLines[i];
  79673. if (!points) {
  79674. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79675. this._debugLines[i] = points;
  79676. }
  79677. this._getBonePosition(points[0], bone, meshMat);
  79678. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  79679. points[0].subtractInPlace(meshPos);
  79680. points[1].subtractInPlace(meshPos);
  79681. }
  79682. };
  79683. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  79684. var len = bones.length;
  79685. var boneNum = 0;
  79686. var meshPos = this.mesh.position;
  79687. for (var i = len - 1; i >= 0; i--) {
  79688. var childBone = bones[i];
  79689. var parentBone = childBone.getParent();
  79690. if (!parentBone) {
  79691. continue;
  79692. }
  79693. var points = this._debugLines[boneNum];
  79694. if (!points) {
  79695. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79696. this._debugLines[boneNum] = points;
  79697. }
  79698. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  79699. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  79700. points[0].subtractInPlace(meshPos);
  79701. points[1].subtractInPlace(meshPos);
  79702. boneNum++;
  79703. }
  79704. };
  79705. SkeletonViewer.prototype.update = function () {
  79706. if (this.autoUpdateBonesMatrices) {
  79707. this.skeleton.computeAbsoluteTransforms();
  79708. }
  79709. if (this.skeleton.bones[0].length === undefined) {
  79710. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79711. }
  79712. else {
  79713. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79714. }
  79715. if (!this._debugMesh) {
  79716. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  79717. this._debugMesh.renderingGroupId = this.renderingGroupId;
  79718. }
  79719. else {
  79720. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  79721. }
  79722. this._debugMesh.position.copyFrom(this.mesh.position);
  79723. this._debugMesh.color = this.color;
  79724. };
  79725. SkeletonViewer.prototype.dispose = function () {
  79726. if (this._debugMesh) {
  79727. this.isEnabled = false;
  79728. this._debugMesh.dispose();
  79729. this._debugMesh = null;
  79730. }
  79731. };
  79732. return SkeletonViewer;
  79733. }());
  79734. return Debug;
  79735. }());
  79736. BABYLON.Debug = Debug;
  79737. })(BABYLON || (BABYLON = {}));
  79738. //# sourceMappingURL=babylon.debugModules.js.map
  79739. "use strict";
  79740. var BABYLON;
  79741. (function (BABYLON) {
  79742. var RayHelper = /** @class */ (function () {
  79743. function RayHelper(ray) {
  79744. this.ray = ray;
  79745. }
  79746. RayHelper.CreateAndShow = function (ray, scene, color) {
  79747. var helper = new RayHelper(ray);
  79748. helper.show(scene, color);
  79749. return helper;
  79750. };
  79751. RayHelper.prototype.show = function (scene, color) {
  79752. if (!this._renderFunction && this.ray) {
  79753. var ray = this.ray;
  79754. this._renderFunction = this._render.bind(this);
  79755. this._scene = scene;
  79756. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  79757. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  79758. if (this._renderFunction) {
  79759. this._scene.registerBeforeRender(this._renderFunction);
  79760. }
  79761. }
  79762. if (color && this._renderLine) {
  79763. this._renderLine.color.copyFrom(color);
  79764. }
  79765. };
  79766. RayHelper.prototype.hide = function () {
  79767. if (this._renderFunction && this._scene) {
  79768. this._scene.unregisterBeforeRender(this._renderFunction);
  79769. this._scene = null;
  79770. this._renderFunction = null;
  79771. if (this._renderLine) {
  79772. this._renderLine.dispose();
  79773. this._renderLine = null;
  79774. }
  79775. this._renderPoints = [];
  79776. }
  79777. };
  79778. RayHelper.prototype._render = function () {
  79779. var ray = this.ray;
  79780. if (!ray) {
  79781. return;
  79782. }
  79783. var point = this._renderPoints[1];
  79784. var len = Math.min(ray.length, 1000000);
  79785. point.copyFrom(ray.direction);
  79786. point.scaleInPlace(len);
  79787. point.addInPlace(ray.origin);
  79788. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  79789. };
  79790. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  79791. this._attachedToMesh = mesh;
  79792. var ray = this.ray;
  79793. if (!ray) {
  79794. return;
  79795. }
  79796. if (!ray.direction) {
  79797. ray.direction = BABYLON.Vector3.Zero();
  79798. }
  79799. if (!ray.origin) {
  79800. ray.origin = BABYLON.Vector3.Zero();
  79801. }
  79802. if (length) {
  79803. ray.length = length;
  79804. }
  79805. if (!meshSpaceOrigin) {
  79806. meshSpaceOrigin = BABYLON.Vector3.Zero();
  79807. }
  79808. if (!meshSpaceDirection) {
  79809. // -1 so that this will work with Mesh.lookAt
  79810. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  79811. }
  79812. if (!this._meshSpaceDirection) {
  79813. this._meshSpaceDirection = meshSpaceDirection.clone();
  79814. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  79815. }
  79816. else {
  79817. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  79818. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  79819. }
  79820. if (!this._updateToMeshFunction) {
  79821. this._updateToMeshFunction = this._updateToMesh.bind(this);
  79822. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  79823. }
  79824. this._updateToMesh();
  79825. };
  79826. RayHelper.prototype.detachFromMesh = function () {
  79827. if (this._attachedToMesh) {
  79828. if (this._updateToMeshFunction) {
  79829. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  79830. }
  79831. this._attachedToMesh = null;
  79832. this._updateToMeshFunction = null;
  79833. }
  79834. };
  79835. RayHelper.prototype._updateToMesh = function () {
  79836. var ray = this.ray;
  79837. if (!this._attachedToMesh || !ray) {
  79838. return;
  79839. }
  79840. if (this._attachedToMesh._isDisposed) {
  79841. this.detachFromMesh();
  79842. return;
  79843. }
  79844. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  79845. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  79846. };
  79847. RayHelper.prototype.dispose = function () {
  79848. this.hide();
  79849. this.detachFromMesh();
  79850. this.ray = null;
  79851. };
  79852. return RayHelper;
  79853. }());
  79854. BABYLON.RayHelper = RayHelper;
  79855. })(BABYLON || (BABYLON = {}));
  79856. //# sourceMappingURL=babylon.rayHelper.js.map
  79857. "use strict";
  79858. var BABYLON;
  79859. (function (BABYLON) {
  79860. // load the inspector using require, if not present in the global namespace.
  79861. var DebugLayer = /** @class */ (function () {
  79862. function DebugLayer(scene) {
  79863. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79864. this._scene = scene;
  79865. // load inspector using require, if it doesn't exist on the global namespace.
  79866. }
  79867. /** Creates the inspector window. */
  79868. DebugLayer.prototype._createInspector = function (config) {
  79869. if (config === void 0) { config = {}; }
  79870. var popup = config.popup || false;
  79871. var initialTab = config.initialTab || 0;
  79872. var parentElement = config.parentElement || null;
  79873. if (!this._inspector) {
  79874. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79875. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  79876. } // else nothing to do,; instance is already existing
  79877. };
  79878. DebugLayer.prototype.isVisible = function () {
  79879. if (!this._inspector) {
  79880. return false;
  79881. }
  79882. return true;
  79883. };
  79884. DebugLayer.prototype.hide = function () {
  79885. if (this._inspector) {
  79886. try {
  79887. this._inspector.dispose();
  79888. }
  79889. catch (e) {
  79890. // If the inspector has been removed directly from the inspector tool
  79891. }
  79892. this._inspector = null;
  79893. }
  79894. };
  79895. DebugLayer.prototype.show = function (config) {
  79896. if (config === void 0) { config = {}; }
  79897. if (typeof this.BJSINSPECTOR == 'undefined') {
  79898. // Load inspector and add it to the DOM
  79899. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  79900. }
  79901. else {
  79902. // Otherwise creates the inspector
  79903. this._createInspector(config);
  79904. }
  79905. };
  79906. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  79907. return DebugLayer;
  79908. }());
  79909. BABYLON.DebugLayer = DebugLayer;
  79910. })(BABYLON || (BABYLON = {}));
  79911. //# sourceMappingURL=babylon.debugLayer.js.map
  79912. "use strict";
  79913. var BABYLON;
  79914. (function (BABYLON) {
  79915. var BoundingBoxRenderer = /** @class */ (function () {
  79916. function BoundingBoxRenderer(scene) {
  79917. this.frontColor = new BABYLON.Color3(1, 1, 1);
  79918. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  79919. this.showBackLines = true;
  79920. this.renderList = new BABYLON.SmartArray(32);
  79921. this._vertexBuffers = {};
  79922. this._scene = scene;
  79923. }
  79924. BoundingBoxRenderer.prototype._prepareRessources = function () {
  79925. if (this._colorShader) {
  79926. return;
  79927. }
  79928. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  79929. attributes: [BABYLON.VertexBuffer.PositionKind],
  79930. uniforms: ["world", "viewProjection", "color"]
  79931. });
  79932. var engine = this._scene.getEngine();
  79933. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  79934. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  79935. this._createIndexBuffer();
  79936. };
  79937. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  79938. var engine = this._scene.getEngine();
  79939. 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]);
  79940. };
  79941. BoundingBoxRenderer.prototype._rebuild = function () {
  79942. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79943. if (vb) {
  79944. vb._rebuild();
  79945. }
  79946. this._createIndexBuffer();
  79947. };
  79948. BoundingBoxRenderer.prototype.reset = function () {
  79949. this.renderList.reset();
  79950. };
  79951. BoundingBoxRenderer.prototype.render = function () {
  79952. if (this.renderList.length === 0) {
  79953. return;
  79954. }
  79955. this._prepareRessources();
  79956. if (!this._colorShader.isReady()) {
  79957. return;
  79958. }
  79959. var engine = this._scene.getEngine();
  79960. engine.setDepthWrite(false);
  79961. this._colorShader._preBind();
  79962. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  79963. var boundingBox = this.renderList.data[boundingBoxIndex];
  79964. var min = boundingBox.minimum;
  79965. var max = boundingBox.maximum;
  79966. var diff = max.subtract(min);
  79967. var median = min.add(diff.scale(0.5));
  79968. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79969. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79970. .multiply(boundingBox.getWorldMatrix());
  79971. // VBOs
  79972. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79973. if (this.showBackLines) {
  79974. // Back
  79975. engine.setDepthFunctionToGreaterOrEqual();
  79976. this._scene.resetCachedMaterial();
  79977. this._colorShader.setColor4("color", this.backColor.toColor4());
  79978. this._colorShader.bind(worldMatrix);
  79979. // Draw order
  79980. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79981. }
  79982. // Front
  79983. engine.setDepthFunctionToLess();
  79984. this._scene.resetCachedMaterial();
  79985. this._colorShader.setColor4("color", this.frontColor.toColor4());
  79986. this._colorShader.bind(worldMatrix);
  79987. // Draw order
  79988. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79989. }
  79990. this._colorShader.unbind();
  79991. engine.setDepthFunctionToLessOrEqual();
  79992. engine.setDepthWrite(true);
  79993. };
  79994. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  79995. this._prepareRessources();
  79996. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  79997. return;
  79998. }
  79999. var engine = this._scene.getEngine();
  80000. engine.setDepthWrite(false);
  80001. engine.setColorWrite(false);
  80002. this._colorShader._preBind();
  80003. var boundingBox = mesh._boundingInfo.boundingBox;
  80004. var min = boundingBox.minimum;
  80005. var max = boundingBox.maximum;
  80006. var diff = max.subtract(min);
  80007. var median = min.add(diff.scale(0.5));
  80008. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80009. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80010. .multiply(boundingBox.getWorldMatrix());
  80011. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80012. engine.setDepthFunctionToLess();
  80013. this._scene.resetCachedMaterial();
  80014. this._colorShader.bind(worldMatrix);
  80015. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80016. this._colorShader.unbind();
  80017. engine.setDepthFunctionToLessOrEqual();
  80018. engine.setDepthWrite(true);
  80019. engine.setColorWrite(true);
  80020. };
  80021. BoundingBoxRenderer.prototype.dispose = function () {
  80022. if (!this._colorShader) {
  80023. return;
  80024. }
  80025. this.renderList.dispose();
  80026. this._colorShader.dispose();
  80027. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80028. if (buffer) {
  80029. buffer.dispose();
  80030. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80031. }
  80032. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80033. };
  80034. return BoundingBoxRenderer;
  80035. }());
  80036. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  80037. })(BABYLON || (BABYLON = {}));
  80038. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  80039. "use strict";
  80040. var BABYLON;
  80041. (function (BABYLON) {
  80042. var MorphTarget = /** @class */ (function () {
  80043. function MorphTarget(name, influence) {
  80044. if (influence === void 0) { influence = 0; }
  80045. this.name = name;
  80046. this.animations = new Array();
  80047. this._positions = null;
  80048. this._normals = null;
  80049. this._tangents = null;
  80050. this.onInfluenceChanged = new BABYLON.Observable();
  80051. this.influence = influence;
  80052. }
  80053. Object.defineProperty(MorphTarget.prototype, "influence", {
  80054. get: function () {
  80055. return this._influence;
  80056. },
  80057. set: function (influence) {
  80058. if (this._influence === influence) {
  80059. return;
  80060. }
  80061. var previous = this._influence;
  80062. this._influence = influence;
  80063. if (this.onInfluenceChanged.hasObservers) {
  80064. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  80065. }
  80066. },
  80067. enumerable: true,
  80068. configurable: true
  80069. });
  80070. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  80071. get: function () {
  80072. return !!this._positions;
  80073. },
  80074. enumerable: true,
  80075. configurable: true
  80076. });
  80077. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  80078. get: function () {
  80079. return !!this._normals;
  80080. },
  80081. enumerable: true,
  80082. configurable: true
  80083. });
  80084. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  80085. get: function () {
  80086. return !!this._tangents;
  80087. },
  80088. enumerable: true,
  80089. configurable: true
  80090. });
  80091. MorphTarget.prototype.setPositions = function (data) {
  80092. this._positions = data;
  80093. };
  80094. MorphTarget.prototype.getPositions = function () {
  80095. return this._positions;
  80096. };
  80097. MorphTarget.prototype.setNormals = function (data) {
  80098. this._normals = data;
  80099. };
  80100. MorphTarget.prototype.getNormals = function () {
  80101. return this._normals;
  80102. };
  80103. MorphTarget.prototype.setTangents = function (data) {
  80104. this._tangents = data;
  80105. };
  80106. MorphTarget.prototype.getTangents = function () {
  80107. return this._tangents;
  80108. };
  80109. /**
  80110. * Serializes the current target into a Serialization object.
  80111. * Returns the serialized object.
  80112. */
  80113. MorphTarget.prototype.serialize = function () {
  80114. var serializationObject = {};
  80115. serializationObject.name = this.name;
  80116. serializationObject.influence = this.influence;
  80117. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  80118. if (this.hasNormals) {
  80119. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  80120. }
  80121. if (this.hasTangents) {
  80122. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  80123. }
  80124. // Animations
  80125. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  80126. return serializationObject;
  80127. };
  80128. // Statics
  80129. MorphTarget.Parse = function (serializationObject) {
  80130. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  80131. result.setPositions(serializationObject.positions);
  80132. if (serializationObject.normals) {
  80133. result.setNormals(serializationObject.normals);
  80134. }
  80135. if (serializationObject.tangents) {
  80136. result.setTangents(serializationObject.tangents);
  80137. }
  80138. // Animations
  80139. if (serializationObject.animations) {
  80140. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  80141. var parsedAnimation = serializationObject.animations[animationIndex];
  80142. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  80143. }
  80144. }
  80145. return result;
  80146. };
  80147. MorphTarget.FromMesh = function (mesh, name, influence) {
  80148. if (!name) {
  80149. name = mesh.name;
  80150. }
  80151. var result = new MorphTarget(name, influence);
  80152. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  80153. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80154. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  80155. }
  80156. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  80157. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  80158. }
  80159. return result;
  80160. };
  80161. return MorphTarget;
  80162. }());
  80163. BABYLON.MorphTarget = MorphTarget;
  80164. })(BABYLON || (BABYLON = {}));
  80165. //# sourceMappingURL=babylon.morphTarget.js.map
  80166. "use strict";
  80167. var BABYLON;
  80168. (function (BABYLON) {
  80169. var MorphTargetManager = /** @class */ (function () {
  80170. function MorphTargetManager(scene) {
  80171. if (scene === void 0) { scene = null; }
  80172. this._targets = new Array();
  80173. this._targetObservable = new Array();
  80174. this._activeTargets = new BABYLON.SmartArray(16);
  80175. this._supportsNormals = false;
  80176. this._supportsTangents = false;
  80177. this._vertexCount = 0;
  80178. this._uniqueId = 0;
  80179. this._tempInfluences = new Array();
  80180. if (!scene) {
  80181. scene = BABYLON.Engine.LastCreatedScene;
  80182. }
  80183. this._scene = scene;
  80184. if (this._scene) {
  80185. this._scene.morphTargetManagers.push(this);
  80186. this._uniqueId = this._scene.getUniqueId();
  80187. }
  80188. }
  80189. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  80190. get: function () {
  80191. return this._uniqueId;
  80192. },
  80193. enumerable: true,
  80194. configurable: true
  80195. });
  80196. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  80197. get: function () {
  80198. return this._vertexCount;
  80199. },
  80200. enumerable: true,
  80201. configurable: true
  80202. });
  80203. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  80204. get: function () {
  80205. return this._supportsNormals;
  80206. },
  80207. enumerable: true,
  80208. configurable: true
  80209. });
  80210. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  80211. get: function () {
  80212. return this._supportsTangents;
  80213. },
  80214. enumerable: true,
  80215. configurable: true
  80216. });
  80217. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  80218. get: function () {
  80219. return this._targets.length;
  80220. },
  80221. enumerable: true,
  80222. configurable: true
  80223. });
  80224. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  80225. get: function () {
  80226. return this._activeTargets.length;
  80227. },
  80228. enumerable: true,
  80229. configurable: true
  80230. });
  80231. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  80232. get: function () {
  80233. return this._influences;
  80234. },
  80235. enumerable: true,
  80236. configurable: true
  80237. });
  80238. MorphTargetManager.prototype.getActiveTarget = function (index) {
  80239. return this._activeTargets.data[index];
  80240. };
  80241. MorphTargetManager.prototype.getTarget = function (index) {
  80242. return this._targets[index];
  80243. };
  80244. MorphTargetManager.prototype.addTarget = function (target) {
  80245. var _this = this;
  80246. this._targets.push(target);
  80247. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  80248. _this._syncActiveTargets(needUpdate);
  80249. }));
  80250. this._syncActiveTargets(true);
  80251. };
  80252. MorphTargetManager.prototype.removeTarget = function (target) {
  80253. var index = this._targets.indexOf(target);
  80254. if (index >= 0) {
  80255. this._targets.splice(index, 1);
  80256. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  80257. this._syncActiveTargets(true);
  80258. }
  80259. };
  80260. /**
  80261. * Serializes the current manager into a Serialization object.
  80262. * Returns the serialized object.
  80263. */
  80264. MorphTargetManager.prototype.serialize = function () {
  80265. var serializationObject = {};
  80266. serializationObject.id = this.uniqueId;
  80267. serializationObject.targets = [];
  80268. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80269. var target = _a[_i];
  80270. serializationObject.targets.push(target.serialize());
  80271. }
  80272. return serializationObject;
  80273. };
  80274. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  80275. var influenceCount = 0;
  80276. this._activeTargets.reset();
  80277. this._supportsNormals = true;
  80278. this._supportsTangents = true;
  80279. this._vertexCount = 0;
  80280. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80281. var target = _a[_i];
  80282. this._activeTargets.push(target);
  80283. this._tempInfluences[influenceCount++] = target.influence;
  80284. var positions = target.getPositions();
  80285. if (positions) {
  80286. this._supportsNormals = this._supportsNormals && target.hasNormals;
  80287. this._supportsTangents = this._supportsTangents && target.hasTangents;
  80288. var vertexCount = positions.length / 3;
  80289. if (this._vertexCount === 0) {
  80290. this._vertexCount = vertexCount;
  80291. }
  80292. else if (this._vertexCount !== vertexCount) {
  80293. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  80294. return;
  80295. }
  80296. }
  80297. }
  80298. if (!this._influences || this._influences.length !== influenceCount) {
  80299. this._influences = new Float32Array(influenceCount);
  80300. }
  80301. for (var index = 0; index < influenceCount; index++) {
  80302. this._influences[index] = this._tempInfluences[index];
  80303. }
  80304. if (needUpdate && this._scene) {
  80305. // Flag meshes as dirty to resync with the active targets
  80306. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  80307. var mesh = _c[_b];
  80308. if (mesh.morphTargetManager === this) {
  80309. mesh._syncGeometryWithMorphTargetManager();
  80310. }
  80311. }
  80312. }
  80313. };
  80314. // Statics
  80315. MorphTargetManager.Parse = function (serializationObject, scene) {
  80316. var result = new MorphTargetManager(scene);
  80317. result._uniqueId = serializationObject.id;
  80318. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  80319. var targetData = _a[_i];
  80320. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  80321. }
  80322. return result;
  80323. };
  80324. return MorphTargetManager;
  80325. }());
  80326. BABYLON.MorphTargetManager = MorphTargetManager;
  80327. })(BABYLON || (BABYLON = {}));
  80328. //# sourceMappingURL=babylon.morphTargetManager.js.map
  80329. "use strict";
  80330. var BABYLON;
  80331. (function (BABYLON) {
  80332. var Octree = /** @class */ (function () {
  80333. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  80334. if (maxDepth === void 0) { maxDepth = 2; }
  80335. this.maxDepth = maxDepth;
  80336. this.dynamicContent = new Array();
  80337. this._maxBlockCapacity = maxBlockCapacity || 64;
  80338. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  80339. this._creationFunc = creationFunc;
  80340. }
  80341. // Methods
  80342. Octree.prototype.update = function (worldMin, worldMax, entries) {
  80343. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  80344. };
  80345. Octree.prototype.addMesh = function (entry) {
  80346. for (var index = 0; index < this.blocks.length; index++) {
  80347. var block = this.blocks[index];
  80348. block.addEntry(entry);
  80349. }
  80350. };
  80351. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  80352. this._selectionContent.reset();
  80353. for (var index = 0; index < this.blocks.length; index++) {
  80354. var block = this.blocks[index];
  80355. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  80356. }
  80357. if (allowDuplicate) {
  80358. this._selectionContent.concat(this.dynamicContent);
  80359. }
  80360. else {
  80361. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80362. }
  80363. return this._selectionContent;
  80364. };
  80365. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  80366. this._selectionContent.reset();
  80367. for (var index = 0; index < this.blocks.length; index++) {
  80368. var block = this.blocks[index];
  80369. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  80370. }
  80371. if (allowDuplicate) {
  80372. this._selectionContent.concat(this.dynamicContent);
  80373. }
  80374. else {
  80375. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80376. }
  80377. return this._selectionContent;
  80378. };
  80379. Octree.prototype.intersectsRay = function (ray) {
  80380. this._selectionContent.reset();
  80381. for (var index = 0; index < this.blocks.length; index++) {
  80382. var block = this.blocks[index];
  80383. block.intersectsRay(ray, this._selectionContent);
  80384. }
  80385. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80386. return this._selectionContent;
  80387. };
  80388. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  80389. target.blocks = new Array();
  80390. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  80391. // Segmenting space
  80392. for (var x = 0; x < 2; x++) {
  80393. for (var y = 0; y < 2; y++) {
  80394. for (var z = 0; z < 2; z++) {
  80395. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  80396. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  80397. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  80398. block.addEntries(entries);
  80399. target.blocks.push(block);
  80400. }
  80401. }
  80402. }
  80403. };
  80404. Octree.CreationFuncForMeshes = function (entry, block) {
  80405. var boundingInfo = entry.getBoundingInfo();
  80406. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80407. block.entries.push(entry);
  80408. }
  80409. };
  80410. Octree.CreationFuncForSubMeshes = function (entry, block) {
  80411. var boundingInfo = entry.getBoundingInfo();
  80412. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80413. block.entries.push(entry);
  80414. }
  80415. };
  80416. return Octree;
  80417. }());
  80418. BABYLON.Octree = Octree;
  80419. })(BABYLON || (BABYLON = {}));
  80420. //# sourceMappingURL=babylon.octree.js.map
  80421. "use strict";
  80422. var BABYLON;
  80423. (function (BABYLON) {
  80424. var OctreeBlock = /** @class */ (function () {
  80425. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  80426. this.entries = new Array();
  80427. this._boundingVectors = new Array();
  80428. this._capacity = capacity;
  80429. this._depth = depth;
  80430. this._maxDepth = maxDepth;
  80431. this._creationFunc = creationFunc;
  80432. this._minPoint = minPoint;
  80433. this._maxPoint = maxPoint;
  80434. this._boundingVectors.push(minPoint.clone());
  80435. this._boundingVectors.push(maxPoint.clone());
  80436. this._boundingVectors.push(minPoint.clone());
  80437. this._boundingVectors[2].x = maxPoint.x;
  80438. this._boundingVectors.push(minPoint.clone());
  80439. this._boundingVectors[3].y = maxPoint.y;
  80440. this._boundingVectors.push(minPoint.clone());
  80441. this._boundingVectors[4].z = maxPoint.z;
  80442. this._boundingVectors.push(maxPoint.clone());
  80443. this._boundingVectors[5].z = minPoint.z;
  80444. this._boundingVectors.push(maxPoint.clone());
  80445. this._boundingVectors[6].x = minPoint.x;
  80446. this._boundingVectors.push(maxPoint.clone());
  80447. this._boundingVectors[7].y = minPoint.y;
  80448. }
  80449. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  80450. // Property
  80451. get: function () {
  80452. return this._capacity;
  80453. },
  80454. enumerable: true,
  80455. configurable: true
  80456. });
  80457. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  80458. get: function () {
  80459. return this._minPoint;
  80460. },
  80461. enumerable: true,
  80462. configurable: true
  80463. });
  80464. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  80465. get: function () {
  80466. return this._maxPoint;
  80467. },
  80468. enumerable: true,
  80469. configurable: true
  80470. });
  80471. // Methods
  80472. OctreeBlock.prototype.addEntry = function (entry) {
  80473. if (this.blocks) {
  80474. for (var index = 0; index < this.blocks.length; index++) {
  80475. var block = this.blocks[index];
  80476. block.addEntry(entry);
  80477. }
  80478. return;
  80479. }
  80480. this._creationFunc(entry, this);
  80481. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  80482. this.createInnerBlocks();
  80483. }
  80484. };
  80485. OctreeBlock.prototype.addEntries = function (entries) {
  80486. for (var index = 0; index < entries.length; index++) {
  80487. var mesh = entries[index];
  80488. this.addEntry(mesh);
  80489. }
  80490. };
  80491. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  80492. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  80493. if (this.blocks) {
  80494. for (var index = 0; index < this.blocks.length; index++) {
  80495. var block = this.blocks[index];
  80496. block.select(frustumPlanes, selection, allowDuplicate);
  80497. }
  80498. return;
  80499. }
  80500. if (allowDuplicate) {
  80501. selection.concat(this.entries);
  80502. }
  80503. else {
  80504. selection.concatWithNoDuplicate(this.entries);
  80505. }
  80506. }
  80507. };
  80508. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  80509. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  80510. if (this.blocks) {
  80511. for (var index = 0; index < this.blocks.length; index++) {
  80512. var block = this.blocks[index];
  80513. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  80514. }
  80515. return;
  80516. }
  80517. if (allowDuplicate) {
  80518. selection.concat(this.entries);
  80519. }
  80520. else {
  80521. selection.concatWithNoDuplicate(this.entries);
  80522. }
  80523. }
  80524. };
  80525. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  80526. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  80527. if (this.blocks) {
  80528. for (var index = 0; index < this.blocks.length; index++) {
  80529. var block = this.blocks[index];
  80530. block.intersectsRay(ray, selection);
  80531. }
  80532. return;
  80533. }
  80534. selection.concatWithNoDuplicate(this.entries);
  80535. }
  80536. };
  80537. OctreeBlock.prototype.createInnerBlocks = function () {
  80538. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  80539. };
  80540. return OctreeBlock;
  80541. }());
  80542. BABYLON.OctreeBlock = OctreeBlock;
  80543. })(BABYLON || (BABYLON = {}));
  80544. //# sourceMappingURL=babylon.octreeBlock.js.map
  80545. "use strict";
  80546. var BABYLON;
  80547. (function (BABYLON) {
  80548. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  80549. __extends(VRDistortionCorrectionPostProcess, _super);
  80550. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  80551. var _this = _super.call(this, name, "vrDistortionCorrection", [
  80552. 'LensCenter',
  80553. 'Scale',
  80554. 'ScaleIn',
  80555. 'HmdWarpParam'
  80556. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  80557. _this._isRightEye = isRightEye;
  80558. _this._distortionFactors = vrMetrics.distortionK;
  80559. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  80560. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  80561. _this.adaptScaleToCurrentViewport = true;
  80562. _this.onSizeChangedObservable.add(function () {
  80563. _this.aspectRatio = _this.width * .5 / _this.height;
  80564. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  80565. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  80566. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  80567. });
  80568. _this.onApplyObservable.add(function (effect) {
  80569. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  80570. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  80571. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  80572. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  80573. });
  80574. return _this;
  80575. }
  80576. return VRDistortionCorrectionPostProcess;
  80577. }(BABYLON.PostProcess));
  80578. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  80579. })(BABYLON || (BABYLON = {}));
  80580. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  80581. "use strict";
  80582. var BABYLON;
  80583. (function (BABYLON) {
  80584. var AnaglyphPostProcess = /** @class */ (function (_super) {
  80585. __extends(AnaglyphPostProcess, _super);
  80586. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  80587. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  80588. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80589. _this.onApplyObservable.add(function (effect) {
  80590. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  80591. });
  80592. return _this;
  80593. }
  80594. return AnaglyphPostProcess;
  80595. }(BABYLON.PostProcess));
  80596. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  80597. })(BABYLON || (BABYLON = {}));
  80598. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  80599. "use strict";
  80600. var BABYLON;
  80601. (function (BABYLON) {
  80602. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  80603. __extends(StereoscopicInterlacePostProcess, _super);
  80604. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  80605. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  80606. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80607. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80608. _this.onSizeChangedObservable.add(function () {
  80609. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80610. });
  80611. _this.onApplyObservable.add(function (effect) {
  80612. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  80613. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  80614. });
  80615. return _this;
  80616. }
  80617. return StereoscopicInterlacePostProcess;
  80618. }(BABYLON.PostProcess));
  80619. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  80620. })(BABYLON || (BABYLON = {}));
  80621. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  80622. "use strict";
  80623. var BABYLON;
  80624. (function (BABYLON) {
  80625. /**
  80626. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  80627. * Screen rotation is taken into account.
  80628. */
  80629. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  80630. function FreeCameraDeviceOrientationInput() {
  80631. var _this = this;
  80632. this._screenOrientationAngle = 0;
  80633. this._screenQuaternion = new BABYLON.Quaternion();
  80634. this._alpha = 0;
  80635. this._beta = 0;
  80636. this._gamma = 0;
  80637. this._orientationChanged = function () {
  80638. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  80639. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  80640. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  80641. };
  80642. this._deviceOrientation = function (evt) {
  80643. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  80644. _this._beta = evt.beta !== null ? evt.beta : 0;
  80645. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  80646. };
  80647. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  80648. this._orientationChanged();
  80649. }
  80650. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  80651. get: function () {
  80652. return this._camera;
  80653. },
  80654. set: function (camera) {
  80655. this._camera = camera;
  80656. if (this._camera != null && !this._camera.rotationQuaternion) {
  80657. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  80658. }
  80659. },
  80660. enumerable: true,
  80661. configurable: true
  80662. });
  80663. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80664. window.addEventListener("orientationchange", this._orientationChanged);
  80665. window.addEventListener("deviceorientation", this._deviceOrientation);
  80666. //In certain cases, the attach control is called AFTER orientation was changed,
  80667. //So this is needed.
  80668. this._orientationChanged();
  80669. };
  80670. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  80671. window.removeEventListener("orientationchange", this._orientationChanged);
  80672. window.removeEventListener("deviceorientation", this._deviceOrientation);
  80673. };
  80674. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  80675. //if no device orientation provided, don't update the rotation.
  80676. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  80677. if (!this._alpha)
  80678. return;
  80679. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  80680. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  80681. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  80682. //Mirror on XY Plane
  80683. this._camera.rotationQuaternion.z *= -1;
  80684. this._camera.rotationQuaternion.w *= -1;
  80685. };
  80686. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  80687. return "FreeCameraDeviceOrientationInput";
  80688. };
  80689. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  80690. return "deviceOrientation";
  80691. };
  80692. return FreeCameraDeviceOrientationInput;
  80693. }());
  80694. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  80695. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  80696. })(BABYLON || (BABYLON = {}));
  80697. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  80698. "use strict";
  80699. var BABYLON;
  80700. (function (BABYLON) {
  80701. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  80702. function ArcRotateCameraVRDeviceOrientationInput() {
  80703. this.alphaCorrection = 1;
  80704. this.betaCorrection = 1;
  80705. this.gammaCorrection = 1;
  80706. this._alpha = 0;
  80707. this._gamma = 0;
  80708. this._dirty = false;
  80709. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  80710. }
  80711. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80712. this.camera.attachControl(element, noPreventDefault);
  80713. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  80714. };
  80715. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  80716. if (evt.alpha !== null) {
  80717. this._alpha = +evt.alpha | 0;
  80718. }
  80719. if (evt.gamma !== null) {
  80720. this._gamma = +evt.gamma | 0;
  80721. }
  80722. this._dirty = true;
  80723. };
  80724. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  80725. if (this._dirty) {
  80726. this._dirty = false;
  80727. if (this._gamma < 0) {
  80728. this._gamma = 180 + this._gamma;
  80729. }
  80730. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  80731. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  80732. }
  80733. };
  80734. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  80735. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  80736. };
  80737. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  80738. return "ArcRotateCameraVRDeviceOrientationInput";
  80739. };
  80740. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  80741. return "VRDeviceOrientation";
  80742. };
  80743. return ArcRotateCameraVRDeviceOrientationInput;
  80744. }());
  80745. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  80746. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  80747. })(BABYLON || (BABYLON = {}));
  80748. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  80749. "use strict";
  80750. var BABYLON;
  80751. (function (BABYLON) {
  80752. var VRCameraMetrics = /** @class */ (function () {
  80753. function VRCameraMetrics() {
  80754. this.compensateDistortion = true;
  80755. }
  80756. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  80757. get: function () {
  80758. return this.hResolution / (2 * this.vResolution);
  80759. },
  80760. enumerable: true,
  80761. configurable: true
  80762. });
  80763. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  80764. get: function () {
  80765. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  80766. },
  80767. enumerable: true,
  80768. configurable: true
  80769. });
  80770. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  80771. get: function () {
  80772. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80773. var h = (4 * meters) / this.hScreenSize;
  80774. return BABYLON.Matrix.Translation(h, 0, 0);
  80775. },
  80776. enumerable: true,
  80777. configurable: true
  80778. });
  80779. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  80780. get: function () {
  80781. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80782. var h = (4 * meters) / this.hScreenSize;
  80783. return BABYLON.Matrix.Translation(-h, 0, 0);
  80784. },
  80785. enumerable: true,
  80786. configurable: true
  80787. });
  80788. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  80789. get: function () {
  80790. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  80791. },
  80792. enumerable: true,
  80793. configurable: true
  80794. });
  80795. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  80796. get: function () {
  80797. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  80798. },
  80799. enumerable: true,
  80800. configurable: true
  80801. });
  80802. VRCameraMetrics.GetDefault = function () {
  80803. var result = new VRCameraMetrics();
  80804. result.hResolution = 1280;
  80805. result.vResolution = 800;
  80806. result.hScreenSize = 0.149759993;
  80807. result.vScreenSize = 0.0935999975;
  80808. result.vScreenCenter = 0.0467999987;
  80809. result.eyeToScreenDistance = 0.0410000011;
  80810. result.lensSeparationDistance = 0.0635000020;
  80811. result.interpupillaryDistance = 0.0640000030;
  80812. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  80813. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  80814. result.postProcessScaleFactor = 1.714605507808412;
  80815. result.lensCenterOffset = 0.151976421;
  80816. return result;
  80817. };
  80818. return VRCameraMetrics;
  80819. }());
  80820. BABYLON.VRCameraMetrics = VRCameraMetrics;
  80821. })(BABYLON || (BABYLON = {}));
  80822. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  80823. "use strict";
  80824. var BABYLON;
  80825. (function (BABYLON) {
  80826. /**
  80827. * This represents a WebVR camera.
  80828. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  80829. * @example http://doc.babylonjs.com/how_to/webvr_camera
  80830. */
  80831. var WebVRFreeCamera = /** @class */ (function (_super) {
  80832. __extends(WebVRFreeCamera, _super);
  80833. /**
  80834. * Instantiates a WebVRFreeCamera.
  80835. * @param name The name of the WebVRFreeCamera
  80836. * @param position The starting anchor position for the camera
  80837. * @param scene The scene the camera belongs to
  80838. * @param webVROptions a set of customizable options for the webVRCamera
  80839. */
  80840. function WebVRFreeCamera(name, position, scene, webVROptions) {
  80841. if (webVROptions === void 0) { webVROptions = {}; }
  80842. var _this = _super.call(this, name, position, scene) || this;
  80843. _this.webVROptions = webVROptions;
  80844. /**
  80845. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  80846. */
  80847. _this._vrDevice = null;
  80848. /**
  80849. * The rawPose of the vrDevice.
  80850. */
  80851. _this.rawPose = null;
  80852. _this._specsVersion = "1.1";
  80853. _this._attached = false;
  80854. _this._descendants = [];
  80855. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  80856. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  80857. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  80858. _this._standingMatrix = null;
  80859. /**
  80860. * Represents device position in babylon space.
  80861. */
  80862. _this.devicePosition = BABYLON.Vector3.Zero();
  80863. /**
  80864. * Represents device rotation in babylon space.
  80865. */
  80866. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  80867. /**
  80868. * The scale of the device to be used when translating from device space to babylon space.
  80869. */
  80870. _this.deviceScaleFactor = 1;
  80871. _this._deviceToWorld = BABYLON.Matrix.Identity();
  80872. _this._worldToDevice = BABYLON.Matrix.Identity();
  80873. /**
  80874. * References to the webVR controllers for the vrDevice.
  80875. */
  80876. _this.controllers = [];
  80877. /**
  80878. * Emits an event when a controller is attached.
  80879. */
  80880. _this.onControllersAttachedObservable = new BABYLON.Observable();
  80881. /**
  80882. * Emits an event when a controller's mesh has been loaded;
  80883. */
  80884. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80885. /**
  80886. * If the rig cameras be used as parent instead of this camera.
  80887. */
  80888. _this.rigParenting = true;
  80889. _this._defaultHeight = undefined;
  80890. _this._workingVector = BABYLON.Vector3.Zero();
  80891. _this._oneVector = BABYLON.Vector3.One();
  80892. _this._workingMatrix = BABYLON.Matrix.Identity();
  80893. _this._cache.position = BABYLON.Vector3.Zero();
  80894. if (webVROptions.defaultHeight) {
  80895. _this._defaultHeight = webVROptions.defaultHeight;
  80896. _this.position.y = _this._defaultHeight;
  80897. }
  80898. _this.minZ = 0.1;
  80899. //legacy support - the compensation boolean was removed.
  80900. if (arguments.length === 5) {
  80901. _this.webVROptions = arguments[4];
  80902. }
  80903. // default webVR options
  80904. if (_this.webVROptions.trackPosition == undefined) {
  80905. _this.webVROptions.trackPosition = true;
  80906. }
  80907. if (_this.webVROptions.controllerMeshes == undefined) {
  80908. _this.webVROptions.controllerMeshes = true;
  80909. }
  80910. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  80911. _this.webVROptions.defaultLightingOnControllers = true;
  80912. }
  80913. _this.rotationQuaternion = new BABYLON.Quaternion();
  80914. if (_this.webVROptions && _this.webVROptions.positionScale) {
  80915. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  80916. }
  80917. //enable VR
  80918. var engine = _this.getEngine();
  80919. _this._onVREnabled = function (success) { if (success) {
  80920. _this.initControllers();
  80921. } };
  80922. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  80923. engine.initWebVR().add(function (event) {
  80924. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  80925. return;
  80926. }
  80927. _this._vrDevice = event.vrDisplay;
  80928. //reset the rig parameters.
  80929. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  80930. if (_this._attached) {
  80931. _this.getEngine().enableVR();
  80932. }
  80933. });
  80934. if (typeof (VRFrameData) !== "undefined")
  80935. _this._frameData = new VRFrameData();
  80936. /**
  80937. * The idea behind the following lines:
  80938. * objects that have the camera as parent should actually have the rig cameras as a parent.
  80939. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  80940. * the second will not show it correctly.
  80941. *
  80942. * To solve this - each object that has the camera as parent will be added to a protected array.
  80943. * When the rig camera renders, it will take this array and set all of those to be its children.
  80944. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  80945. * Amazing!
  80946. */
  80947. scene.onBeforeCameraRenderObservable.add(function (camera) {
  80948. if (camera.parent === _this && _this.rigParenting) {
  80949. _this._descendants = _this.getDescendants(true, function (n) {
  80950. // don't take the cameras or the controllers!
  80951. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  80952. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  80953. return !isController && !isRigCamera;
  80954. });
  80955. _this._descendants.forEach(function (node) {
  80956. node.parent = camera;
  80957. });
  80958. }
  80959. });
  80960. scene.onAfterCameraRenderObservable.add(function (camera) {
  80961. if (camera.parent === _this && _this.rigParenting) {
  80962. _this._descendants.forEach(function (node) {
  80963. node.parent = _this;
  80964. });
  80965. }
  80966. });
  80967. return _this;
  80968. }
  80969. /**
  80970. * Gets the device distance from the ground in meters.
  80971. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  80972. */
  80973. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  80974. if (this._standingMatrix) {
  80975. // Add standing matrix offset to get real offset from ground in room
  80976. this._standingMatrix.getTranslationToRef(this._workingVector);
  80977. return this._deviceRoomPosition.y + this._workingVector.y;
  80978. }
  80979. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  80980. return this._defaultHeight || 0;
  80981. };
  80982. /**
  80983. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80984. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  80985. */
  80986. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  80987. var _this = this;
  80988. if (callback === void 0) { callback = function (bool) { }; }
  80989. // Use standing matrix if available
  80990. this.getEngine().initWebVRAsync().then(function (result) {
  80991. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  80992. callback(false);
  80993. }
  80994. else {
  80995. _this._standingMatrix = new BABYLON.Matrix();
  80996. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  80997. if (!_this.getScene().useRightHandedSystem) {
  80998. [2, 6, 8, 9, 14].forEach(function (num) {
  80999. if (_this._standingMatrix) {
  81000. _this._standingMatrix.m[num] *= -1;
  81001. }
  81002. });
  81003. }
  81004. callback(true);
  81005. }
  81006. });
  81007. };
  81008. /**
  81009. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81010. * @returns A promise with a boolean set to if the standing matrix is supported.
  81011. */
  81012. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  81013. var _this = this;
  81014. return new Promise(function (res, rej) {
  81015. _this.useStandingMatrix(function (supported) {
  81016. res(supported);
  81017. });
  81018. });
  81019. };
  81020. /**
  81021. * Disposes the camera
  81022. */
  81023. WebVRFreeCamera.prototype.dispose = function () {
  81024. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  81025. _super.prototype.dispose.call(this);
  81026. };
  81027. /**
  81028. * Gets a vrController by name.
  81029. * @param name The name of the controller to retreive
  81030. * @returns the controller matching the name specified or null if not found
  81031. */
  81032. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  81033. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  81034. var gp = _a[_i];
  81035. if (gp.hand === name) {
  81036. return gp;
  81037. }
  81038. }
  81039. return null;
  81040. };
  81041. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  81042. /**
  81043. * The controller corrisponding to the users left hand.
  81044. */
  81045. get: function () {
  81046. if (!this._leftController) {
  81047. this._leftController = this.getControllerByName("left");
  81048. }
  81049. return this._leftController;
  81050. },
  81051. enumerable: true,
  81052. configurable: true
  81053. });
  81054. ;
  81055. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  81056. /**
  81057. * The controller corrisponding to the users right hand.
  81058. */
  81059. get: function () {
  81060. if (!this._rightController) {
  81061. this._rightController = this.getControllerByName("right");
  81062. }
  81063. return this._rightController;
  81064. },
  81065. enumerable: true,
  81066. configurable: true
  81067. });
  81068. ;
  81069. /**
  81070. * Casts a ray forward from the vrCamera's gaze.
  81071. * @param length Length of the ray (default: 100)
  81072. * @returns the ray corrisponding to the gaze
  81073. */
  81074. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  81075. if (length === void 0) { length = 100; }
  81076. if (this.leftCamera) {
  81077. // Use left eye to avoid computation to compute center on every call
  81078. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  81079. }
  81080. else {
  81081. return _super.prototype.getForwardRay.call(this, length);
  81082. }
  81083. };
  81084. /**
  81085. * Updates the camera based on device's frame data
  81086. */
  81087. WebVRFreeCamera.prototype._checkInputs = function () {
  81088. if (this._vrDevice && this._vrDevice.isPresenting) {
  81089. this._vrDevice.getFrameData(this._frameData);
  81090. this.updateFromDevice(this._frameData.pose);
  81091. }
  81092. _super.prototype._checkInputs.call(this);
  81093. };
  81094. /**
  81095. * Updates the poseControlled values based on the input device pose.
  81096. * @param poseData Pose coming from the device
  81097. */
  81098. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  81099. if (poseData && poseData.orientation) {
  81100. this.rawPose = poseData;
  81101. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  81102. if (this.getScene().useRightHandedSystem) {
  81103. this._deviceRoomRotationQuaternion.z *= -1;
  81104. this._deviceRoomRotationQuaternion.w *= -1;
  81105. }
  81106. if (this.webVROptions.trackPosition && this.rawPose.position) {
  81107. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  81108. if (this.getScene().useRightHandedSystem) {
  81109. this._deviceRoomPosition.z *= -1;
  81110. }
  81111. }
  81112. }
  81113. };
  81114. /**
  81115. * WebVR's attach control will start broadcasting frames to the device.
  81116. * Note that in certain browsers (chrome for example) this function must be called
  81117. * within a user-interaction callback. Example:
  81118. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  81119. *
  81120. * @param element html element to attach the vrDevice to
  81121. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  81122. */
  81123. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  81124. _super.prototype.attachControl.call(this, element, noPreventDefault);
  81125. this._attached = true;
  81126. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  81127. if (this._vrDevice) {
  81128. this.getEngine().enableVR();
  81129. }
  81130. };
  81131. /**
  81132. * Detaches the camera from the html element and disables VR
  81133. *
  81134. * @param element html element to detach from
  81135. */
  81136. WebVRFreeCamera.prototype.detachControl = function (element) {
  81137. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81138. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81139. _super.prototype.detachControl.call(this, element);
  81140. this._attached = false;
  81141. this.getEngine().disableVR();
  81142. };
  81143. /**
  81144. * @returns the name of this class
  81145. */
  81146. WebVRFreeCamera.prototype.getClassName = function () {
  81147. return "WebVRFreeCamera";
  81148. };
  81149. /**
  81150. * Calls resetPose on the vrDisplay
  81151. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  81152. */
  81153. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  81154. //uses the vrDisplay's "resetPose()".
  81155. //pitch and roll won't be affected.
  81156. this._vrDevice.resetPose();
  81157. };
  81158. /**
  81159. * Updates the rig cameras (left and right eye)
  81160. */
  81161. WebVRFreeCamera.prototype._updateRigCameras = function () {
  81162. var camLeft = this._rigCameras[0];
  81163. var camRight = this._rigCameras[1];
  81164. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81165. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81166. camLeft.position.copyFrom(this._deviceRoomPosition);
  81167. camRight.position.copyFrom(this._deviceRoomPosition);
  81168. };
  81169. /**
  81170. * Updates the cached values of the camera
  81171. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  81172. */
  81173. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  81174. var _this = this;
  81175. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  81176. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  81177. if (!this.updateCacheCalled) {
  81178. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  81179. this.updateCacheCalled = true;
  81180. this.update();
  81181. }
  81182. // Set working vector to the device position in room space rotated by the new rotation
  81183. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  81184. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  81185. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  81186. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  81187. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  81188. // Add translation from anchor position
  81189. this._deviceToWorld.getTranslationToRef(this._workingVector);
  81190. this._workingVector.addInPlace(this.position);
  81191. this._workingVector.subtractInPlace(this._cache.position);
  81192. this._deviceToWorld.setTranslation(this._workingVector);
  81193. // Set an inverted matrix to be used when updating the camera
  81194. this._deviceToWorld.invertToRef(this._worldToDevice);
  81195. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  81196. this.controllers.forEach(function (controller) {
  81197. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  81198. controller.update();
  81199. });
  81200. }
  81201. if (!ignoreParentClass) {
  81202. _super.prototype._updateCache.call(this);
  81203. }
  81204. this.updateCacheCalled = false;
  81205. };
  81206. /**
  81207. * Updates the current device position and rotation in the babylon world
  81208. */
  81209. WebVRFreeCamera.prototype.update = function () {
  81210. // Get current device position in babylon world
  81211. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  81212. // Get current device rotation in babylon world
  81213. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  81214. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  81215. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81216. _super.prototype.update.call(this);
  81217. };
  81218. /**
  81219. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  81220. * @returns an identity matrix
  81221. */
  81222. WebVRFreeCamera.prototype._getViewMatrix = function () {
  81223. return BABYLON.Matrix.Identity();
  81224. };
  81225. /**
  81226. * This function is called by the two RIG cameras.
  81227. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  81228. */
  81229. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  81230. var _this = this;
  81231. // Update the parent camera prior to using a child camera to avoid desynchronization
  81232. var parentCamera = this._cameraRigParams["parentCamera"];
  81233. parentCamera._updateCache();
  81234. //WebVR 1.1
  81235. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  81236. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  81237. if (!this.getScene().useRightHandedSystem) {
  81238. [2, 6, 8, 9, 14].forEach(function (num) {
  81239. _this._webvrViewMatrix.m[num] *= -1;
  81240. });
  81241. }
  81242. // update the camera rotation matrix
  81243. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  81244. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  81245. // Computing target and final matrix
  81246. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  81247. // should the view matrix be updated with scale and position offset?
  81248. if (parentCamera.deviceScaleFactor !== 1) {
  81249. this._webvrViewMatrix.invert();
  81250. // scale the position, if set
  81251. if (parentCamera.deviceScaleFactor) {
  81252. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  81253. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  81254. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  81255. }
  81256. this._webvrViewMatrix.invert();
  81257. }
  81258. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  81259. return this._webvrViewMatrix;
  81260. };
  81261. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  81262. var _this = this;
  81263. var parentCamera = this.parent;
  81264. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  81265. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  81266. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  81267. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  81268. //babylon compatible matrix
  81269. if (!this.getScene().useRightHandedSystem) {
  81270. [8, 9, 10, 11].forEach(function (num) {
  81271. _this._projectionMatrix.m[num] *= -1;
  81272. });
  81273. }
  81274. return this._projectionMatrix;
  81275. };
  81276. /**
  81277. * Initializes the controllers and their meshes
  81278. */
  81279. WebVRFreeCamera.prototype.initControllers = function () {
  81280. var _this = this;
  81281. this.controllers = [];
  81282. var manager = this.getScene().gamepadManager;
  81283. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81284. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81285. var webVrController = gamepad;
  81286. if (webVrController.defaultModel) {
  81287. webVrController.defaultModel.setEnabled(false);
  81288. }
  81289. if (webVrController.hand === "right") {
  81290. _this._rightController = null;
  81291. }
  81292. if (webVrController.hand === "left") {
  81293. _this._leftController = null;
  81294. }
  81295. var controllerIndex = _this.controllers.indexOf(webVrController);
  81296. if (controllerIndex !== -1) {
  81297. _this.controllers.splice(controllerIndex, 1);
  81298. }
  81299. }
  81300. });
  81301. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81302. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81303. var webVrController_1 = gamepad;
  81304. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  81305. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  81306. if (_this.webVROptions.controllerMeshes) {
  81307. if (webVrController_1.defaultModel) {
  81308. webVrController_1.defaultModel.setEnabled(true);
  81309. }
  81310. else {
  81311. // Load the meshes
  81312. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  81313. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  81314. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  81315. if (_this.webVROptions.defaultLightingOnControllers) {
  81316. if (!_this._lightOnControllers) {
  81317. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  81318. }
  81319. var activateLightOnSubMeshes_1 = function (mesh, light) {
  81320. var children = mesh.getChildren();
  81321. if (children.length !== 0) {
  81322. children.forEach(function (mesh) {
  81323. light.includedOnlyMeshes.push(mesh);
  81324. activateLightOnSubMeshes_1(mesh, light);
  81325. });
  81326. }
  81327. };
  81328. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  81329. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  81330. }
  81331. });
  81332. }
  81333. }
  81334. webVrController_1.attachToPoseControlledCamera(_this);
  81335. // since this is async - sanity check. Is the controller already stored?
  81336. if (_this.controllers.indexOf(webVrController_1) === -1) {
  81337. //add to the controllers array
  81338. _this.controllers.push(webVrController_1);
  81339. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  81340. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  81341. // So we're overriding setting left & right manually to be sure
  81342. var firstViveWandDetected = false;
  81343. for (var i = 0; i < _this.controllers.length; i++) {
  81344. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81345. if (!firstViveWandDetected) {
  81346. firstViveWandDetected = true;
  81347. _this.controllers[i].hand = "left";
  81348. }
  81349. else {
  81350. _this.controllers[i].hand = "right";
  81351. }
  81352. }
  81353. }
  81354. //did we find enough controllers? Great! let the developer know.
  81355. if (_this.controllers.length >= 2) {
  81356. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  81357. }
  81358. }
  81359. }
  81360. });
  81361. };
  81362. return WebVRFreeCamera;
  81363. }(BABYLON.FreeCamera));
  81364. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  81365. })(BABYLON || (BABYLON = {}));
  81366. //# sourceMappingURL=babylon.webVRCamera.js.map
  81367. "use strict";
  81368. var BABYLON;
  81369. (function (BABYLON) {
  81370. // We're mainly based on the logic defined into the FreeCamera code
  81371. /**
  81372. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  81373. * being tilted forward or back and left or right.
  81374. */
  81375. var DeviceOrientationCamera = /** @class */ (function (_super) {
  81376. __extends(DeviceOrientationCamera, _super);
  81377. /**
  81378. * Creates a new device orientation camera. @see DeviceOrientationCamera
  81379. * @param name The name of the camera
  81380. * @param position The start position camera
  81381. * @param scene The scene the camera belongs to
  81382. */
  81383. function DeviceOrientationCamera(name, position, scene) {
  81384. var _this = _super.call(this, name, position, scene) || this;
  81385. _this._quaternionCache = new BABYLON.Quaternion();
  81386. _this.inputs.addDeviceOrientation();
  81387. return _this;
  81388. }
  81389. /**
  81390. * Gets the current instance class name ("DeviceOrientationCamera").
  81391. * This helps avoiding instanceof at run time.
  81392. * @returns the class name
  81393. */
  81394. DeviceOrientationCamera.prototype.getClassName = function () {
  81395. return "DeviceOrientationCamera";
  81396. };
  81397. /**
  81398. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  81399. */
  81400. DeviceOrientationCamera.prototype._checkInputs = function () {
  81401. _super.prototype._checkInputs.call(this);
  81402. this._quaternionCache.copyFrom(this.rotationQuaternion);
  81403. if (this._initialQuaternion) {
  81404. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81405. }
  81406. };
  81407. /**
  81408. * Reset the camera to its default orientation on the specified axis only.
  81409. * @param axis The axis to reset
  81410. */
  81411. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  81412. var _this = this;
  81413. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  81414. //can only work if this camera has a rotation quaternion already.
  81415. if (!this.rotationQuaternion)
  81416. return;
  81417. if (!this._initialQuaternion) {
  81418. this._initialQuaternion = new BABYLON.Quaternion();
  81419. }
  81420. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  81421. ['x', 'y', 'z'].forEach(function (axisName) {
  81422. if (!axis[axisName]) {
  81423. _this._initialQuaternion[axisName] = 0;
  81424. }
  81425. else {
  81426. _this._initialQuaternion[axisName] *= -1;
  81427. }
  81428. });
  81429. this._initialQuaternion.normalize();
  81430. //force rotation update
  81431. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81432. };
  81433. return DeviceOrientationCamera;
  81434. }(BABYLON.FreeCamera));
  81435. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  81436. })(BABYLON || (BABYLON = {}));
  81437. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  81438. "use strict";
  81439. var BABYLON;
  81440. (function (BABYLON) {
  81441. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  81442. __extends(VRDeviceOrientationFreeCamera, _super);
  81443. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81444. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81445. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81446. var _this = _super.call(this, name, position, scene) || this;
  81447. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81448. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81449. return _this;
  81450. }
  81451. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  81452. return "VRDeviceOrientationFreeCamera";
  81453. };
  81454. return VRDeviceOrientationFreeCamera;
  81455. }(BABYLON.DeviceOrientationCamera));
  81456. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  81457. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  81458. __extends(VRDeviceOrientationGamepadCamera, _super);
  81459. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81460. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81461. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81462. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  81463. _this.inputs.addGamepad();
  81464. return _this;
  81465. }
  81466. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  81467. return "VRDeviceOrientationGamepadCamera";
  81468. };
  81469. return VRDeviceOrientationGamepadCamera;
  81470. }(VRDeviceOrientationFreeCamera));
  81471. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  81472. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  81473. __extends(VRDeviceOrientationArcRotateCamera, _super);
  81474. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  81475. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81476. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81477. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81478. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81479. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81480. _this.inputs.addVRDeviceOrientation();
  81481. return _this;
  81482. }
  81483. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  81484. return "VRDeviceOrientationArcRotateCamera";
  81485. };
  81486. return VRDeviceOrientationArcRotateCamera;
  81487. }(BABYLON.ArcRotateCamera));
  81488. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  81489. })(BABYLON || (BABYLON = {}));
  81490. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  81491. "use strict";
  81492. var BABYLON;
  81493. (function (BABYLON) {
  81494. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  81495. __extends(AnaglyphFreeCamera, _super);
  81496. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  81497. var _this = _super.call(this, name, position, scene) || this;
  81498. _this.interaxialDistance = interaxialDistance;
  81499. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81500. return _this;
  81501. }
  81502. AnaglyphFreeCamera.prototype.getClassName = function () {
  81503. return "AnaglyphFreeCamera";
  81504. };
  81505. return AnaglyphFreeCamera;
  81506. }(BABYLON.FreeCamera));
  81507. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  81508. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  81509. __extends(AnaglyphArcRotateCamera, _super);
  81510. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  81511. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81512. _this.interaxialDistance = interaxialDistance;
  81513. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81514. return _this;
  81515. }
  81516. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  81517. return "AnaglyphArcRotateCamera";
  81518. };
  81519. return AnaglyphArcRotateCamera;
  81520. }(BABYLON.ArcRotateCamera));
  81521. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  81522. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  81523. __extends(AnaglyphGamepadCamera, _super);
  81524. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  81525. var _this = _super.call(this, name, position, scene) || this;
  81526. _this.interaxialDistance = interaxialDistance;
  81527. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81528. return _this;
  81529. }
  81530. AnaglyphGamepadCamera.prototype.getClassName = function () {
  81531. return "AnaglyphGamepadCamera";
  81532. };
  81533. return AnaglyphGamepadCamera;
  81534. }(BABYLON.GamepadCamera));
  81535. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  81536. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  81537. __extends(AnaglyphUniversalCamera, _super);
  81538. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  81539. var _this = _super.call(this, name, position, scene) || this;
  81540. _this.interaxialDistance = interaxialDistance;
  81541. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81542. return _this;
  81543. }
  81544. AnaglyphUniversalCamera.prototype.getClassName = function () {
  81545. return "AnaglyphUniversalCamera";
  81546. };
  81547. return AnaglyphUniversalCamera;
  81548. }(BABYLON.UniversalCamera));
  81549. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  81550. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  81551. __extends(StereoscopicFreeCamera, _super);
  81552. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81553. var _this = _super.call(this, name, position, scene) || this;
  81554. _this.interaxialDistance = interaxialDistance;
  81555. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81556. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81557. return _this;
  81558. }
  81559. StereoscopicFreeCamera.prototype.getClassName = function () {
  81560. return "StereoscopicFreeCamera";
  81561. };
  81562. return StereoscopicFreeCamera;
  81563. }(BABYLON.FreeCamera));
  81564. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  81565. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  81566. __extends(StereoscopicArcRotateCamera, _super);
  81567. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  81568. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81569. _this.interaxialDistance = interaxialDistance;
  81570. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81571. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81572. return _this;
  81573. }
  81574. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  81575. return "StereoscopicArcRotateCamera";
  81576. };
  81577. return StereoscopicArcRotateCamera;
  81578. }(BABYLON.ArcRotateCamera));
  81579. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  81580. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  81581. __extends(StereoscopicGamepadCamera, _super);
  81582. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81583. var _this = _super.call(this, name, position, scene) || this;
  81584. _this.interaxialDistance = interaxialDistance;
  81585. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81586. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81587. return _this;
  81588. }
  81589. StereoscopicGamepadCamera.prototype.getClassName = function () {
  81590. return "StereoscopicGamepadCamera";
  81591. };
  81592. return StereoscopicGamepadCamera;
  81593. }(BABYLON.GamepadCamera));
  81594. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  81595. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  81596. __extends(StereoscopicUniversalCamera, _super);
  81597. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81598. var _this = _super.call(this, name, position, scene) || this;
  81599. _this.interaxialDistance = interaxialDistance;
  81600. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81601. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81602. return _this;
  81603. }
  81604. StereoscopicUniversalCamera.prototype.getClassName = function () {
  81605. return "StereoscopicUniversalCamera";
  81606. };
  81607. return StereoscopicUniversalCamera;
  81608. }(BABYLON.UniversalCamera));
  81609. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  81610. })(BABYLON || (BABYLON = {}));
  81611. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  81612. "use strict";
  81613. var BABYLON;
  81614. (function (BABYLON) {
  81615. var VRExperienceHelperGazer = /** @class */ (function () {
  81616. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  81617. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  81618. this.scene = scene;
  81619. this._pointerDownOnMeshAsked = false;
  81620. this._isActionableMesh = false;
  81621. this._teleportationRequestInitiated = false;
  81622. this._teleportationBackRequestInitiated = false;
  81623. this._dpadPressed = true;
  81624. this._activePointer = false;
  81625. this._id = VRExperienceHelperGazer._idCounter++;
  81626. // Gaze tracker
  81627. if (!gazeTrackerToClone) {
  81628. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  81629. this._gazeTracker.bakeCurrentTransformIntoVertices();
  81630. this._gazeTracker.isPickable = false;
  81631. this._gazeTracker.isVisible = false;
  81632. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  81633. targetMat.specularColor = BABYLON.Color3.Black();
  81634. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81635. targetMat.backFaceCulling = false;
  81636. this._gazeTracker.material = targetMat;
  81637. }
  81638. else {
  81639. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  81640. }
  81641. }
  81642. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  81643. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  81644. };
  81645. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  81646. this._pointerDownOnMeshAsked = true;
  81647. if (this._currentMeshSelected && this._currentHit) {
  81648. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  81649. }
  81650. };
  81651. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  81652. if (this._currentMeshSelected && this._currentHit) {
  81653. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  81654. }
  81655. this._pointerDownOnMeshAsked = false;
  81656. };
  81657. VRExperienceHelperGazer.prototype._activatePointer = function () {
  81658. this._activePointer = true;
  81659. };
  81660. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  81661. this._activePointer = false;
  81662. };
  81663. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  81664. };
  81665. VRExperienceHelperGazer.prototype.dispose = function () {
  81666. this._interactionsEnabled = false;
  81667. this._teleportationEnabled = false;
  81668. };
  81669. VRExperienceHelperGazer._idCounter = 0;
  81670. return VRExperienceHelperGazer;
  81671. }());
  81672. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  81673. __extends(VRExperienceHelperControllerGazer, _super);
  81674. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  81675. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  81676. _this.webVRController = webVRController;
  81677. // Laser pointer
  81678. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  81679. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  81680. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81681. laserPointerMaterial.alpha = 0.6;
  81682. _this._laserPointer.material = laserPointerMaterial;
  81683. _this._laserPointer.rotation.x = Math.PI / 2;
  81684. _this._laserPointer.position.z = -0.5;
  81685. _this._laserPointer.isVisible = false;
  81686. if (!webVRController.mesh) {
  81687. // Create an empty mesh that is used prior to loading the high quality model
  81688. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  81689. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  81690. preloadPointerPose.rotation.x = -0.7;
  81691. preloadMesh.addChild(preloadPointerPose);
  81692. webVRController.attachToMesh(preloadMesh);
  81693. }
  81694. _this._setLaserPointerParent(webVRController.mesh);
  81695. return _this;
  81696. }
  81697. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  81698. return this.webVRController.getForwardRay(length);
  81699. };
  81700. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  81701. _super.prototype._activatePointer.call(this);
  81702. this._laserPointer.isVisible = true;
  81703. };
  81704. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  81705. _super.prototype._deactivatePointer.call(this);
  81706. this._laserPointer.isVisible = false;
  81707. };
  81708. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  81709. this._laserPointer.material.emissiveColor = color;
  81710. };
  81711. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  81712. var makeNotPick = function (root) {
  81713. root.name += " laserPointer";
  81714. root.getChildMeshes().forEach(function (c) {
  81715. makeNotPick(c);
  81716. });
  81717. };
  81718. makeNotPick(mesh);
  81719. var childMeshes = mesh.getChildMeshes();
  81720. this.webVRController._pointingPoseNode = null;
  81721. for (var i = 0; i < childMeshes.length; i++) {
  81722. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  81723. mesh = childMeshes[i];
  81724. this.webVRController._pointingPoseNode = mesh;
  81725. break;
  81726. }
  81727. }
  81728. this._laserPointer.parent = mesh;
  81729. };
  81730. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  81731. this._laserPointer.scaling.y = distance;
  81732. this._laserPointer.position.z = -distance / 2;
  81733. };
  81734. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  81735. _super.prototype.dispose.call(this);
  81736. this._laserPointer.dispose();
  81737. };
  81738. return VRExperienceHelperControllerGazer;
  81739. }(VRExperienceHelperGazer));
  81740. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  81741. __extends(VRExperienceHelperCameraGazer, _super);
  81742. function VRExperienceHelperCameraGazer(getCamera, scene) {
  81743. var _this = _super.call(this, scene) || this;
  81744. _this.getCamera = getCamera;
  81745. return _this;
  81746. }
  81747. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  81748. var camera = this.getCamera();
  81749. if (camera) {
  81750. return camera.getForwardRay(length);
  81751. }
  81752. else {
  81753. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  81754. }
  81755. };
  81756. return VRExperienceHelperCameraGazer;
  81757. }(VRExperienceHelperGazer));
  81758. /**
  81759. * Helps to quickly add VR support to an existing scene.
  81760. * See http://doc.babylonjs.com/how_to/webvr_helper
  81761. */
  81762. var VRExperienceHelper = /** @class */ (function () {
  81763. /**
  81764. * Instantiates a VRExperienceHelper.
  81765. * Helps to quickly add VR support to an existing scene.
  81766. * @param scene The scene the VRExperienceHelper belongs to.
  81767. * @param webVROptions Options to modify the vr experience helper's behavior.
  81768. */
  81769. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  81770. if (webVROptions === void 0) { webVROptions = {}; }
  81771. var _this = this;
  81772. this.webVROptions = webVROptions;
  81773. // Can the system support WebVR, even if a headset isn't plugged in?
  81774. this._webVRsupported = false;
  81775. // If WebVR is supported, is a headset plugged in and are we ready to present?
  81776. this._webVRready = false;
  81777. // Are we waiting for the requestPresent callback to complete?
  81778. this._webVRrequesting = false;
  81779. // Are we presenting to the headset right now?
  81780. this._webVRpresenting = false;
  81781. // Are we presenting in the fullscreen fallback?
  81782. this._fullscreenVRpresenting = false;
  81783. /**
  81784. * Observable raised when entering VR.
  81785. */
  81786. this.onEnteringVRObservable = new BABYLON.Observable();
  81787. /**
  81788. * Observable raised when exiting VR.
  81789. */
  81790. this.onExitingVRObservable = new BABYLON.Observable();
  81791. /**
  81792. * Observable raised when controller mesh is loaded.
  81793. */
  81794. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81795. this._useCustomVRButton = false;
  81796. this._teleportationRequested = false;
  81797. this._teleportActive = false;
  81798. this._floorMeshesCollection = [];
  81799. this._rotationAllowed = true;
  81800. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  81801. this._rotationRightAsked = false;
  81802. this._rotationLeftAsked = false;
  81803. this._isDefaultTeleportationTarget = true;
  81804. this._teleportationFillColor = "#444444";
  81805. this._teleportationBorderColor = "#FFFFFF";
  81806. this._rotationAngle = 0;
  81807. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  81808. this._padSensibilityUp = 0.65;
  81809. this._padSensibilityDown = 0.35;
  81810. this.leftController = null;
  81811. this.rightController = null;
  81812. /**
  81813. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  81814. */
  81815. this.onNewMeshSelected = new BABYLON.Observable();
  81816. /**
  81817. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  81818. */
  81819. this.onNewMeshPicked = new BABYLON.Observable();
  81820. /**
  81821. * Observable raised before camera teleportation
  81822. */
  81823. this.onBeforeCameraTeleport = new BABYLON.Observable();
  81824. /**
  81825. * Observable raised after camera teleportation
  81826. */
  81827. this.onAfterCameraTeleport = new BABYLON.Observable();
  81828. /**
  81829. * Observable raised when current selected mesh gets unselected
  81830. */
  81831. this.onSelectedMeshUnselected = new BABYLON.Observable();
  81832. /**
  81833. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  81834. */
  81835. this.teleportationEnabled = true;
  81836. this._teleportationInitialized = false;
  81837. this._interactionsEnabled = false;
  81838. this._interactionsRequested = false;
  81839. this._displayGaze = true;
  81840. this._displayLaserPointer = true;
  81841. this._onResize = function () {
  81842. _this.moveButtonToBottomRight();
  81843. if (_this._fullscreenVRpresenting && _this._webVRready) {
  81844. _this.exitVR();
  81845. }
  81846. };
  81847. this._onFullscreenChange = function () {
  81848. if (document.fullscreen !== undefined) {
  81849. _this._fullscreenVRpresenting = document.fullscreen;
  81850. }
  81851. else if (document.mozFullScreen !== undefined) {
  81852. _this._fullscreenVRpresenting = document.mozFullScreen;
  81853. }
  81854. else if (document.webkitIsFullScreen !== undefined) {
  81855. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  81856. }
  81857. else if (document.msIsFullScreen !== undefined) {
  81858. _this._fullscreenVRpresenting = document.msIsFullScreen;
  81859. }
  81860. if (!_this._fullscreenVRpresenting && _this._canvas) {
  81861. _this.exitVR();
  81862. if (!_this._useCustomVRButton) {
  81863. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  81864. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  81865. }
  81866. }
  81867. };
  81868. this.beforeRender = function () {
  81869. if (_this.leftController && _this.leftController._activePointer) {
  81870. _this._castRayAndSelectObject(_this.leftController);
  81871. }
  81872. if (_this.rightController && _this.rightController._activePointer) {
  81873. _this._castRayAndSelectObject(_this.rightController);
  81874. }
  81875. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  81876. _this._castRayAndSelectObject(_this._cameraGazer);
  81877. }
  81878. else {
  81879. _this._cameraGazer._gazeTracker.isVisible = false;
  81880. }
  81881. };
  81882. this._onNewGamepadConnected = function (gamepad) {
  81883. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81884. if (gamepad.leftStick) {
  81885. gamepad.onleftstickchanged(function (stickValues) {
  81886. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  81887. // Listening to classic/xbox gamepad only if no VR controller is active
  81888. if ((!_this.leftController && !_this.rightController) ||
  81889. ((_this.leftController && !_this.leftController._activePointer) &&
  81890. (_this.rightController && !_this.rightController._activePointer))) {
  81891. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  81892. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  81893. }
  81894. }
  81895. });
  81896. }
  81897. if (gamepad.rightStick) {
  81898. gamepad.onrightstickchanged(function (stickValues) {
  81899. if (_this._teleportationInitialized) {
  81900. _this._checkRotate(stickValues, _this._cameraGazer);
  81901. }
  81902. });
  81903. }
  81904. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  81905. gamepad.onbuttondown(function (buttonPressed) {
  81906. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81907. _this._cameraGazer._selectionPointerDown();
  81908. }
  81909. });
  81910. gamepad.onbuttonup(function (buttonPressed) {
  81911. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81912. _this._cameraGazer._selectionPointerUp();
  81913. }
  81914. });
  81915. }
  81916. }
  81917. else {
  81918. var webVRController = gamepad;
  81919. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  81920. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  81921. _this.rightController = controller;
  81922. }
  81923. else {
  81924. _this.leftController = controller;
  81925. }
  81926. _this._tryEnableInteractionOnController(controller);
  81927. }
  81928. };
  81929. // 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
  81930. this._tryEnableInteractionOnController = function (controller) {
  81931. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  81932. _this._enableInteractionOnController(controller);
  81933. }
  81934. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  81935. _this._enableTeleportationOnController(controller);
  81936. }
  81937. };
  81938. this._onNewGamepadDisconnected = function (gamepad) {
  81939. if (gamepad instanceof BABYLON.WebVRController) {
  81940. if (gamepad.hand === "left" && _this.leftController != null) {
  81941. _this.leftController.dispose();
  81942. _this.leftController = null;
  81943. }
  81944. if (gamepad.hand === "right" && _this.rightController != null) {
  81945. _this.rightController.dispose();
  81946. _this.rightController = null;
  81947. }
  81948. }
  81949. };
  81950. this._workingVector = BABYLON.Vector3.Zero();
  81951. this._workingQuaternion = BABYLON.Quaternion.Identity();
  81952. this._workingMatrix = BABYLON.Matrix.Identity();
  81953. this._scene = scene;
  81954. this._canvas = scene.getEngine().getRenderingCanvas();
  81955. // Parse options
  81956. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  81957. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  81958. }
  81959. if (webVROptions.createDeviceOrientationCamera === undefined) {
  81960. webVROptions.createDeviceOrientationCamera = true;
  81961. }
  81962. if (webVROptions.defaultHeight === undefined) {
  81963. webVROptions.defaultHeight = 1.7;
  81964. }
  81965. if (webVROptions.useCustomVRButton) {
  81966. this._useCustomVRButton = true;
  81967. if (webVROptions.customVRButton) {
  81968. this._btnVR = webVROptions.customVRButton;
  81969. }
  81970. }
  81971. if (webVROptions.rayLength) {
  81972. this._rayLength = webVROptions.rayLength;
  81973. }
  81974. this._defaultHeight = webVROptions.defaultHeight;
  81975. if (webVROptions.positionScale) {
  81976. this._rayLength *= webVROptions.positionScale;
  81977. this._defaultHeight *= webVROptions.positionScale;
  81978. }
  81979. // Set position
  81980. if (this._scene.activeCamera) {
  81981. this._position = this._scene.activeCamera.position.clone();
  81982. }
  81983. else {
  81984. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  81985. }
  81986. // Set non-vr camera
  81987. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  81988. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  81989. // Copy data from existing camera
  81990. if (this._scene.activeCamera) {
  81991. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  81992. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  81993. // Set rotation from previous camera
  81994. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  81995. var targetCamera = this._scene.activeCamera;
  81996. if (targetCamera.rotationQuaternion) {
  81997. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  81998. }
  81999. else {
  82000. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  82001. }
  82002. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  82003. }
  82004. }
  82005. this._scene.activeCamera = this._deviceOrientationCamera;
  82006. if (this._canvas) {
  82007. this._scene.activeCamera.attachControl(this._canvas);
  82008. }
  82009. }
  82010. else {
  82011. this._existingCamera = this._scene.activeCamera;
  82012. }
  82013. // Create VR cameras
  82014. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82015. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  82016. }
  82017. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  82018. this._webVRCamera.useStandingMatrix();
  82019. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  82020. // Create default button
  82021. if (!this._useCustomVRButton) {
  82022. this._btnVR = document.createElement("BUTTON");
  82023. this._btnVR.className = "babylonVRicon";
  82024. this._btnVR.id = "babylonVRiconbtn";
  82025. this._btnVR.title = "Click to switch to VR";
  82026. 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) }";
  82027. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  82028. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  82029. // css += ".babylonVRicon.vrdisplaysupported { }";
  82030. // css += ".babylonVRicon.vrdisplayready { }";
  82031. // css += ".babylonVRicon.vrdisplayrequesting { }";
  82032. var style = document.createElement('style');
  82033. style.appendChild(document.createTextNode(css));
  82034. document.getElementsByTagName('head')[0].appendChild(style);
  82035. this.moveButtonToBottomRight();
  82036. }
  82037. // VR button click event
  82038. if (this._btnVR) {
  82039. this._btnVR.addEventListener("click", function () {
  82040. if (!_this.isInVRMode) {
  82041. _this.enterVR();
  82042. }
  82043. else {
  82044. _this.exitVR();
  82045. }
  82046. });
  82047. }
  82048. // Window events
  82049. window.addEventListener("resize", this._onResize);
  82050. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  82051. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  82052. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  82053. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  82054. // Display vr button when headset is connected
  82055. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82056. this.displayVRButton();
  82057. }
  82058. else {
  82059. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  82060. if (e.vrDisplay) {
  82061. _this.displayVRButton();
  82062. }
  82063. });
  82064. }
  82065. // Exiting VR mode using 'ESC' key on desktop
  82066. this._onKeyDown = function (event) {
  82067. if (event.keyCode === 27 && _this.isInVRMode) {
  82068. _this.exitVR();
  82069. }
  82070. };
  82071. document.addEventListener("keydown", this._onKeyDown);
  82072. // Exiting VR mode double tapping the touch screen
  82073. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  82074. if (_this.isInVRMode) {
  82075. _this.exitVR();
  82076. if (_this._fullscreenVRpresenting) {
  82077. _this._scene.getEngine().switchFullscreen(true);
  82078. }
  82079. }
  82080. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  82081. // Listen for WebVR display changes
  82082. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  82083. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  82084. this._onVRRequestPresentStart = function () {
  82085. _this._webVRrequesting = true;
  82086. _this.updateButtonVisibility();
  82087. };
  82088. this._onVRRequestPresentComplete = function (success) {
  82089. _this._webVRrequesting = false;
  82090. _this.updateButtonVisibility();
  82091. };
  82092. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  82093. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  82094. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  82095. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82096. scene.onDisposeObservable.add(function () {
  82097. _this.dispose();
  82098. });
  82099. // Gamepad connection events
  82100. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  82101. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  82102. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  82103. this.updateButtonVisibility();
  82104. //create easing functions
  82105. this._circleEase = new BABYLON.CircleEase();
  82106. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82107. }
  82108. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  82109. /** Return this.onEnteringVRObservable
  82110. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  82111. */
  82112. get: function () {
  82113. return this.onEnteringVRObservable;
  82114. },
  82115. enumerable: true,
  82116. configurable: true
  82117. });
  82118. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  82119. /** Return this.onExitingVRObservable
  82120. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  82121. */
  82122. get: function () {
  82123. return this.onExitingVRObservable;
  82124. },
  82125. enumerable: true,
  82126. configurable: true
  82127. });
  82128. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  82129. /** Return this.onControllerMeshLoadedObservable
  82130. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  82131. */
  82132. get: function () {
  82133. return this.onControllerMeshLoadedObservable;
  82134. },
  82135. enumerable: true,
  82136. configurable: true
  82137. });
  82138. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  82139. /**
  82140. * The mesh used to display where the user is going to teleport.
  82141. */
  82142. get: function () {
  82143. return this._teleportationTarget;
  82144. },
  82145. /**
  82146. * Sets the mesh to be used to display where the user is going to teleport.
  82147. */
  82148. set: function (value) {
  82149. if (value) {
  82150. value.name = "teleportationTarget";
  82151. this._isDefaultTeleportationTarget = false;
  82152. this._teleportationTarget = value;
  82153. }
  82154. },
  82155. enumerable: true,
  82156. configurable: true
  82157. });
  82158. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  82159. /**
  82160. * The mesh used to display where the user is selecting,
  82161. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  82162. * See http://doc.babylonjs.com/resources/baking_transformations
  82163. */
  82164. get: function () {
  82165. return this._cameraGazer._gazeTracker;
  82166. },
  82167. set: function (value) {
  82168. if (value) {
  82169. this._cameraGazer._gazeTracker = value;
  82170. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  82171. this._cameraGazer._gazeTracker.isPickable = false;
  82172. this._cameraGazer._gazeTracker.isVisible = false;
  82173. this._cameraGazer._gazeTracker.name = "gazeTracker";
  82174. if (this.leftController) {
  82175. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82176. }
  82177. if (this.rightController) {
  82178. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82179. }
  82180. }
  82181. },
  82182. enumerable: true,
  82183. configurable: true
  82184. });
  82185. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  82186. /**
  82187. * If the ray of the gaze should be displayed.
  82188. */
  82189. get: function () {
  82190. return this._displayGaze;
  82191. },
  82192. /**
  82193. * Sets if the ray of the gaze should be displayed.
  82194. */
  82195. set: function (value) {
  82196. this._displayGaze = value;
  82197. if (!value) {
  82198. this._cameraGazer._gazeTracker.isVisible = false;
  82199. if (this.leftController) {
  82200. this.leftController._gazeTracker.isVisible = false;
  82201. }
  82202. if (this.rightController) {
  82203. this.rightController._gazeTracker.isVisible = false;
  82204. }
  82205. }
  82206. },
  82207. enumerable: true,
  82208. configurable: true
  82209. });
  82210. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  82211. /**
  82212. * If the ray of the LaserPointer should be displayed.
  82213. */
  82214. get: function () {
  82215. return this._displayLaserPointer;
  82216. },
  82217. /**
  82218. * Sets if the ray of the LaserPointer should be displayed.
  82219. */
  82220. set: function (value) {
  82221. this._displayLaserPointer = value;
  82222. if (!value) {
  82223. if (this.rightController) {
  82224. this.rightController._deactivatePointer();
  82225. this.rightController._gazeTracker.isVisible = false;
  82226. }
  82227. if (this.leftController) {
  82228. this.leftController._deactivatePointer();
  82229. this.leftController._gazeTracker.isVisible = false;
  82230. }
  82231. }
  82232. else {
  82233. if (this.rightController) {
  82234. this.rightController._activatePointer();
  82235. }
  82236. else if (this.leftController) {
  82237. this.leftController._activatePointer();
  82238. }
  82239. }
  82240. },
  82241. enumerable: true,
  82242. configurable: true
  82243. });
  82244. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  82245. /**
  82246. * The deviceOrientationCamera used as the camera when not in VR.
  82247. */
  82248. get: function () {
  82249. return this._deviceOrientationCamera;
  82250. },
  82251. enumerable: true,
  82252. configurable: true
  82253. });
  82254. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  82255. /**
  82256. * Based on the current WebVR support, returns the current VR camera used.
  82257. */
  82258. get: function () {
  82259. if (this._webVRready) {
  82260. return this._webVRCamera;
  82261. }
  82262. else {
  82263. return this._scene.activeCamera;
  82264. }
  82265. },
  82266. enumerable: true,
  82267. configurable: true
  82268. });
  82269. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  82270. /**
  82271. * The webVRCamera which is used when in VR.
  82272. */
  82273. get: function () {
  82274. return this._webVRCamera;
  82275. },
  82276. enumerable: true,
  82277. configurable: true
  82278. });
  82279. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  82280. /**
  82281. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  82282. */
  82283. get: function () {
  82284. return this._vrDeviceOrientationCamera;
  82285. },
  82286. enumerable: true,
  82287. configurable: true
  82288. });
  82289. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  82290. get: function () {
  82291. var result = this._cameraGazer._teleportationRequestInitiated
  82292. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  82293. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  82294. return result;
  82295. },
  82296. enumerable: true,
  82297. configurable: true
  82298. });
  82299. // Raised when one of the controller has loaded successfully its associated default mesh
  82300. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  82301. if (this.leftController && this.leftController.webVRController == webVRController) {
  82302. if (webVRController.mesh) {
  82303. this.leftController._setLaserPointerParent(webVRController.mesh);
  82304. }
  82305. }
  82306. if (this.rightController && this.rightController.webVRController == webVRController) {
  82307. if (webVRController.mesh) {
  82308. this.rightController._setLaserPointerParent(webVRController.mesh);
  82309. }
  82310. }
  82311. try {
  82312. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  82313. }
  82314. catch (err) {
  82315. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  82316. }
  82317. };
  82318. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  82319. /**
  82320. * Gets a value indicating if we are currently in VR mode.
  82321. */
  82322. get: function () {
  82323. return this._webVRpresenting || this._fullscreenVRpresenting;
  82324. },
  82325. enumerable: true,
  82326. configurable: true
  82327. });
  82328. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  82329. var vrDisplay = this._scene.getEngine().getVRDevice();
  82330. if (vrDisplay) {
  82331. var wasPresenting = this._webVRpresenting;
  82332. // A VR display is connected
  82333. this._webVRpresenting = vrDisplay.isPresenting;
  82334. if (wasPresenting && !this._webVRpresenting)
  82335. this.exitVR();
  82336. }
  82337. else {
  82338. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  82339. }
  82340. this.updateButtonVisibility();
  82341. };
  82342. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  82343. this._webVRsupported = eventArgs.vrSupported;
  82344. this._webVRready = !!eventArgs.vrDisplay;
  82345. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  82346. this.updateButtonVisibility();
  82347. };
  82348. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  82349. if (this._canvas && !this._useCustomVRButton) {
  82350. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  82351. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  82352. }
  82353. };
  82354. VRExperienceHelper.prototype.displayVRButton = function () {
  82355. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  82356. document.body.appendChild(this._btnVR);
  82357. this._btnVRDisplayed = true;
  82358. }
  82359. };
  82360. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  82361. if (!this._btnVR || this._useCustomVRButton) {
  82362. return;
  82363. }
  82364. this._btnVR.className = "babylonVRicon";
  82365. if (this.isInVRMode) {
  82366. this._btnVR.className += " vrdisplaypresenting";
  82367. }
  82368. else {
  82369. if (this._webVRready)
  82370. this._btnVR.className += " vrdisplayready";
  82371. if (this._webVRsupported)
  82372. this._btnVR.className += " vrdisplaysupported";
  82373. if (this._webVRrequesting)
  82374. this._btnVR.className += " vrdisplayrequesting";
  82375. }
  82376. };
  82377. /**
  82378. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  82379. * Otherwise, will use the fullscreen API.
  82380. */
  82381. VRExperienceHelper.prototype.enterVR = function () {
  82382. if (this.onEnteringVRObservable) {
  82383. try {
  82384. this.onEnteringVRObservable.notifyObservers(this);
  82385. }
  82386. catch (err) {
  82387. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  82388. }
  82389. }
  82390. if (this._scene.activeCamera) {
  82391. this._position = this._scene.activeCamera.position.clone();
  82392. // make sure that we return to the last active camera
  82393. this._existingCamera = this._scene.activeCamera;
  82394. }
  82395. if (this._webVRrequesting)
  82396. return;
  82397. // If WebVR is supported and a headset is connected
  82398. if (this._webVRready) {
  82399. if (!this._webVRpresenting) {
  82400. this._webVRCamera.position = this._position;
  82401. this._scene.activeCamera = this._webVRCamera;
  82402. }
  82403. }
  82404. else if (this._vrDeviceOrientationCamera) {
  82405. this._vrDeviceOrientationCamera.position = this._position;
  82406. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  82407. this._scene.getEngine().switchFullscreen(true);
  82408. this.updateButtonVisibility();
  82409. }
  82410. if (this._scene.activeCamera && this._canvas) {
  82411. this._scene.activeCamera.attachControl(this._canvas);
  82412. }
  82413. if (this._interactionsEnabled) {
  82414. this._scene.registerBeforeRender(this.beforeRender);
  82415. }
  82416. };
  82417. /**
  82418. * Attempt to exit VR, or fullscreen.
  82419. */
  82420. VRExperienceHelper.prototype.exitVR = function () {
  82421. if (this.onExitingVRObservable) {
  82422. try {
  82423. this.onExitingVRObservable.notifyObservers(this);
  82424. }
  82425. catch (err) {
  82426. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  82427. }
  82428. }
  82429. if (this._webVRpresenting) {
  82430. this._scene.getEngine().disableVR();
  82431. }
  82432. if (this._scene.activeCamera) {
  82433. this._position = this._scene.activeCamera.position.clone();
  82434. }
  82435. if (this._deviceOrientationCamera) {
  82436. this._deviceOrientationCamera.position = this._position;
  82437. this._scene.activeCamera = this._deviceOrientationCamera;
  82438. if (this._canvas) {
  82439. this._scene.activeCamera.attachControl(this._canvas);
  82440. }
  82441. }
  82442. else if (this._existingCamera) {
  82443. this._existingCamera.position = this._position;
  82444. this._scene.activeCamera = this._existingCamera;
  82445. }
  82446. this.updateButtonVisibility();
  82447. if (this._interactionsEnabled) {
  82448. this._scene.unregisterBeforeRender(this.beforeRender);
  82449. }
  82450. };
  82451. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  82452. /**
  82453. * The position of the vr experience helper.
  82454. */
  82455. get: function () {
  82456. return this._position;
  82457. },
  82458. /**
  82459. * Sets the position of the vr experience helper.
  82460. */
  82461. set: function (value) {
  82462. this._position = value;
  82463. if (this._scene.activeCamera) {
  82464. this._scene.activeCamera.position = value;
  82465. }
  82466. },
  82467. enumerable: true,
  82468. configurable: true
  82469. });
  82470. /**
  82471. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  82472. */
  82473. VRExperienceHelper.prototype.enableInteractions = function () {
  82474. var _this = this;
  82475. if (!this._interactionsEnabled) {
  82476. this._interactionsRequested = true;
  82477. if (this.leftController) {
  82478. this._enableInteractionOnController(this.leftController);
  82479. }
  82480. if (this.rightController) {
  82481. this._enableInteractionOnController(this.rightController);
  82482. }
  82483. this.raySelectionPredicate = function (mesh) {
  82484. return mesh.isVisible;
  82485. };
  82486. this.meshSelectionPredicate = function (mesh) {
  82487. return true;
  82488. };
  82489. this._raySelectionPredicate = function (mesh) {
  82490. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  82491. && mesh.name.indexOf("teleportationTarget") === -1
  82492. && mesh.name.indexOf("torusTeleportation") === -1
  82493. && mesh.name.indexOf("laserPointer") === -1)) {
  82494. return _this.raySelectionPredicate(mesh);
  82495. }
  82496. return false;
  82497. };
  82498. this._interactionsEnabled = true;
  82499. }
  82500. };
  82501. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  82502. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  82503. if (this._floorMeshesCollection[i].id === mesh.id) {
  82504. return true;
  82505. }
  82506. }
  82507. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  82508. return true;
  82509. }
  82510. return false;
  82511. };
  82512. /**
  82513. * Adds a floor mesh to be used for teleportation.
  82514. * @param floorMesh the mesh to be used for teleportation.
  82515. */
  82516. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  82517. if (!this._floorMeshesCollection) {
  82518. return;
  82519. }
  82520. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  82521. return;
  82522. }
  82523. this._floorMeshesCollection.push(floorMesh);
  82524. };
  82525. /**
  82526. * Removes a floor mesh from being used for teleportation.
  82527. * @param floorMesh the mesh to be removed.
  82528. */
  82529. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  82530. if (!this._floorMeshesCollection) {
  82531. return;
  82532. }
  82533. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  82534. if (meshIndex !== -1) {
  82535. this._floorMeshesCollection.splice(meshIndex, 1);
  82536. }
  82537. };
  82538. /**
  82539. * Enables interactions and teleportation using the VR controllers and gaze.
  82540. * @param vrTeleportationOptions options to modify teleportation behavior.
  82541. */
  82542. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  82543. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  82544. if (!this._teleportationInitialized) {
  82545. this._teleportationRequested = true;
  82546. this.enableInteractions();
  82547. if (vrTeleportationOptions.floorMeshName) {
  82548. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  82549. }
  82550. if (vrTeleportationOptions.floorMeshes) {
  82551. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  82552. }
  82553. if (this.leftController != null) {
  82554. this._enableTeleportationOnController(this.leftController);
  82555. }
  82556. if (this.rightController != null) {
  82557. this._enableTeleportationOnController(this.rightController);
  82558. }
  82559. // Creates an image processing post process for the vignette not relying
  82560. // on the main scene configuration for image processing to reduce setup and spaces
  82561. // (gamma/linear) conflicts.
  82562. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  82563. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  82564. imageProcessingConfiguration.vignetteEnabled = true;
  82565. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  82566. this._webVRCamera.detachPostProcess(this._postProcessMove);
  82567. this._teleportationInitialized = true;
  82568. if (this._isDefaultTeleportationTarget) {
  82569. this._createTeleportationCircles();
  82570. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  82571. }
  82572. }
  82573. };
  82574. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  82575. var _this = this;
  82576. var controllerMesh = controller.webVRController.mesh;
  82577. if (controllerMesh) {
  82578. controller._interactionsEnabled = true;
  82579. controller._activatePointer();
  82580. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  82581. // Enabling / disabling laserPointer
  82582. if (_this._displayLaserPointer && stateObject.value === 1) {
  82583. if (controller._activePointer) {
  82584. controller._deactivatePointer();
  82585. }
  82586. else {
  82587. controller._activatePointer();
  82588. }
  82589. if (_this.displayGaze) {
  82590. controller._gazeTracker.isVisible = controller._activePointer;
  82591. }
  82592. }
  82593. });
  82594. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  82595. if (!controller._pointerDownOnMeshAsked) {
  82596. if (stateObject.value > _this._padSensibilityUp) {
  82597. controller._selectionPointerDown();
  82598. }
  82599. }
  82600. else if (stateObject.value < _this._padSensibilityDown) {
  82601. controller._selectionPointerUp();
  82602. }
  82603. });
  82604. }
  82605. };
  82606. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  82607. // Dont teleport if another gaze already requested teleportation
  82608. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  82609. return;
  82610. }
  82611. if (!gazer._teleportationRequestInitiated) {
  82612. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  82613. gazer._activatePointer();
  82614. gazer._teleportationRequestInitiated = true;
  82615. }
  82616. }
  82617. else {
  82618. // Listening to the proper controller values changes to confirm teleportation
  82619. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  82620. if (this._teleportActive) {
  82621. this._teleportCamera(this._haloCenter);
  82622. }
  82623. gazer._teleportationRequestInitiated = false;
  82624. }
  82625. }
  82626. };
  82627. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  82628. // Only rotate when user is not currently selecting a teleportation location
  82629. if (gazer._teleportationRequestInitiated) {
  82630. return;
  82631. }
  82632. if (!this._rotationLeftAsked) {
  82633. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  82634. this._rotationLeftAsked = true;
  82635. if (this._rotationAllowed) {
  82636. this._rotateCamera(false);
  82637. }
  82638. }
  82639. }
  82640. else {
  82641. if (stateObject.x > -this._padSensibilityDown) {
  82642. this._rotationLeftAsked = false;
  82643. }
  82644. }
  82645. if (!this._rotationRightAsked) {
  82646. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  82647. this._rotationRightAsked = true;
  82648. if (this._rotationAllowed) {
  82649. this._rotateCamera(true);
  82650. }
  82651. }
  82652. }
  82653. else {
  82654. if (stateObject.x < this._padSensibilityDown) {
  82655. this._rotationRightAsked = false;
  82656. }
  82657. }
  82658. };
  82659. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  82660. // Only teleport backwards when user is not currently selecting a teleportation location
  82661. if (gazer._teleportationRequestInitiated) {
  82662. return;
  82663. }
  82664. // Teleport backwards
  82665. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  82666. if (!gazer._teleportationBackRequestInitiated) {
  82667. if (!this.currentVRCamera) {
  82668. return;
  82669. }
  82670. // Get rotation and position of the current camera
  82671. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  82672. var position = this.currentVRCamera.position;
  82673. // If the camera has device position, use that instead
  82674. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  82675. rotation = this.currentVRCamera.deviceRotationQuaternion;
  82676. position = this.currentVRCamera.devicePosition;
  82677. }
  82678. // Get matrix with only the y rotation of the device rotation
  82679. rotation.toEulerAnglesToRef(this._workingVector);
  82680. this._workingVector.z = 0;
  82681. this._workingVector.x = 0;
  82682. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  82683. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  82684. // Rotate backwards ray by device rotation to cast at the ground behind the user
  82685. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  82686. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  82687. var ray = new BABYLON.Ray(position, this._workingVector);
  82688. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  82689. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  82690. this._teleportCamera(hit.pickedPoint);
  82691. }
  82692. gazer._teleportationBackRequestInitiated = true;
  82693. }
  82694. }
  82695. else {
  82696. gazer._teleportationBackRequestInitiated = false;
  82697. }
  82698. };
  82699. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  82700. var _this = this;
  82701. var controllerMesh = controller.webVRController.mesh;
  82702. if (controllerMesh) {
  82703. if (!controller._interactionsEnabled) {
  82704. this._enableInteractionOnController(controller);
  82705. }
  82706. controller._interactionsEnabled = true;
  82707. controller._teleportationEnabled = true;
  82708. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82709. controller._dpadPressed = false;
  82710. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  82711. controller._dpadPressed = stateObject.pressed;
  82712. if (!controller._dpadPressed) {
  82713. _this._rotationLeftAsked = false;
  82714. _this._rotationRightAsked = false;
  82715. controller._teleportationBackRequestInitiated = false;
  82716. }
  82717. });
  82718. }
  82719. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  82720. if (_this.teleportationEnabled) {
  82721. _this._checkTeleportBackwards(stateObject, controller);
  82722. _this._checkTeleportWithRay(stateObject, controller);
  82723. }
  82724. _this._checkRotate(stateObject, controller);
  82725. });
  82726. }
  82727. };
  82728. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  82729. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  82730. this._teleportationTarget.isPickable = false;
  82731. var length = 512;
  82732. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  82733. dynamicTexture.hasAlpha = true;
  82734. var context = dynamicTexture.getContext();
  82735. var centerX = length / 2;
  82736. var centerY = length / 2;
  82737. var radius = 200;
  82738. context.beginPath();
  82739. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  82740. context.fillStyle = this._teleportationFillColor;
  82741. context.fill();
  82742. context.lineWidth = 10;
  82743. context.strokeStyle = this._teleportationBorderColor;
  82744. context.stroke();
  82745. context.closePath();
  82746. dynamicTexture.update();
  82747. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  82748. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  82749. this._teleportationTarget.material = teleportationCircleMaterial;
  82750. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  82751. torus.isPickable = false;
  82752. torus.parent = this._teleportationTarget;
  82753. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  82754. var keys = [];
  82755. keys.push({
  82756. frame: 0,
  82757. value: 0
  82758. });
  82759. keys.push({
  82760. frame: 30,
  82761. value: 0.4
  82762. });
  82763. keys.push({
  82764. frame: 60,
  82765. value: 0
  82766. });
  82767. animationInnerCircle.setKeys(keys);
  82768. var easingFunction = new BABYLON.SineEase();
  82769. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82770. animationInnerCircle.setEasingFunction(easingFunction);
  82771. torus.animations = [];
  82772. torus.animations.push(animationInnerCircle);
  82773. this._scene.beginAnimation(torus, 0, 60, true);
  82774. this._hideTeleportationTarget();
  82775. };
  82776. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  82777. this._teleportActive = true;
  82778. if (this._teleportationInitialized) {
  82779. this._teleportationTarget.isVisible = true;
  82780. if (this._isDefaultTeleportationTarget) {
  82781. this._teleportationTarget.getChildren()[0].isVisible = true;
  82782. }
  82783. }
  82784. };
  82785. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  82786. this._teleportActive = false;
  82787. if (this._teleportationInitialized) {
  82788. this._teleportationTarget.isVisible = false;
  82789. if (this._isDefaultTeleportationTarget) {
  82790. this._teleportationTarget.getChildren()[0].isVisible = false;
  82791. }
  82792. }
  82793. };
  82794. VRExperienceHelper.prototype._rotateCamera = function (right) {
  82795. var _this = this;
  82796. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82797. return;
  82798. }
  82799. if (right) {
  82800. this._rotationAngle++;
  82801. }
  82802. else {
  82803. this._rotationAngle--;
  82804. }
  82805. this.currentVRCamera.animations = [];
  82806. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  82807. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82808. var animationRotationKeys = [];
  82809. animationRotationKeys.push({
  82810. frame: 0,
  82811. value: this.currentVRCamera.rotationQuaternion
  82812. });
  82813. animationRotationKeys.push({
  82814. frame: 6,
  82815. value: target
  82816. });
  82817. animationRotation.setKeys(animationRotationKeys);
  82818. animationRotation.setEasingFunction(this._circleEase);
  82819. this.currentVRCamera.animations.push(animationRotation);
  82820. this._postProcessMove.animations = [];
  82821. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82822. var vignetteWeightKeys = [];
  82823. vignetteWeightKeys.push({
  82824. frame: 0,
  82825. value: 0
  82826. });
  82827. vignetteWeightKeys.push({
  82828. frame: 3,
  82829. value: 4
  82830. });
  82831. vignetteWeightKeys.push({
  82832. frame: 6,
  82833. value: 0
  82834. });
  82835. animationPP.setKeys(vignetteWeightKeys);
  82836. animationPP.setEasingFunction(this._circleEase);
  82837. this._postProcessMove.animations.push(animationPP);
  82838. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82839. var vignetteStretchKeys = [];
  82840. vignetteStretchKeys.push({
  82841. frame: 0,
  82842. value: 0
  82843. });
  82844. vignetteStretchKeys.push({
  82845. frame: 3,
  82846. value: 10
  82847. });
  82848. vignetteStretchKeys.push({
  82849. frame: 6,
  82850. value: 0
  82851. });
  82852. animationPP2.setKeys(vignetteStretchKeys);
  82853. animationPP2.setEasingFunction(this._circleEase);
  82854. this._postProcessMove.animations.push(animationPP2);
  82855. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82856. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82857. this._postProcessMove.samples = 4;
  82858. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82859. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  82860. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82861. });
  82862. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  82863. };
  82864. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  82865. if (hit.pickedPoint) {
  82866. if (gazer._teleportationRequestInitiated) {
  82867. this._displayTeleportationTarget();
  82868. this._haloCenter.copyFrom(hit.pickedPoint);
  82869. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  82870. }
  82871. var pickNormal = hit.getNormal(true, false);
  82872. if (pickNormal) {
  82873. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82874. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82875. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  82876. }
  82877. this._teleportationTarget.position.y += 0.1;
  82878. }
  82879. };
  82880. VRExperienceHelper.prototype._teleportCamera = function (location) {
  82881. var _this = this;
  82882. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82883. return;
  82884. }
  82885. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  82886. // offset of the headset from the anchor.
  82887. if (this.webVRCamera.leftCamera) {
  82888. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  82889. this._workingVector.subtractInPlace(this.webVRCamera.position);
  82890. location.subtractToRef(this._workingVector, this._workingVector);
  82891. }
  82892. else {
  82893. this._workingVector.copyFrom(location);
  82894. }
  82895. // Add height to account for user's height offset
  82896. if (this.isInVRMode) {
  82897. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  82898. }
  82899. else {
  82900. this._workingVector.y += this._defaultHeight;
  82901. }
  82902. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  82903. // Create animation from the camera's position to the new location
  82904. this.currentVRCamera.animations = [];
  82905. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82906. var animationCameraTeleportationKeys = [{
  82907. frame: 0,
  82908. value: this.currentVRCamera.position
  82909. },
  82910. {
  82911. frame: 11,
  82912. value: this._workingVector
  82913. }
  82914. ];
  82915. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  82916. animationCameraTeleportation.setEasingFunction(this._circleEase);
  82917. this.currentVRCamera.animations.push(animationCameraTeleportation);
  82918. this._postProcessMove.animations = [];
  82919. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82920. var vignetteWeightKeys = [];
  82921. vignetteWeightKeys.push({
  82922. frame: 0,
  82923. value: 0
  82924. });
  82925. vignetteWeightKeys.push({
  82926. frame: 5,
  82927. value: 8
  82928. });
  82929. vignetteWeightKeys.push({
  82930. frame: 11,
  82931. value: 0
  82932. });
  82933. animationPP.setKeys(vignetteWeightKeys);
  82934. this._postProcessMove.animations.push(animationPP);
  82935. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82936. var vignetteStretchKeys = [];
  82937. vignetteStretchKeys.push({
  82938. frame: 0,
  82939. value: 0
  82940. });
  82941. vignetteStretchKeys.push({
  82942. frame: 5,
  82943. value: 10
  82944. });
  82945. vignetteStretchKeys.push({
  82946. frame: 11,
  82947. value: 0
  82948. });
  82949. animationPP2.setKeys(vignetteStretchKeys);
  82950. this._postProcessMove.animations.push(animationPP2);
  82951. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82952. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82953. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82954. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  82955. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82956. });
  82957. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  82958. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  82959. });
  82960. this._hideTeleportationTarget();
  82961. };
  82962. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  82963. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82964. return;
  82965. }
  82966. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  82967. // Moving the gazeTracker on the mesh face targetted
  82968. if (hit && hit.pickedPoint) {
  82969. if (this._displayGaze) {
  82970. var multiplier = 1;
  82971. gazer._gazeTracker.isVisible = true;
  82972. if (gazer._isActionableMesh) {
  82973. multiplier = 3;
  82974. }
  82975. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  82976. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  82977. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  82978. var pickNormal = hit.getNormal();
  82979. // To avoid z-fighting
  82980. var deltaFighting = 0.002;
  82981. if (pickNormal) {
  82982. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82983. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82984. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  82985. }
  82986. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  82987. if (gazer._gazeTracker.position.x < 0) {
  82988. gazer._gazeTracker.position.x += deltaFighting;
  82989. }
  82990. else {
  82991. gazer._gazeTracker.position.x -= deltaFighting;
  82992. }
  82993. if (gazer._gazeTracker.position.y < 0) {
  82994. gazer._gazeTracker.position.y += deltaFighting;
  82995. }
  82996. else {
  82997. gazer._gazeTracker.position.y -= deltaFighting;
  82998. }
  82999. if (gazer._gazeTracker.position.z < 0) {
  83000. gazer._gazeTracker.position.z += deltaFighting;
  83001. }
  83002. else {
  83003. gazer._gazeTracker.position.z -= deltaFighting;
  83004. }
  83005. }
  83006. // Changing the size of the laser pointer based on the distance from the targetted point
  83007. gazer._updatePointerDistance(hit.distance);
  83008. }
  83009. else {
  83010. gazer._gazeTracker.isVisible = false;
  83011. }
  83012. if (hit && hit.pickedMesh) {
  83013. gazer._currentHit = hit;
  83014. if (gazer._pointerDownOnMeshAsked) {
  83015. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  83016. }
  83017. // The object selected is the floor, we're in a teleportation scenario
  83018. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  83019. // Moving the teleportation area to this targetted point
  83020. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  83021. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  83022. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83023. }
  83024. gazer._currentMeshSelected = null;
  83025. if (gazer._teleportationRequestInitiated) {
  83026. this._moveTeleportationSelectorTo(hit, gazer);
  83027. }
  83028. return;
  83029. }
  83030. // If not, we're in a selection scenario
  83031. //this._teleportationAllowed = false;
  83032. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  83033. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  83034. this.onNewMeshPicked.notifyObservers(hit);
  83035. gazer._currentMeshSelected = hit.pickedMesh;
  83036. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  83037. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  83038. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  83039. gazer._isActionableMesh = true;
  83040. }
  83041. else {
  83042. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83043. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83044. gazer._isActionableMesh = false;
  83045. }
  83046. try {
  83047. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  83048. }
  83049. catch (err) {
  83050. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  83051. }
  83052. }
  83053. else {
  83054. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83055. gazer._currentMeshSelected = null;
  83056. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83057. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83058. }
  83059. }
  83060. }
  83061. else {
  83062. gazer._currentHit = null;
  83063. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83064. gazer._currentMeshSelected = null;
  83065. //this._teleportationAllowed = false;
  83066. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83067. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83068. }
  83069. };
  83070. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  83071. if (mesh) {
  83072. this.onSelectedMeshUnselected.notifyObservers(mesh);
  83073. }
  83074. };
  83075. /**
  83076. * Sets the color of the laser ray from the vr controllers.
  83077. * @param color new color for the ray.
  83078. */
  83079. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  83080. if (this.leftController) {
  83081. this.leftController._setLaserPointerColor(color);
  83082. }
  83083. if (this.rightController) {
  83084. this.rightController._setLaserPointerColor(color);
  83085. }
  83086. };
  83087. /**
  83088. * Sets the color of the ray from the vr headsets gaze.
  83089. * @param color new color for the ray.
  83090. */
  83091. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  83092. if (!this._cameraGazer._gazeTracker.material) {
  83093. return;
  83094. }
  83095. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  83096. if (this.leftController) {
  83097. this.leftController._gazeTracker.material.emissiveColor = color;
  83098. }
  83099. if (this.rightController) {
  83100. this.rightController._gazeTracker.material.emissiveColor = color;
  83101. }
  83102. };
  83103. /**
  83104. * Exits VR and disposes of the vr experience helper
  83105. */
  83106. VRExperienceHelper.prototype.dispose = function () {
  83107. if (this.isInVRMode) {
  83108. this.exitVR();
  83109. }
  83110. if (this._postProcessMove) {
  83111. this._postProcessMove.dispose();
  83112. }
  83113. if (this._webVRCamera) {
  83114. this._webVRCamera.dispose();
  83115. }
  83116. if (this._vrDeviceOrientationCamera) {
  83117. this._vrDeviceOrientationCamera.dispose();
  83118. }
  83119. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  83120. document.body.removeChild(this._btnVR);
  83121. }
  83122. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  83123. this._deviceOrientationCamera.dispose();
  83124. }
  83125. if (this._cameraGazer) {
  83126. this._cameraGazer.dispose();
  83127. }
  83128. if (this.leftController) {
  83129. this.leftController.dispose();
  83130. }
  83131. if (this.rightController) {
  83132. this.rightController.dispose();
  83133. }
  83134. if (this._teleportationTarget) {
  83135. this._teleportationTarget.dispose();
  83136. }
  83137. this._floorMeshesCollection = [];
  83138. document.removeEventListener("keydown", this._onKeyDown);
  83139. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83140. window.removeEventListener("resize", this._onResize);
  83141. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  83142. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  83143. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  83144. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  83145. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  83146. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  83147. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  83148. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83149. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  83150. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  83151. this._scene.unregisterBeforeRender(this.beforeRender);
  83152. };
  83153. /**
  83154. * Gets the name of the VRExperienceHelper class
  83155. * @returns "VRExperienceHelper"
  83156. */
  83157. VRExperienceHelper.prototype.getClassName = function () {
  83158. return "VRExperienceHelper";
  83159. };
  83160. return VRExperienceHelper;
  83161. }());
  83162. BABYLON.VRExperienceHelper = VRExperienceHelper;
  83163. })(BABYLON || (BABYLON = {}));
  83164. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  83165. "use strict";
  83166. // Mainly based on these 2 articles :
  83167. // 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
  83168. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  83169. var BABYLON;
  83170. (function (BABYLON) {
  83171. var JoystickAxis;
  83172. (function (JoystickAxis) {
  83173. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  83174. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  83175. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  83176. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  83177. var VirtualJoystick = /** @class */ (function () {
  83178. function VirtualJoystick(leftJoystick) {
  83179. var _this = this;
  83180. if (leftJoystick) {
  83181. this._leftJoystick = true;
  83182. }
  83183. else {
  83184. this._leftJoystick = false;
  83185. }
  83186. VirtualJoystick._globalJoystickIndex++;
  83187. // By default left & right arrow keys are moving the X
  83188. // and up & down keys are moving the Y
  83189. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83190. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83191. this.reverseLeftRight = false;
  83192. this.reverseUpDown = false;
  83193. // collections of pointers
  83194. this._touches = new BABYLON.StringDictionary();
  83195. this.deltaPosition = BABYLON.Vector3.Zero();
  83196. this._joystickSensibility = 25;
  83197. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83198. this._onResize = function (evt) {
  83199. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83200. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83201. if (VirtualJoystick.vjCanvas) {
  83202. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  83203. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  83204. }
  83205. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  83206. };
  83207. // injecting a canvas element on top of the canvas 3D game
  83208. if (!VirtualJoystick.vjCanvas) {
  83209. window.addEventListener("resize", this._onResize, false);
  83210. VirtualJoystick.vjCanvas = document.createElement("canvas");
  83211. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83212. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83213. VirtualJoystick.vjCanvas.width = window.innerWidth;
  83214. VirtualJoystick.vjCanvas.height = window.innerHeight;
  83215. VirtualJoystick.vjCanvas.style.width = "100%";
  83216. VirtualJoystick.vjCanvas.style.height = "100%";
  83217. VirtualJoystick.vjCanvas.style.position = "absolute";
  83218. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  83219. VirtualJoystick.vjCanvas.style.top = "0px";
  83220. VirtualJoystick.vjCanvas.style.left = "0px";
  83221. VirtualJoystick.vjCanvas.style.zIndex = "5";
  83222. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  83223. // Support for jQuery PEP polyfill
  83224. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  83225. var context = VirtualJoystick.vjCanvas.getContext('2d');
  83226. if (!context) {
  83227. throw new Error("Unable to create canvas for virtual joystick");
  83228. }
  83229. VirtualJoystick.vjCanvasContext = context;
  83230. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  83231. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83232. document.body.appendChild(VirtualJoystick.vjCanvas);
  83233. }
  83234. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  83235. this.pressed = false;
  83236. // default joystick color
  83237. this._joystickColor = "cyan";
  83238. this._joystickPointerID = -1;
  83239. // current joystick position
  83240. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  83241. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  83242. // origin joystick position
  83243. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  83244. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  83245. this._onPointerDownHandlerRef = function (evt) {
  83246. _this._onPointerDown(evt);
  83247. };
  83248. this._onPointerMoveHandlerRef = function (evt) {
  83249. _this._onPointerMove(evt);
  83250. };
  83251. this._onPointerUpHandlerRef = function (evt) {
  83252. _this._onPointerUp(evt);
  83253. };
  83254. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  83255. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  83256. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  83257. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  83258. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  83259. evt.preventDefault(); // Disables system menu
  83260. }, false);
  83261. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83262. }
  83263. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  83264. this._joystickSensibility = newJoystickSensibility;
  83265. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83266. };
  83267. VirtualJoystick.prototype._onPointerDown = function (e) {
  83268. var positionOnScreenCondition;
  83269. e.preventDefault();
  83270. if (this._leftJoystick === true) {
  83271. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  83272. }
  83273. else {
  83274. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  83275. }
  83276. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  83277. // First contact will be dedicated to the virtual joystick
  83278. this._joystickPointerID = e.pointerId;
  83279. this._joystickPointerStartPos.x = e.clientX;
  83280. this._joystickPointerStartPos.y = e.clientY;
  83281. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  83282. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  83283. this._deltaJoystickVector.x = 0;
  83284. this._deltaJoystickVector.y = 0;
  83285. this.pressed = true;
  83286. this._touches.add(e.pointerId.toString(), e);
  83287. }
  83288. else {
  83289. // You can only trigger the action buttons with a joystick declared
  83290. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  83291. this._action();
  83292. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  83293. }
  83294. }
  83295. };
  83296. VirtualJoystick.prototype._onPointerMove = function (e) {
  83297. // If the current pointer is the one associated to the joystick (first touch contact)
  83298. if (this._joystickPointerID == e.pointerId) {
  83299. this._joystickPointerPos.x = e.clientX;
  83300. this._joystickPointerPos.y = e.clientY;
  83301. this._deltaJoystickVector = this._joystickPointerPos.clone();
  83302. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  83303. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  83304. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  83305. switch (this._axisTargetedByLeftAndRight) {
  83306. case JoystickAxis.X:
  83307. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  83308. break;
  83309. case JoystickAxis.Y:
  83310. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  83311. break;
  83312. case JoystickAxis.Z:
  83313. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  83314. break;
  83315. }
  83316. var directionUpDown = this.reverseUpDown ? 1 : -1;
  83317. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  83318. switch (this._axisTargetedByUpAndDown) {
  83319. case JoystickAxis.X:
  83320. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  83321. break;
  83322. case JoystickAxis.Y:
  83323. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  83324. break;
  83325. case JoystickAxis.Z:
  83326. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  83327. break;
  83328. }
  83329. }
  83330. else {
  83331. var data = this._touches.get(e.pointerId.toString());
  83332. if (data) {
  83333. data.x = e.clientX;
  83334. data.y = e.clientY;
  83335. }
  83336. }
  83337. };
  83338. VirtualJoystick.prototype._onPointerUp = function (e) {
  83339. if (this._joystickPointerID == e.pointerId) {
  83340. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  83341. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  83342. this._joystickPointerID = -1;
  83343. this.pressed = false;
  83344. }
  83345. else {
  83346. var touch = this._touches.get(e.pointerId.toString());
  83347. if (touch) {
  83348. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83349. }
  83350. }
  83351. this._deltaJoystickVector.x = 0;
  83352. this._deltaJoystickVector.y = 0;
  83353. this._touches.remove(e.pointerId.toString());
  83354. };
  83355. /**
  83356. * Change the color of the virtual joystick
  83357. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  83358. */
  83359. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  83360. this._joystickColor = newColor;
  83361. };
  83362. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  83363. this._action = action;
  83364. };
  83365. // Define which axis you'd like to control for left & right
  83366. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  83367. switch (axis) {
  83368. case JoystickAxis.X:
  83369. case JoystickAxis.Y:
  83370. case JoystickAxis.Z:
  83371. this._axisTargetedByLeftAndRight = axis;
  83372. break;
  83373. default:
  83374. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83375. break;
  83376. }
  83377. };
  83378. // Define which axis you'd like to control for up & down
  83379. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  83380. switch (axis) {
  83381. case JoystickAxis.X:
  83382. case JoystickAxis.Y:
  83383. case JoystickAxis.Z:
  83384. this._axisTargetedByUpAndDown = axis;
  83385. break;
  83386. default:
  83387. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83388. break;
  83389. }
  83390. };
  83391. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  83392. var _this = this;
  83393. if (this.pressed) {
  83394. this._touches.forEach(function (key, touch) {
  83395. if (touch.pointerId === _this._joystickPointerID) {
  83396. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  83397. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  83398. VirtualJoystick.vjCanvasContext.beginPath();
  83399. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83400. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83401. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  83402. VirtualJoystick.vjCanvasContext.stroke();
  83403. VirtualJoystick.vjCanvasContext.closePath();
  83404. VirtualJoystick.vjCanvasContext.beginPath();
  83405. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83406. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83407. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  83408. VirtualJoystick.vjCanvasContext.stroke();
  83409. VirtualJoystick.vjCanvasContext.closePath();
  83410. VirtualJoystick.vjCanvasContext.beginPath();
  83411. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83412. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  83413. VirtualJoystick.vjCanvasContext.stroke();
  83414. VirtualJoystick.vjCanvasContext.closePath();
  83415. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  83416. }
  83417. else {
  83418. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83419. VirtualJoystick.vjCanvasContext.beginPath();
  83420. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  83421. VirtualJoystick.vjCanvasContext.beginPath();
  83422. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  83423. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83424. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  83425. VirtualJoystick.vjCanvasContext.stroke();
  83426. VirtualJoystick.vjCanvasContext.closePath();
  83427. touch.prevX = touch.x;
  83428. touch.prevY = touch.y;
  83429. }
  83430. ;
  83431. });
  83432. }
  83433. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83434. };
  83435. VirtualJoystick.prototype.releaseCanvas = function () {
  83436. if (VirtualJoystick.vjCanvas) {
  83437. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  83438. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  83439. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  83440. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  83441. window.removeEventListener("resize", this._onResize);
  83442. document.body.removeChild(VirtualJoystick.vjCanvas);
  83443. VirtualJoystick.vjCanvas = null;
  83444. }
  83445. };
  83446. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  83447. VirtualJoystick._globalJoystickIndex = 0;
  83448. return VirtualJoystick;
  83449. }());
  83450. BABYLON.VirtualJoystick = VirtualJoystick;
  83451. })(BABYLON || (BABYLON = {}));
  83452. //# sourceMappingURL=babylon.virtualJoystick.js.map
  83453. "use strict";
  83454. var BABYLON;
  83455. (function (BABYLON) {
  83456. // We're mainly based on the logic defined into the FreeCamera code
  83457. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  83458. __extends(VirtualJoysticksCamera, _super);
  83459. function VirtualJoysticksCamera(name, position, scene) {
  83460. var _this = _super.call(this, name, position, scene) || this;
  83461. _this.inputs.addVirtualJoystick();
  83462. return _this;
  83463. }
  83464. VirtualJoysticksCamera.prototype.getClassName = function () {
  83465. return "VirtualJoysticksCamera";
  83466. };
  83467. return VirtualJoysticksCamera;
  83468. }(BABYLON.FreeCamera));
  83469. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  83470. })(BABYLON || (BABYLON = {}));
  83471. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  83472. "use strict";
  83473. var BABYLON;
  83474. (function (BABYLON) {
  83475. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  83476. function FreeCameraVirtualJoystickInput() {
  83477. }
  83478. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  83479. return this._leftjoystick;
  83480. };
  83481. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  83482. return this._rightjoystick;
  83483. };
  83484. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  83485. if (this._leftjoystick) {
  83486. var camera = this.camera;
  83487. var speed = camera._computeLocalCameraSpeed() * 50;
  83488. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  83489. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  83490. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  83491. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  83492. if (!this._leftjoystick.pressed) {
  83493. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  83494. }
  83495. if (!this._rightjoystick.pressed) {
  83496. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  83497. }
  83498. }
  83499. };
  83500. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  83501. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  83502. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  83503. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  83504. this._leftjoystick.setJoystickSensibility(0.15);
  83505. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  83506. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  83507. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  83508. this._rightjoystick.reverseUpDown = true;
  83509. this._rightjoystick.setJoystickSensibility(0.05);
  83510. this._rightjoystick.setJoystickColor("yellow");
  83511. };
  83512. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  83513. this._leftjoystick.releaseCanvas();
  83514. this._rightjoystick.releaseCanvas();
  83515. };
  83516. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  83517. return "FreeCameraVirtualJoystickInput";
  83518. };
  83519. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  83520. return "virtualJoystick";
  83521. };
  83522. return FreeCameraVirtualJoystickInput;
  83523. }());
  83524. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  83525. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  83526. })(BABYLON || (BABYLON = {}));
  83527. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  83528. "use strict";
  83529. var BABYLON;
  83530. (function (BABYLON) {
  83531. var SimplificationSettings = /** @class */ (function () {
  83532. function SimplificationSettings(quality, distance, optimizeMesh) {
  83533. this.quality = quality;
  83534. this.distance = distance;
  83535. this.optimizeMesh = optimizeMesh;
  83536. }
  83537. return SimplificationSettings;
  83538. }());
  83539. BABYLON.SimplificationSettings = SimplificationSettings;
  83540. var SimplificationQueue = /** @class */ (function () {
  83541. function SimplificationQueue() {
  83542. this.running = false;
  83543. this._simplificationArray = [];
  83544. }
  83545. SimplificationQueue.prototype.addTask = function (task) {
  83546. this._simplificationArray.push(task);
  83547. };
  83548. SimplificationQueue.prototype.executeNext = function () {
  83549. var task = this._simplificationArray.pop();
  83550. if (task) {
  83551. this.running = true;
  83552. this.runSimplification(task);
  83553. }
  83554. else {
  83555. this.running = false;
  83556. }
  83557. };
  83558. SimplificationQueue.prototype.runSimplification = function (task) {
  83559. var _this = this;
  83560. if (task.parallelProcessing) {
  83561. //parallel simplifier
  83562. task.settings.forEach(function (setting) {
  83563. var simplifier = _this.getSimplifier(task);
  83564. simplifier.simplify(setting, function (newMesh) {
  83565. task.mesh.addLODLevel(setting.distance, newMesh);
  83566. newMesh.isVisible = true;
  83567. //check if it is the last
  83568. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  83569. //all done, run the success callback.
  83570. task.successCallback();
  83571. }
  83572. _this.executeNext();
  83573. });
  83574. });
  83575. }
  83576. else {
  83577. //single simplifier.
  83578. var simplifier = this.getSimplifier(task);
  83579. var runDecimation = function (setting, callback) {
  83580. simplifier.simplify(setting, function (newMesh) {
  83581. task.mesh.addLODLevel(setting.distance, newMesh);
  83582. newMesh.isVisible = true;
  83583. //run the next quality level
  83584. callback();
  83585. });
  83586. };
  83587. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  83588. runDecimation(task.settings[loop.index], function () {
  83589. loop.executeNext();
  83590. });
  83591. }, function () {
  83592. //execution ended, run the success callback.
  83593. if (task.successCallback) {
  83594. task.successCallback();
  83595. }
  83596. _this.executeNext();
  83597. });
  83598. }
  83599. };
  83600. SimplificationQueue.prototype.getSimplifier = function (task) {
  83601. switch (task.simplificationType) {
  83602. case SimplificationType.QUADRATIC:
  83603. default:
  83604. return new QuadraticErrorSimplification(task.mesh);
  83605. }
  83606. };
  83607. return SimplificationQueue;
  83608. }());
  83609. BABYLON.SimplificationQueue = SimplificationQueue;
  83610. /**
  83611. * The implemented types of simplification.
  83612. * At the moment only Quadratic Error Decimation is implemented.
  83613. */
  83614. var SimplificationType;
  83615. (function (SimplificationType) {
  83616. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  83617. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  83618. var DecimationTriangle = /** @class */ (function () {
  83619. function DecimationTriangle(vertices) {
  83620. this.vertices = vertices;
  83621. this.error = new Array(4);
  83622. this.deleted = false;
  83623. this.isDirty = false;
  83624. this.deletePending = false;
  83625. this.borderFactor = 0;
  83626. }
  83627. return DecimationTriangle;
  83628. }());
  83629. BABYLON.DecimationTriangle = DecimationTriangle;
  83630. var DecimationVertex = /** @class */ (function () {
  83631. function DecimationVertex(position, id) {
  83632. this.position = position;
  83633. this.id = id;
  83634. this.isBorder = true;
  83635. this.q = new QuadraticMatrix();
  83636. this.triangleCount = 0;
  83637. this.triangleStart = 0;
  83638. this.originalOffsets = [];
  83639. }
  83640. DecimationVertex.prototype.updatePosition = function (newPosition) {
  83641. this.position.copyFrom(newPosition);
  83642. };
  83643. return DecimationVertex;
  83644. }());
  83645. BABYLON.DecimationVertex = DecimationVertex;
  83646. var QuadraticMatrix = /** @class */ (function () {
  83647. function QuadraticMatrix(data) {
  83648. this.data = new Array(10);
  83649. for (var i = 0; i < 10; ++i) {
  83650. if (data && data[i]) {
  83651. this.data[i] = data[i];
  83652. }
  83653. else {
  83654. this.data[i] = 0;
  83655. }
  83656. }
  83657. }
  83658. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  83659. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  83660. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  83661. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  83662. return det;
  83663. };
  83664. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  83665. for (var i = 0; i < 10; ++i) {
  83666. this.data[i] += matrix.data[i];
  83667. }
  83668. };
  83669. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  83670. for (var i = 0; i < 10; ++i) {
  83671. this.data[i] += data[i];
  83672. }
  83673. };
  83674. QuadraticMatrix.prototype.add = function (matrix) {
  83675. var m = new QuadraticMatrix();
  83676. for (var i = 0; i < 10; ++i) {
  83677. m.data[i] = this.data[i] + matrix.data[i];
  83678. }
  83679. return m;
  83680. };
  83681. QuadraticMatrix.FromData = function (a, b, c, d) {
  83682. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  83683. };
  83684. //returning an array to avoid garbage collection
  83685. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  83686. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  83687. };
  83688. return QuadraticMatrix;
  83689. }());
  83690. BABYLON.QuadraticMatrix = QuadraticMatrix;
  83691. var Reference = /** @class */ (function () {
  83692. function Reference(vertexId, triangleId) {
  83693. this.vertexId = vertexId;
  83694. this.triangleId = triangleId;
  83695. }
  83696. return Reference;
  83697. }());
  83698. BABYLON.Reference = Reference;
  83699. /**
  83700. * An implementation of the Quadratic Error simplification algorithm.
  83701. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  83702. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  83703. * @author RaananW
  83704. */
  83705. var QuadraticErrorSimplification = /** @class */ (function () {
  83706. function QuadraticErrorSimplification(_mesh) {
  83707. this._mesh = _mesh;
  83708. this.syncIterations = 5000;
  83709. this.aggressiveness = 7;
  83710. this.decimationIterations = 100;
  83711. this.boundingBoxEpsilon = BABYLON.Epsilon;
  83712. }
  83713. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  83714. var _this = this;
  83715. this.initDecimatedMesh();
  83716. //iterating through the submeshes array, one after the other.
  83717. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  83718. _this.initWithMesh(loop.index, function () {
  83719. _this.runDecimation(settings, loop.index, function () {
  83720. loop.executeNext();
  83721. });
  83722. }, settings.optimizeMesh);
  83723. }, function () {
  83724. setTimeout(function () {
  83725. successCallback(_this._reconstructedMesh);
  83726. }, 0);
  83727. });
  83728. };
  83729. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  83730. var _this = this;
  83731. var targetCount = ~~(this.triangles.length * settings.quality);
  83732. var deletedTriangles = 0;
  83733. var triangleCount = this.triangles.length;
  83734. var iterationFunction = function (iteration, callback) {
  83735. setTimeout(function () {
  83736. if (iteration % 5 === 0) {
  83737. _this.updateMesh(iteration === 0);
  83738. }
  83739. for (var i = 0; i < _this.triangles.length; ++i) {
  83740. _this.triangles[i].isDirty = false;
  83741. }
  83742. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  83743. var trianglesIterator = function (i) {
  83744. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  83745. var t = _this.triangles[tIdx];
  83746. if (!t)
  83747. return;
  83748. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  83749. return;
  83750. }
  83751. for (var j = 0; j < 3; ++j) {
  83752. if (t.error[j] < threshold) {
  83753. var deleted0 = [];
  83754. var deleted1 = [];
  83755. var v0 = t.vertices[j];
  83756. var v1 = t.vertices[(j + 1) % 3];
  83757. if (v0.isBorder || v1.isBorder)
  83758. continue;
  83759. var p = BABYLON.Vector3.Zero();
  83760. var n = BABYLON.Vector3.Zero();
  83761. var uv = BABYLON.Vector2.Zero();
  83762. var color = new BABYLON.Color4(0, 0, 0, 1);
  83763. _this.calculateError(v0, v1, p, n, uv, color);
  83764. var delTr = new Array();
  83765. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  83766. continue;
  83767. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  83768. continue;
  83769. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  83770. continue;
  83771. var uniqueArray = new Array();
  83772. delTr.forEach(function (deletedT) {
  83773. if (uniqueArray.indexOf(deletedT) === -1) {
  83774. deletedT.deletePending = true;
  83775. uniqueArray.push(deletedT);
  83776. }
  83777. });
  83778. if (uniqueArray.length % 2 !== 0) {
  83779. continue;
  83780. }
  83781. v0.q = v1.q.add(v0.q);
  83782. v0.updatePosition(p);
  83783. var tStart = _this.references.length;
  83784. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  83785. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  83786. var tCount = _this.references.length - tStart;
  83787. if (tCount <= v0.triangleCount) {
  83788. if (tCount) {
  83789. for (var c = 0; c < tCount; c++) {
  83790. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  83791. }
  83792. }
  83793. }
  83794. else {
  83795. v0.triangleStart = tStart;
  83796. }
  83797. v0.triangleCount = tCount;
  83798. break;
  83799. }
  83800. }
  83801. };
  83802. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  83803. }, 0);
  83804. };
  83805. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  83806. if (triangleCount - deletedTriangles <= targetCount)
  83807. loop.breakLoop();
  83808. else {
  83809. iterationFunction(loop.index, function () {
  83810. loop.executeNext();
  83811. });
  83812. }
  83813. }, function () {
  83814. setTimeout(function () {
  83815. //reconstruct this part of the mesh
  83816. _this.reconstructMesh(submeshIndex);
  83817. successCallback();
  83818. }, 0);
  83819. });
  83820. };
  83821. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  83822. var _this = this;
  83823. this.vertices = [];
  83824. this.triangles = [];
  83825. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83826. var indices = this._mesh.getIndices();
  83827. var submesh = this._mesh.subMeshes[submeshIndex];
  83828. var findInVertices = function (positionToSearch) {
  83829. if (optimizeMesh) {
  83830. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  83831. if (_this.vertices[ii].position.equals(positionToSearch)) {
  83832. return _this.vertices[ii];
  83833. }
  83834. }
  83835. }
  83836. return null;
  83837. };
  83838. var vertexReferences = [];
  83839. var vertexInit = function (i) {
  83840. if (!positionData) {
  83841. return;
  83842. }
  83843. var offset = i + submesh.verticesStart;
  83844. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  83845. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  83846. vertex.originalOffsets.push(offset);
  83847. if (vertex.id === _this.vertices.length) {
  83848. _this.vertices.push(vertex);
  83849. }
  83850. vertexReferences.push(vertex.id);
  83851. };
  83852. //var totalVertices = mesh.getTotalVertices();
  83853. var totalVertices = submesh.verticesCount;
  83854. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  83855. var indicesInit = function (i) {
  83856. if (!indices) {
  83857. return;
  83858. }
  83859. var offset = (submesh.indexStart / 3) + i;
  83860. var pos = (offset * 3);
  83861. var i0 = indices[pos + 0];
  83862. var i1 = indices[pos + 1];
  83863. var i2 = indices[pos + 2];
  83864. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  83865. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  83866. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  83867. var triangle = new DecimationTriangle([v0, v1, v2]);
  83868. triangle.originalOffset = pos;
  83869. _this.triangles.push(triangle);
  83870. };
  83871. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  83872. _this.init(callback);
  83873. });
  83874. });
  83875. };
  83876. QuadraticErrorSimplification.prototype.init = function (callback) {
  83877. var _this = this;
  83878. var triangleInit1 = function (i) {
  83879. var t = _this.triangles[i];
  83880. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  83881. for (var j = 0; j < 3; j++) {
  83882. 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))));
  83883. }
  83884. };
  83885. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  83886. var triangleInit2 = function (i) {
  83887. var t = _this.triangles[i];
  83888. for (var j = 0; j < 3; ++j) {
  83889. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  83890. }
  83891. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83892. };
  83893. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  83894. callback();
  83895. });
  83896. });
  83897. };
  83898. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  83899. var newTriangles = [];
  83900. var i;
  83901. for (i = 0; i < this.vertices.length; ++i) {
  83902. this.vertices[i].triangleCount = 0;
  83903. }
  83904. var t;
  83905. var j;
  83906. for (i = 0; i < this.triangles.length; ++i) {
  83907. if (!this.triangles[i].deleted) {
  83908. t = this.triangles[i];
  83909. for (j = 0; j < 3; ++j) {
  83910. t.vertices[j].triangleCount = 1;
  83911. }
  83912. newTriangles.push(t);
  83913. }
  83914. }
  83915. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  83916. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  83917. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  83918. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  83919. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  83920. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83921. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  83922. var vertexCount = 0;
  83923. for (i = 0; i < this.vertices.length; ++i) {
  83924. var vertex = this.vertices[i];
  83925. vertex.id = vertexCount;
  83926. if (vertex.triangleCount) {
  83927. vertex.originalOffsets.forEach(function (originalOffset) {
  83928. if (!normalData) {
  83929. return;
  83930. }
  83931. newPositionData.push(vertex.position.x);
  83932. newPositionData.push(vertex.position.y);
  83933. newPositionData.push(vertex.position.z);
  83934. newNormalData.push(normalData[originalOffset * 3]);
  83935. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  83936. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  83937. if (uvs && uvs.length) {
  83938. newUVsData.push(uvs[(originalOffset * 2)]);
  83939. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  83940. }
  83941. else if (colorsData && colorsData.length) {
  83942. newColorsData.push(colorsData[(originalOffset * 4)]);
  83943. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  83944. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  83945. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  83946. }
  83947. ++vertexCount;
  83948. });
  83949. }
  83950. }
  83951. var startingIndex = this._reconstructedMesh.getTotalIndices();
  83952. var startingVertex = this._reconstructedMesh.getTotalVertices();
  83953. var submeshesArray = this._reconstructedMesh.subMeshes;
  83954. this._reconstructedMesh.subMeshes = [];
  83955. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  83956. var originalIndices = this._mesh.getIndices();
  83957. for (i = 0; i < newTriangles.length; ++i) {
  83958. t = newTriangles[i]; //now get the new referencing point for each vertex
  83959. [0, 1, 2].forEach(function (idx) {
  83960. var id = originalIndices[t.originalOffset + idx];
  83961. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  83962. if (offset < 0)
  83963. offset = 0;
  83964. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  83965. });
  83966. }
  83967. //overwriting the old vertex buffers and indices.
  83968. this._reconstructedMesh.setIndices(newIndicesArray);
  83969. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  83970. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  83971. if (newUVsData.length > 0)
  83972. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  83973. if (newColorsData.length > 0)
  83974. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  83975. //create submesh
  83976. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  83977. if (submeshIndex > 0) {
  83978. this._reconstructedMesh.subMeshes = [];
  83979. submeshesArray.forEach(function (submesh) {
  83980. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  83981. });
  83982. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  83983. }
  83984. };
  83985. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  83986. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  83987. this._reconstructedMesh.material = this._mesh.material;
  83988. this._reconstructedMesh.parent = this._mesh.parent;
  83989. this._reconstructedMesh.isVisible = false;
  83990. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  83991. };
  83992. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  83993. for (var i = 0; i < vertex1.triangleCount; ++i) {
  83994. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  83995. if (t.deleted)
  83996. continue;
  83997. var s = this.references[vertex1.triangleStart + i].vertexId;
  83998. var v1 = t.vertices[(s + 1) % 3];
  83999. var v2 = t.vertices[(s + 2) % 3];
  84000. if ((v1 === vertex2 || v2 === vertex2)) {
  84001. deletedArray[i] = true;
  84002. delTr.push(t);
  84003. continue;
  84004. }
  84005. var d1 = v1.position.subtract(point);
  84006. d1 = d1.normalize();
  84007. var d2 = v2.position.subtract(point);
  84008. d2 = d2.normalize();
  84009. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  84010. return true;
  84011. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  84012. deletedArray[i] = false;
  84013. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  84014. return true;
  84015. }
  84016. return false;
  84017. };
  84018. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  84019. var newDeleted = deletedTriangles;
  84020. for (var i = 0; i < vertex.triangleCount; ++i) {
  84021. var ref = this.references[vertex.triangleStart + i];
  84022. var t = this.triangles[ref.triangleId];
  84023. if (t.deleted)
  84024. continue;
  84025. if (deletedArray[i] && t.deletePending) {
  84026. t.deleted = true;
  84027. newDeleted++;
  84028. continue;
  84029. }
  84030. t.vertices[ref.vertexId] = origVertex;
  84031. t.isDirty = true;
  84032. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  84033. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  84034. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  84035. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84036. this.references.push(ref);
  84037. }
  84038. return newDeleted;
  84039. };
  84040. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  84041. for (var i = 0; i < this.vertices.length; ++i) {
  84042. var vCount = [];
  84043. var vId = [];
  84044. var v = this.vertices[i];
  84045. var j;
  84046. for (j = 0; j < v.triangleCount; ++j) {
  84047. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  84048. for (var ii = 0; ii < 3; ii++) {
  84049. var ofs = 0;
  84050. var vv = triangle.vertices[ii];
  84051. while (ofs < vCount.length) {
  84052. if (vId[ofs] === vv.id)
  84053. break;
  84054. ++ofs;
  84055. }
  84056. if (ofs === vCount.length) {
  84057. vCount.push(1);
  84058. vId.push(vv.id);
  84059. }
  84060. else {
  84061. vCount[ofs]++;
  84062. }
  84063. }
  84064. }
  84065. for (j = 0; j < vCount.length; ++j) {
  84066. if (vCount[j] === 1) {
  84067. this.vertices[vId[j]].isBorder = true;
  84068. }
  84069. else {
  84070. this.vertices[vId[j]].isBorder = false;
  84071. }
  84072. }
  84073. }
  84074. };
  84075. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  84076. if (identifyBorders === void 0) { identifyBorders = false; }
  84077. var i;
  84078. if (!identifyBorders) {
  84079. var newTrianglesVector = [];
  84080. for (i = 0; i < this.triangles.length; ++i) {
  84081. if (!this.triangles[i].deleted) {
  84082. newTrianglesVector.push(this.triangles[i]);
  84083. }
  84084. }
  84085. this.triangles = newTrianglesVector;
  84086. }
  84087. for (i = 0; i < this.vertices.length; ++i) {
  84088. this.vertices[i].triangleCount = 0;
  84089. this.vertices[i].triangleStart = 0;
  84090. }
  84091. var t;
  84092. var j;
  84093. var v;
  84094. for (i = 0; i < this.triangles.length; ++i) {
  84095. t = this.triangles[i];
  84096. for (j = 0; j < 3; ++j) {
  84097. v = t.vertices[j];
  84098. v.triangleCount++;
  84099. }
  84100. }
  84101. var tStart = 0;
  84102. for (i = 0; i < this.vertices.length; ++i) {
  84103. this.vertices[i].triangleStart = tStart;
  84104. tStart += this.vertices[i].triangleCount;
  84105. this.vertices[i].triangleCount = 0;
  84106. }
  84107. var newReferences = new Array(this.triangles.length * 3);
  84108. for (i = 0; i < this.triangles.length; ++i) {
  84109. t = this.triangles[i];
  84110. for (j = 0; j < 3; ++j) {
  84111. v = t.vertices[j];
  84112. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  84113. v.triangleCount++;
  84114. }
  84115. }
  84116. this.references = newReferences;
  84117. if (identifyBorders) {
  84118. this.identifyBorder();
  84119. }
  84120. };
  84121. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  84122. var x = point.x;
  84123. var y = point.y;
  84124. var z = point.z;
  84125. 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
  84126. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  84127. };
  84128. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  84129. var q = vertex1.q.add(vertex2.q);
  84130. var border = vertex1.isBorder && vertex2.isBorder;
  84131. var error = 0;
  84132. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  84133. if (qDet !== 0 && !border) {
  84134. if (!pointResult) {
  84135. pointResult = BABYLON.Vector3.Zero();
  84136. }
  84137. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  84138. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  84139. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  84140. error = this.vertexError(q, pointResult);
  84141. }
  84142. else {
  84143. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  84144. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  84145. var error1 = this.vertexError(q, vertex1.position);
  84146. var error2 = this.vertexError(q, vertex2.position);
  84147. var error3 = this.vertexError(q, p3);
  84148. error = Math.min(error1, error2, error3);
  84149. if (error === error1) {
  84150. if (pointResult) {
  84151. pointResult.copyFrom(vertex1.position);
  84152. }
  84153. }
  84154. else if (error === error2) {
  84155. if (pointResult) {
  84156. pointResult.copyFrom(vertex2.position);
  84157. }
  84158. }
  84159. else {
  84160. if (pointResult) {
  84161. pointResult.copyFrom(p3);
  84162. }
  84163. }
  84164. }
  84165. return error;
  84166. };
  84167. return QuadraticErrorSimplification;
  84168. }());
  84169. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  84170. })(BABYLON || (BABYLON = {}));
  84171. //# sourceMappingURL=babylon.meshSimplification.js.map
  84172. "use strict";
  84173. var BABYLON;
  84174. (function (BABYLON) {
  84175. var MeshLODLevel = /** @class */ (function () {
  84176. function MeshLODLevel(distance, mesh) {
  84177. this.distance = distance;
  84178. this.mesh = mesh;
  84179. }
  84180. return MeshLODLevel;
  84181. }());
  84182. BABYLON.MeshLODLevel = MeshLODLevel;
  84183. })(BABYLON || (BABYLON = {}));
  84184. //# sourceMappingURL=babylon.meshLODLevel.js.map
  84185. "use strict";
  84186. var BABYLON;
  84187. (function (BABYLON) {
  84188. /**
  84189. * Defines the root class used to create scene optimization to use with SceneOptimizer
  84190. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84191. */
  84192. var SceneOptimization = /** @class */ (function () {
  84193. /**
  84194. * Creates the SceneOptimization object
  84195. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84196. * @param desc defines the description associated with the optimization
  84197. */
  84198. function SceneOptimization(
  84199. /**
  84200. * Defines the priority of this optimization (0 by default which means first in the list)
  84201. */
  84202. priority) {
  84203. if (priority === void 0) { priority = 0; }
  84204. this.priority = priority;
  84205. }
  84206. /**
  84207. * Gets a string describing the action executed by the current optimization
  84208. * @returns description string
  84209. */
  84210. SceneOptimization.prototype.getDescription = function () {
  84211. return "";
  84212. };
  84213. /**
  84214. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84215. * @param scene defines the current scene where to apply this optimization
  84216. * @param optimizer defines the current optimizer
  84217. * @returns true if everything that can be done was applied
  84218. */
  84219. SceneOptimization.prototype.apply = function (scene, optimizer) {
  84220. return true;
  84221. };
  84222. ;
  84223. return SceneOptimization;
  84224. }());
  84225. BABYLON.SceneOptimization = SceneOptimization;
  84226. /**
  84227. * Defines an optimization used to reduce the size of render target textures
  84228. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84229. */
  84230. var TextureOptimization = /** @class */ (function (_super) {
  84231. __extends(TextureOptimization, _super);
  84232. /**
  84233. * Creates the TextureOptimization object
  84234. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84235. * @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
  84236. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84237. */
  84238. function TextureOptimization(
  84239. /**
  84240. * Defines the priority of this optimization (0 by default which means first in the list)
  84241. */
  84242. priority,
  84243. /**
  84244. * 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
  84245. */
  84246. maximumSize,
  84247. /**
  84248. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84249. */
  84250. step) {
  84251. if (priority === void 0) { priority = 0; }
  84252. if (maximumSize === void 0) { maximumSize = 1024; }
  84253. if (step === void 0) { step = 0.5; }
  84254. var _this = _super.call(this, priority) || this;
  84255. _this.priority = priority;
  84256. _this.maximumSize = maximumSize;
  84257. _this.step = step;
  84258. return _this;
  84259. }
  84260. /**
  84261. * Gets a string describing the action executed by the current optimization
  84262. * @returns description string
  84263. */
  84264. TextureOptimization.prototype.getDescription = function () {
  84265. return "Reducing render target texture size to " + this.maximumSize;
  84266. };
  84267. /**
  84268. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84269. * @param scene defines the current scene where to apply this optimization
  84270. * @param optimizer defines the current optimizer
  84271. * @returns true if everything that can be done was applied
  84272. */
  84273. TextureOptimization.prototype.apply = function (scene, optimizer) {
  84274. var allDone = true;
  84275. for (var index = 0; index < scene.textures.length; index++) {
  84276. var texture = scene.textures[index];
  84277. if (!texture.canRescale || texture.getContext) {
  84278. continue;
  84279. }
  84280. var currentSize = texture.getSize();
  84281. var maxDimension = Math.max(currentSize.width, currentSize.height);
  84282. if (maxDimension > this.maximumSize) {
  84283. texture.scale(this.step);
  84284. allDone = false;
  84285. }
  84286. }
  84287. return allDone;
  84288. };
  84289. return TextureOptimization;
  84290. }(SceneOptimization));
  84291. BABYLON.TextureOptimization = TextureOptimization;
  84292. /**
  84293. * Defines an optimization used to increase or decrease the rendering resolution
  84294. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84295. */
  84296. var HardwareScalingOptimization = /** @class */ (function (_super) {
  84297. __extends(HardwareScalingOptimization, _super);
  84298. /**
  84299. * Creates the HardwareScalingOptimization object
  84300. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84301. * @param maximumScale defines the maximum scale to use (2 by default)
  84302. * @param step defines the step to use between two passes (0.5 by default)
  84303. */
  84304. function HardwareScalingOptimization(
  84305. /**
  84306. * Defines the priority of this optimization (0 by default which means first in the list)
  84307. */
  84308. priority,
  84309. /**
  84310. * Defines the maximum scale to use (2 by default)
  84311. */
  84312. maximumScale,
  84313. /**
  84314. * Defines the step to use between two passes (0.5 by default)
  84315. */
  84316. step) {
  84317. if (priority === void 0) { priority = 0; }
  84318. if (maximumScale === void 0) { maximumScale = 2; }
  84319. if (step === void 0) { step = 0.25; }
  84320. var _this = _super.call(this, priority) || this;
  84321. _this.priority = priority;
  84322. _this.maximumScale = maximumScale;
  84323. _this.step = step;
  84324. _this._currentScale = -1;
  84325. _this._directionOffset = 1;
  84326. return _this;
  84327. }
  84328. /**
  84329. * Gets a string describing the action executed by the current optimization
  84330. * @return description string
  84331. */
  84332. HardwareScalingOptimization.prototype.getDescription = function () {
  84333. return "Setting hardware scaling level to " + this._currentScale;
  84334. };
  84335. /**
  84336. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84337. * @param scene defines the current scene where to apply this optimization
  84338. * @param optimizer defines the current optimizer
  84339. * @returns true if everything that can be done was applied
  84340. */
  84341. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  84342. if (this._currentScale === -1) {
  84343. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  84344. if (this._currentScale > this.maximumScale) {
  84345. this._directionOffset = -1;
  84346. }
  84347. }
  84348. this._currentScale += this._directionOffset * this.step;
  84349. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  84350. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  84351. };
  84352. ;
  84353. return HardwareScalingOptimization;
  84354. }(SceneOptimization));
  84355. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  84356. /**
  84357. * Defines an optimization used to remove shadows
  84358. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84359. */
  84360. var ShadowsOptimization = /** @class */ (function (_super) {
  84361. __extends(ShadowsOptimization, _super);
  84362. function ShadowsOptimization() {
  84363. return _super !== null && _super.apply(this, arguments) || this;
  84364. }
  84365. /**
  84366. * Gets a string describing the action executed by the current optimization
  84367. * @return description string
  84368. */
  84369. ShadowsOptimization.prototype.getDescription = function () {
  84370. return "Turning shadows on/off";
  84371. };
  84372. /**
  84373. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84374. * @param scene defines the current scene where to apply this optimization
  84375. * @param optimizer defines the current optimizer
  84376. * @returns true if everything that can be done was applied
  84377. */
  84378. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  84379. scene.shadowsEnabled = optimizer.isInImprovementMode;
  84380. return true;
  84381. };
  84382. ;
  84383. return ShadowsOptimization;
  84384. }(SceneOptimization));
  84385. BABYLON.ShadowsOptimization = ShadowsOptimization;
  84386. /**
  84387. * Defines an optimization used to turn post-processes off
  84388. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84389. */
  84390. var PostProcessesOptimization = /** @class */ (function (_super) {
  84391. __extends(PostProcessesOptimization, _super);
  84392. function PostProcessesOptimization() {
  84393. return _super !== null && _super.apply(this, arguments) || this;
  84394. }
  84395. /**
  84396. * Gets a string describing the action executed by the current optimization
  84397. * @return description string
  84398. */
  84399. PostProcessesOptimization.prototype.getDescription = function () {
  84400. return "Turning post-processes on/off";
  84401. };
  84402. /**
  84403. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84404. * @param scene defines the current scene where to apply this optimization
  84405. * @param optimizer defines the current optimizer
  84406. * @returns true if everything that can be done was applied
  84407. */
  84408. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  84409. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  84410. return true;
  84411. };
  84412. ;
  84413. return PostProcessesOptimization;
  84414. }(SceneOptimization));
  84415. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  84416. /**
  84417. * Defines an optimization used to turn lens flares off
  84418. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84419. */
  84420. var LensFlaresOptimization = /** @class */ (function (_super) {
  84421. __extends(LensFlaresOptimization, _super);
  84422. function LensFlaresOptimization() {
  84423. return _super !== null && _super.apply(this, arguments) || this;
  84424. }
  84425. /**
  84426. * Gets a string describing the action executed by the current optimization
  84427. * @return description string
  84428. */
  84429. LensFlaresOptimization.prototype.getDescription = function () {
  84430. return "Turning lens flares on/off";
  84431. };
  84432. /**
  84433. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84434. * @param scene defines the current scene where to apply this optimization
  84435. * @param optimizer defines the current optimizer
  84436. * @returns true if everything that can be done was applied
  84437. */
  84438. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  84439. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  84440. return true;
  84441. };
  84442. ;
  84443. return LensFlaresOptimization;
  84444. }(SceneOptimization));
  84445. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  84446. /**
  84447. * Defines an optimization based on user defined callback.
  84448. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84449. */
  84450. var CustomOptimization = /** @class */ (function (_super) {
  84451. __extends(CustomOptimization, _super);
  84452. function CustomOptimization() {
  84453. return _super !== null && _super.apply(this, arguments) || this;
  84454. }
  84455. /**
  84456. * Gets a string describing the action executed by the current optimization
  84457. * @returns description string
  84458. */
  84459. CustomOptimization.prototype.getDescription = function () {
  84460. if (this.onGetDescription) {
  84461. return this.onGetDescription();
  84462. }
  84463. return "Running user defined callback";
  84464. };
  84465. /**
  84466. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84467. * @param scene defines the current scene where to apply this optimization
  84468. * @param optimizer defines the current optimizer
  84469. * @returns true if everything that can be done was applied
  84470. */
  84471. CustomOptimization.prototype.apply = function (scene, optimizer) {
  84472. if (this.onApply) {
  84473. return this.onApply(scene, optimizer);
  84474. }
  84475. return true;
  84476. };
  84477. ;
  84478. return CustomOptimization;
  84479. }(SceneOptimization));
  84480. BABYLON.CustomOptimization = CustomOptimization;
  84481. /**
  84482. * Defines an optimization used to turn particles off
  84483. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84484. */
  84485. var ParticlesOptimization = /** @class */ (function (_super) {
  84486. __extends(ParticlesOptimization, _super);
  84487. function ParticlesOptimization() {
  84488. return _super !== null && _super.apply(this, arguments) || this;
  84489. }
  84490. /**
  84491. * Gets a string describing the action executed by the current optimization
  84492. * @return description string
  84493. */
  84494. ParticlesOptimization.prototype.getDescription = function () {
  84495. return "Turning particles on/off";
  84496. };
  84497. /**
  84498. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84499. * @param scene defines the current scene where to apply this optimization
  84500. * @param optimizer defines the current optimizer
  84501. * @returns true if everything that can be done was applied
  84502. */
  84503. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  84504. scene.particlesEnabled = optimizer.isInImprovementMode;
  84505. return true;
  84506. };
  84507. ;
  84508. return ParticlesOptimization;
  84509. }(SceneOptimization));
  84510. BABYLON.ParticlesOptimization = ParticlesOptimization;
  84511. /**
  84512. * Defines an optimization used to turn render targets off
  84513. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84514. */
  84515. var RenderTargetsOptimization = /** @class */ (function (_super) {
  84516. __extends(RenderTargetsOptimization, _super);
  84517. function RenderTargetsOptimization() {
  84518. return _super !== null && _super.apply(this, arguments) || this;
  84519. }
  84520. /**
  84521. * Gets a string describing the action executed by the current optimization
  84522. * @return description string
  84523. */
  84524. RenderTargetsOptimization.prototype.getDescription = function () {
  84525. return "Turning render targets off";
  84526. };
  84527. /**
  84528. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84529. * @param scene defines the current scene where to apply this optimization
  84530. * @param optimizer defines the current optimizer
  84531. * @returns true if everything that can be done was applied
  84532. */
  84533. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  84534. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  84535. return true;
  84536. };
  84537. ;
  84538. return RenderTargetsOptimization;
  84539. }(SceneOptimization));
  84540. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  84541. /**
  84542. * Defines an optimization used to merge meshes with compatible materials
  84543. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84544. */
  84545. var MergeMeshesOptimization = /** @class */ (function (_super) {
  84546. __extends(MergeMeshesOptimization, _super);
  84547. function MergeMeshesOptimization() {
  84548. var _this = _super !== null && _super.apply(this, arguments) || this;
  84549. _this._canBeMerged = function (abstractMesh) {
  84550. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  84551. return false;
  84552. }
  84553. var mesh = abstractMesh;
  84554. if (!mesh.isVisible || !mesh.isEnabled()) {
  84555. return false;
  84556. }
  84557. if (mesh.instances.length > 0) {
  84558. return false;
  84559. }
  84560. if (mesh.skeleton || mesh.hasLODLevels) {
  84561. return false;
  84562. }
  84563. if (mesh.parent) {
  84564. return false;
  84565. }
  84566. return true;
  84567. };
  84568. return _this;
  84569. }
  84570. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  84571. /**
  84572. * Gets or sets a boolean which defines if optimization octree has to be updated
  84573. */
  84574. get: function () {
  84575. return MergeMeshesOptimization._UpdateSelectionTree;
  84576. },
  84577. /**
  84578. * Gets or sets a boolean which defines if optimization octree has to be updated
  84579. */
  84580. set: function (value) {
  84581. MergeMeshesOptimization._UpdateSelectionTree = value;
  84582. },
  84583. enumerable: true,
  84584. configurable: true
  84585. });
  84586. /**
  84587. * Gets a string describing the action executed by the current optimization
  84588. * @return description string
  84589. */
  84590. MergeMeshesOptimization.prototype.getDescription = function () {
  84591. return "Merging similar meshes together";
  84592. };
  84593. /**
  84594. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84595. * @param scene defines the current scene where to apply this optimization
  84596. * @param optimizer defines the current optimizer
  84597. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  84598. * @returns true if everything that can be done was applied
  84599. */
  84600. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  84601. var globalPool = scene.meshes.slice(0);
  84602. var globalLength = globalPool.length;
  84603. for (var index = 0; index < globalLength; index++) {
  84604. var currentPool = new Array();
  84605. var current = globalPool[index];
  84606. // Checks
  84607. if (!this._canBeMerged(current)) {
  84608. continue;
  84609. }
  84610. currentPool.push(current);
  84611. // Find compatible meshes
  84612. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  84613. var otherMesh = globalPool[subIndex];
  84614. if (!this._canBeMerged(otherMesh)) {
  84615. continue;
  84616. }
  84617. if (otherMesh.material !== current.material) {
  84618. continue;
  84619. }
  84620. if (otherMesh.checkCollisions !== current.checkCollisions) {
  84621. continue;
  84622. }
  84623. currentPool.push(otherMesh);
  84624. globalLength--;
  84625. globalPool.splice(subIndex, 1);
  84626. subIndex--;
  84627. }
  84628. if (currentPool.length < 2) {
  84629. continue;
  84630. }
  84631. // Merge meshes
  84632. BABYLON.Mesh.MergeMeshes(currentPool);
  84633. }
  84634. if (updateSelectionTree != undefined) {
  84635. if (updateSelectionTree) {
  84636. scene.createOrUpdateSelectionOctree();
  84637. }
  84638. }
  84639. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  84640. scene.createOrUpdateSelectionOctree();
  84641. }
  84642. return true;
  84643. };
  84644. ;
  84645. MergeMeshesOptimization._UpdateSelectionTree = false;
  84646. return MergeMeshesOptimization;
  84647. }(SceneOptimization));
  84648. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  84649. /**
  84650. * Defines a list of options used by SceneOptimizer
  84651. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84652. */
  84653. var SceneOptimizerOptions = /** @class */ (function () {
  84654. /**
  84655. * Creates a new list of options used by SceneOptimizer
  84656. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  84657. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  84658. */
  84659. function SceneOptimizerOptions(
  84660. /**
  84661. * Defines the target frame rate to reach (60 by default)
  84662. */
  84663. targetFrameRate,
  84664. /**
  84665. * Defines the interval between two checkes (2000ms by default)
  84666. */
  84667. trackerDuration) {
  84668. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  84669. if (trackerDuration === void 0) { trackerDuration = 2000; }
  84670. this.targetFrameRate = targetFrameRate;
  84671. this.trackerDuration = trackerDuration;
  84672. /**
  84673. * Gets the list of optimizations to apply
  84674. */
  84675. this.optimizations = new Array();
  84676. }
  84677. /**
  84678. * Add a new optimization
  84679. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  84680. * @returns the current SceneOptimizerOptions
  84681. */
  84682. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  84683. this.optimizations.push(optimization);
  84684. return this;
  84685. };
  84686. /**
  84687. * Add a new custom optimization
  84688. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  84689. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  84690. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84691. * @returns the current SceneOptimizerOptions
  84692. */
  84693. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  84694. if (priority === void 0) { priority = 0; }
  84695. var optimization = new CustomOptimization(priority);
  84696. optimization.onApply = onApply;
  84697. optimization.onGetDescription = onGetDescription;
  84698. this.optimizations.push(optimization);
  84699. return this;
  84700. };
  84701. /**
  84702. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  84703. * @param targetFrameRate defines the target frame rate (60 by default)
  84704. * @returns a SceneOptimizerOptions object
  84705. */
  84706. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  84707. var result = new SceneOptimizerOptions(targetFrameRate);
  84708. var priority = 0;
  84709. result.addOptimization(new MergeMeshesOptimization(priority));
  84710. result.addOptimization(new ShadowsOptimization(priority));
  84711. result.addOptimization(new LensFlaresOptimization(priority));
  84712. // Next priority
  84713. priority++;
  84714. result.addOptimization(new PostProcessesOptimization(priority));
  84715. result.addOptimization(new ParticlesOptimization(priority));
  84716. // Next priority
  84717. priority++;
  84718. result.addOptimization(new TextureOptimization(priority, 1024));
  84719. return result;
  84720. };
  84721. /**
  84722. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  84723. * @param targetFrameRate defines the target frame rate (60 by default)
  84724. * @returns a SceneOptimizerOptions object
  84725. */
  84726. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  84727. var result = new SceneOptimizerOptions(targetFrameRate);
  84728. var priority = 0;
  84729. result.addOptimization(new MergeMeshesOptimization(priority));
  84730. result.addOptimization(new ShadowsOptimization(priority));
  84731. result.addOptimization(new LensFlaresOptimization(priority));
  84732. // Next priority
  84733. priority++;
  84734. result.addOptimization(new PostProcessesOptimization(priority));
  84735. result.addOptimization(new ParticlesOptimization(priority));
  84736. // Next priority
  84737. priority++;
  84738. result.addOptimization(new TextureOptimization(priority, 512));
  84739. // Next priority
  84740. priority++;
  84741. result.addOptimization(new RenderTargetsOptimization(priority));
  84742. // Next priority
  84743. priority++;
  84744. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  84745. return result;
  84746. };
  84747. /**
  84748. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  84749. * @param targetFrameRate defines the target frame rate (60 by default)
  84750. * @returns a SceneOptimizerOptions object
  84751. */
  84752. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  84753. var result = new SceneOptimizerOptions(targetFrameRate);
  84754. var priority = 0;
  84755. result.addOptimization(new MergeMeshesOptimization(priority));
  84756. result.addOptimization(new ShadowsOptimization(priority));
  84757. result.addOptimization(new LensFlaresOptimization(priority));
  84758. // Next priority
  84759. priority++;
  84760. result.addOptimization(new PostProcessesOptimization(priority));
  84761. result.addOptimization(new ParticlesOptimization(priority));
  84762. // Next priority
  84763. priority++;
  84764. result.addOptimization(new TextureOptimization(priority, 256));
  84765. // Next priority
  84766. priority++;
  84767. result.addOptimization(new RenderTargetsOptimization(priority));
  84768. // Next priority
  84769. priority++;
  84770. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  84771. return result;
  84772. };
  84773. return SceneOptimizerOptions;
  84774. }());
  84775. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  84776. /**
  84777. * Class used to run optimizations in order to reach a target frame rate
  84778. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84779. */
  84780. var SceneOptimizer = /** @class */ (function () {
  84781. /**
  84782. * Creates a new SceneOptimizer
  84783. * @param scene defines the scene to work on
  84784. * @param options defines the options to use with the SceneOptimizer
  84785. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  84786. * @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)
  84787. */
  84788. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  84789. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  84790. if (improvementMode === void 0) { improvementMode = false; }
  84791. var _this = this;
  84792. this._isRunning = false;
  84793. this._currentPriorityLevel = 0;
  84794. this._targetFrameRate = 60;
  84795. this._trackerDuration = 2000;
  84796. this._currentFrameRate = 0;
  84797. this._improvementMode = false;
  84798. /**
  84799. * Defines an observable called when the optimizer reaches the target frame rate
  84800. */
  84801. this.onSuccessObservable = new BABYLON.Observable();
  84802. /**
  84803. * Defines an observable called when the optimizer enables an optimization
  84804. */
  84805. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  84806. /**
  84807. * Defines an observable called when the optimizer is not able to reach the target frame rate
  84808. */
  84809. this.onFailureObservable = new BABYLON.Observable();
  84810. if (!options) {
  84811. this._options = new SceneOptimizerOptions();
  84812. }
  84813. else {
  84814. this._options = options;
  84815. }
  84816. if (this._options.targetFrameRate) {
  84817. this._targetFrameRate = this._options.targetFrameRate;
  84818. }
  84819. if (this._options.trackerDuration) {
  84820. this._trackerDuration = this._options.trackerDuration;
  84821. }
  84822. if (autoGeneratePriorities) {
  84823. var priority = 0;
  84824. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  84825. var optim = _a[_i];
  84826. optim.priority = priority++;
  84827. }
  84828. }
  84829. this._improvementMode = improvementMode;
  84830. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84831. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  84832. _this._sceneDisposeObserver = null;
  84833. _this.dispose();
  84834. });
  84835. }
  84836. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  84837. /**
  84838. * Gets a boolean indicating if the optimizer is in improvement mode
  84839. */
  84840. get: function () {
  84841. return this._improvementMode;
  84842. },
  84843. enumerable: true,
  84844. configurable: true
  84845. });
  84846. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  84847. /**
  84848. * Gets the current priority level (0 at start)
  84849. */
  84850. get: function () {
  84851. return this._currentPriorityLevel;
  84852. },
  84853. enumerable: true,
  84854. configurable: true
  84855. });
  84856. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  84857. /**
  84858. * Gets the current frame rate checked by the SceneOptimizer
  84859. */
  84860. get: function () {
  84861. return this._currentFrameRate;
  84862. },
  84863. enumerable: true,
  84864. configurable: true
  84865. });
  84866. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  84867. /**
  84868. * Gets or sets the current target frame rate (60 by default)
  84869. */
  84870. get: function () {
  84871. return this._targetFrameRate;
  84872. },
  84873. /**
  84874. * Gets or sets the current target frame rate (60 by default)
  84875. */
  84876. set: function (value) {
  84877. this._targetFrameRate = value;
  84878. },
  84879. enumerable: true,
  84880. configurable: true
  84881. });
  84882. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  84883. /**
  84884. * Gets or sets the current interval between two checks (every 2000ms by default)
  84885. */
  84886. get: function () {
  84887. return this._trackerDuration;
  84888. },
  84889. /**
  84890. * Gets or sets the current interval between two checks (every 2000ms by default)
  84891. */
  84892. set: function (value) {
  84893. this._trackerDuration = value;
  84894. },
  84895. enumerable: true,
  84896. configurable: true
  84897. });
  84898. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  84899. /**
  84900. * Gets the list of active optimizations
  84901. */
  84902. get: function () {
  84903. return this._options.optimizations;
  84904. },
  84905. enumerable: true,
  84906. configurable: true
  84907. });
  84908. /**
  84909. * Stops the current optimizer
  84910. */
  84911. SceneOptimizer.prototype.stop = function () {
  84912. this._isRunning = false;
  84913. };
  84914. /**
  84915. * Reset the optimizer to initial step (current priority level = 0)
  84916. */
  84917. SceneOptimizer.prototype.reset = function () {
  84918. this._currentPriorityLevel = 0;
  84919. };
  84920. /**
  84921. * Start the optimizer. By default it will try to reach a specific framerate
  84922. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  84923. */
  84924. SceneOptimizer.prototype.start = function () {
  84925. var _this = this;
  84926. if (this._isRunning) {
  84927. return;
  84928. }
  84929. this._isRunning = true;
  84930. // Let's wait for the scene to be ready before running our check
  84931. this._scene.executeWhenReady(function () {
  84932. setTimeout(function () {
  84933. _this._checkCurrentState();
  84934. }, _this._trackerDuration);
  84935. });
  84936. };
  84937. SceneOptimizer.prototype._checkCurrentState = function () {
  84938. var _this = this;
  84939. if (!this._isRunning) {
  84940. return;
  84941. }
  84942. var scene = this._scene;
  84943. var options = this._options;
  84944. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  84945. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  84946. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  84947. this._isRunning = false;
  84948. this.onSuccessObservable.notifyObservers(this);
  84949. return;
  84950. }
  84951. // Apply current level of optimizations
  84952. var allDone = true;
  84953. var noOptimizationApplied = true;
  84954. for (var index = 0; index < options.optimizations.length; index++) {
  84955. var optimization = options.optimizations[index];
  84956. if (optimization.priority === this._currentPriorityLevel) {
  84957. noOptimizationApplied = false;
  84958. allDone = allDone && optimization.apply(scene, this);
  84959. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  84960. }
  84961. }
  84962. // If no optimization was applied, this is a failure :(
  84963. if (noOptimizationApplied) {
  84964. this._isRunning = false;
  84965. this.onFailureObservable.notifyObservers(this);
  84966. return;
  84967. }
  84968. // If all optimizations were done, move to next level
  84969. if (allDone) {
  84970. this._currentPriorityLevel++;
  84971. }
  84972. // Let's the system running for a specific amount of time before checking FPS
  84973. scene.executeWhenReady(function () {
  84974. setTimeout(function () {
  84975. _this._checkCurrentState();
  84976. }, _this._trackerDuration);
  84977. });
  84978. };
  84979. /**
  84980. * Release all resources
  84981. */
  84982. SceneOptimizer.prototype.dispose = function () {
  84983. this.stop();
  84984. this.onSuccessObservable.clear();
  84985. this.onFailureObservable.clear();
  84986. this.onNewOptimizationAppliedObservable.clear();
  84987. if (this._sceneDisposeObserver) {
  84988. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  84989. }
  84990. };
  84991. /**
  84992. * Helper function to create a SceneOptimizer with one single line of code
  84993. * @param scene defines the scene to work on
  84994. * @param options defines the options to use with the SceneOptimizer
  84995. * @param onSuccess defines a callback to call on success
  84996. * @param onFailure defines a callback to call on failure
  84997. * @returns the new SceneOptimizer object
  84998. */
  84999. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  85000. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  85001. if (onSuccess) {
  85002. optimizer.onSuccessObservable.add(function () {
  85003. onSuccess();
  85004. });
  85005. }
  85006. if (onFailure) {
  85007. optimizer.onFailureObservable.add(function () {
  85008. onFailure();
  85009. });
  85010. }
  85011. optimizer.start();
  85012. return optimizer;
  85013. };
  85014. return SceneOptimizer;
  85015. }());
  85016. BABYLON.SceneOptimizer = SceneOptimizer;
  85017. })(BABYLON || (BABYLON = {}));
  85018. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  85019. "use strict";
  85020. var BABYLON;
  85021. (function (BABYLON) {
  85022. var OutlineRenderer = /** @class */ (function () {
  85023. function OutlineRenderer(scene) {
  85024. this.zOffset = 1;
  85025. this._scene = scene;
  85026. }
  85027. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  85028. var _this = this;
  85029. if (useOverlay === void 0) { useOverlay = false; }
  85030. var scene = this._scene;
  85031. var engine = this._scene.getEngine();
  85032. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85033. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  85034. return;
  85035. }
  85036. var mesh = subMesh.getRenderingMesh();
  85037. var material = subMesh.getMaterial();
  85038. if (!material || !scene.activeCamera) {
  85039. return;
  85040. }
  85041. engine.enableEffect(this._effect);
  85042. // Logarithmic depth
  85043. if (material.useLogarithmicDepth) {
  85044. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  85045. }
  85046. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  85047. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  85048. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85049. // Bones
  85050. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85051. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85052. }
  85053. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  85054. // Alpha test
  85055. if (material && material.needAlphaTesting()) {
  85056. var alphaTexture = material.getAlphaTestTexture();
  85057. if (alphaTexture) {
  85058. this._effect.setTexture("diffuseSampler", alphaTexture);
  85059. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85060. }
  85061. }
  85062. engine.setZOffset(-this.zOffset);
  85063. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  85064. engine.setZOffset(0);
  85065. };
  85066. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  85067. var defines = [];
  85068. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85069. var mesh = subMesh.getMesh();
  85070. var material = subMesh.getMaterial();
  85071. if (material) {
  85072. // Alpha test
  85073. if (material.needAlphaTesting()) {
  85074. defines.push("#define ALPHATEST");
  85075. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85076. attribs.push(BABYLON.VertexBuffer.UVKind);
  85077. defines.push("#define UV1");
  85078. }
  85079. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85080. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85081. defines.push("#define UV2");
  85082. }
  85083. }
  85084. //Logarithmic depth
  85085. if (material.useLogarithmicDepth) {
  85086. defines.push("#define LOGARITHMICDEPTH");
  85087. }
  85088. }
  85089. // Bones
  85090. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85091. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85092. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85093. if (mesh.numBoneInfluencers > 4) {
  85094. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85095. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85096. }
  85097. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85098. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  85099. }
  85100. else {
  85101. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85102. }
  85103. // Instances
  85104. if (useInstances) {
  85105. defines.push("#define INSTANCES");
  85106. attribs.push("world0");
  85107. attribs.push("world1");
  85108. attribs.push("world2");
  85109. attribs.push("world3");
  85110. }
  85111. // Get correct effect
  85112. var join = defines.join("\n");
  85113. if (this._cachedDefines !== join) {
  85114. this._cachedDefines = join;
  85115. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  85116. }
  85117. return this._effect.isReady();
  85118. };
  85119. return OutlineRenderer;
  85120. }());
  85121. BABYLON.OutlineRenderer = OutlineRenderer;
  85122. })(BABYLON || (BABYLON = {}));
  85123. //# sourceMappingURL=babylon.outlineRenderer.js.map
  85124. "use strict";
  85125. var BABYLON;
  85126. (function (BABYLON) {
  85127. var FaceAdjacencies = /** @class */ (function () {
  85128. function FaceAdjacencies() {
  85129. this.edges = new Array();
  85130. this.edgesConnectedCount = 0;
  85131. }
  85132. return FaceAdjacencies;
  85133. }());
  85134. var EdgesRenderer = /** @class */ (function () {
  85135. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  85136. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  85137. if (epsilon === void 0) { epsilon = 0.95; }
  85138. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  85139. this.edgesWidthScalerForOrthographic = 1000.0;
  85140. this.edgesWidthScalerForPerspective = 50.0;
  85141. this._linesPositions = new Array();
  85142. this._linesNormals = new Array();
  85143. this._linesIndices = new Array();
  85144. this._buffers = {};
  85145. this._checkVerticesInsteadOfIndices = false;
  85146. this._source = source;
  85147. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  85148. this._epsilon = epsilon;
  85149. this._prepareRessources();
  85150. this._generateEdgesLines();
  85151. }
  85152. EdgesRenderer.prototype._prepareRessources = function () {
  85153. if (this._lineShader) {
  85154. return;
  85155. }
  85156. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  85157. attributes: ["position", "normal"],
  85158. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  85159. });
  85160. this._lineShader.disableDepthWrite = true;
  85161. this._lineShader.backFaceCulling = false;
  85162. };
  85163. EdgesRenderer.prototype._rebuild = function () {
  85164. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85165. if (buffer) {
  85166. buffer._rebuild();
  85167. }
  85168. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85169. if (buffer) {
  85170. buffer._rebuild();
  85171. }
  85172. var scene = this._source.getScene();
  85173. var engine = scene.getEngine();
  85174. this._ib = engine.createIndexBuffer(this._linesIndices);
  85175. };
  85176. EdgesRenderer.prototype.dispose = function () {
  85177. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85178. if (buffer) {
  85179. buffer.dispose();
  85180. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  85181. }
  85182. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85183. if (buffer) {
  85184. buffer.dispose();
  85185. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  85186. }
  85187. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  85188. this._lineShader.dispose();
  85189. };
  85190. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  85191. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  85192. return 0;
  85193. }
  85194. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  85195. return 1;
  85196. }
  85197. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  85198. return 2;
  85199. }
  85200. return -1;
  85201. };
  85202. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  85203. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  85204. return 0;
  85205. }
  85206. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  85207. return 1;
  85208. }
  85209. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  85210. return 2;
  85211. }
  85212. return -1;
  85213. };
  85214. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  85215. var needToCreateLine;
  85216. if (edge === undefined) {
  85217. needToCreateLine = true;
  85218. }
  85219. else {
  85220. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  85221. needToCreateLine = dotProduct < this._epsilon;
  85222. }
  85223. if (needToCreateLine) {
  85224. var offset = this._linesPositions.length / 3;
  85225. var normal = p0.subtract(p1);
  85226. normal.normalize();
  85227. // Positions
  85228. this._linesPositions.push(p0.x);
  85229. this._linesPositions.push(p0.y);
  85230. this._linesPositions.push(p0.z);
  85231. this._linesPositions.push(p0.x);
  85232. this._linesPositions.push(p0.y);
  85233. this._linesPositions.push(p0.z);
  85234. this._linesPositions.push(p1.x);
  85235. this._linesPositions.push(p1.y);
  85236. this._linesPositions.push(p1.z);
  85237. this._linesPositions.push(p1.x);
  85238. this._linesPositions.push(p1.y);
  85239. this._linesPositions.push(p1.z);
  85240. // Normals
  85241. this._linesNormals.push(p1.x);
  85242. this._linesNormals.push(p1.y);
  85243. this._linesNormals.push(p1.z);
  85244. this._linesNormals.push(-1);
  85245. this._linesNormals.push(p1.x);
  85246. this._linesNormals.push(p1.y);
  85247. this._linesNormals.push(p1.z);
  85248. this._linesNormals.push(1);
  85249. this._linesNormals.push(p0.x);
  85250. this._linesNormals.push(p0.y);
  85251. this._linesNormals.push(p0.z);
  85252. this._linesNormals.push(-1);
  85253. this._linesNormals.push(p0.x);
  85254. this._linesNormals.push(p0.y);
  85255. this._linesNormals.push(p0.z);
  85256. this._linesNormals.push(1);
  85257. // Indices
  85258. this._linesIndices.push(offset);
  85259. this._linesIndices.push(offset + 1);
  85260. this._linesIndices.push(offset + 2);
  85261. this._linesIndices.push(offset);
  85262. this._linesIndices.push(offset + 2);
  85263. this._linesIndices.push(offset + 3);
  85264. }
  85265. };
  85266. EdgesRenderer.prototype._generateEdgesLines = function () {
  85267. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  85268. var indices = this._source.getIndices();
  85269. if (!indices || !positions) {
  85270. return;
  85271. }
  85272. // First let's find adjacencies
  85273. var adjacencies = new Array();
  85274. var faceNormals = new Array();
  85275. var index;
  85276. var faceAdjacencies;
  85277. // Prepare faces
  85278. for (index = 0; index < indices.length; index += 3) {
  85279. faceAdjacencies = new FaceAdjacencies();
  85280. var p0Index = indices[index];
  85281. var p1Index = indices[index + 1];
  85282. var p2Index = indices[index + 2];
  85283. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  85284. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  85285. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  85286. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  85287. faceNormal.normalize();
  85288. faceNormals.push(faceNormal);
  85289. adjacencies.push(faceAdjacencies);
  85290. }
  85291. // Scan
  85292. for (index = 0; index < adjacencies.length; index++) {
  85293. faceAdjacencies = adjacencies[index];
  85294. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  85295. var otherFaceAdjacencies = adjacencies[otherIndex];
  85296. if (faceAdjacencies.edgesConnectedCount === 3) {
  85297. break;
  85298. }
  85299. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  85300. continue;
  85301. }
  85302. var otherP0 = indices[otherIndex * 3];
  85303. var otherP1 = indices[otherIndex * 3 + 1];
  85304. var otherP2 = indices[otherIndex * 3 + 2];
  85305. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  85306. var otherEdgeIndex = 0;
  85307. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  85308. continue;
  85309. }
  85310. switch (edgeIndex) {
  85311. case 0:
  85312. if (this._checkVerticesInsteadOfIndices) {
  85313. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85314. }
  85315. else {
  85316. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  85317. }
  85318. break;
  85319. case 1:
  85320. if (this._checkVerticesInsteadOfIndices) {
  85321. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85322. }
  85323. else {
  85324. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  85325. }
  85326. break;
  85327. case 2:
  85328. if (this._checkVerticesInsteadOfIndices) {
  85329. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85330. }
  85331. else {
  85332. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  85333. }
  85334. break;
  85335. }
  85336. if (otherEdgeIndex === -1) {
  85337. continue;
  85338. }
  85339. faceAdjacencies.edges[edgeIndex] = otherIndex;
  85340. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  85341. faceAdjacencies.edgesConnectedCount++;
  85342. otherFaceAdjacencies.edgesConnectedCount++;
  85343. if (faceAdjacencies.edgesConnectedCount === 3) {
  85344. break;
  85345. }
  85346. }
  85347. }
  85348. }
  85349. // Create lines
  85350. for (index = 0; index < adjacencies.length; index++) {
  85351. // 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
  85352. var current = adjacencies[index];
  85353. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  85354. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  85355. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  85356. }
  85357. // Merge into a single mesh
  85358. var engine = this._source.getScene().getEngine();
  85359. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  85360. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  85361. this._ib = engine.createIndexBuffer(this._linesIndices);
  85362. this._indicesCount = this._linesIndices.length;
  85363. };
  85364. EdgesRenderer.prototype.render = function () {
  85365. var scene = this._source.getScene();
  85366. if (!this._lineShader.isReady() || !scene.activeCamera) {
  85367. return;
  85368. }
  85369. var engine = scene.getEngine();
  85370. this._lineShader._preBind();
  85371. // VBOs
  85372. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  85373. scene.resetCachedMaterial();
  85374. this._lineShader.setColor4("color", this._source.edgesColor);
  85375. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  85376. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  85377. }
  85378. else {
  85379. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  85380. }
  85381. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  85382. this._lineShader.bind(this._source.getWorldMatrix());
  85383. // Draw order
  85384. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  85385. this._lineShader.unbind();
  85386. engine.setDepthWrite(true);
  85387. };
  85388. return EdgesRenderer;
  85389. }());
  85390. BABYLON.EdgesRenderer = EdgesRenderer;
  85391. })(BABYLON || (BABYLON = {}));
  85392. //# sourceMappingURL=babylon.edgesRenderer.js.map
  85393. "use strict";
  85394. var __assign = (this && this.__assign) || Object.assign || function(t) {
  85395. for (var s, i = 1, n = arguments.length; i < n; i++) {
  85396. s = arguments[i];
  85397. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  85398. t[p] = s[p];
  85399. }
  85400. return t;
  85401. };
  85402. var BABYLON;
  85403. (function (BABYLON) {
  85404. /**
  85405. * The effect layer Helps adding post process effect blended with the main pass.
  85406. *
  85407. * This can be for instance use to generate glow or higlight effects on the scene.
  85408. *
  85409. * The effect layer class can not be used directly and is intented to inherited from to be
  85410. * customized per effects.
  85411. */
  85412. var EffectLayer = /** @class */ (function () {
  85413. /**
  85414. * Instantiates a new effect Layer and references it in the scene.
  85415. * @param name The name of the layer
  85416. * @param scene The scene to use the layer in
  85417. */
  85418. function EffectLayer(
  85419. /** The Friendly of the effect in the scene */
  85420. name, scene) {
  85421. this.name = name;
  85422. this._vertexBuffers = {};
  85423. this._maxSize = 0;
  85424. this._mainTextureDesiredSize = { width: 0, height: 0 };
  85425. this._shouldRender = true;
  85426. this._postProcesses = [];
  85427. this._textures = [];
  85428. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  85429. /**
  85430. * The clear color of the texture used to generate the glow map.
  85431. */
  85432. this.neutralColor = new BABYLON.Color4();
  85433. /**
  85434. * Specifies wether the highlight layer is enabled or not.
  85435. */
  85436. this.isEnabled = true;
  85437. /**
  85438. * An event triggered when the effect layer has been disposed.
  85439. */
  85440. this.onDisposeObservable = new BABYLON.Observable();
  85441. /**
  85442. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  85443. */
  85444. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  85445. /**
  85446. * An event triggered when the generated texture is being merged in the scene.
  85447. */
  85448. this.onBeforeComposeObservable = new BABYLON.Observable();
  85449. /**
  85450. * An event triggered when the generated texture has been merged in the scene.
  85451. */
  85452. this.onAfterComposeObservable = new BABYLON.Observable();
  85453. /**
  85454. * An event triggered when the efffect layer changes its size.
  85455. */
  85456. this.onSizeChangedObservable = new BABYLON.Observable();
  85457. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85458. this._engine = scene.getEngine();
  85459. this._maxSize = this._engine.getCaps().maxTextureSize;
  85460. this._scene.effectLayers.push(this);
  85461. // Generate Buffers
  85462. this._generateIndexBuffer();
  85463. this._genrateVertexBuffer();
  85464. }
  85465. Object.defineProperty(EffectLayer.prototype, "camera", {
  85466. /**
  85467. * Gets the camera attached to the layer.
  85468. */
  85469. get: function () {
  85470. return this._effectLayerOptions.camera;
  85471. },
  85472. enumerable: true,
  85473. configurable: true
  85474. });
  85475. /**
  85476. * Initializes the effect layer with the required options.
  85477. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  85478. */
  85479. EffectLayer.prototype._init = function (options) {
  85480. // Adapt options
  85481. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85482. this._setMainTextureSize();
  85483. this._createMainTexture();
  85484. this._createTextureAndPostProcesses();
  85485. this._mergeEffect = this._createMergeEffect();
  85486. };
  85487. /**
  85488. * Generates the index buffer of the full screen quad blending to the main canvas.
  85489. */
  85490. EffectLayer.prototype._generateIndexBuffer = function () {
  85491. // Indices
  85492. var indices = [];
  85493. indices.push(0);
  85494. indices.push(1);
  85495. indices.push(2);
  85496. indices.push(0);
  85497. indices.push(2);
  85498. indices.push(3);
  85499. this._indexBuffer = this._engine.createIndexBuffer(indices);
  85500. };
  85501. /**
  85502. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  85503. */
  85504. EffectLayer.prototype._genrateVertexBuffer = function () {
  85505. // VBO
  85506. var vertices = [];
  85507. vertices.push(1, 1);
  85508. vertices.push(-1, 1);
  85509. vertices.push(-1, -1);
  85510. vertices.push(1, -1);
  85511. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85512. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  85513. };
  85514. /**
  85515. * Sets the main texture desired size which is the closest power of two
  85516. * of the engine canvas size.
  85517. */
  85518. EffectLayer.prototype._setMainTextureSize = function () {
  85519. if (this._effectLayerOptions.mainTextureFixedSize) {
  85520. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  85521. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  85522. }
  85523. else {
  85524. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  85525. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  85526. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  85527. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  85528. }
  85529. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  85530. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  85531. };
  85532. /**
  85533. * Creates the main texture for the effect layer.
  85534. */
  85535. EffectLayer.prototype._createMainTexture = function () {
  85536. var _this = this;
  85537. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  85538. width: this._mainTextureDesiredSize.width,
  85539. height: this._mainTextureDesiredSize.height
  85540. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85541. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  85542. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85543. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85544. this._mainTexture.anisotropicFilteringLevel = 1;
  85545. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85546. this._mainTexture.renderParticles = false;
  85547. this._mainTexture.renderList = null;
  85548. this._mainTexture.ignoreCameraViewport = true;
  85549. // Custom render function
  85550. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85551. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  85552. var index;
  85553. var engine = _this._scene.getEngine();
  85554. if (depthOnlySubMeshes.length) {
  85555. engine.setColorWrite(false);
  85556. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85557. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  85558. }
  85559. engine.setColorWrite(true);
  85560. }
  85561. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85562. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  85563. }
  85564. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85565. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  85566. }
  85567. for (index = 0; index < transparentSubMeshes.length; index++) {
  85568. _this._renderSubMesh(transparentSubMeshes.data[index]);
  85569. }
  85570. };
  85571. this._mainTexture.onClearObservable.add(function (engine) {
  85572. engine.clear(_this.neutralColor, true, true, true);
  85573. });
  85574. };
  85575. /**
  85576. * Checks for the readiness of the element composing the layer.
  85577. * @param subMesh the mesh to check for
  85578. * @param useInstances specify wether or not to use instances to render the mesh
  85579. * @param emissiveTexture the associated emissive texture used to generate the glow
  85580. * @return true if ready otherwise, false
  85581. */
  85582. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  85583. var material = subMesh.getMaterial();
  85584. if (!material) {
  85585. return false;
  85586. }
  85587. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  85588. return false;
  85589. }
  85590. var defines = [];
  85591. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85592. var mesh = subMesh.getMesh();
  85593. var uv1 = false;
  85594. var uv2 = false;
  85595. // Alpha test
  85596. if (material && material.needAlphaTesting()) {
  85597. var alphaTexture = material.getAlphaTestTexture();
  85598. if (alphaTexture) {
  85599. defines.push("#define ALPHATEST");
  85600. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85601. alphaTexture.coordinatesIndex === 1) {
  85602. defines.push("#define DIFFUSEUV2");
  85603. uv2 = true;
  85604. }
  85605. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85606. defines.push("#define DIFFUSEUV1");
  85607. uv1 = true;
  85608. }
  85609. }
  85610. }
  85611. // Emissive
  85612. if (emissiveTexture) {
  85613. defines.push("#define EMISSIVE");
  85614. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85615. emissiveTexture.coordinatesIndex === 1) {
  85616. defines.push("#define EMISSIVEUV2");
  85617. uv2 = true;
  85618. }
  85619. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85620. defines.push("#define EMISSIVEUV1");
  85621. uv1 = true;
  85622. }
  85623. }
  85624. if (uv1) {
  85625. attribs.push(BABYLON.VertexBuffer.UVKind);
  85626. defines.push("#define UV1");
  85627. }
  85628. if (uv2) {
  85629. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85630. defines.push("#define UV2");
  85631. }
  85632. // Bones
  85633. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85634. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85635. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85636. if (mesh.numBoneInfluencers > 4) {
  85637. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85638. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85639. }
  85640. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85641. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  85642. }
  85643. else {
  85644. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85645. }
  85646. // Instances
  85647. if (useInstances) {
  85648. defines.push("#define INSTANCES");
  85649. attribs.push("world0");
  85650. attribs.push("world1");
  85651. attribs.push("world2");
  85652. attribs.push("world3");
  85653. }
  85654. // Get correct effect
  85655. var join = defines.join("\n");
  85656. if (this._cachedDefines !== join) {
  85657. this._cachedDefines = join;
  85658. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  85659. }
  85660. return this._effectLayerMapGenerationEffect.isReady();
  85661. };
  85662. /**
  85663. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  85664. */
  85665. EffectLayer.prototype.render = function () {
  85666. var currentEffect = this._mergeEffect;
  85667. // Check
  85668. if (!currentEffect.isReady())
  85669. return;
  85670. for (var i = 0; i < this._postProcesses.length; i++) {
  85671. if (!this._postProcesses[i].isReady()) {
  85672. return;
  85673. }
  85674. }
  85675. var engine = this._scene.getEngine();
  85676. this.onBeforeComposeObservable.notifyObservers(this);
  85677. // Render
  85678. engine.enableEffect(currentEffect);
  85679. engine.setState(false);
  85680. // VBOs
  85681. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  85682. // Cache
  85683. var previousAlphaMode = engine.getAlphaMode();
  85684. // Go Blend.
  85685. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  85686. // Blends the map on the main canvas.
  85687. this._internalRender(currentEffect);
  85688. // Restore Alpha
  85689. engine.setAlphaMode(previousAlphaMode);
  85690. this.onAfterComposeObservable.notifyObservers(this);
  85691. // Handle size changes.
  85692. var size = this._mainTexture.getSize();
  85693. this._setMainTextureSize();
  85694. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  85695. // Recreate RTT and post processes on size change.
  85696. this.onSizeChangedObservable.notifyObservers(this);
  85697. this._disposeTextureAndPostProcesses();
  85698. this._createMainTexture();
  85699. this._createTextureAndPostProcesses();
  85700. }
  85701. };
  85702. /**
  85703. * Determine if a given mesh will be used in the current effect.
  85704. * @param mesh mesh to test
  85705. * @returns true if the mesh will be used
  85706. */
  85707. EffectLayer.prototype.hasMesh = function (mesh) {
  85708. return true;
  85709. };
  85710. /**
  85711. * Returns true if the layer contains information to display, otherwise false.
  85712. * @returns true if the glow layer should be rendered
  85713. */
  85714. EffectLayer.prototype.shouldRender = function () {
  85715. return this.isEnabled && this._shouldRender;
  85716. };
  85717. /**
  85718. * Returns true if the mesh should render, otherwise false.
  85719. * @param mesh The mesh to render
  85720. * @returns true if it should render otherwise false
  85721. */
  85722. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  85723. return true;
  85724. };
  85725. /**
  85726. * Returns true if the mesh should render, otherwise false.
  85727. * @param mesh The mesh to render
  85728. * @returns true if it should render otherwise false
  85729. */
  85730. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  85731. return true;
  85732. };
  85733. /**
  85734. * Renders the submesh passed in parameter to the generation map.
  85735. */
  85736. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  85737. var _this = this;
  85738. if (!this.shouldRender()) {
  85739. return;
  85740. }
  85741. var material = subMesh.getMaterial();
  85742. var mesh = subMesh.getRenderingMesh();
  85743. var scene = this._scene;
  85744. var engine = scene.getEngine();
  85745. if (!material) {
  85746. return;
  85747. }
  85748. // Do not block in blend mode.
  85749. if (material.needAlphaBlendingForMesh(mesh)) {
  85750. return;
  85751. }
  85752. // Culling
  85753. engine.setState(material.backFaceCulling);
  85754. // Managing instances
  85755. var batch = mesh._getInstancesRenderList(subMesh._id);
  85756. if (batch.mustReturn) {
  85757. return;
  85758. }
  85759. // Early Exit per mesh
  85760. if (!this._shouldRenderMesh(mesh)) {
  85761. return;
  85762. }
  85763. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85764. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  85765. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  85766. engine.enableEffect(this._effectLayerMapGenerationEffect);
  85767. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  85768. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  85769. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  85770. // Alpha test
  85771. if (material && material.needAlphaTesting()) {
  85772. var alphaTexture = material.getAlphaTestTexture();
  85773. if (alphaTexture) {
  85774. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  85775. var textureMatrix = alphaTexture.getTextureMatrix();
  85776. if (textureMatrix) {
  85777. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  85778. }
  85779. }
  85780. }
  85781. // Glow emissive only
  85782. if (this._emissiveTextureAndColor.texture) {
  85783. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  85784. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  85785. }
  85786. // Bones
  85787. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85788. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85789. }
  85790. // Draw
  85791. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  85792. }
  85793. else {
  85794. // Need to reset refresh rate of the shadowMap
  85795. this._mainTexture.resetRefreshCounter();
  85796. }
  85797. };
  85798. /**
  85799. * Rebuild the required buffers.
  85800. * @ignore Internal use only.
  85801. */
  85802. EffectLayer.prototype._rebuild = function () {
  85803. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85804. if (vb) {
  85805. vb._rebuild();
  85806. }
  85807. this._generateIndexBuffer();
  85808. };
  85809. /**
  85810. * Dispose only the render target textures and post process.
  85811. */
  85812. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  85813. this._mainTexture.dispose();
  85814. for (var i = 0; i < this._postProcesses.length; i++) {
  85815. if (this._postProcesses[i]) {
  85816. this._postProcesses[i].dispose();
  85817. }
  85818. }
  85819. this._postProcesses = [];
  85820. for (var i = 0; i < this._textures.length; i++) {
  85821. if (this._textures[i]) {
  85822. this._textures[i].dispose();
  85823. }
  85824. }
  85825. this._textures = [];
  85826. };
  85827. /**
  85828. * Dispose the highlight layer and free resources.
  85829. */
  85830. EffectLayer.prototype.dispose = function () {
  85831. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85832. if (vertexBuffer) {
  85833. vertexBuffer.dispose();
  85834. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85835. }
  85836. if (this._indexBuffer) {
  85837. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85838. this._indexBuffer = null;
  85839. }
  85840. // Clean textures and post processes
  85841. this._disposeTextureAndPostProcesses();
  85842. // Remove from scene
  85843. var index = this._scene.effectLayers.indexOf(this, 0);
  85844. if (index > -1) {
  85845. this._scene.effectLayers.splice(index, 1);
  85846. }
  85847. // Callback
  85848. this.onDisposeObservable.notifyObservers(this);
  85849. this.onDisposeObservable.clear();
  85850. this.onBeforeRenderMainTextureObservable.clear();
  85851. this.onBeforeComposeObservable.clear();
  85852. this.onAfterComposeObservable.clear();
  85853. this.onSizeChangedObservable.clear();
  85854. };
  85855. return EffectLayer;
  85856. }());
  85857. BABYLON.EffectLayer = EffectLayer;
  85858. })(BABYLON || (BABYLON = {}));
  85859. //# sourceMappingURL=babylon.effectLayer.js.map
  85860. "use strict";
  85861. var BABYLON;
  85862. (function (BABYLON) {
  85863. /**
  85864. * Special Glow Blur post process only blurring the alpha channel
  85865. * It enforces keeping the most luminous color in the color channel.
  85866. */
  85867. var GlowBlurPostProcess = /** @class */ (function (_super) {
  85868. __extends(GlowBlurPostProcess, _super);
  85869. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  85870. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85871. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  85872. _this.direction = direction;
  85873. _this.kernel = kernel;
  85874. _this.onApplyObservable.add(function (effect) {
  85875. effect.setFloat2("screenSize", _this.width, _this.height);
  85876. effect.setVector2("direction", _this.direction);
  85877. effect.setFloat("blurWidth", _this.kernel);
  85878. });
  85879. return _this;
  85880. }
  85881. return GlowBlurPostProcess;
  85882. }(BABYLON.PostProcess));
  85883. /**
  85884. * The highlight layer Helps adding a glow effect around a mesh.
  85885. *
  85886. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85887. * glowy meshes to your scene.
  85888. *
  85889. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  85890. */
  85891. var HighlightLayer = /** @class */ (function (_super) {
  85892. __extends(HighlightLayer, _super);
  85893. /**
  85894. * Instantiates a new highlight Layer and references it to the scene..
  85895. * @param name The name of the layer
  85896. * @param scene The scene to use the layer in
  85897. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  85898. */
  85899. function HighlightLayer(name, scene, options) {
  85900. var _this = _super.call(this, name, scene) || this;
  85901. _this.name = name;
  85902. /**
  85903. * Specifies whether or not the inner glow is ACTIVE in the layer.
  85904. */
  85905. _this.innerGlow = true;
  85906. /**
  85907. * Specifies whether or not the outer glow is ACTIVE in the layer.
  85908. */
  85909. _this.outerGlow = true;
  85910. /**
  85911. * An event triggered when the highlight layer is being blurred.
  85912. */
  85913. _this.onBeforeBlurObservable = new BABYLON.Observable();
  85914. /**
  85915. * An event triggered when the highlight layer has been blurred.
  85916. */
  85917. _this.onAfterBlurObservable = new BABYLON.Observable();
  85918. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  85919. _this._meshes = {};
  85920. _this._excludedMeshes = {};
  85921. _this.neutralColor = HighlightLayer.NeutralColor;
  85922. // Warn on stencil
  85923. if (!_this._engine.isStencilEnable) {
  85924. 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 }");
  85925. }
  85926. // Adapt options
  85927. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85928. // Initialize the layer
  85929. _this._init({
  85930. alphaBlendingMode: _this._options.alphaBlendingMode,
  85931. camera: _this._options.camera,
  85932. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85933. mainTextureRatio: _this._options.mainTextureRatio
  85934. });
  85935. // Do not render as long as no meshes have been added
  85936. _this._shouldRender = false;
  85937. return _this;
  85938. }
  85939. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  85940. /**
  85941. * Gets the horizontal size of the blur.
  85942. */
  85943. get: function () {
  85944. return this._horizontalBlurPostprocess.kernel;
  85945. },
  85946. /**
  85947. * Specifies the horizontal size of the blur.
  85948. */
  85949. set: function (value) {
  85950. this._horizontalBlurPostprocess.kernel = value;
  85951. },
  85952. enumerable: true,
  85953. configurable: true
  85954. });
  85955. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  85956. /**
  85957. * Gets the vertical size of the blur.
  85958. */
  85959. get: function () {
  85960. return this._verticalBlurPostprocess.kernel;
  85961. },
  85962. /**
  85963. * Specifies the vertical size of the blur.
  85964. */
  85965. set: function (value) {
  85966. this._verticalBlurPostprocess.kernel = value;
  85967. },
  85968. enumerable: true,
  85969. configurable: true
  85970. });
  85971. /**
  85972. * Get the effect name of the layer.
  85973. * @return The effect name
  85974. */
  85975. HighlightLayer.prototype.getEffectName = function () {
  85976. return HighlightLayer.EffectName;
  85977. };
  85978. /**
  85979. * Create the merge effect. This is the shader use to blit the information back
  85980. * to the main canvas at the end of the scene rendering.
  85981. */
  85982. HighlightLayer.prototype._createMergeEffect = function () {
  85983. // Effect
  85984. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  85985. };
  85986. /**
  85987. * Creates the render target textures and post processes used in the highlight layer.
  85988. */
  85989. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  85990. var _this = this;
  85991. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  85992. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  85993. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85994. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85995. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  85996. width: blurTextureWidth,
  85997. height: blurTextureHeight
  85998. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85999. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86000. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86001. this._blurTexture.anisotropicFilteringLevel = 16;
  86002. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86003. this._blurTexture.renderParticles = false;
  86004. this._blurTexture.ignoreCameraViewport = true;
  86005. this._textures = [this._blurTexture];
  86006. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  86007. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86008. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  86009. effect.setTexture("textureSampler", _this._mainTexture);
  86010. });
  86011. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86012. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86013. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86014. });
  86015. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86016. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  86017. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86018. });
  86019. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86020. }
  86021. else {
  86022. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  86023. width: blurTextureWidth,
  86024. height: blurTextureHeight
  86025. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86026. this._horizontalBlurPostprocess.width = blurTextureWidth;
  86027. this._horizontalBlurPostprocess.height = blurTextureHeight;
  86028. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86029. effect.setTexture("textureSampler", _this._mainTexture);
  86030. });
  86031. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  86032. width: blurTextureWidth,
  86033. height: blurTextureHeight
  86034. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86035. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86036. }
  86037. this._mainTexture.onAfterUnbindObservable.add(function () {
  86038. _this.onBeforeBlurObservable.notifyObservers(_this);
  86039. var internalTexture = _this._blurTexture.getInternalTexture();
  86040. if (internalTexture) {
  86041. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  86042. }
  86043. _this.onAfterBlurObservable.notifyObservers(_this);
  86044. });
  86045. // Prevent autoClear.
  86046. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86047. };
  86048. /**
  86049. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86050. */
  86051. HighlightLayer.prototype.needStencil = function () {
  86052. return true;
  86053. };
  86054. /**
  86055. * Checks for the readiness of the element composing the layer.
  86056. * @param subMesh the mesh to check for
  86057. * @param useInstances specify wether or not to use instances to render the mesh
  86058. * @param emissiveTexture the associated emissive texture used to generate the glow
  86059. * @return true if ready otherwise, false
  86060. */
  86061. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  86062. var material = subMesh.getMaterial();
  86063. var mesh = subMesh.getRenderingMesh();
  86064. if (!material || !mesh || !this._meshes) {
  86065. return false;
  86066. }
  86067. var emissiveTexture = null;
  86068. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86069. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86070. emissiveTexture = material.emissiveTexture;
  86071. }
  86072. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86073. };
  86074. /**
  86075. * Implementation specific of rendering the generating effect on the main canvas.
  86076. * @param effect The effect used to render through
  86077. */
  86078. HighlightLayer.prototype._internalRender = function (effect) {
  86079. // Texture
  86080. effect.setTexture("textureSampler", this._blurTexture);
  86081. // Cache
  86082. var engine = this._engine;
  86083. var previousStencilBuffer = engine.getStencilBuffer();
  86084. var previousStencilFunction = engine.getStencilFunction();
  86085. var previousStencilMask = engine.getStencilMask();
  86086. var previousStencilOperationPass = engine.getStencilOperationPass();
  86087. var previousStencilOperationFail = engine.getStencilOperationFail();
  86088. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  86089. var previousStencilReference = engine.getStencilFunctionReference();
  86090. // Stencil operations
  86091. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  86092. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  86093. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  86094. // Draw order
  86095. engine.setStencilMask(0x00);
  86096. engine.setStencilBuffer(true);
  86097. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  86098. // 2 passes inner outer
  86099. if (this.outerGlow) {
  86100. effect.setFloat("offset", 0);
  86101. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  86102. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86103. }
  86104. if (this.innerGlow) {
  86105. effect.setFloat("offset", 1);
  86106. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  86107. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86108. }
  86109. // Restore Cache
  86110. engine.setStencilFunction(previousStencilFunction);
  86111. engine.setStencilMask(previousStencilMask);
  86112. engine.setStencilBuffer(previousStencilBuffer);
  86113. engine.setStencilOperationPass(previousStencilOperationPass);
  86114. engine.setStencilOperationFail(previousStencilOperationFail);
  86115. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  86116. engine.setStencilFunctionReference(previousStencilReference);
  86117. };
  86118. /**
  86119. * Returns true if the layer contains information to display, otherwise false.
  86120. */
  86121. HighlightLayer.prototype.shouldRender = function () {
  86122. if (_super.prototype.shouldRender.call(this)) {
  86123. return this._meshes ? true : false;
  86124. }
  86125. return false;
  86126. };
  86127. /**
  86128. * Returns true if the mesh should render, otherwise false.
  86129. * @param mesh The mesh to render
  86130. * @returns true if it should render otherwise false
  86131. */
  86132. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  86133. // Excluded Mesh
  86134. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  86135. return false;
  86136. }
  86137. ;
  86138. return true;
  86139. };
  86140. /**
  86141. * Sets the required values for both the emissive texture and and the main color.
  86142. */
  86143. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86144. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86145. if (highlightLayerMesh) {
  86146. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  86147. }
  86148. else {
  86149. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86150. }
  86151. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86152. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86153. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  86154. }
  86155. else {
  86156. this._emissiveTextureAndColor.texture = null;
  86157. }
  86158. };
  86159. /**
  86160. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  86161. * @param mesh The mesh to exclude from the highlight layer
  86162. */
  86163. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  86164. if (!this._excludedMeshes) {
  86165. return;
  86166. }
  86167. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86168. if (!meshExcluded) {
  86169. this._excludedMeshes[mesh.uniqueId] = {
  86170. mesh: mesh,
  86171. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  86172. mesh.getEngine().setStencilBuffer(false);
  86173. }),
  86174. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  86175. mesh.getEngine().setStencilBuffer(true);
  86176. }),
  86177. };
  86178. }
  86179. };
  86180. /**
  86181. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  86182. * @param mesh The mesh to highlight
  86183. */
  86184. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  86185. if (!this._excludedMeshes) {
  86186. return;
  86187. }
  86188. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86189. if (meshExcluded) {
  86190. if (meshExcluded.beforeRender) {
  86191. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  86192. }
  86193. if (meshExcluded.afterRender) {
  86194. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  86195. }
  86196. }
  86197. this._excludedMeshes[mesh.uniqueId] = null;
  86198. };
  86199. /**
  86200. * Determine if a given mesh will be highlighted by the current HighlightLayer
  86201. * @param mesh mesh to test
  86202. * @returns true if the mesh will be highlighted by the current HighlightLayer
  86203. */
  86204. HighlightLayer.prototype.hasMesh = function (mesh) {
  86205. if (!this._meshes) {
  86206. return false;
  86207. }
  86208. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  86209. };
  86210. /**
  86211. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  86212. * @param mesh The mesh to highlight
  86213. * @param color The color of the highlight
  86214. * @param glowEmissiveOnly Extract the glow from the emissive texture
  86215. */
  86216. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  86217. var _this = this;
  86218. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  86219. if (!this._meshes) {
  86220. return;
  86221. }
  86222. var meshHighlight = this._meshes[mesh.uniqueId];
  86223. if (meshHighlight) {
  86224. meshHighlight.color = color;
  86225. }
  86226. else {
  86227. this._meshes[mesh.uniqueId] = {
  86228. mesh: mesh,
  86229. color: color,
  86230. // Lambda required for capture due to Observable this context
  86231. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  86232. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  86233. _this._defaultStencilReference(mesh);
  86234. }
  86235. else {
  86236. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  86237. }
  86238. }),
  86239. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  86240. glowEmissiveOnly: glowEmissiveOnly
  86241. };
  86242. }
  86243. this._shouldRender = true;
  86244. };
  86245. /**
  86246. * Remove a mesh from the highlight layer in order to make it stop glowing.
  86247. * @param mesh The mesh to highlight
  86248. */
  86249. HighlightLayer.prototype.removeMesh = function (mesh) {
  86250. if (!this._meshes) {
  86251. return;
  86252. }
  86253. var meshHighlight = this._meshes[mesh.uniqueId];
  86254. if (meshHighlight) {
  86255. if (meshHighlight.observerHighlight) {
  86256. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86257. }
  86258. if (meshHighlight.observerDefault) {
  86259. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86260. }
  86261. delete this._meshes[mesh.uniqueId];
  86262. }
  86263. this._shouldRender = false;
  86264. for (var meshHighlightToCheck in this._meshes) {
  86265. if (this._meshes[meshHighlightToCheck]) {
  86266. this._shouldRender = true;
  86267. break;
  86268. }
  86269. }
  86270. };
  86271. /**
  86272. * Force the stencil to the normal expected value for none glowing parts
  86273. */
  86274. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  86275. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  86276. };
  86277. /**
  86278. * Free any resources and references associated to a mesh.
  86279. * Internal use
  86280. * @param mesh The mesh to free.
  86281. */
  86282. HighlightLayer.prototype._disposeMesh = function (mesh) {
  86283. this.removeMesh(mesh);
  86284. this.removeExcludedMesh(mesh);
  86285. };
  86286. /**
  86287. * Dispose the highlight layer and free resources.
  86288. */
  86289. HighlightLayer.prototype.dispose = function () {
  86290. if (this._meshes) {
  86291. // Clean mesh references
  86292. for (var id in this._meshes) {
  86293. var meshHighlight = this._meshes[id];
  86294. if (meshHighlight && meshHighlight.mesh) {
  86295. if (meshHighlight.observerHighlight) {
  86296. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86297. }
  86298. if (meshHighlight.observerDefault) {
  86299. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86300. }
  86301. }
  86302. }
  86303. this._meshes = null;
  86304. }
  86305. if (this._excludedMeshes) {
  86306. for (var id in this._excludedMeshes) {
  86307. var meshHighlight = this._excludedMeshes[id];
  86308. if (meshHighlight) {
  86309. if (meshHighlight.beforeRender) {
  86310. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  86311. }
  86312. if (meshHighlight.afterRender) {
  86313. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  86314. }
  86315. }
  86316. }
  86317. this._excludedMeshes = null;
  86318. }
  86319. _super.prototype.dispose.call(this);
  86320. };
  86321. /**
  86322. * Effect Name of the highlight layer.
  86323. */
  86324. HighlightLayer.EffectName = "HighlightLayer";
  86325. /**
  86326. * The neutral color used during the preparation of the glow effect.
  86327. * This is black by default as the blend operation is a blend operation.
  86328. */
  86329. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  86330. /**
  86331. * Stencil value used for glowing meshes.
  86332. */
  86333. HighlightLayer.GlowingMeshStencilReference = 0x02;
  86334. /**
  86335. * Stencil value used for the other meshes in the scene.
  86336. */
  86337. HighlightLayer.NormalMeshStencilReference = 0x01;
  86338. return HighlightLayer;
  86339. }(BABYLON.EffectLayer));
  86340. BABYLON.HighlightLayer = HighlightLayer;
  86341. })(BABYLON || (BABYLON = {}));
  86342. //# sourceMappingURL=babylon.highlightLayer.js.map
  86343. "use strict";
  86344. var BABYLON;
  86345. (function (BABYLON) {
  86346. /**
  86347. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  86348. *
  86349. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86350. * glowy meshes to your scene.
  86351. *
  86352. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  86353. */
  86354. var GlowLayer = /** @class */ (function (_super) {
  86355. __extends(GlowLayer, _super);
  86356. /**
  86357. * Instantiates a new glow Layer and references it to the scene.
  86358. * @param name The name of the layer
  86359. * @param scene The scene to use the layer in
  86360. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  86361. */
  86362. function GlowLayer(name, scene, options) {
  86363. var _this = _super.call(this, name, scene) || this;
  86364. _this.name = name;
  86365. _this._intensity = 1.0;
  86366. _this._includedOnlyMeshes = [];
  86367. _this._excludedMeshes = [];
  86368. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  86369. // Adapt options
  86370. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  86371. // Initialize the layer
  86372. _this._init({
  86373. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  86374. camera: _this._options.camera,
  86375. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86376. mainTextureRatio: _this._options.mainTextureRatio
  86377. });
  86378. return _this;
  86379. }
  86380. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  86381. /**
  86382. * Gets the kernel size of the blur.
  86383. */
  86384. get: function () {
  86385. return this._horizontalBlurPostprocess1.kernel;
  86386. },
  86387. /**
  86388. * Sets the kernel size of the blur.
  86389. */
  86390. set: function (value) {
  86391. this._horizontalBlurPostprocess1.kernel = value;
  86392. this._verticalBlurPostprocess1.kernel = value;
  86393. this._horizontalBlurPostprocess2.kernel = value;
  86394. this._verticalBlurPostprocess2.kernel = value;
  86395. },
  86396. enumerable: true,
  86397. configurable: true
  86398. });
  86399. Object.defineProperty(GlowLayer.prototype, "intensity", {
  86400. /**
  86401. * Gets the glow intensity.
  86402. */
  86403. get: function () {
  86404. return this._intensity;
  86405. },
  86406. /**
  86407. * Sets the glow intensity.
  86408. */
  86409. set: function (value) {
  86410. this._intensity = value;
  86411. },
  86412. enumerable: true,
  86413. configurable: true
  86414. });
  86415. /**
  86416. * Get the effect name of the layer.
  86417. * @return The effect name
  86418. */
  86419. GlowLayer.prototype.getEffectName = function () {
  86420. return GlowLayer.EffectName;
  86421. };
  86422. /**
  86423. * Create the merge effect. This is the shader use to blit the information back
  86424. * to the main canvas at the end of the scene rendering.
  86425. */
  86426. GlowLayer.prototype._createMergeEffect = function () {
  86427. // Effect
  86428. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  86429. };
  86430. /**
  86431. * Creates the render target textures and post processes used in the glow layer.
  86432. */
  86433. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  86434. var _this = this;
  86435. var blurTextureWidth = this._mainTextureDesiredSize.width;
  86436. var blurTextureHeight = this._mainTextureDesiredSize.height;
  86437. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86438. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86439. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  86440. width: blurTextureWidth,
  86441. height: blurTextureHeight
  86442. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86443. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86444. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86445. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86446. this._blurTexture1.renderParticles = false;
  86447. this._blurTexture1.ignoreCameraViewport = true;
  86448. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  86449. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  86450. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  86451. width: blurTextureWidth2,
  86452. height: blurTextureHeight2
  86453. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86454. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86455. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86456. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86457. this._blurTexture2.renderParticles = false;
  86458. this._blurTexture2.ignoreCameraViewport = true;
  86459. this._textures = [this._blurTexture1, this._blurTexture2];
  86460. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86461. width: blurTextureWidth,
  86462. height: blurTextureHeight
  86463. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86464. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  86465. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  86466. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  86467. effect.setTexture("textureSampler", _this._mainTexture);
  86468. });
  86469. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86470. width: blurTextureWidth,
  86471. height: blurTextureHeight
  86472. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86473. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86474. width: blurTextureWidth2,
  86475. height: blurTextureHeight2
  86476. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86477. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  86478. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  86479. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  86480. effect.setTexture("textureSampler", _this._blurTexture1);
  86481. });
  86482. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86483. width: blurTextureWidth2,
  86484. height: blurTextureHeight2
  86485. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86486. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86487. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  86488. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86489. this._mainTexture.samples = this._options.mainTextureSamples;
  86490. this._mainTexture.onAfterUnbindObservable.add(function () {
  86491. var internalTexture = _this._blurTexture1.getInternalTexture();
  86492. if (internalTexture) {
  86493. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  86494. internalTexture = _this._blurTexture2.getInternalTexture();
  86495. if (internalTexture) {
  86496. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  86497. }
  86498. }
  86499. });
  86500. // Prevent autoClear.
  86501. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86502. };
  86503. /**
  86504. * Checks for the readiness of the element composing the layer.
  86505. * @param subMesh the mesh to check for
  86506. * @param useInstances specify wether or not to use instances to render the mesh
  86507. * @param emissiveTexture the associated emissive texture used to generate the glow
  86508. * @return true if ready otherwise, false
  86509. */
  86510. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  86511. var material = subMesh.getMaterial();
  86512. var mesh = subMesh.getRenderingMesh();
  86513. if (!material || !mesh) {
  86514. return false;
  86515. }
  86516. var emissiveTexture = material.emissiveTexture;
  86517. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86518. };
  86519. /**
  86520. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86521. */
  86522. GlowLayer.prototype.needStencil = function () {
  86523. return false;
  86524. };
  86525. /**
  86526. * Implementation specific of rendering the generating effect on the main canvas.
  86527. * @param effect The effect used to render through
  86528. */
  86529. GlowLayer.prototype._internalRender = function (effect) {
  86530. // Texture
  86531. effect.setTexture("textureSampler", this._blurTexture1);
  86532. effect.setTexture("textureSampler2", this._blurTexture2);
  86533. effect.setFloat("offset", this._intensity);
  86534. // Cache
  86535. var engine = this._engine;
  86536. var previousStencilBuffer = engine.getStencilBuffer();
  86537. // Draw order
  86538. engine.setStencilBuffer(false);
  86539. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86540. // Draw order
  86541. engine.setStencilBuffer(previousStencilBuffer);
  86542. };
  86543. /**
  86544. * Sets the required values for both the emissive texture and and the main color.
  86545. */
  86546. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86547. var textureLevel = 1.0;
  86548. if (this.customEmissiveTextureSelector) {
  86549. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  86550. }
  86551. else {
  86552. if (material) {
  86553. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86554. if (this._emissiveTextureAndColor.texture) {
  86555. textureLevel = this._emissiveTextureAndColor.texture.level;
  86556. }
  86557. }
  86558. else {
  86559. this._emissiveTextureAndColor.texture = null;
  86560. }
  86561. }
  86562. if (this.customEmissiveColorSelector) {
  86563. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  86564. }
  86565. else {
  86566. if (material.emissiveColor) {
  86567. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  86568. }
  86569. else {
  86570. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86571. }
  86572. }
  86573. };
  86574. /**
  86575. * Returns true if the mesh should render, otherwise false.
  86576. * @param mesh The mesh to render
  86577. * @returns true if it should render otherwise false
  86578. */
  86579. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  86580. return this.hasMesh(mesh);
  86581. };
  86582. /**
  86583. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  86584. * @param mesh The mesh to exclude from the glow layer
  86585. */
  86586. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  86587. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  86588. this._excludedMeshes.push(mesh.uniqueId);
  86589. }
  86590. };
  86591. /**
  86592. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  86593. * @param mesh The mesh to remove
  86594. */
  86595. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  86596. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  86597. if (index !== -1) {
  86598. this._excludedMeshes.splice(index, 1);
  86599. }
  86600. };
  86601. /**
  86602. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  86603. * @param mesh The mesh to include in the glow layer
  86604. */
  86605. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  86606. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  86607. this._includedOnlyMeshes.push(mesh.uniqueId);
  86608. }
  86609. };
  86610. /**
  86611. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  86612. * @param mesh The mesh to remove
  86613. */
  86614. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  86615. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  86616. if (index !== -1) {
  86617. this._includedOnlyMeshes.splice(index, 1);
  86618. }
  86619. };
  86620. /**
  86621. * Determine if a given mesh will be used in the glow layer
  86622. * @param mesh The mesh to test
  86623. * @returns true if the mesh will be highlighted by the current glow layer
  86624. */
  86625. GlowLayer.prototype.hasMesh = function (mesh) {
  86626. // Included Mesh
  86627. if (this._includedOnlyMeshes.length) {
  86628. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  86629. }
  86630. ;
  86631. // Excluded Mesh
  86632. if (this._excludedMeshes.length) {
  86633. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  86634. }
  86635. ;
  86636. return true;
  86637. };
  86638. /**
  86639. * Free any resources and references associated to a mesh.
  86640. * Internal use
  86641. * @param mesh The mesh to free.
  86642. */
  86643. GlowLayer.prototype._disposeMesh = function (mesh) {
  86644. this.removeIncludedOnlyMesh(mesh);
  86645. this.removeExcludedMesh(mesh);
  86646. };
  86647. /**
  86648. * Effect Name of the layer.
  86649. */
  86650. GlowLayer.EffectName = "GlowLayer";
  86651. /**
  86652. * The default blur kernel size used for the glow.
  86653. */
  86654. GlowLayer.DefaultBlurKernelSize = 32;
  86655. /**
  86656. * The default texture size ratio used for the glow.
  86657. */
  86658. GlowLayer.DefaultTextureRatio = 0.5;
  86659. return GlowLayer;
  86660. }(BABYLON.EffectLayer));
  86661. BABYLON.GlowLayer = GlowLayer;
  86662. })(BABYLON || (BABYLON = {}));
  86663. //# sourceMappingURL=babylon.glowLayer.js.map
  86664. "use strict";
  86665. var BABYLON;
  86666. (function (BABYLON) {
  86667. /**
  86668. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  86669. */
  86670. var AssetTaskState;
  86671. (function (AssetTaskState) {
  86672. /**
  86673. * Initialization
  86674. */
  86675. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  86676. /**
  86677. * Running
  86678. */
  86679. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  86680. /**
  86681. * Done
  86682. */
  86683. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  86684. /**
  86685. * Error
  86686. */
  86687. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  86688. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  86689. /**
  86690. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  86691. */
  86692. var AbstractAssetTask = /** @class */ (function () {
  86693. /**
  86694. * Creates a new {BABYLON.AssetsManager}
  86695. * @param name defines the name of the task
  86696. */
  86697. function AbstractAssetTask(
  86698. /**
  86699. * Task name
  86700. */ name) {
  86701. this.name = name;
  86702. this._isCompleted = false;
  86703. this._taskState = AssetTaskState.INIT;
  86704. }
  86705. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  86706. /**
  86707. * Get if the task is completed
  86708. */
  86709. get: function () {
  86710. return this._isCompleted;
  86711. },
  86712. enumerable: true,
  86713. configurable: true
  86714. });
  86715. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  86716. /**
  86717. * Gets the current state of the task
  86718. */
  86719. get: function () {
  86720. return this._taskState;
  86721. },
  86722. enumerable: true,
  86723. configurable: true
  86724. });
  86725. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  86726. /**
  86727. * Gets the current error object (if task is in error)
  86728. */
  86729. get: function () {
  86730. return this._errorObject;
  86731. },
  86732. enumerable: true,
  86733. configurable: true
  86734. });
  86735. /**
  86736. * Internal only
  86737. * @ignore
  86738. */
  86739. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  86740. if (this._errorObject) {
  86741. return;
  86742. }
  86743. this._errorObject = {
  86744. message: message,
  86745. exception: exception
  86746. };
  86747. };
  86748. /**
  86749. * Execute the current task
  86750. * @param scene defines the scene where you want your assets to be loaded
  86751. * @param onSuccess is a callback called when the task is successfully executed
  86752. * @param onError is a callback called if an error occurs
  86753. */
  86754. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86755. var _this = this;
  86756. this._taskState = AssetTaskState.RUNNING;
  86757. this.runTask(scene, function () {
  86758. _this.onDoneCallback(onSuccess, onError);
  86759. }, function (msg, exception) {
  86760. _this.onErrorCallback(onError, msg, exception);
  86761. });
  86762. };
  86763. /**
  86764. * Execute the current task
  86765. * @param scene defines the scene where you want your assets to be loaded
  86766. * @param onSuccess is a callback called when the task is successfully executed
  86767. * @param onError is a callback called if an error occurs
  86768. */
  86769. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86770. throw new Error("runTask is not implemented");
  86771. };
  86772. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  86773. this._taskState = AssetTaskState.ERROR;
  86774. this._errorObject = {
  86775. message: message,
  86776. exception: exception
  86777. };
  86778. if (this.onError) {
  86779. this.onError(this, message, exception);
  86780. }
  86781. onError();
  86782. };
  86783. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  86784. try {
  86785. this._taskState = AssetTaskState.DONE;
  86786. this._isCompleted = true;
  86787. if (this.onSuccess) {
  86788. this.onSuccess(this);
  86789. }
  86790. onSuccess();
  86791. }
  86792. catch (e) {
  86793. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  86794. }
  86795. };
  86796. return AbstractAssetTask;
  86797. }());
  86798. BABYLON.AbstractAssetTask = AbstractAssetTask;
  86799. /**
  86800. * Class used to share progress information about assets loading
  86801. */
  86802. var AssetsProgressEvent = /** @class */ (function () {
  86803. /**
  86804. * Creates a {BABYLON.AssetsProgressEvent}
  86805. * @param remainingCount defines the number of remaining tasks to process
  86806. * @param totalCount defines the total number of tasks
  86807. * @param task defines the task that was just processed
  86808. */
  86809. function AssetsProgressEvent(remainingCount, totalCount, task) {
  86810. this.remainingCount = remainingCount;
  86811. this.totalCount = totalCount;
  86812. this.task = task;
  86813. }
  86814. return AssetsProgressEvent;
  86815. }());
  86816. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  86817. /**
  86818. * Define a task used by {BABYLON.AssetsManager} to load meshes
  86819. */
  86820. var MeshAssetTask = /** @class */ (function (_super) {
  86821. __extends(MeshAssetTask, _super);
  86822. /**
  86823. * Creates a new {BABYLON.MeshAssetTask}
  86824. * @param name defines the name of the task
  86825. * @param meshesNames defines the list of mesh's names you want to load
  86826. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  86827. * @param sceneFilename defines the filename of the scene to load from
  86828. */
  86829. function MeshAssetTask(
  86830. /**
  86831. * Defines the name of the task
  86832. */
  86833. name,
  86834. /**
  86835. * Defines the list of mesh's names you want to load
  86836. */
  86837. meshesNames,
  86838. /**
  86839. * Defines the root url to use as a base to load your meshes and associated resources
  86840. */
  86841. rootUrl,
  86842. /**
  86843. * Defines the filename of the scene to load from
  86844. */
  86845. sceneFilename) {
  86846. var _this = _super.call(this, name) || this;
  86847. _this.name = name;
  86848. _this.meshesNames = meshesNames;
  86849. _this.rootUrl = rootUrl;
  86850. _this.sceneFilename = sceneFilename;
  86851. return _this;
  86852. }
  86853. /**
  86854. * Execute the current task
  86855. * @param scene defines the scene where you want your assets to be loaded
  86856. * @param onSuccess is a callback called when the task is successfully executed
  86857. * @param onError is a callback called if an error occurs
  86858. */
  86859. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86860. var _this = this;
  86861. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  86862. _this.loadedMeshes = meshes;
  86863. _this.loadedParticleSystems = particleSystems;
  86864. _this.loadedSkeletons = skeletons;
  86865. onSuccess();
  86866. }, null, function (scene, message, exception) {
  86867. onError(message, exception);
  86868. });
  86869. };
  86870. return MeshAssetTask;
  86871. }(AbstractAssetTask));
  86872. BABYLON.MeshAssetTask = MeshAssetTask;
  86873. /**
  86874. * Define a task used by {BABYLON.AssetsManager} to load text content
  86875. */
  86876. var TextFileAssetTask = /** @class */ (function (_super) {
  86877. __extends(TextFileAssetTask, _super);
  86878. /**
  86879. * Creates a new TextFileAssetTask object
  86880. * @param name defines the name of the task
  86881. * @param url defines the location of the file to load
  86882. */
  86883. function TextFileAssetTask(
  86884. /**
  86885. * Defines the name of the task
  86886. */
  86887. name,
  86888. /**
  86889. * Defines the location of the file to load
  86890. */
  86891. url) {
  86892. var _this = _super.call(this, name) || this;
  86893. _this.name = name;
  86894. _this.url = url;
  86895. return _this;
  86896. }
  86897. /**
  86898. * Execute the current task
  86899. * @param scene defines the scene where you want your assets to be loaded
  86900. * @param onSuccess is a callback called when the task is successfully executed
  86901. * @param onError is a callback called if an error occurs
  86902. */
  86903. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86904. var _this = this;
  86905. scene._loadFile(this.url, function (data) {
  86906. _this.text = data;
  86907. onSuccess();
  86908. }, undefined, false, false, function (request, exception) {
  86909. if (request) {
  86910. onError(request.status + " " + request.statusText, exception);
  86911. }
  86912. });
  86913. };
  86914. return TextFileAssetTask;
  86915. }(AbstractAssetTask));
  86916. BABYLON.TextFileAssetTask = TextFileAssetTask;
  86917. /**
  86918. * Define a task used by {BABYLON.AssetsManager} to load binary data
  86919. */
  86920. var BinaryFileAssetTask = /** @class */ (function (_super) {
  86921. __extends(BinaryFileAssetTask, _super);
  86922. /**
  86923. * Creates a new BinaryFileAssetTask object
  86924. * @param name defines the name of the new task
  86925. * @param url defines the location of the file to load
  86926. */
  86927. function BinaryFileAssetTask(
  86928. /**
  86929. * Defines the name of the task
  86930. */
  86931. name,
  86932. /**
  86933. * Defines the location of the file to load
  86934. */
  86935. url) {
  86936. var _this = _super.call(this, name) || this;
  86937. _this.name = name;
  86938. _this.url = url;
  86939. return _this;
  86940. }
  86941. /**
  86942. * Execute the current task
  86943. * @param scene defines the scene where you want your assets to be loaded
  86944. * @param onSuccess is a callback called when the task is successfully executed
  86945. * @param onError is a callback called if an error occurs
  86946. */
  86947. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86948. var _this = this;
  86949. scene._loadFile(this.url, function (data) {
  86950. _this.data = data;
  86951. onSuccess();
  86952. }, undefined, true, true, function (request, exception) {
  86953. if (request) {
  86954. onError(request.status + " " + request.statusText, exception);
  86955. }
  86956. });
  86957. };
  86958. return BinaryFileAssetTask;
  86959. }(AbstractAssetTask));
  86960. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  86961. /**
  86962. * Define a task used by {BABYLON.AssetsManager} to load images
  86963. */
  86964. var ImageAssetTask = /** @class */ (function (_super) {
  86965. __extends(ImageAssetTask, _super);
  86966. /**
  86967. * Creates a new ImageAssetTask
  86968. * @param name defines the name of the task
  86969. * @param url defines the location of the image to load
  86970. */
  86971. function ImageAssetTask(
  86972. /**
  86973. * Defines the name of the task
  86974. */
  86975. name,
  86976. /**
  86977. * Defines the location of the image to load
  86978. */
  86979. url) {
  86980. var _this = _super.call(this, name) || this;
  86981. _this.name = name;
  86982. _this.url = url;
  86983. return _this;
  86984. }
  86985. /**
  86986. * Execute the current task
  86987. * @param scene defines the scene where you want your assets to be loaded
  86988. * @param onSuccess is a callback called when the task is successfully executed
  86989. * @param onError is a callback called if an error occurs
  86990. */
  86991. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86992. var _this = this;
  86993. var img = new Image();
  86994. BABYLON.Tools.SetCorsBehavior(this.url, img);
  86995. img.onload = function () {
  86996. _this.image = img;
  86997. onSuccess();
  86998. };
  86999. img.onerror = function (err) {
  87000. onError("Error loading image", err);
  87001. };
  87002. img.src = this.url;
  87003. };
  87004. return ImageAssetTask;
  87005. }(AbstractAssetTask));
  87006. BABYLON.ImageAssetTask = ImageAssetTask;
  87007. /**
  87008. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  87009. */
  87010. var TextureAssetTask = /** @class */ (function (_super) {
  87011. __extends(TextureAssetTask, _super);
  87012. /**
  87013. * Creates a new TextureAssetTask object
  87014. * @param name defines the name of the task
  87015. * @param url defines the location of the file to load
  87016. * @param noMipmap defines if mipmap should not be generated (default is false)
  87017. * @param invertY defines if texture must be inverted on Y axis (default is false)
  87018. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87019. */
  87020. function TextureAssetTask(
  87021. /**
  87022. * Defines the name of the task
  87023. */
  87024. name,
  87025. /**
  87026. * Defines the location of the file to load
  87027. */
  87028. url,
  87029. /**
  87030. * Defines if mipmap should not be generated (default is false)
  87031. */
  87032. noMipmap,
  87033. /**
  87034. * Defines if texture must be inverted on Y axis (default is false)
  87035. */
  87036. invertY,
  87037. /**
  87038. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87039. */
  87040. samplingMode) {
  87041. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87042. var _this = _super.call(this, name) || this;
  87043. _this.name = name;
  87044. _this.url = url;
  87045. _this.noMipmap = noMipmap;
  87046. _this.invertY = invertY;
  87047. _this.samplingMode = samplingMode;
  87048. return _this;
  87049. }
  87050. /**
  87051. * Execute the current task
  87052. * @param scene defines the scene where you want your assets to be loaded
  87053. * @param onSuccess is a callback called when the task is successfully executed
  87054. * @param onError is a callback called if an error occurs
  87055. */
  87056. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87057. var onload = function () {
  87058. onSuccess();
  87059. };
  87060. var onerror = function (message, exception) {
  87061. onError(message, exception);
  87062. };
  87063. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  87064. };
  87065. return TextureAssetTask;
  87066. }(AbstractAssetTask));
  87067. BABYLON.TextureAssetTask = TextureAssetTask;
  87068. /**
  87069. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  87070. */
  87071. var CubeTextureAssetTask = /** @class */ (function (_super) {
  87072. __extends(CubeTextureAssetTask, _super);
  87073. /**
  87074. * Creates a new CubeTextureAssetTask
  87075. * @param name defines the name of the task
  87076. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87077. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87078. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87079. * @param files defines the explicit list of files (undefined by default)
  87080. */
  87081. function CubeTextureAssetTask(
  87082. /**
  87083. * Defines the name of the task
  87084. */
  87085. name,
  87086. /**
  87087. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87088. */
  87089. url,
  87090. /**
  87091. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87092. */
  87093. extensions,
  87094. /**
  87095. * Defines if mipmaps should not be generated (default is false)
  87096. */
  87097. noMipmap,
  87098. /**
  87099. * Defines the explicit list of files (undefined by default)
  87100. */
  87101. files) {
  87102. var _this = _super.call(this, name) || this;
  87103. _this.name = name;
  87104. _this.url = url;
  87105. _this.extensions = extensions;
  87106. _this.noMipmap = noMipmap;
  87107. _this.files = files;
  87108. return _this;
  87109. }
  87110. /**
  87111. * Execute the current task
  87112. * @param scene defines the scene where you want your assets to be loaded
  87113. * @param onSuccess is a callback called when the task is successfully executed
  87114. * @param onError is a callback called if an error occurs
  87115. */
  87116. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87117. var onload = function () {
  87118. onSuccess();
  87119. };
  87120. var onerror = function (message, exception) {
  87121. onError(message, exception);
  87122. };
  87123. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  87124. };
  87125. return CubeTextureAssetTask;
  87126. }(AbstractAssetTask));
  87127. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  87128. /**
  87129. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  87130. */
  87131. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  87132. __extends(HDRCubeTextureAssetTask, _super);
  87133. /**
  87134. * Creates a new HDRCubeTextureAssetTask object
  87135. * @param name defines the name of the task
  87136. * @param url defines the location of the file to load
  87137. * @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.
  87138. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87139. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87140. * @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)
  87141. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87142. */
  87143. function HDRCubeTextureAssetTask(
  87144. /**
  87145. * Defines the name of the task
  87146. */
  87147. name,
  87148. /**
  87149. * Defines the location of the file to load
  87150. */
  87151. url,
  87152. /**
  87153. * 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.
  87154. */
  87155. size,
  87156. /**
  87157. * Defines if mipmaps should not be generated (default is false)
  87158. */
  87159. noMipmap,
  87160. /**
  87161. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87162. */
  87163. generateHarmonics,
  87164. /**
  87165. * 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)
  87166. */
  87167. useInGammaSpace,
  87168. /**
  87169. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87170. */
  87171. usePMREMGenerator) {
  87172. if (noMipmap === void 0) { noMipmap = false; }
  87173. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87174. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87175. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87176. var _this = _super.call(this, name) || this;
  87177. _this.name = name;
  87178. _this.url = url;
  87179. _this.size = size;
  87180. _this.noMipmap = noMipmap;
  87181. _this.generateHarmonics = generateHarmonics;
  87182. _this.useInGammaSpace = useInGammaSpace;
  87183. _this.usePMREMGenerator = usePMREMGenerator;
  87184. return _this;
  87185. }
  87186. /**
  87187. * Execute the current task
  87188. * @param scene defines the scene where you want your assets to be loaded
  87189. * @param onSuccess is a callback called when the task is successfully executed
  87190. * @param onError is a callback called if an error occurs
  87191. */
  87192. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87193. var onload = function () {
  87194. onSuccess();
  87195. };
  87196. var onerror = function (message, exception) {
  87197. onError(message, exception);
  87198. };
  87199. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  87200. };
  87201. return HDRCubeTextureAssetTask;
  87202. }(AbstractAssetTask));
  87203. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  87204. /**
  87205. * This class can be used to easily import assets into a scene
  87206. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  87207. */
  87208. var AssetsManager = /** @class */ (function () {
  87209. /**
  87210. * Creates a new AssetsManager
  87211. * @param scene defines the scene to work on
  87212. */
  87213. function AssetsManager(scene) {
  87214. this._isLoading = false;
  87215. this._tasks = new Array();
  87216. this._waitingTasksCount = 0;
  87217. this._totalTasksCount = 0;
  87218. /**
  87219. * Observable called when all tasks are processed
  87220. */
  87221. this.onTaskSuccessObservable = new BABYLON.Observable();
  87222. /**
  87223. * Observable called when a task had an error
  87224. */
  87225. this.onTaskErrorObservable = new BABYLON.Observable();
  87226. /**
  87227. * Observable called when a task is successful
  87228. */
  87229. this.onTasksDoneObservable = new BABYLON.Observable();
  87230. /**
  87231. * Observable called when a task is done (whatever the result is)
  87232. */
  87233. this.onProgressObservable = new BABYLON.Observable();
  87234. /**
  87235. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  87236. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  87237. */
  87238. this.useDefaultLoadingScreen = true;
  87239. this._scene = scene;
  87240. }
  87241. /**
  87242. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  87243. * @param taskName defines the name of the new task
  87244. * @param meshesNames defines the name of meshes to load
  87245. * @param rootUrl defines the root url to use to locate files
  87246. * @param sceneFilename defines the filename of the scene file
  87247. * @returns a new {BABYLON.MeshAssetTask} object
  87248. */
  87249. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  87250. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  87251. this._tasks.push(task);
  87252. return task;
  87253. };
  87254. /**
  87255. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  87256. * @param taskName defines the name of the new task
  87257. * @param url defines the url of the file to load
  87258. * @returns a new {BABYLON.TextFileAssetTask} object
  87259. */
  87260. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  87261. var task = new TextFileAssetTask(taskName, url);
  87262. this._tasks.push(task);
  87263. return task;
  87264. };
  87265. /**
  87266. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  87267. * @param taskName defines the name of the new task
  87268. * @param url defines the url of the file to load
  87269. * @returns a new {BABYLON.BinaryFileAssetTask} object
  87270. */
  87271. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  87272. var task = new BinaryFileAssetTask(taskName, url);
  87273. this._tasks.push(task);
  87274. return task;
  87275. };
  87276. /**
  87277. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  87278. * @param taskName defines the name of the new task
  87279. * @param url defines the url of the file to load
  87280. * @returns a new {BABYLON.ImageAssetTask} object
  87281. */
  87282. AssetsManager.prototype.addImageTask = function (taskName, url) {
  87283. var task = new ImageAssetTask(taskName, url);
  87284. this._tasks.push(task);
  87285. return task;
  87286. };
  87287. /**
  87288. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  87289. * @param taskName defines the name of the new task
  87290. * @param url defines the url of the file to load
  87291. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87292. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  87293. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  87294. * @returns a new {BABYLON.TextureAssetTask} object
  87295. */
  87296. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  87297. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87298. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  87299. this._tasks.push(task);
  87300. return task;
  87301. };
  87302. /**
  87303. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  87304. * @param taskName defines the name of the new task
  87305. * @param url defines the url of the file to load
  87306. * @param extensions defines the extension to use to load the cube map (can be null)
  87307. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87308. * @param files defines the list of files to load (can be null)
  87309. * @returns a new {BABYLON.CubeTextureAssetTask} object
  87310. */
  87311. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  87312. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  87313. this._tasks.push(task);
  87314. return task;
  87315. };
  87316. /**
  87317. *
  87318. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  87319. * @param taskName defines the name of the new task
  87320. * @param url defines the url of the file to load
  87321. * @param size defines the size you want for the cubemap (can be null)
  87322. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87323. * @param generateHarmonics defines if you want to automatically generate (true by default)
  87324. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  87325. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  87326. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  87327. */
  87328. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  87329. if (noMipmap === void 0) { noMipmap = false; }
  87330. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87331. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87332. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87333. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  87334. this._tasks.push(task);
  87335. return task;
  87336. };
  87337. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  87338. var _this = this;
  87339. this._waitingTasksCount--;
  87340. try {
  87341. if (task.taskState === AssetTaskState.DONE) {
  87342. // Let's remove successfull tasks
  87343. BABYLON.Tools.SetImmediate(function () {
  87344. var index = _this._tasks.indexOf(task);
  87345. if (index > -1) {
  87346. _this._tasks.splice(index, 1);
  87347. }
  87348. });
  87349. }
  87350. if (this.onProgress) {
  87351. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  87352. }
  87353. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  87354. }
  87355. catch (e) {
  87356. BABYLON.Tools.Error("Error running progress callbacks.");
  87357. console.log(e);
  87358. }
  87359. if (this._waitingTasksCount === 0) {
  87360. try {
  87361. if (this.onFinish) {
  87362. this.onFinish(this._tasks);
  87363. }
  87364. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87365. }
  87366. catch (e) {
  87367. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  87368. console.log(e);
  87369. }
  87370. this._isLoading = false;
  87371. this._scene.getEngine().hideLoadingUI();
  87372. }
  87373. };
  87374. AssetsManager.prototype._runTask = function (task) {
  87375. var _this = this;
  87376. var done = function () {
  87377. try {
  87378. if (_this.onTaskSuccess) {
  87379. _this.onTaskSuccess(task);
  87380. }
  87381. _this.onTaskSuccessObservable.notifyObservers(task);
  87382. _this._decreaseWaitingTasksCount(task);
  87383. }
  87384. catch (e) {
  87385. error("Error executing task success callbacks", e);
  87386. }
  87387. };
  87388. var error = function (message, exception) {
  87389. task._setErrorObject(message, exception);
  87390. if (_this.onTaskError) {
  87391. _this.onTaskError(task);
  87392. }
  87393. _this.onTaskErrorObservable.notifyObservers(task);
  87394. _this._decreaseWaitingTasksCount(task);
  87395. };
  87396. task.run(this._scene, done, error);
  87397. };
  87398. /**
  87399. * Reset the {BABYLON.AssetsManager} and remove all tasks
  87400. * @return the current instance of the {BABYLON.AssetsManager}
  87401. */
  87402. AssetsManager.prototype.reset = function () {
  87403. this._isLoading = false;
  87404. this._tasks = new Array();
  87405. return this;
  87406. };
  87407. /**
  87408. * Start the loading process
  87409. * @return the current instance of the {BABYLON.AssetsManager}
  87410. */
  87411. AssetsManager.prototype.load = function () {
  87412. if (this._isLoading) {
  87413. return this;
  87414. }
  87415. this._isLoading = true;
  87416. this._waitingTasksCount = this._tasks.length;
  87417. this._totalTasksCount = this._tasks.length;
  87418. if (this._waitingTasksCount === 0) {
  87419. this._isLoading = false;
  87420. if (this.onFinish) {
  87421. this.onFinish(this._tasks);
  87422. }
  87423. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87424. return this;
  87425. }
  87426. if (this.useDefaultLoadingScreen) {
  87427. this._scene.getEngine().displayLoadingUI();
  87428. }
  87429. for (var index = 0; index < this._tasks.length; index++) {
  87430. var task = this._tasks[index];
  87431. this._runTask(task);
  87432. }
  87433. return this;
  87434. };
  87435. return AssetsManager;
  87436. }());
  87437. BABYLON.AssetsManager = AssetsManager;
  87438. })(BABYLON || (BABYLON = {}));
  87439. //# sourceMappingURL=babylon.assetsManager.js.map
  87440. "use strict";
  87441. var BABYLON;
  87442. (function (BABYLON) {
  87443. var serializedGeometries = [];
  87444. var serializeGeometry = function (geometry, serializationGeometries) {
  87445. if (serializedGeometries[geometry.id]) {
  87446. return;
  87447. }
  87448. if (geometry.doNotSerialize) {
  87449. return;
  87450. }
  87451. if (geometry instanceof BABYLON.BoxGeometry) {
  87452. serializationGeometries.boxes.push(geometry.serialize());
  87453. }
  87454. else if (geometry instanceof BABYLON.SphereGeometry) {
  87455. serializationGeometries.spheres.push(geometry.serialize());
  87456. }
  87457. else if (geometry instanceof BABYLON.CylinderGeometry) {
  87458. serializationGeometries.cylinders.push(geometry.serialize());
  87459. }
  87460. else if (geometry instanceof BABYLON.TorusGeometry) {
  87461. serializationGeometries.toruses.push(geometry.serialize());
  87462. }
  87463. else if (geometry instanceof BABYLON.GroundGeometry) {
  87464. serializationGeometries.grounds.push(geometry.serialize());
  87465. }
  87466. else if (geometry instanceof BABYLON.Plane) {
  87467. serializationGeometries.planes.push(geometry.serialize());
  87468. }
  87469. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  87470. serializationGeometries.torusKnots.push(geometry.serialize());
  87471. }
  87472. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  87473. throw new Error("Unknown primitive type");
  87474. }
  87475. else {
  87476. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  87477. }
  87478. serializedGeometries[geometry.id] = true;
  87479. };
  87480. var serializeMesh = function (mesh, serializationScene) {
  87481. var serializationObject = {};
  87482. // Geometry
  87483. var geometry = mesh._geometry;
  87484. if (geometry) {
  87485. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  87486. // 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
  87487. serializeGeometry(geometry, serializationScene.geometries);
  87488. }
  87489. }
  87490. // Custom
  87491. if (mesh.serialize) {
  87492. mesh.serialize(serializationObject);
  87493. }
  87494. return serializationObject;
  87495. };
  87496. var finalizeSingleMesh = function (mesh, serializationObject) {
  87497. //only works if the mesh is already loaded
  87498. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87499. //serialize material
  87500. if (mesh.material) {
  87501. if (mesh.material instanceof BABYLON.StandardMaterial) {
  87502. serializationObject.materials = serializationObject.materials || [];
  87503. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87504. serializationObject.materials.push(mesh.material.serialize());
  87505. }
  87506. }
  87507. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  87508. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  87509. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87510. serializationObject.multiMaterials.push(mesh.material.serialize());
  87511. }
  87512. }
  87513. }
  87514. //serialize geometry
  87515. var geometry = mesh._geometry;
  87516. if (geometry) {
  87517. if (!serializationObject.geometries) {
  87518. serializationObject.geometries = {};
  87519. serializationObject.geometries.boxes = [];
  87520. serializationObject.geometries.spheres = [];
  87521. serializationObject.geometries.cylinders = [];
  87522. serializationObject.geometries.toruses = [];
  87523. serializationObject.geometries.grounds = [];
  87524. serializationObject.geometries.planes = [];
  87525. serializationObject.geometries.torusKnots = [];
  87526. serializationObject.geometries.vertexData = [];
  87527. }
  87528. serializeGeometry(geometry, serializationObject.geometries);
  87529. }
  87530. // Skeletons
  87531. if (mesh.skeleton) {
  87532. serializationObject.skeletons = serializationObject.skeletons || [];
  87533. serializationObject.skeletons.push(mesh.skeleton.serialize());
  87534. }
  87535. //serialize the actual mesh
  87536. serializationObject.meshes = serializationObject.meshes || [];
  87537. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87538. }
  87539. };
  87540. var SceneSerializer = /** @class */ (function () {
  87541. function SceneSerializer() {
  87542. }
  87543. SceneSerializer.ClearCache = function () {
  87544. serializedGeometries = [];
  87545. };
  87546. SceneSerializer.Serialize = function (scene) {
  87547. var serializationObject = {};
  87548. SceneSerializer.ClearCache();
  87549. // Scene
  87550. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  87551. serializationObject.autoClear = scene.autoClear;
  87552. serializationObject.clearColor = scene.clearColor.asArray();
  87553. serializationObject.ambientColor = scene.ambientColor.asArray();
  87554. serializationObject.gravity = scene.gravity.asArray();
  87555. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  87556. serializationObject.workerCollisions = scene.workerCollisions;
  87557. // Fog
  87558. if (scene.fogMode && scene.fogMode !== 0) {
  87559. serializationObject.fogMode = scene.fogMode;
  87560. serializationObject.fogColor = scene.fogColor.asArray();
  87561. serializationObject.fogStart = scene.fogStart;
  87562. serializationObject.fogEnd = scene.fogEnd;
  87563. serializationObject.fogDensity = scene.fogDensity;
  87564. }
  87565. //Physics
  87566. if (scene.isPhysicsEnabled()) {
  87567. var physicEngine = scene.getPhysicsEngine();
  87568. if (physicEngine) {
  87569. serializationObject.physicsEnabled = true;
  87570. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  87571. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  87572. }
  87573. }
  87574. // Metadata
  87575. if (scene.metadata) {
  87576. serializationObject.metadata = scene.metadata;
  87577. }
  87578. // Morph targets
  87579. serializationObject.morphTargetManagers = [];
  87580. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  87581. var abstractMesh = _a[_i];
  87582. var manager = abstractMesh.morphTargetManager;
  87583. if (manager) {
  87584. serializationObject.morphTargetManagers.push(manager.serialize());
  87585. }
  87586. }
  87587. // Lights
  87588. serializationObject.lights = [];
  87589. var index;
  87590. var light;
  87591. for (index = 0; index < scene.lights.length; index++) {
  87592. light = scene.lights[index];
  87593. if (!light.doNotSerialize) {
  87594. serializationObject.lights.push(light.serialize());
  87595. }
  87596. }
  87597. // Cameras
  87598. serializationObject.cameras = [];
  87599. for (index = 0; index < scene.cameras.length; index++) {
  87600. var camera = scene.cameras[index];
  87601. if (!camera.doNotSerialize) {
  87602. serializationObject.cameras.push(camera.serialize());
  87603. }
  87604. }
  87605. if (scene.activeCamera) {
  87606. serializationObject.activeCameraID = scene.activeCamera.id;
  87607. }
  87608. // Animations
  87609. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  87610. // Materials
  87611. serializationObject.materials = [];
  87612. serializationObject.multiMaterials = [];
  87613. var material;
  87614. for (index = 0; index < scene.materials.length; index++) {
  87615. material = scene.materials[index];
  87616. if (!material.doNotSerialize) {
  87617. serializationObject.materials.push(material.serialize());
  87618. }
  87619. }
  87620. // MultiMaterials
  87621. serializationObject.multiMaterials = [];
  87622. for (index = 0; index < scene.multiMaterials.length; index++) {
  87623. var multiMaterial = scene.multiMaterials[index];
  87624. serializationObject.multiMaterials.push(multiMaterial.serialize());
  87625. }
  87626. // Environment texture
  87627. if (scene.environmentTexture) {
  87628. serializationObject.environmentTexture = scene.environmentTexture.name;
  87629. }
  87630. // Skeletons
  87631. serializationObject.skeletons = [];
  87632. for (index = 0; index < scene.skeletons.length; index++) {
  87633. var skeleton = scene.skeletons[index];
  87634. if (!skeleton.doNotSerialize) {
  87635. serializationObject.skeletons.push(skeleton.serialize());
  87636. }
  87637. }
  87638. // Transform nodes
  87639. serializationObject.transformNodes = [];
  87640. for (index = 0; index < scene.transformNodes.length; index++) {
  87641. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  87642. }
  87643. // Geometries
  87644. serializationObject.geometries = {};
  87645. serializationObject.geometries.boxes = [];
  87646. serializationObject.geometries.spheres = [];
  87647. serializationObject.geometries.cylinders = [];
  87648. serializationObject.geometries.toruses = [];
  87649. serializationObject.geometries.grounds = [];
  87650. serializationObject.geometries.planes = [];
  87651. serializationObject.geometries.torusKnots = [];
  87652. serializationObject.geometries.vertexData = [];
  87653. serializedGeometries = [];
  87654. var geometries = scene.getGeometries();
  87655. for (index = 0; index < geometries.length; index++) {
  87656. var geometry = geometries[index];
  87657. if (geometry.isReady()) {
  87658. serializeGeometry(geometry, serializationObject.geometries);
  87659. }
  87660. }
  87661. // Meshes
  87662. serializationObject.meshes = [];
  87663. for (index = 0; index < scene.meshes.length; index++) {
  87664. var abstractMesh = scene.meshes[index];
  87665. if (abstractMesh instanceof BABYLON.Mesh) {
  87666. var mesh = abstractMesh;
  87667. if (!mesh.doNotSerialize) {
  87668. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87669. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87670. }
  87671. }
  87672. }
  87673. }
  87674. // Particles Systems
  87675. serializationObject.particleSystems = [];
  87676. for (index = 0; index < scene.particleSystems.length; index++) {
  87677. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  87678. }
  87679. // Lens flares
  87680. serializationObject.lensFlareSystems = [];
  87681. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  87682. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  87683. }
  87684. // Shadows
  87685. serializationObject.shadowGenerators = [];
  87686. for (index = 0; index < scene.lights.length; index++) {
  87687. light = scene.lights[index];
  87688. var shadowGenerator = light.getShadowGenerator();
  87689. if (shadowGenerator) {
  87690. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  87691. }
  87692. }
  87693. // Action Manager
  87694. if (scene.actionManager) {
  87695. serializationObject.actions = scene.actionManager.serialize("scene");
  87696. }
  87697. // Audio
  87698. serializationObject.sounds = [];
  87699. for (index = 0; index < scene.soundTracks.length; index++) {
  87700. var soundtrack = scene.soundTracks[index];
  87701. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  87702. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  87703. }
  87704. }
  87705. return serializationObject;
  87706. };
  87707. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  87708. if (withParents === void 0) { withParents = false; }
  87709. if (withChildren === void 0) { withChildren = false; }
  87710. var serializationObject = {};
  87711. SceneSerializer.ClearCache();
  87712. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  87713. if (withParents || withChildren) {
  87714. //deliberate for loop! not for each, appended should be processed as well.
  87715. for (var i = 0; i < toSerialize.length; ++i) {
  87716. if (withChildren) {
  87717. toSerialize[i].getDescendants().forEach(function (node) {
  87718. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  87719. toSerialize.push(node);
  87720. }
  87721. });
  87722. }
  87723. //make sure the array doesn't contain the object already
  87724. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  87725. toSerialize.push(toSerialize[i].parent);
  87726. }
  87727. }
  87728. }
  87729. toSerialize.forEach(function (mesh) {
  87730. finalizeSingleMesh(mesh, serializationObject);
  87731. });
  87732. return serializationObject;
  87733. };
  87734. return SceneSerializer;
  87735. }());
  87736. BABYLON.SceneSerializer = SceneSerializer;
  87737. })(BABYLON || (BABYLON = {}));
  87738. //# sourceMappingURL=babylon.sceneSerializer.js.map
  87739. "use strict";
  87740. var BABYLON;
  87741. (function (BABYLON) {
  87742. var ReflectionProbe = /** @class */ (function () {
  87743. function ReflectionProbe(name, size, scene, generateMipMaps) {
  87744. if (generateMipMaps === void 0) { generateMipMaps = true; }
  87745. var _this = this;
  87746. this.name = name;
  87747. this._viewMatrix = BABYLON.Matrix.Identity();
  87748. this._target = BABYLON.Vector3.Zero();
  87749. this._add = BABYLON.Vector3.Zero();
  87750. this._invertYAxis = false;
  87751. this.position = BABYLON.Vector3.Zero();
  87752. this._scene = scene;
  87753. this._scene.reflectionProbes.push(this);
  87754. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  87755. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  87756. switch (faceIndex) {
  87757. case 0:
  87758. _this._add.copyFromFloats(1, 0, 0);
  87759. break;
  87760. case 1:
  87761. _this._add.copyFromFloats(-1, 0, 0);
  87762. break;
  87763. case 2:
  87764. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  87765. break;
  87766. case 3:
  87767. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  87768. break;
  87769. case 4:
  87770. _this._add.copyFromFloats(0, 0, 1);
  87771. break;
  87772. case 5:
  87773. _this._add.copyFromFloats(0, 0, -1);
  87774. break;
  87775. }
  87776. if (_this._attachedMesh) {
  87777. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  87778. }
  87779. _this.position.addToRef(_this._add, _this._target);
  87780. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  87781. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  87782. scene._forcedViewPosition = _this.position;
  87783. });
  87784. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  87785. scene._forcedViewPosition = null;
  87786. scene.updateTransformMatrix(true);
  87787. });
  87788. if (scene.activeCamera) {
  87789. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  87790. }
  87791. }
  87792. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  87793. get: function () {
  87794. return this._renderTargetTexture.samples;
  87795. },
  87796. set: function (value) {
  87797. this._renderTargetTexture.samples = value;
  87798. },
  87799. enumerable: true,
  87800. configurable: true
  87801. });
  87802. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  87803. get: function () {
  87804. return this._renderTargetTexture.refreshRate;
  87805. },
  87806. set: function (value) {
  87807. this._renderTargetTexture.refreshRate = value;
  87808. },
  87809. enumerable: true,
  87810. configurable: true
  87811. });
  87812. ReflectionProbe.prototype.getScene = function () {
  87813. return this._scene;
  87814. };
  87815. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  87816. get: function () {
  87817. return this._renderTargetTexture;
  87818. },
  87819. enumerable: true,
  87820. configurable: true
  87821. });
  87822. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  87823. get: function () {
  87824. return this._renderTargetTexture.renderList;
  87825. },
  87826. enumerable: true,
  87827. configurable: true
  87828. });
  87829. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  87830. this._attachedMesh = mesh;
  87831. };
  87832. /**
  87833. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  87834. *
  87835. * @param renderingGroupId The rendering group id corresponding to its index
  87836. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  87837. */
  87838. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  87839. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  87840. };
  87841. ReflectionProbe.prototype.dispose = function () {
  87842. var index = this._scene.reflectionProbes.indexOf(this);
  87843. if (index !== -1) {
  87844. // Remove from the scene if found
  87845. this._scene.reflectionProbes.splice(index, 1);
  87846. }
  87847. if (this._renderTargetTexture) {
  87848. this._renderTargetTexture.dispose();
  87849. this._renderTargetTexture = null;
  87850. }
  87851. };
  87852. return ReflectionProbe;
  87853. }());
  87854. BABYLON.ReflectionProbe = ReflectionProbe;
  87855. })(BABYLON || (BABYLON = {}));
  87856. //# sourceMappingURL=babylon.reflectionProbe.js.map
  87857. "use strict";
  87858. var BABYLON;
  87859. (function (BABYLON) {
  87860. var Layer = /** @class */ (function () {
  87861. function Layer(name, imgUrl, scene, isBackground, color) {
  87862. this.name = name;
  87863. this.scale = new BABYLON.Vector2(1, 1);
  87864. this.offset = new BABYLON.Vector2(0, 0);
  87865. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  87866. this.layerMask = 0x0FFFFFFF;
  87867. this._vertexBuffers = {};
  87868. // Events
  87869. /**
  87870. * An event triggered when the layer is disposed.
  87871. * @type {BABYLON.Observable}
  87872. */
  87873. this.onDisposeObservable = new BABYLON.Observable();
  87874. /**
  87875. * An event triggered before rendering the scene
  87876. * @type {BABYLON.Observable}
  87877. */
  87878. this.onBeforeRenderObservable = new BABYLON.Observable();
  87879. /**
  87880. * An event triggered after rendering the scene
  87881. * @type {BABYLON.Observable}
  87882. */
  87883. this.onAfterRenderObservable = new BABYLON.Observable();
  87884. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  87885. this.isBackground = isBackground === undefined ? true : isBackground;
  87886. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  87887. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  87888. this._scene.layers.push(this);
  87889. var engine = this._scene.getEngine();
  87890. // VBO
  87891. var vertices = [];
  87892. vertices.push(1, 1);
  87893. vertices.push(-1, 1);
  87894. vertices.push(-1, -1);
  87895. vertices.push(1, -1);
  87896. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87897. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  87898. this._createIndexBuffer();
  87899. // Effects
  87900. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  87901. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  87902. }
  87903. Object.defineProperty(Layer.prototype, "onDispose", {
  87904. set: function (callback) {
  87905. if (this._onDisposeObserver) {
  87906. this.onDisposeObservable.remove(this._onDisposeObserver);
  87907. }
  87908. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  87909. },
  87910. enumerable: true,
  87911. configurable: true
  87912. });
  87913. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  87914. set: function (callback) {
  87915. if (this._onBeforeRenderObserver) {
  87916. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  87917. }
  87918. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  87919. },
  87920. enumerable: true,
  87921. configurable: true
  87922. });
  87923. Object.defineProperty(Layer.prototype, "onAfterRender", {
  87924. set: function (callback) {
  87925. if (this._onAfterRenderObserver) {
  87926. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87927. }
  87928. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  87929. },
  87930. enumerable: true,
  87931. configurable: true
  87932. });
  87933. Layer.prototype._createIndexBuffer = function () {
  87934. var engine = this._scene.getEngine();
  87935. // Indices
  87936. var indices = [];
  87937. indices.push(0);
  87938. indices.push(1);
  87939. indices.push(2);
  87940. indices.push(0);
  87941. indices.push(2);
  87942. indices.push(3);
  87943. this._indexBuffer = engine.createIndexBuffer(indices);
  87944. };
  87945. Layer.prototype._rebuild = function () {
  87946. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87947. if (vb) {
  87948. vb._rebuild();
  87949. }
  87950. this._createIndexBuffer();
  87951. };
  87952. Layer.prototype.render = function () {
  87953. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  87954. // Check
  87955. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  87956. return;
  87957. var engine = this._scene.getEngine();
  87958. this.onBeforeRenderObservable.notifyObservers(this);
  87959. // Render
  87960. engine.enableEffect(currentEffect);
  87961. engine.setState(false);
  87962. // Texture
  87963. currentEffect.setTexture("textureSampler", this.texture);
  87964. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  87965. // Color
  87966. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  87967. // Scale / offset
  87968. currentEffect.setVector2("offset", this.offset);
  87969. currentEffect.setVector2("scale", this.scale);
  87970. // VBOs
  87971. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  87972. // Draw order
  87973. if (!this.alphaTest) {
  87974. engine.setAlphaMode(this.alphaBlendingMode);
  87975. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87976. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  87977. }
  87978. else {
  87979. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87980. }
  87981. this.onAfterRenderObservable.notifyObservers(this);
  87982. };
  87983. Layer.prototype.dispose = function () {
  87984. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87985. if (vertexBuffer) {
  87986. vertexBuffer.dispose();
  87987. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87988. }
  87989. if (this._indexBuffer) {
  87990. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87991. this._indexBuffer = null;
  87992. }
  87993. if (this.texture) {
  87994. this.texture.dispose();
  87995. this.texture = null;
  87996. }
  87997. // Remove from scene
  87998. var index = this._scene.layers.indexOf(this);
  87999. this._scene.layers.splice(index, 1);
  88000. // Callback
  88001. this.onDisposeObservable.notifyObservers(this);
  88002. this.onDisposeObservable.clear();
  88003. this.onAfterRenderObservable.clear();
  88004. this.onBeforeRenderObservable.clear();
  88005. };
  88006. return Layer;
  88007. }());
  88008. BABYLON.Layer = Layer;
  88009. })(BABYLON || (BABYLON = {}));
  88010. //# sourceMappingURL=babylon.layer.js.map
  88011. "use strict";
  88012. var BABYLON;
  88013. (function (BABYLON) {
  88014. var TextureTools = /** @class */ (function () {
  88015. function TextureTools() {
  88016. }
  88017. /**
  88018. * Uses the GPU to create a copy texture rescaled at a given size
  88019. * @param texture Texture to copy from
  88020. * @param width Desired width
  88021. * @param height Desired height
  88022. * @return Generated texture
  88023. */
  88024. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  88025. if (useBilinearMode === void 0) { useBilinearMode = true; }
  88026. var scene = texture.getScene();
  88027. var engine = scene.getEngine();
  88028. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  88029. rtt.wrapU = texture.wrapU;
  88030. rtt.wrapV = texture.wrapV;
  88031. rtt.uOffset = texture.uOffset;
  88032. rtt.vOffset = texture.vOffset;
  88033. rtt.uScale = texture.uScale;
  88034. rtt.vScale = texture.vScale;
  88035. rtt.uAng = texture.uAng;
  88036. rtt.vAng = texture.vAng;
  88037. rtt.wAng = texture.wAng;
  88038. rtt.coordinatesIndex = texture.coordinatesIndex;
  88039. rtt.level = texture.level;
  88040. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  88041. rtt._texture.isReady = false;
  88042. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88043. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88044. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88045. passPostProcess.getEffect().executeWhenCompiled(function () {
  88046. passPostProcess.onApply = function (effect) {
  88047. effect.setTexture("textureSampler", texture);
  88048. };
  88049. var internalTexture = rtt.getInternalTexture();
  88050. if (internalTexture) {
  88051. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  88052. engine.unBindFramebuffer(internalTexture);
  88053. rtt.disposeFramebufferObjects();
  88054. passPostProcess.dispose();
  88055. internalTexture.isReady = true;
  88056. }
  88057. });
  88058. return rtt;
  88059. };
  88060. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  88061. if (!scene._environmentBRDFTexture) {
  88062. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88063. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88064. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88065. scene._environmentBRDFTexture = texture;
  88066. }
  88067. return scene._environmentBRDFTexture;
  88068. };
  88069. 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=";
  88070. return TextureTools;
  88071. }());
  88072. BABYLON.TextureTools = TextureTools;
  88073. })(BABYLON || (BABYLON = {}));
  88074. //# sourceMappingURL=babylon.textureTools.js.map
  88075. "use strict";
  88076. var BABYLON;
  88077. (function (BABYLON) {
  88078. var FramingBehavior = /** @class */ (function () {
  88079. function FramingBehavior() {
  88080. this._mode = FramingBehavior.FitFrustumSidesMode;
  88081. this._radiusScale = 1.0;
  88082. this._positionScale = 0.5;
  88083. this._defaultElevation = 0.3;
  88084. this._elevationReturnTime = 1500;
  88085. this._elevationReturnWaitTime = 1000;
  88086. this._zoomStopsAnimation = false;
  88087. this._framingTime = 1500;
  88088. this._isPointerDown = false;
  88089. this._lastInteractionTime = -Infinity;
  88090. // Framing control
  88091. this._animatables = new Array();
  88092. this._betaIsAnimating = false;
  88093. }
  88094. Object.defineProperty(FramingBehavior.prototype, "name", {
  88095. get: function () {
  88096. return "Framing";
  88097. },
  88098. enumerable: true,
  88099. configurable: true
  88100. });
  88101. Object.defineProperty(FramingBehavior.prototype, "mode", {
  88102. /**
  88103. * Gets current mode used by the behavior.
  88104. */
  88105. get: function () {
  88106. return this._mode;
  88107. },
  88108. /**
  88109. * Sets the current mode used by the behavior
  88110. */
  88111. set: function (mode) {
  88112. this._mode = mode;
  88113. },
  88114. enumerable: true,
  88115. configurable: true
  88116. });
  88117. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  88118. /**
  88119. * Gets the scale applied to the radius
  88120. */
  88121. get: function () {
  88122. return this._radiusScale;
  88123. },
  88124. /**
  88125. * Sets the scale applied to the radius (1 by default)
  88126. */
  88127. set: function (radius) {
  88128. this._radiusScale = radius;
  88129. },
  88130. enumerable: true,
  88131. configurable: true
  88132. });
  88133. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  88134. /**
  88135. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88136. */
  88137. get: function () {
  88138. return this._positionScale;
  88139. },
  88140. /**
  88141. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88142. */
  88143. set: function (scale) {
  88144. this._positionScale = scale;
  88145. },
  88146. enumerable: true,
  88147. configurable: true
  88148. });
  88149. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  88150. /**
  88151. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88152. * behaviour is triggered, in radians.
  88153. */
  88154. get: function () {
  88155. return this._defaultElevation;
  88156. },
  88157. /**
  88158. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88159. * behaviour is triggered, in radians.
  88160. */
  88161. set: function (elevation) {
  88162. this._defaultElevation = elevation;
  88163. },
  88164. enumerable: true,
  88165. configurable: true
  88166. });
  88167. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  88168. /**
  88169. * Gets the time (in milliseconds) taken to return to the default beta position.
  88170. * Negative value indicates camera should not return to default.
  88171. */
  88172. get: function () {
  88173. return this._elevationReturnTime;
  88174. },
  88175. /**
  88176. * Sets the time (in milliseconds) taken to return to the default beta position.
  88177. * Negative value indicates camera should not return to default.
  88178. */
  88179. set: function (speed) {
  88180. this._elevationReturnTime = speed;
  88181. },
  88182. enumerable: true,
  88183. configurable: true
  88184. });
  88185. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  88186. /**
  88187. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88188. */
  88189. get: function () {
  88190. return this._elevationReturnWaitTime;
  88191. },
  88192. /**
  88193. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88194. */
  88195. set: function (time) {
  88196. this._elevationReturnWaitTime = time;
  88197. },
  88198. enumerable: true,
  88199. configurable: true
  88200. });
  88201. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  88202. /**
  88203. * Gets the flag that indicates if user zooming should stop animation.
  88204. */
  88205. get: function () {
  88206. return this._zoomStopsAnimation;
  88207. },
  88208. /**
  88209. * Sets the flag that indicates if user zooming should stop animation.
  88210. */
  88211. set: function (flag) {
  88212. this._zoomStopsAnimation = flag;
  88213. },
  88214. enumerable: true,
  88215. configurable: true
  88216. });
  88217. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  88218. /**
  88219. * Gets the transition time when framing the mesh, in milliseconds
  88220. */
  88221. get: function () {
  88222. return this._framingTime;
  88223. },
  88224. /**
  88225. * Sets the transition time when framing the mesh, in milliseconds
  88226. */
  88227. set: function (time) {
  88228. this._framingTime = time;
  88229. },
  88230. enumerable: true,
  88231. configurable: true
  88232. });
  88233. FramingBehavior.prototype.init = function () {
  88234. // Do notihng
  88235. };
  88236. FramingBehavior.prototype.attach = function (camera) {
  88237. var _this = this;
  88238. this._attachedCamera = camera;
  88239. var scene = this._attachedCamera.getScene();
  88240. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  88241. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88242. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88243. _this._isPointerDown = true;
  88244. return;
  88245. }
  88246. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88247. _this._isPointerDown = false;
  88248. }
  88249. });
  88250. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88251. if (mesh) {
  88252. _this.zoomOnMesh(mesh);
  88253. }
  88254. });
  88255. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88256. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88257. _this._applyUserInteraction();
  88258. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  88259. // back to the default position after a given timeout
  88260. _this._maintainCameraAboveGround();
  88261. });
  88262. };
  88263. FramingBehavior.prototype.detach = function () {
  88264. if (!this._attachedCamera) {
  88265. return;
  88266. }
  88267. var scene = this._attachedCamera.getScene();
  88268. if (this._onPrePointerObservableObserver) {
  88269. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88270. }
  88271. if (this._onAfterCheckInputsObserver) {
  88272. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88273. }
  88274. if (this._onMeshTargetChangedObserver) {
  88275. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88276. }
  88277. this._attachedCamera = null;
  88278. };
  88279. /**
  88280. * Targets the given mesh and updates zoom level accordingly.
  88281. * @param mesh The mesh to target.
  88282. * @param radius Optional. If a cached radius position already exists, overrides default.
  88283. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88284. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88285. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88286. */
  88287. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88288. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88289. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88290. mesh.computeWorldMatrix(true);
  88291. var boundingBox = mesh.getBoundingInfo().boundingBox;
  88292. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  88293. };
  88294. /**
  88295. * Targets the given mesh with its children and updates zoom level accordingly.
  88296. * @param mesh The mesh to target.
  88297. * @param radius Optional. If a cached radius position already exists, overrides default.
  88298. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88299. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88300. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88301. */
  88302. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88303. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88304. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88305. mesh.computeWorldMatrix(true);
  88306. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  88307. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  88308. };
  88309. /**
  88310. * Targets the given meshes with their children and updates zoom level accordingly.
  88311. * @param meshes The mesh to target.
  88312. * @param radius Optional. If a cached radius position already exists, overrides default.
  88313. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88314. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88315. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88316. */
  88317. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  88318. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88319. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88320. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  88321. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  88322. for (var i = 0; i < meshes.length; i++) {
  88323. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  88324. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  88325. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  88326. }
  88327. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  88328. };
  88329. /**
  88330. * Targets the given mesh and updates zoom level accordingly.
  88331. * @param mesh The mesh to target.
  88332. * @param radius Optional. If a cached radius position already exists, overrides default.
  88333. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88334. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88335. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88336. */
  88337. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  88338. var _this = this;
  88339. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88340. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88341. var zoomTarget;
  88342. if (!this._attachedCamera) {
  88343. return;
  88344. }
  88345. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  88346. var bottom = minimumWorld.y;
  88347. var top = maximumWorld.y;
  88348. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  88349. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  88350. if (focusOnOriginXZ) {
  88351. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  88352. }
  88353. else {
  88354. var centerWorld = minimumWorld.add(radiusWorld);
  88355. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  88356. }
  88357. if (!this._vectorTransition) {
  88358. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  88359. }
  88360. this._betaIsAnimating = true;
  88361. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  88362. if (animatable) {
  88363. this._animatables.push(animatable);
  88364. }
  88365. // sets the radius and lower radius bounds
  88366. // Small delta ensures camera is not always at lower zoom limit.
  88367. var radius = 0;
  88368. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  88369. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88370. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  88371. radius = position;
  88372. }
  88373. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88374. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88375. if (this._attachedCamera.lowerRadiusLimit === null) {
  88376. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  88377. }
  88378. }
  88379. // Set sensibilities
  88380. var extend = maximumWorld.subtract(minimumWorld).length();
  88381. this._attachedCamera.panningSensibility = 5000 / extend;
  88382. this._attachedCamera.wheelPrecision = 100 / radius;
  88383. // transition to new radius
  88384. if (!this._radiusTransition) {
  88385. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88386. }
  88387. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  88388. _this.stopAllAnimations();
  88389. if (onAnimationEnd) {
  88390. onAnimationEnd();
  88391. }
  88392. if (_this._attachedCamera) {
  88393. _this._attachedCamera.storeState();
  88394. }
  88395. });
  88396. if (animatable) {
  88397. this._animatables.push(animatable);
  88398. }
  88399. };
  88400. /**
  88401. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  88402. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  88403. * frustum width.
  88404. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  88405. * to fully enclose the mesh in the viewing frustum.
  88406. */
  88407. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  88408. var size = maximumWorld.subtract(minimumWorld);
  88409. var boxVectorGlobalDiagonal = size.length();
  88410. var frustumSlope = this._getFrustumSlope();
  88411. // Formula for setting distance
  88412. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  88413. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  88414. // Horizon distance
  88415. var radius = radiusWithoutFraming * this._radiusScale;
  88416. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  88417. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  88418. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  88419. var camera = this._attachedCamera;
  88420. if (!camera) {
  88421. return 0;
  88422. }
  88423. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88424. // Don't exceed the requested limit
  88425. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  88426. }
  88427. // Don't exceed the upper radius limit
  88428. if (camera.upperRadiusLimit) {
  88429. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  88430. }
  88431. return distance;
  88432. };
  88433. /**
  88434. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  88435. * is automatically returned to its default position (expected to be above ground plane).
  88436. */
  88437. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  88438. var _this = this;
  88439. if (this._elevationReturnTime < 0) {
  88440. return;
  88441. }
  88442. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  88443. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  88444. var limitBeta = Math.PI * 0.5;
  88445. // Bring the camera back up if below the ground plane
  88446. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  88447. this._betaIsAnimating = true;
  88448. //Transition to new position
  88449. this.stopAllAnimations();
  88450. if (!this._betaTransition) {
  88451. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88452. }
  88453. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  88454. _this._clearAnimationLocks();
  88455. _this.stopAllAnimations();
  88456. });
  88457. if (animatabe) {
  88458. this._animatables.push(animatabe);
  88459. }
  88460. }
  88461. };
  88462. /**
  88463. * Returns the frustum slope based on the canvas ratio and camera FOV
  88464. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  88465. */
  88466. FramingBehavior.prototype._getFrustumSlope = function () {
  88467. // Calculate the viewport ratio
  88468. // Aspect Ratio is Height/Width.
  88469. var camera = this._attachedCamera;
  88470. if (!camera) {
  88471. return BABYLON.Vector2.Zero();
  88472. }
  88473. var engine = camera.getScene().getEngine();
  88474. var aspectRatio = engine.getAspectRatio(camera);
  88475. // Camera FOV is the vertical field of view (top-bottom) in radians.
  88476. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  88477. var frustumSlopeY = Math.tan(camera.fov / 2);
  88478. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  88479. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  88480. // along the forward vector.
  88481. var frustumSlopeX = frustumSlopeY * aspectRatio;
  88482. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  88483. };
  88484. /**
  88485. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  88486. */
  88487. FramingBehavior.prototype._clearAnimationLocks = function () {
  88488. this._betaIsAnimating = false;
  88489. };
  88490. /**
  88491. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88492. */
  88493. FramingBehavior.prototype._applyUserInteraction = function () {
  88494. if (this.isUserIsMoving) {
  88495. this._lastInteractionTime = BABYLON.Tools.Now;
  88496. this.stopAllAnimations();
  88497. this._clearAnimationLocks();
  88498. }
  88499. };
  88500. /**
  88501. * Stops and removes all animations that have been applied to the camera
  88502. */
  88503. FramingBehavior.prototype.stopAllAnimations = function () {
  88504. if (this._attachedCamera) {
  88505. this._attachedCamera.animations = [];
  88506. }
  88507. while (this._animatables.length) {
  88508. if (this._animatables[0]) {
  88509. this._animatables[0].onAnimationEnd = null;
  88510. this._animatables[0].stop();
  88511. }
  88512. this._animatables.shift();
  88513. }
  88514. };
  88515. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  88516. /**
  88517. * Gets a value indicating if the user is moving the camera
  88518. */
  88519. get: function () {
  88520. if (!this._attachedCamera) {
  88521. return false;
  88522. }
  88523. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88524. this._attachedCamera.inertialBetaOffset !== 0 ||
  88525. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88526. this._attachedCamera.inertialPanningX !== 0 ||
  88527. this._attachedCamera.inertialPanningY !== 0 ||
  88528. this._isPointerDown;
  88529. },
  88530. enumerable: true,
  88531. configurable: true
  88532. });
  88533. /**
  88534. * The easing function used by animations
  88535. */
  88536. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  88537. /**
  88538. * The easing mode used by animations
  88539. */
  88540. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  88541. // Statics
  88542. /**
  88543. * The camera can move all the way towards the mesh.
  88544. */
  88545. FramingBehavior.IgnoreBoundsSizeMode = 0;
  88546. /**
  88547. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  88548. */
  88549. FramingBehavior.FitFrustumSidesMode = 1;
  88550. return FramingBehavior;
  88551. }());
  88552. BABYLON.FramingBehavior = FramingBehavior;
  88553. })(BABYLON || (BABYLON = {}));
  88554. //# sourceMappingURL=babylon.framingBehavior.js.map
  88555. "use strict";
  88556. var BABYLON;
  88557. (function (BABYLON) {
  88558. /**
  88559. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  88560. */
  88561. var BouncingBehavior = /** @class */ (function () {
  88562. function BouncingBehavior() {
  88563. /**
  88564. * The duration of the animation, in milliseconds
  88565. */
  88566. this.transitionDuration = 450;
  88567. /**
  88568. * Length of the distance animated by the transition when lower radius is reached
  88569. */
  88570. this.lowerRadiusTransitionRange = 2;
  88571. /**
  88572. * Length of the distance animated by the transition when upper radius is reached
  88573. */
  88574. this.upperRadiusTransitionRange = -2;
  88575. this._autoTransitionRange = false;
  88576. // Animations
  88577. this._radiusIsAnimating = false;
  88578. this._radiusBounceTransition = null;
  88579. this._animatables = new Array();
  88580. }
  88581. Object.defineProperty(BouncingBehavior.prototype, "name", {
  88582. get: function () {
  88583. return "Bouncing";
  88584. },
  88585. enumerable: true,
  88586. configurable: true
  88587. });
  88588. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  88589. /**
  88590. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88591. */
  88592. get: function () {
  88593. return this._autoTransitionRange;
  88594. },
  88595. /**
  88596. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88597. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  88598. */
  88599. set: function (value) {
  88600. var _this = this;
  88601. if (this._autoTransitionRange === value) {
  88602. return;
  88603. }
  88604. this._autoTransitionRange = value;
  88605. var camera = this._attachedCamera;
  88606. if (!camera) {
  88607. return;
  88608. }
  88609. if (value) {
  88610. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88611. if (!mesh) {
  88612. return;
  88613. }
  88614. mesh.computeWorldMatrix(true);
  88615. var diagonal = mesh.getBoundingInfo().diagonalLength;
  88616. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  88617. _this.upperRadiusTransitionRange = diagonal * 0.05;
  88618. });
  88619. }
  88620. else if (this._onMeshTargetChangedObserver) {
  88621. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88622. }
  88623. },
  88624. enumerable: true,
  88625. configurable: true
  88626. });
  88627. BouncingBehavior.prototype.init = function () {
  88628. // Do notihng
  88629. };
  88630. BouncingBehavior.prototype.attach = function (camera) {
  88631. var _this = this;
  88632. this._attachedCamera = camera;
  88633. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88634. if (!_this._attachedCamera) {
  88635. return;
  88636. }
  88637. // Add the bounce animation to the lower radius limit
  88638. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  88639. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  88640. }
  88641. // Add the bounce animation to the upper radius limit
  88642. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  88643. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  88644. }
  88645. });
  88646. };
  88647. BouncingBehavior.prototype.detach = function () {
  88648. if (!this._attachedCamera) {
  88649. return;
  88650. }
  88651. if (this._onAfterCheckInputsObserver) {
  88652. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88653. }
  88654. if (this._onMeshTargetChangedObserver) {
  88655. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88656. }
  88657. this._attachedCamera = null;
  88658. };
  88659. /**
  88660. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  88661. * @param radiusLimit The limit to check against.
  88662. * @return Bool to indicate if at limit.
  88663. */
  88664. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  88665. if (!this._attachedCamera) {
  88666. return false;
  88667. }
  88668. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  88669. return true;
  88670. }
  88671. return false;
  88672. };
  88673. /**
  88674. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  88675. * @param radiusDelta The delta by which to animate to. Can be negative.
  88676. */
  88677. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  88678. var _this = this;
  88679. if (!this._attachedCamera) {
  88680. return;
  88681. }
  88682. if (!this._radiusBounceTransition) {
  88683. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  88684. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  88685. }
  88686. // Prevent zoom until bounce has completed
  88687. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  88688. this._attachedCamera.wheelPrecision = Infinity;
  88689. this._attachedCamera.inertialRadiusOffset = 0;
  88690. // Animate to the radius limit
  88691. this.stopAllAnimations();
  88692. this._radiusIsAnimating = true;
  88693. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  88694. if (animatable) {
  88695. this._animatables.push(animatable);
  88696. }
  88697. };
  88698. /**
  88699. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  88700. */
  88701. BouncingBehavior.prototype._clearAnimationLocks = function () {
  88702. this._radiusIsAnimating = false;
  88703. if (this._attachedCamera) {
  88704. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  88705. }
  88706. };
  88707. /**
  88708. * Stops and removes all animations that have been applied to the camera
  88709. */
  88710. BouncingBehavior.prototype.stopAllAnimations = function () {
  88711. if (this._attachedCamera) {
  88712. this._attachedCamera.animations = [];
  88713. }
  88714. while (this._animatables.length) {
  88715. this._animatables[0].onAnimationEnd = null;
  88716. this._animatables[0].stop();
  88717. this._animatables.shift();
  88718. }
  88719. };
  88720. /**
  88721. * The easing function used by animations
  88722. */
  88723. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  88724. /**
  88725. * The easing mode used by animations
  88726. */
  88727. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  88728. return BouncingBehavior;
  88729. }());
  88730. BABYLON.BouncingBehavior = BouncingBehavior;
  88731. })(BABYLON || (BABYLON = {}));
  88732. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  88733. "use strict";
  88734. var BABYLON;
  88735. (function (BABYLON) {
  88736. var AutoRotationBehavior = /** @class */ (function () {
  88737. function AutoRotationBehavior() {
  88738. this._zoomStopsAnimation = false;
  88739. this._idleRotationSpeed = 0.05;
  88740. this._idleRotationWaitTime = 2000;
  88741. this._idleRotationSpinupTime = 2000;
  88742. this._isPointerDown = false;
  88743. this._lastFrameTime = null;
  88744. this._lastInteractionTime = -Infinity;
  88745. this._cameraRotationSpeed = 0;
  88746. this._lastFrameRadius = 0;
  88747. }
  88748. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  88749. get: function () {
  88750. return "AutoRotation";
  88751. },
  88752. enumerable: true,
  88753. configurable: true
  88754. });
  88755. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  88756. /**
  88757. * Gets the flag that indicates if user zooming should stop animation.
  88758. */
  88759. get: function () {
  88760. return this._zoomStopsAnimation;
  88761. },
  88762. /**
  88763. * Sets the flag that indicates if user zooming should stop animation.
  88764. */
  88765. set: function (flag) {
  88766. this._zoomStopsAnimation = flag;
  88767. },
  88768. enumerable: true,
  88769. configurable: true
  88770. });
  88771. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  88772. /**
  88773. * Gets the default speed at which the camera rotates around the model.
  88774. */
  88775. get: function () {
  88776. return this._idleRotationSpeed;
  88777. },
  88778. /**
  88779. * Sets the default speed at which the camera rotates around the model.
  88780. */
  88781. set: function (speed) {
  88782. this._idleRotationSpeed = speed;
  88783. },
  88784. enumerable: true,
  88785. configurable: true
  88786. });
  88787. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  88788. /**
  88789. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  88790. */
  88791. get: function () {
  88792. return this._idleRotationWaitTime;
  88793. },
  88794. /**
  88795. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  88796. */
  88797. set: function (time) {
  88798. this._idleRotationWaitTime = time;
  88799. },
  88800. enumerable: true,
  88801. configurable: true
  88802. });
  88803. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  88804. /**
  88805. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88806. */
  88807. get: function () {
  88808. return this._idleRotationSpinupTime;
  88809. },
  88810. /**
  88811. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88812. */
  88813. set: function (time) {
  88814. this._idleRotationSpinupTime = time;
  88815. },
  88816. enumerable: true,
  88817. configurable: true
  88818. });
  88819. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  88820. /**
  88821. * Gets a value indicating if the camera is currently rotating because of this behavior
  88822. */
  88823. get: function () {
  88824. return Math.abs(this._cameraRotationSpeed) > 0;
  88825. },
  88826. enumerable: true,
  88827. configurable: true
  88828. });
  88829. AutoRotationBehavior.prototype.init = function () {
  88830. // Do notihng
  88831. };
  88832. AutoRotationBehavior.prototype.attach = function (camera) {
  88833. var _this = this;
  88834. this._attachedCamera = camera;
  88835. var scene = this._attachedCamera.getScene();
  88836. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88837. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88838. _this._isPointerDown = true;
  88839. return;
  88840. }
  88841. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88842. _this._isPointerDown = false;
  88843. }
  88844. });
  88845. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88846. var now = BABYLON.Tools.Now;
  88847. var dt = 0;
  88848. if (_this._lastFrameTime != null) {
  88849. dt = now - _this._lastFrameTime;
  88850. }
  88851. _this._lastFrameTime = now;
  88852. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88853. _this._applyUserInteraction();
  88854. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  88855. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  88856. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  88857. // Step camera rotation by rotation speed
  88858. if (_this._attachedCamera) {
  88859. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  88860. }
  88861. });
  88862. };
  88863. AutoRotationBehavior.prototype.detach = function () {
  88864. if (!this._attachedCamera) {
  88865. return;
  88866. }
  88867. var scene = this._attachedCamera.getScene();
  88868. if (this._onPrePointerObservableObserver) {
  88869. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88870. }
  88871. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88872. this._attachedCamera = null;
  88873. };
  88874. /**
  88875. * Returns true if user is scrolling.
  88876. * @return true if user is scrolling.
  88877. */
  88878. AutoRotationBehavior.prototype._userIsZooming = function () {
  88879. if (!this._attachedCamera) {
  88880. return false;
  88881. }
  88882. return this._attachedCamera.inertialRadiusOffset !== 0;
  88883. };
  88884. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  88885. if (!this._attachedCamera) {
  88886. return false;
  88887. }
  88888. var zoomHasHitLimit = false;
  88889. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  88890. zoomHasHitLimit = true;
  88891. }
  88892. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  88893. this._lastFrameRadius = this._attachedCamera.radius;
  88894. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  88895. };
  88896. /**
  88897. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88898. */
  88899. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  88900. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  88901. this._lastInteractionTime = BABYLON.Tools.Now;
  88902. }
  88903. };
  88904. // Tools
  88905. AutoRotationBehavior.prototype._userIsMoving = function () {
  88906. if (!this._attachedCamera) {
  88907. return false;
  88908. }
  88909. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88910. this._attachedCamera.inertialBetaOffset !== 0 ||
  88911. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88912. this._attachedCamera.inertialPanningX !== 0 ||
  88913. this._attachedCamera.inertialPanningY !== 0 ||
  88914. this._isPointerDown;
  88915. };
  88916. return AutoRotationBehavior;
  88917. }());
  88918. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  88919. })(BABYLON || (BABYLON = {}));
  88920. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  88921. "use strict";
  88922. var BABYLON;
  88923. (function (BABYLON) {
  88924. /**
  88925. * This class can be used to get instrumentation data from a Babylon engine
  88926. */
  88927. var EngineInstrumentation = /** @class */ (function () {
  88928. function EngineInstrumentation(engine) {
  88929. this.engine = engine;
  88930. this._captureGPUFrameTime = false;
  88931. this._gpuFrameTime = new BABYLON.PerfCounter();
  88932. this._captureShaderCompilationTime = false;
  88933. this._shaderCompilationTime = new BABYLON.PerfCounter();
  88934. // Observers
  88935. this._onBeginFrameObserver = null;
  88936. this._onEndFrameObserver = null;
  88937. this._onBeforeShaderCompilationObserver = null;
  88938. this._onAfterShaderCompilationObserver = null;
  88939. }
  88940. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  88941. // Properties
  88942. /**
  88943. * Gets the perf counter used for GPU frame time
  88944. */
  88945. get: function () {
  88946. return this._gpuFrameTime;
  88947. },
  88948. enumerable: true,
  88949. configurable: true
  88950. });
  88951. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  88952. /**
  88953. * Gets the GPU frame time capture status
  88954. */
  88955. get: function () {
  88956. return this._captureGPUFrameTime;
  88957. },
  88958. /**
  88959. * Enable or disable the GPU frame time capture
  88960. */
  88961. set: function (value) {
  88962. var _this = this;
  88963. if (value === this._captureGPUFrameTime) {
  88964. return;
  88965. }
  88966. this._captureGPUFrameTime = value;
  88967. if (value) {
  88968. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  88969. if (!_this._gpuFrameTimeToken) {
  88970. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  88971. }
  88972. });
  88973. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  88974. if (!_this._gpuFrameTimeToken) {
  88975. return;
  88976. }
  88977. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  88978. if (time > -1) {
  88979. _this._gpuFrameTimeToken = null;
  88980. _this._gpuFrameTime.fetchNewFrame();
  88981. _this._gpuFrameTime.addCount(time, true);
  88982. }
  88983. });
  88984. }
  88985. else {
  88986. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  88987. this._onBeginFrameObserver = null;
  88988. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  88989. this._onEndFrameObserver = null;
  88990. }
  88991. },
  88992. enumerable: true,
  88993. configurable: true
  88994. });
  88995. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  88996. /**
  88997. * Gets the perf counter used for shader compilation time
  88998. */
  88999. get: function () {
  89000. return this._shaderCompilationTime;
  89001. },
  89002. enumerable: true,
  89003. configurable: true
  89004. });
  89005. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  89006. /**
  89007. * Gets the shader compilation time capture status
  89008. */
  89009. get: function () {
  89010. return this._captureShaderCompilationTime;
  89011. },
  89012. /**
  89013. * Enable or disable the shader compilation time capture
  89014. */
  89015. set: function (value) {
  89016. var _this = this;
  89017. if (value === this._captureShaderCompilationTime) {
  89018. return;
  89019. }
  89020. this._captureShaderCompilationTime = value;
  89021. if (value) {
  89022. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  89023. _this._shaderCompilationTime.fetchNewFrame();
  89024. _this._shaderCompilationTime.beginMonitoring();
  89025. });
  89026. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  89027. _this._shaderCompilationTime.endMonitoring();
  89028. });
  89029. }
  89030. else {
  89031. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89032. this._onBeforeShaderCompilationObserver = null;
  89033. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89034. this._onAfterShaderCompilationObserver = null;
  89035. }
  89036. },
  89037. enumerable: true,
  89038. configurable: true
  89039. });
  89040. EngineInstrumentation.prototype.dispose = function () {
  89041. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89042. this._onBeginFrameObserver = null;
  89043. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89044. this._onEndFrameObserver = null;
  89045. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89046. this._onBeforeShaderCompilationObserver = null;
  89047. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89048. this._onAfterShaderCompilationObserver = null;
  89049. this.engine = null;
  89050. };
  89051. return EngineInstrumentation;
  89052. }());
  89053. BABYLON.EngineInstrumentation = EngineInstrumentation;
  89054. })(BABYLON || (BABYLON = {}));
  89055. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  89056. "use strict";
  89057. var BABYLON;
  89058. (function (BABYLON) {
  89059. /**
  89060. * This class can be used to get instrumentation data from a Babylon engine
  89061. */
  89062. var SceneInstrumentation = /** @class */ (function () {
  89063. function SceneInstrumentation(scene) {
  89064. var _this = this;
  89065. this.scene = scene;
  89066. this._captureActiveMeshesEvaluationTime = false;
  89067. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  89068. this._captureRenderTargetsRenderTime = false;
  89069. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  89070. this._captureFrameTime = false;
  89071. this._frameTime = new BABYLON.PerfCounter();
  89072. this._captureRenderTime = false;
  89073. this._renderTime = new BABYLON.PerfCounter();
  89074. this._captureInterFrameTime = false;
  89075. this._interFrameTime = new BABYLON.PerfCounter();
  89076. this._captureParticlesRenderTime = false;
  89077. this._particlesRenderTime = new BABYLON.PerfCounter();
  89078. this._captureSpritesRenderTime = false;
  89079. this._spritesRenderTime = new BABYLON.PerfCounter();
  89080. this._capturePhysicsTime = false;
  89081. this._physicsTime = new BABYLON.PerfCounter();
  89082. this._captureAnimationsTime = false;
  89083. this._animationsTime = new BABYLON.PerfCounter();
  89084. // Observers
  89085. this._onBeforeActiveMeshesEvaluationObserver = null;
  89086. this._onAfterActiveMeshesEvaluationObserver = null;
  89087. this._onBeforeRenderTargetsRenderObserver = null;
  89088. this._onAfterRenderTargetsRenderObserver = null;
  89089. this._onAfterRenderObserver = null;
  89090. this._onBeforeDrawPhaseObserver = null;
  89091. this._onAfterDrawPhaseObserver = null;
  89092. this._onBeforeAnimationsObserver = null;
  89093. this._onBeforeParticlesRenderingObserver = null;
  89094. this._onAfterParticlesRenderingObserver = null;
  89095. this._onBeforeSpritesRenderingObserver = null;
  89096. this._onAfterSpritesRenderingObserver = null;
  89097. this._onBeforePhysicsObserver = null;
  89098. this._onAfterPhysicsObserver = null;
  89099. this._onAfterAnimationsObserver = null;
  89100. // Before render
  89101. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  89102. if (_this._captureActiveMeshesEvaluationTime) {
  89103. _this._activeMeshesEvaluationTime.fetchNewFrame();
  89104. }
  89105. if (_this._captureRenderTargetsRenderTime) {
  89106. _this._renderTargetsRenderTime.fetchNewFrame();
  89107. }
  89108. if (_this._captureFrameTime) {
  89109. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  89110. _this._frameTime.beginMonitoring();
  89111. }
  89112. if (_this._captureInterFrameTime) {
  89113. _this._interFrameTime.endMonitoring();
  89114. }
  89115. if (_this._captureParticlesRenderTime) {
  89116. _this._particlesRenderTime.fetchNewFrame();
  89117. }
  89118. if (_this._captureSpritesRenderTime) {
  89119. _this._spritesRenderTime.fetchNewFrame();
  89120. }
  89121. if (_this._captureAnimationsTime) {
  89122. _this._animationsTime.beginMonitoring();
  89123. }
  89124. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  89125. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  89126. });
  89127. // After render
  89128. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  89129. if (_this._captureFrameTime) {
  89130. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  89131. _this._frameTime.endMonitoring();
  89132. }
  89133. if (_this._captureRenderTime) {
  89134. _this._renderTime.endMonitoring(false);
  89135. }
  89136. if (_this._captureInterFrameTime) {
  89137. _this._interFrameTime.beginMonitoring();
  89138. }
  89139. });
  89140. }
  89141. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  89142. // Properties
  89143. /**
  89144. * Gets the perf counter used for active meshes evaluation time
  89145. */
  89146. get: function () {
  89147. return this._activeMeshesEvaluationTime;
  89148. },
  89149. enumerable: true,
  89150. configurable: true
  89151. });
  89152. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  89153. /**
  89154. * Gets the active meshes evaluation time capture status
  89155. */
  89156. get: function () {
  89157. return this._captureActiveMeshesEvaluationTime;
  89158. },
  89159. /**
  89160. * Enable or disable the active meshes evaluation time capture
  89161. */
  89162. set: function (value) {
  89163. var _this = this;
  89164. if (value === this._captureActiveMeshesEvaluationTime) {
  89165. return;
  89166. }
  89167. this._captureActiveMeshesEvaluationTime = value;
  89168. if (value) {
  89169. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  89170. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  89171. _this._activeMeshesEvaluationTime.beginMonitoring();
  89172. });
  89173. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  89174. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  89175. _this._activeMeshesEvaluationTime.endMonitoring();
  89176. });
  89177. }
  89178. else {
  89179. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89180. this._onBeforeActiveMeshesEvaluationObserver = null;
  89181. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89182. this._onAfterActiveMeshesEvaluationObserver = null;
  89183. }
  89184. },
  89185. enumerable: true,
  89186. configurable: true
  89187. });
  89188. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  89189. /**
  89190. * Gets the perf counter used for render targets render time
  89191. */
  89192. get: function () {
  89193. return this._renderTargetsRenderTime;
  89194. },
  89195. enumerable: true,
  89196. configurable: true
  89197. });
  89198. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  89199. /**
  89200. * Gets the render targets render time capture status
  89201. */
  89202. get: function () {
  89203. return this._captureRenderTargetsRenderTime;
  89204. },
  89205. /**
  89206. * Enable or disable the render targets render time capture
  89207. */
  89208. set: function (value) {
  89209. var _this = this;
  89210. if (value === this._captureRenderTargetsRenderTime) {
  89211. return;
  89212. }
  89213. this._captureRenderTargetsRenderTime = value;
  89214. if (value) {
  89215. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  89216. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  89217. _this._renderTargetsRenderTime.beginMonitoring();
  89218. });
  89219. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  89220. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  89221. _this._renderTargetsRenderTime.endMonitoring(false);
  89222. });
  89223. }
  89224. else {
  89225. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89226. this._onBeforeRenderTargetsRenderObserver = null;
  89227. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89228. this._onAfterRenderTargetsRenderObserver = null;
  89229. }
  89230. },
  89231. enumerable: true,
  89232. configurable: true
  89233. });
  89234. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  89235. /**
  89236. * Gets the perf counter used for particles render time
  89237. */
  89238. get: function () {
  89239. return this._particlesRenderTime;
  89240. },
  89241. enumerable: true,
  89242. configurable: true
  89243. });
  89244. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  89245. /**
  89246. * Gets the particles render time capture status
  89247. */
  89248. get: function () {
  89249. return this._captureParticlesRenderTime;
  89250. },
  89251. /**
  89252. * Enable or disable the particles render time capture
  89253. */
  89254. set: function (value) {
  89255. var _this = this;
  89256. if (value === this._captureParticlesRenderTime) {
  89257. return;
  89258. }
  89259. this._captureParticlesRenderTime = value;
  89260. if (value) {
  89261. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  89262. BABYLON.Tools.StartPerformanceCounter("Particles");
  89263. _this._particlesRenderTime.beginMonitoring();
  89264. });
  89265. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  89266. BABYLON.Tools.EndPerformanceCounter("Particles");
  89267. _this._particlesRenderTime.endMonitoring(false);
  89268. });
  89269. }
  89270. else {
  89271. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89272. this._onBeforeParticlesRenderingObserver = null;
  89273. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89274. this._onAfterParticlesRenderingObserver = null;
  89275. }
  89276. },
  89277. enumerable: true,
  89278. configurable: true
  89279. });
  89280. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  89281. /**
  89282. * Gets the perf counter used for sprites render time
  89283. */
  89284. get: function () {
  89285. return this._spritesRenderTime;
  89286. },
  89287. enumerable: true,
  89288. configurable: true
  89289. });
  89290. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  89291. /**
  89292. * Gets the sprites render time capture status
  89293. */
  89294. get: function () {
  89295. return this._captureSpritesRenderTime;
  89296. },
  89297. /**
  89298. * Enable or disable the sprites render time capture
  89299. */
  89300. set: function (value) {
  89301. var _this = this;
  89302. if (value === this._captureSpritesRenderTime) {
  89303. return;
  89304. }
  89305. this._captureSpritesRenderTime = value;
  89306. if (value) {
  89307. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  89308. BABYLON.Tools.StartPerformanceCounter("Sprites");
  89309. _this._spritesRenderTime.beginMonitoring();
  89310. });
  89311. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  89312. BABYLON.Tools.EndPerformanceCounter("Sprites");
  89313. _this._spritesRenderTime.endMonitoring(false);
  89314. });
  89315. }
  89316. else {
  89317. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89318. this._onBeforeSpritesRenderingObserver = null;
  89319. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89320. this._onAfterSpritesRenderingObserver = null;
  89321. }
  89322. },
  89323. enumerable: true,
  89324. configurable: true
  89325. });
  89326. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  89327. /**
  89328. * Gets the perf counter used for physics time
  89329. */
  89330. get: function () {
  89331. return this._physicsTime;
  89332. },
  89333. enumerable: true,
  89334. configurable: true
  89335. });
  89336. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  89337. /**
  89338. * Gets the physics time capture status
  89339. */
  89340. get: function () {
  89341. return this._capturePhysicsTime;
  89342. },
  89343. /**
  89344. * Enable or disable the physics time capture
  89345. */
  89346. set: function (value) {
  89347. var _this = this;
  89348. if (value === this._capturePhysicsTime) {
  89349. return;
  89350. }
  89351. this._capturePhysicsTime = value;
  89352. if (value) {
  89353. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  89354. BABYLON.Tools.StartPerformanceCounter("Physics");
  89355. _this._physicsTime.beginMonitoring();
  89356. });
  89357. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  89358. BABYLON.Tools.EndPerformanceCounter("Physics");
  89359. _this._physicsTime.endMonitoring();
  89360. });
  89361. }
  89362. else {
  89363. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89364. this._onBeforePhysicsObserver = null;
  89365. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89366. this._onAfterPhysicsObserver = null;
  89367. }
  89368. },
  89369. enumerable: true,
  89370. configurable: true
  89371. });
  89372. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  89373. /**
  89374. * Gets the perf counter used for animations time
  89375. */
  89376. get: function () {
  89377. return this._animationsTime;
  89378. },
  89379. enumerable: true,
  89380. configurable: true
  89381. });
  89382. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  89383. /**
  89384. * Gets the animations time capture status
  89385. */
  89386. get: function () {
  89387. return this._captureAnimationsTime;
  89388. },
  89389. /**
  89390. * Enable or disable the animations time capture
  89391. */
  89392. set: function (value) {
  89393. var _this = this;
  89394. if (value === this._captureAnimationsTime) {
  89395. return;
  89396. }
  89397. this._captureAnimationsTime = value;
  89398. if (value) {
  89399. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  89400. _this._animationsTime.endMonitoring();
  89401. });
  89402. }
  89403. else {
  89404. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89405. this._onAfterAnimationsObserver = null;
  89406. }
  89407. },
  89408. enumerable: true,
  89409. configurable: true
  89410. });
  89411. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  89412. /**
  89413. * Gets the perf counter used for frame time capture
  89414. */
  89415. get: function () {
  89416. return this._frameTime;
  89417. },
  89418. enumerable: true,
  89419. configurable: true
  89420. });
  89421. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  89422. /**
  89423. * Gets the frame time capture status
  89424. */
  89425. get: function () {
  89426. return this._captureFrameTime;
  89427. },
  89428. /**
  89429. * Enable or disable the frame time capture
  89430. */
  89431. set: function (value) {
  89432. this._captureFrameTime = value;
  89433. },
  89434. enumerable: true,
  89435. configurable: true
  89436. });
  89437. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  89438. /**
  89439. * Gets the perf counter used for inter-frames time capture
  89440. */
  89441. get: function () {
  89442. return this._interFrameTime;
  89443. },
  89444. enumerable: true,
  89445. configurable: true
  89446. });
  89447. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  89448. /**
  89449. * Gets the inter-frames time capture status
  89450. */
  89451. get: function () {
  89452. return this._captureInterFrameTime;
  89453. },
  89454. /**
  89455. * Enable or disable the inter-frames time capture
  89456. */
  89457. set: function (value) {
  89458. this._captureInterFrameTime = value;
  89459. },
  89460. enumerable: true,
  89461. configurable: true
  89462. });
  89463. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  89464. /**
  89465. * Gets the perf counter used for render time capture
  89466. */
  89467. get: function () {
  89468. return this._renderTime;
  89469. },
  89470. enumerable: true,
  89471. configurable: true
  89472. });
  89473. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  89474. /**
  89475. * Gets the render time capture status
  89476. */
  89477. get: function () {
  89478. return this._captureRenderTime;
  89479. },
  89480. /**
  89481. * Enable or disable the render time capture
  89482. */
  89483. set: function (value) {
  89484. var _this = this;
  89485. if (value === this._captureRenderTime) {
  89486. return;
  89487. }
  89488. this._captureRenderTime = value;
  89489. if (value) {
  89490. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  89491. _this._renderTime.beginMonitoring();
  89492. BABYLON.Tools.StartPerformanceCounter("Main render");
  89493. });
  89494. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  89495. _this._renderTime.endMonitoring(false);
  89496. BABYLON.Tools.EndPerformanceCounter("Main render");
  89497. });
  89498. }
  89499. else {
  89500. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89501. this._onBeforeDrawPhaseObserver = null;
  89502. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89503. this._onAfterDrawPhaseObserver = null;
  89504. }
  89505. },
  89506. enumerable: true,
  89507. configurable: true
  89508. });
  89509. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  89510. /**
  89511. * Gets the perf counter used for draw calls
  89512. */
  89513. get: function () {
  89514. return this.scene.getEngine()._drawCalls;
  89515. },
  89516. enumerable: true,
  89517. configurable: true
  89518. });
  89519. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  89520. /**
  89521. * Gets the perf counter used for texture collisions
  89522. */
  89523. get: function () {
  89524. return this.scene.getEngine()._textureCollisions;
  89525. },
  89526. enumerable: true,
  89527. configurable: true
  89528. });
  89529. SceneInstrumentation.prototype.dispose = function () {
  89530. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89531. this._onAfterRenderObserver = null;
  89532. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89533. this._onBeforeActiveMeshesEvaluationObserver = null;
  89534. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89535. this._onAfterActiveMeshesEvaluationObserver = null;
  89536. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89537. this._onBeforeRenderTargetsRenderObserver = null;
  89538. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89539. this._onAfterRenderTargetsRenderObserver = null;
  89540. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  89541. this._onBeforeAnimationsObserver = null;
  89542. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89543. this._onBeforeParticlesRenderingObserver = null;
  89544. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89545. this._onAfterParticlesRenderingObserver = null;
  89546. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89547. this._onBeforeSpritesRenderingObserver = null;
  89548. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89549. this._onAfterSpritesRenderingObserver = null;
  89550. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89551. this._onBeforeDrawPhaseObserver = null;
  89552. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89553. this._onAfterDrawPhaseObserver = null;
  89554. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89555. this._onBeforePhysicsObserver = null;
  89556. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89557. this._onAfterPhysicsObserver = null;
  89558. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89559. this._onAfterAnimationsObserver = null;
  89560. this.scene = null;
  89561. };
  89562. return SceneInstrumentation;
  89563. }());
  89564. BABYLON.SceneInstrumentation = SceneInstrumentation;
  89565. })(BABYLON || (BABYLON = {}));
  89566. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  89567. "use strict";
  89568. var BABYLON;
  89569. (function (BABYLON) {
  89570. var _TimeToken = /** @class */ (function () {
  89571. function _TimeToken() {
  89572. this._timeElapsedQueryEnded = false;
  89573. }
  89574. return _TimeToken;
  89575. }());
  89576. BABYLON._TimeToken = _TimeToken;
  89577. })(BABYLON || (BABYLON = {}));
  89578. //# sourceMappingURL=babylon.timeToken.js.map
  89579. "use strict";
  89580. var BABYLON;
  89581. (function (BABYLON) {
  89582. /**
  89583. * Background material defines definition.
  89584. * @ignore Mainly internal Use
  89585. */
  89586. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  89587. __extends(BackgroundMaterialDefines, _super);
  89588. /**
  89589. * Constructor of the defines.
  89590. */
  89591. function BackgroundMaterialDefines() {
  89592. var _this = _super.call(this) || this;
  89593. /**
  89594. * True if the diffuse texture is in use.
  89595. */
  89596. _this.DIFFUSE = false;
  89597. /**
  89598. * The direct UV channel to use.
  89599. */
  89600. _this.DIFFUSEDIRECTUV = 0;
  89601. /**
  89602. * True if the diffuse texture is in gamma space.
  89603. */
  89604. _this.GAMMADIFFUSE = false;
  89605. /**
  89606. * True if the diffuse texture has opacity in the alpha channel.
  89607. */
  89608. _this.DIFFUSEHASALPHA = false;
  89609. /**
  89610. * True if you want the material to fade to transparent at grazing angle.
  89611. */
  89612. _this.OPACITYFRESNEL = false;
  89613. /**
  89614. * True if an extra blur needs to be added in the reflection.
  89615. */
  89616. _this.REFLECTIONBLUR = false;
  89617. /**
  89618. * True if you want the material to fade to reflection at grazing angle.
  89619. */
  89620. _this.REFLECTIONFRESNEL = false;
  89621. /**
  89622. * True if you want the material to falloff as far as you move away from the scene center.
  89623. */
  89624. _this.REFLECTIONFALLOFF = false;
  89625. /**
  89626. * False if the current Webgl implementation does not support the texture lod extension.
  89627. */
  89628. _this.TEXTURELODSUPPORT = false;
  89629. /**
  89630. * True to ensure the data are premultiplied.
  89631. */
  89632. _this.PREMULTIPLYALPHA = false;
  89633. /**
  89634. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  89635. */
  89636. _this.USERGBCOLOR = false;
  89637. /**
  89638. * True to add noise in order to reduce the banding effect.
  89639. */
  89640. _this.NOISE = false;
  89641. /**
  89642. * is the reflection texture in BGR color scheme?
  89643. * Mainly used to solve a bug in ios10 video tag
  89644. */
  89645. _this.REFLECTIONBGR = false;
  89646. _this.IMAGEPROCESSING = false;
  89647. _this.VIGNETTE = false;
  89648. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  89649. _this.VIGNETTEBLENDMODEOPAQUE = false;
  89650. _this.TONEMAPPING = false;
  89651. _this.CONTRAST = false;
  89652. _this.COLORCURVES = false;
  89653. _this.COLORGRADING = false;
  89654. _this.COLORGRADING3D = false;
  89655. _this.SAMPLER3DGREENDEPTH = false;
  89656. _this.SAMPLER3DBGRMAP = false;
  89657. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  89658. _this.EXPOSURE = false;
  89659. _this.GRAIN = false;
  89660. // Reflection.
  89661. _this.REFLECTION = false;
  89662. _this.REFLECTIONMAP_3D = false;
  89663. _this.REFLECTIONMAP_SPHERICAL = false;
  89664. _this.REFLECTIONMAP_PLANAR = false;
  89665. _this.REFLECTIONMAP_CUBIC = false;
  89666. _this.REFLECTIONMAP_PROJECTION = false;
  89667. _this.REFLECTIONMAP_SKYBOX = false;
  89668. _this.REFLECTIONMAP_EXPLICIT = false;
  89669. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89670. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89671. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89672. _this.INVERTCUBICMAP = false;
  89673. _this.REFLECTIONMAP_OPPOSITEZ = false;
  89674. _this.LODINREFLECTIONALPHA = false;
  89675. _this.GAMMAREFLECTION = false;
  89676. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  89677. // Default BJS.
  89678. _this.MAINUV1 = false;
  89679. _this.MAINUV2 = false;
  89680. _this.UV1 = false;
  89681. _this.UV2 = false;
  89682. _this.CLIPPLANE = false;
  89683. _this.POINTSIZE = false;
  89684. _this.FOG = false;
  89685. _this.NORMAL = false;
  89686. _this.NUM_BONE_INFLUENCERS = 0;
  89687. _this.BonesPerMesh = 0;
  89688. _this.INSTANCES = false;
  89689. _this.SHADOWFLOAT = false;
  89690. _this.rebuild();
  89691. return _this;
  89692. }
  89693. return BackgroundMaterialDefines;
  89694. }(BABYLON.MaterialDefines));
  89695. /**
  89696. * Background material used to create an efficient environement around your scene.
  89697. */
  89698. var BackgroundMaterial = /** @class */ (function (_super) {
  89699. __extends(BackgroundMaterial, _super);
  89700. /**
  89701. * Instantiates a Background Material in the given scene
  89702. * @param name The friendly name of the material
  89703. * @param scene The scene to add the material to
  89704. */
  89705. function BackgroundMaterial(name, scene) {
  89706. var _this = _super.call(this, name, scene) || this;
  89707. /**
  89708. * Key light Color (multiply against the R channel of the environement texture)
  89709. */
  89710. _this.primaryColor = BABYLON.Color3.White();
  89711. /**
  89712. * Key light Level (allowing HDR output of the background)
  89713. */
  89714. _this.primaryLevel = 1;
  89715. /**
  89716. * Secondary light Color (multiply against the G channel of the environement texture)
  89717. */
  89718. _this.secondaryColor = BABYLON.Color3.Gray();
  89719. /**
  89720. * Secondary light Level (allowing HDR output of the background)
  89721. */
  89722. _this.secondaryLevel = 1;
  89723. /**
  89724. * Tertiary light Color (multiply against the B channel of the environement texture)
  89725. */
  89726. _this.tertiaryColor = BABYLON.Color3.Black();
  89727. /**
  89728. * Tertiary light Level (allowing HDR output of the background)
  89729. */
  89730. _this.tertiaryLevel = 1;
  89731. /**
  89732. * Reflection Texture used in the material.
  89733. * Should be author in a specific way for the best result (refer to the documentation).
  89734. */
  89735. _this.reflectionTexture = null;
  89736. /**
  89737. * Reflection Texture level of blur.
  89738. *
  89739. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  89740. * texture twice.
  89741. */
  89742. _this.reflectionBlur = 0;
  89743. /**
  89744. * Diffuse Texture used in the material.
  89745. * Should be author in a specific way for the best result (refer to the documentation).
  89746. */
  89747. _this.diffuseTexture = null;
  89748. _this._shadowLights = null;
  89749. /**
  89750. * Specify the list of lights casting shadow on the material.
  89751. * All scene shadow lights will be included if null.
  89752. */
  89753. _this.shadowLights = null;
  89754. /**
  89755. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  89756. * soft lighting on the background.
  89757. */
  89758. _this.shadowBlurScale = 1;
  89759. /**
  89760. * Helps adjusting the shadow to a softer level if required.
  89761. * 0 means black shadows and 1 means no shadows.
  89762. */
  89763. _this.shadowLevel = 0;
  89764. /**
  89765. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  89766. * It is usually zero but might be interesting to modify according to your setup.
  89767. */
  89768. _this.sceneCenter = BABYLON.Vector3.Zero();
  89769. /**
  89770. * This helps specifying that the material is falling off to the sky box at grazing angle.
  89771. * This helps ensuring a nice transition when the camera goes under the ground.
  89772. */
  89773. _this.opacityFresnel = true;
  89774. /**
  89775. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  89776. * This helps adding a mirror texture on the ground.
  89777. */
  89778. _this.reflectionFresnel = false;
  89779. /**
  89780. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  89781. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  89782. */
  89783. _this.reflectionFalloffDistance = 0.0;
  89784. /**
  89785. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  89786. */
  89787. _this.reflectionAmount = 1.0;
  89788. /**
  89789. * This specifies the weight of the reflection at grazing angle.
  89790. */
  89791. _this.reflectionReflectance0 = 0.05;
  89792. /**
  89793. * This specifies the weight of the reflection at a perpendicular point of view.
  89794. */
  89795. _this.reflectionReflectance90 = 0.5;
  89796. /**
  89797. * Helps to directly use the maps channels instead of their level.
  89798. */
  89799. _this.useRGBColor = true;
  89800. /**
  89801. * This helps reducing the banding effect that could occur on the background.
  89802. */
  89803. _this.enableNoise = false;
  89804. _this._fovMultiplier = 1.0;
  89805. /**
  89806. * Enable the FOV adjustment feature controlled by fovMultiplier.
  89807. * @type {boolean}
  89808. */
  89809. _this.useEquirectangularFOV = false;
  89810. _this._maxSimultaneousLights = 4;
  89811. /**
  89812. * Number of Simultaneous lights allowed on the material.
  89813. */
  89814. _this.maxSimultaneousLights = 4;
  89815. /**
  89816. * Keep track of the image processing observer to allow dispose and replace.
  89817. */
  89818. _this._imageProcessingObserver = null;
  89819. /**
  89820. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  89821. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  89822. */
  89823. _this.switchToBGR = false;
  89824. // Temp values kept as cache in the material.
  89825. _this._renderTargets = new BABYLON.SmartArray(16);
  89826. _this._reflectionControls = BABYLON.Vector4.Zero();
  89827. // Setup the default processing configuration to the scene.
  89828. _this._attachImageProcessingConfiguration(null);
  89829. _this.getRenderTargetTextures = function () {
  89830. _this._renderTargets.reset();
  89831. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  89832. _this._renderTargets.push(_this._diffuseTexture);
  89833. }
  89834. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  89835. _this._renderTargets.push(_this._reflectionTexture);
  89836. }
  89837. return _this._renderTargets;
  89838. };
  89839. return _this;
  89840. }
  89841. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  89842. /**
  89843. * Sets the reflection reflectance fresnel values according to the default standard
  89844. * empirically know to work well :-)
  89845. */
  89846. set: function (value) {
  89847. var reflectionWeight = value;
  89848. if (reflectionWeight < 0.5) {
  89849. reflectionWeight = reflectionWeight * 2.0;
  89850. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  89851. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  89852. }
  89853. else {
  89854. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  89855. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  89856. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  89857. }
  89858. },
  89859. enumerable: true,
  89860. configurable: true
  89861. });
  89862. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  89863. /**
  89864. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  89865. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  89866. * Recommended to be keep at 1.0 except for special cases.
  89867. */
  89868. get: function () {
  89869. return this._fovMultiplier;
  89870. },
  89871. set: function (value) {
  89872. if (isNaN(value)) {
  89873. value = 1.0;
  89874. }
  89875. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  89876. },
  89877. enumerable: true,
  89878. configurable: true
  89879. });
  89880. /**
  89881. * Attaches a new image processing configuration to the PBR Material.
  89882. * @param configuration (if null the scene configuration will be use)
  89883. */
  89884. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  89885. var _this = this;
  89886. if (configuration === this._imageProcessingConfiguration) {
  89887. return;
  89888. }
  89889. // Detaches observer.
  89890. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89891. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89892. }
  89893. // Pick the scene configuration if needed.
  89894. if (!configuration) {
  89895. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  89896. }
  89897. else {
  89898. this._imageProcessingConfiguration = configuration;
  89899. }
  89900. // Attaches observer.
  89901. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  89902. _this._markAllSubMeshesAsImageProcessingDirty();
  89903. });
  89904. };
  89905. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  89906. /**
  89907. * Gets the image processing configuration used either in this material.
  89908. */
  89909. get: function () {
  89910. return this._imageProcessingConfiguration;
  89911. },
  89912. /**
  89913. * Sets the Default image processing configuration used either in the this material.
  89914. *
  89915. * If sets to null, the scene one is in use.
  89916. */
  89917. set: function (value) {
  89918. this._attachImageProcessingConfiguration(value);
  89919. // Ensure the effect will be rebuilt.
  89920. this._markAllSubMeshesAsTexturesDirty();
  89921. },
  89922. enumerable: true,
  89923. configurable: true
  89924. });
  89925. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  89926. /**
  89927. * Gets wether the color curves effect is enabled.
  89928. */
  89929. get: function () {
  89930. return this.imageProcessingConfiguration.colorCurvesEnabled;
  89931. },
  89932. /**
  89933. * Sets wether the color curves effect is enabled.
  89934. */
  89935. set: function (value) {
  89936. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  89937. },
  89938. enumerable: true,
  89939. configurable: true
  89940. });
  89941. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  89942. /**
  89943. * Gets wether the color grading effect is enabled.
  89944. */
  89945. get: function () {
  89946. return this.imageProcessingConfiguration.colorGradingEnabled;
  89947. },
  89948. /**
  89949. * Gets wether the color grading effect is enabled.
  89950. */
  89951. set: function (value) {
  89952. this.imageProcessingConfiguration.colorGradingEnabled = value;
  89953. },
  89954. enumerable: true,
  89955. configurable: true
  89956. });
  89957. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  89958. /**
  89959. * Gets wether tonemapping is enabled or not.
  89960. */
  89961. get: function () {
  89962. return this._imageProcessingConfiguration.toneMappingEnabled;
  89963. },
  89964. /**
  89965. * Sets wether tonemapping is enabled or not
  89966. */
  89967. set: function (value) {
  89968. this._imageProcessingConfiguration.toneMappingEnabled = value;
  89969. },
  89970. enumerable: true,
  89971. configurable: true
  89972. });
  89973. ;
  89974. ;
  89975. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  89976. /**
  89977. * The camera exposure used on this material.
  89978. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  89979. * This corresponds to a photographic exposure.
  89980. */
  89981. get: function () {
  89982. return this._imageProcessingConfiguration.exposure;
  89983. },
  89984. /**
  89985. * The camera exposure used on this material.
  89986. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  89987. * This corresponds to a photographic exposure.
  89988. */
  89989. set: function (value) {
  89990. this._imageProcessingConfiguration.exposure = value;
  89991. },
  89992. enumerable: true,
  89993. configurable: true
  89994. });
  89995. ;
  89996. ;
  89997. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  89998. /**
  89999. * Gets The camera contrast used on this material.
  90000. */
  90001. get: function () {
  90002. return this._imageProcessingConfiguration.contrast;
  90003. },
  90004. /**
  90005. * Sets The camera contrast used on this material.
  90006. */
  90007. set: function (value) {
  90008. this._imageProcessingConfiguration.contrast = value;
  90009. },
  90010. enumerable: true,
  90011. configurable: true
  90012. });
  90013. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  90014. /**
  90015. * Gets the Color Grading 2D Lookup Texture.
  90016. */
  90017. get: function () {
  90018. return this._imageProcessingConfiguration.colorGradingTexture;
  90019. },
  90020. /**
  90021. * Sets the Color Grading 2D Lookup Texture.
  90022. */
  90023. set: function (value) {
  90024. this.imageProcessingConfiguration.colorGradingTexture = value;
  90025. },
  90026. enumerable: true,
  90027. configurable: true
  90028. });
  90029. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  90030. /**
  90031. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90032. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90033. * 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;
  90034. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90035. */
  90036. get: function () {
  90037. return this.imageProcessingConfiguration.colorCurves;
  90038. },
  90039. /**
  90040. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90041. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90042. * 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;
  90043. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90044. */
  90045. set: function (value) {
  90046. this.imageProcessingConfiguration.colorCurves = value;
  90047. },
  90048. enumerable: true,
  90049. configurable: true
  90050. });
  90051. /**
  90052. * The entire material has been created in order to prevent overdraw.
  90053. * @returns false
  90054. */
  90055. BackgroundMaterial.prototype.needAlphaTesting = function () {
  90056. return true;
  90057. };
  90058. /**
  90059. * The entire material has been created in order to prevent overdraw.
  90060. * @returns true if blending is enable
  90061. */
  90062. BackgroundMaterial.prototype.needAlphaBlending = function () {
  90063. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  90064. };
  90065. /**
  90066. * Checks wether the material is ready to be rendered for a given mesh.
  90067. * @param mesh The mesh to render
  90068. * @param subMesh The submesh to check against
  90069. * @param useInstances Specify wether or not the material is used with instances
  90070. * @returns true if all the dependencies are ready (Textures, Effects...)
  90071. */
  90072. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  90073. var _this = this;
  90074. if (useInstances === void 0) { useInstances = false; }
  90075. if (subMesh.effect && this.isFrozen) {
  90076. if (this._wasPreviouslyReady) {
  90077. return true;
  90078. }
  90079. }
  90080. if (!subMesh._materialDefines) {
  90081. subMesh._materialDefines = new BackgroundMaterialDefines();
  90082. }
  90083. var scene = this.getScene();
  90084. var defines = subMesh._materialDefines;
  90085. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  90086. if (defines._renderId === scene.getRenderId()) {
  90087. return true;
  90088. }
  90089. }
  90090. var engine = scene.getEngine();
  90091. // Lights
  90092. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  90093. defines._needNormals = true;
  90094. // Textures
  90095. if (defines._areTexturesDirty) {
  90096. defines._needUVs = false;
  90097. if (scene.texturesEnabled) {
  90098. if (scene.getEngine().getCaps().textureLOD) {
  90099. defines.TEXTURELODSUPPORT = true;
  90100. }
  90101. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90102. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  90103. return false;
  90104. }
  90105. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  90106. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  90107. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  90108. defines.OPACITYFRESNEL = this._opacityFresnel;
  90109. }
  90110. else {
  90111. defines.DIFFUSE = false;
  90112. defines.DIFFUSEHASALPHA = false;
  90113. defines.GAMMADIFFUSE = false;
  90114. defines.OPACITYFRESNEL = false;
  90115. }
  90116. var reflectionTexture = this._reflectionTexture;
  90117. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90118. if (!reflectionTexture.isReadyOrNotBlocking()) {
  90119. return false;
  90120. }
  90121. defines.REFLECTION = true;
  90122. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  90123. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  90124. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  90125. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  90126. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  90127. defines.REFLECTIONBGR = this.switchToBGR;
  90128. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  90129. defines.INVERTCUBICMAP = true;
  90130. }
  90131. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  90132. switch (reflectionTexture.coordinatesMode) {
  90133. case BABYLON.Texture.CUBIC_MODE:
  90134. case BABYLON.Texture.INVCUBIC_MODE:
  90135. defines.REFLECTIONMAP_CUBIC = true;
  90136. break;
  90137. case BABYLON.Texture.EXPLICIT_MODE:
  90138. defines.REFLECTIONMAP_EXPLICIT = true;
  90139. break;
  90140. case BABYLON.Texture.PLANAR_MODE:
  90141. defines.REFLECTIONMAP_PLANAR = true;
  90142. break;
  90143. case BABYLON.Texture.PROJECTION_MODE:
  90144. defines.REFLECTIONMAP_PROJECTION = true;
  90145. break;
  90146. case BABYLON.Texture.SKYBOX_MODE:
  90147. defines.REFLECTIONMAP_SKYBOX = true;
  90148. break;
  90149. case BABYLON.Texture.SPHERICAL_MODE:
  90150. defines.REFLECTIONMAP_SPHERICAL = true;
  90151. break;
  90152. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  90153. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  90154. break;
  90155. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  90156. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  90157. break;
  90158. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  90159. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  90160. break;
  90161. }
  90162. if (this.reflectionFresnel) {
  90163. defines.REFLECTIONFRESNEL = true;
  90164. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  90165. this._reflectionControls.x = this.reflectionAmount;
  90166. this._reflectionControls.y = this.reflectionReflectance0;
  90167. this._reflectionControls.z = this.reflectionReflectance90;
  90168. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  90169. }
  90170. else {
  90171. defines.REFLECTIONFRESNEL = false;
  90172. defines.REFLECTIONFALLOFF = false;
  90173. }
  90174. }
  90175. else {
  90176. defines.REFLECTION = false;
  90177. defines.REFLECTIONFALLOFF = false;
  90178. defines.REFLECTIONBLUR = false;
  90179. defines.REFLECTIONMAP_3D = false;
  90180. defines.REFLECTIONMAP_SPHERICAL = false;
  90181. defines.REFLECTIONMAP_PLANAR = false;
  90182. defines.REFLECTIONMAP_CUBIC = false;
  90183. defines.REFLECTIONMAP_PROJECTION = false;
  90184. defines.REFLECTIONMAP_SKYBOX = false;
  90185. defines.REFLECTIONMAP_EXPLICIT = false;
  90186. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90187. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90188. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90189. defines.INVERTCUBICMAP = false;
  90190. defines.REFLECTIONMAP_OPPOSITEZ = false;
  90191. defines.LODINREFLECTIONALPHA = false;
  90192. defines.GAMMAREFLECTION = false;
  90193. }
  90194. }
  90195. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  90196. defines.USERGBCOLOR = this._useRGBColor;
  90197. defines.NOISE = this._enableNoise;
  90198. }
  90199. if (defines._areImageProcessingDirty) {
  90200. if (!this._imageProcessingConfiguration.isReady()) {
  90201. return false;
  90202. }
  90203. this._imageProcessingConfiguration.prepareDefines(defines);
  90204. }
  90205. // Misc.
  90206. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  90207. // Values that need to be evaluated on every frame
  90208. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  90209. // Attribs
  90210. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  90211. if (mesh) {
  90212. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90213. mesh.createNormals(true);
  90214. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  90215. }
  90216. }
  90217. }
  90218. // Get correct effect
  90219. if (defines.isDirty) {
  90220. defines.markAsProcessed();
  90221. scene.resetCachedMaterial();
  90222. // Fallbacks
  90223. var fallbacks = new BABYLON.EffectFallbacks();
  90224. if (defines.FOG) {
  90225. fallbacks.addFallback(0, "FOG");
  90226. }
  90227. if (defines.POINTSIZE) {
  90228. fallbacks.addFallback(1, "POINTSIZE");
  90229. }
  90230. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  90231. if (defines.NUM_BONE_INFLUENCERS > 0) {
  90232. fallbacks.addCPUSkinningFallback(0, mesh);
  90233. }
  90234. //Attributes
  90235. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90236. if (defines.NORMAL) {
  90237. attribs.push(BABYLON.VertexBuffer.NormalKind);
  90238. }
  90239. if (defines.UV1) {
  90240. attribs.push(BABYLON.VertexBuffer.UVKind);
  90241. }
  90242. if (defines.UV2) {
  90243. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90244. }
  90245. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  90246. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  90247. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  90248. "vFogInfos", "vFogColor", "pointSize",
  90249. "vClipPlane", "mBones",
  90250. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  90251. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  90252. "shadowLevel", "alpha",
  90253. "vBackgroundCenter", "vReflectionControl",
  90254. "vDiffuseInfos", "diffuseMatrix",
  90255. ];
  90256. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  90257. var uniformBuffers = ["Material", "Scene"];
  90258. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  90259. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  90260. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  90261. uniformsNames: uniforms,
  90262. uniformBuffersNames: uniformBuffers,
  90263. samplers: samplers,
  90264. defines: defines,
  90265. maxSimultaneousLights: this._maxSimultaneousLights
  90266. });
  90267. var onCompiled = function (effect) {
  90268. if (_this.onCompiled) {
  90269. _this.onCompiled(effect);
  90270. }
  90271. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  90272. };
  90273. var join = defines.toString();
  90274. subMesh.setEffect(scene.getEngine().createEffect("background", {
  90275. attributes: attribs,
  90276. uniformsNames: uniforms,
  90277. uniformBuffersNames: uniformBuffers,
  90278. samplers: samplers,
  90279. defines: join,
  90280. fallbacks: fallbacks,
  90281. onCompiled: onCompiled,
  90282. onError: this.onError,
  90283. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  90284. }, engine), defines);
  90285. this.buildUniformLayout();
  90286. }
  90287. if (!subMesh.effect || !subMesh.effect.isReady()) {
  90288. return false;
  90289. }
  90290. defines._renderId = scene.getRenderId();
  90291. this._wasPreviouslyReady = true;
  90292. return true;
  90293. };
  90294. /**
  90295. * Build the uniform buffer used in the material.
  90296. */
  90297. BackgroundMaterial.prototype.buildUniformLayout = function () {
  90298. // Order is important !
  90299. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  90300. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  90301. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  90302. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  90303. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  90304. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  90305. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  90306. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  90307. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  90308. this._uniformBuffer.addUniform("pointSize", 1);
  90309. this._uniformBuffer.addUniform("shadowLevel", 1);
  90310. this._uniformBuffer.addUniform("alpha", 1);
  90311. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  90312. this._uniformBuffer.addUniform("vReflectionControl", 4);
  90313. this._uniformBuffer.create();
  90314. };
  90315. /**
  90316. * Unbind the material.
  90317. */
  90318. BackgroundMaterial.prototype.unbind = function () {
  90319. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  90320. this._uniformBuffer.setTexture("diffuseSampler", null);
  90321. }
  90322. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  90323. this._uniformBuffer.setTexture("reflectionSampler", null);
  90324. }
  90325. _super.prototype.unbind.call(this);
  90326. };
  90327. /**
  90328. * Bind only the world matrix to the material.
  90329. * @param world The world matrix to bind.
  90330. */
  90331. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  90332. this._activeEffect.setMatrix("world", world);
  90333. };
  90334. /**
  90335. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  90336. * @param world The world matrix to bind.
  90337. * @param subMesh The submesh to bind for.
  90338. */
  90339. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  90340. var scene = this.getScene();
  90341. var defines = subMesh._materialDefines;
  90342. if (!defines) {
  90343. return;
  90344. }
  90345. var effect = subMesh.effect;
  90346. if (!effect) {
  90347. return;
  90348. }
  90349. this._activeEffect = effect;
  90350. // Matrices
  90351. this.bindOnlyWorldMatrix(world);
  90352. // Bones
  90353. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  90354. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  90355. if (mustRebind) {
  90356. this._uniformBuffer.bindToEffect(effect, "Material");
  90357. this.bindViewProjection(effect);
  90358. var reflectionTexture = this._reflectionTexture;
  90359. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  90360. // Texture uniforms
  90361. if (scene.texturesEnabled) {
  90362. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90363. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  90364. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  90365. }
  90366. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90367. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  90368. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  90369. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  90370. }
  90371. }
  90372. if (this.shadowLevel > 0) {
  90373. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  90374. }
  90375. this._uniformBuffer.updateFloat("alpha", this.alpha);
  90376. // Point size
  90377. if (this.pointsCloud) {
  90378. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  90379. }
  90380. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  90381. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  90382. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  90383. }
  90384. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  90385. // Textures
  90386. if (scene.texturesEnabled) {
  90387. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90388. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  90389. }
  90390. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90391. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  90392. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90393. }
  90394. else if (!defines.REFLECTIONBLUR) {
  90395. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90396. }
  90397. else {
  90398. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  90399. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  90400. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  90401. }
  90402. if (defines.REFLECTIONFRESNEL) {
  90403. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  90404. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  90405. }
  90406. }
  90407. }
  90408. // Clip plane
  90409. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  90410. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  90411. }
  90412. if (mustRebind || !this.isFrozen) {
  90413. if (scene.lightsEnabled) {
  90414. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  90415. }
  90416. // View
  90417. this.bindView(effect);
  90418. // Fog
  90419. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  90420. // image processing
  90421. this._imageProcessingConfiguration.bind(this._activeEffect);
  90422. }
  90423. this._uniformBuffer.update();
  90424. this._afterBind(mesh);
  90425. };
  90426. /**
  90427. * Dispose the material.
  90428. * @param forceDisposeEffect Force disposal of the associated effect.
  90429. * @param forceDisposeTextures Force disposal of the associated textures.
  90430. */
  90431. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  90432. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  90433. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  90434. if (forceDisposeTextures) {
  90435. if (this.diffuseTexture) {
  90436. this.diffuseTexture.dispose();
  90437. }
  90438. if (this.reflectionTexture) {
  90439. this.reflectionTexture.dispose();
  90440. }
  90441. }
  90442. this._renderTargets.dispose();
  90443. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90444. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90445. }
  90446. _super.prototype.dispose.call(this, forceDisposeEffect);
  90447. };
  90448. /**
  90449. * Clones the material.
  90450. * @param name The cloned name.
  90451. * @returns The cloned material.
  90452. */
  90453. BackgroundMaterial.prototype.clone = function (name) {
  90454. var _this = this;
  90455. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  90456. };
  90457. /**
  90458. * Serializes the current material to its JSON representation.
  90459. * @returns The JSON representation.
  90460. */
  90461. BackgroundMaterial.prototype.serialize = function () {
  90462. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90463. serializationObject.customType = "BABYLON.BackgroundMaterial";
  90464. return serializationObject;
  90465. };
  90466. /**
  90467. * Gets the class name of the material
  90468. * @returns "BackgroundMaterial"
  90469. */
  90470. BackgroundMaterial.prototype.getClassName = function () {
  90471. return "BackgroundMaterial";
  90472. };
  90473. /**
  90474. * Parse a JSON input to create back a background material.
  90475. * @param source The JSON data to parse
  90476. * @param scene The scene to create the parsed material in
  90477. * @param rootUrl The root url of the assets the material depends upon
  90478. * @returns the instantiated BackgroundMaterial.
  90479. */
  90480. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  90481. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  90482. };
  90483. /**
  90484. * Standard reflectance value at parallel view angle.
  90485. */
  90486. BackgroundMaterial.StandardReflectance0 = 0.05;
  90487. /**
  90488. * Standard reflectance value at grazing angle.
  90489. */
  90490. BackgroundMaterial.StandardReflectance90 = 0.5;
  90491. __decorate([
  90492. BABYLON.serializeAsColor3()
  90493. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  90494. __decorate([
  90495. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90496. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  90497. __decorate([
  90498. BABYLON.serialize()
  90499. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  90500. __decorate([
  90501. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90502. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  90503. __decorate([
  90504. BABYLON.serializeAsColor3()
  90505. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  90506. __decorate([
  90507. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90508. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  90509. __decorate([
  90510. BABYLON.serialize()
  90511. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  90512. __decorate([
  90513. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90514. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  90515. __decorate([
  90516. BABYLON.serializeAsColor3()
  90517. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  90518. __decorate([
  90519. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90520. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  90521. __decorate([
  90522. BABYLON.serialize()
  90523. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  90524. __decorate([
  90525. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90526. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  90527. __decorate([
  90528. BABYLON.serializeAsTexture()
  90529. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  90530. __decorate([
  90531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90532. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  90533. __decorate([
  90534. BABYLON.serialize()
  90535. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  90536. __decorate([
  90537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90538. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  90539. __decorate([
  90540. BABYLON.serializeAsTexture()
  90541. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  90542. __decorate([
  90543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90544. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  90545. __decorate([
  90546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90547. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  90548. __decorate([
  90549. BABYLON.serialize()
  90550. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  90551. __decorate([
  90552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90553. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  90554. __decorate([
  90555. BABYLON.serialize()
  90556. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  90557. __decorate([
  90558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90559. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  90560. __decorate([
  90561. BABYLON.serializeAsVector3()
  90562. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  90563. __decorate([
  90564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90565. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  90566. __decorate([
  90567. BABYLON.serialize()
  90568. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  90569. __decorate([
  90570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90571. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  90572. __decorate([
  90573. BABYLON.serialize()
  90574. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  90575. __decorate([
  90576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90577. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  90578. __decorate([
  90579. BABYLON.serialize()
  90580. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  90581. __decorate([
  90582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90583. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  90584. __decorate([
  90585. BABYLON.serialize()
  90586. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  90587. __decorate([
  90588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90589. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  90590. __decorate([
  90591. BABYLON.serialize()
  90592. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  90593. __decorate([
  90594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90595. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  90596. __decorate([
  90597. BABYLON.serialize()
  90598. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  90599. __decorate([
  90600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90601. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  90602. __decorate([
  90603. BABYLON.serialize()
  90604. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  90605. __decorate([
  90606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90607. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  90608. __decorate([
  90609. BABYLON.serialize()
  90610. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  90611. __decorate([
  90612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90613. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  90614. __decorate([
  90615. BABYLON.serialize()
  90616. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  90617. __decorate([
  90618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90619. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  90620. __decorate([
  90621. BABYLON.serializeAsImageProcessingConfiguration()
  90622. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  90623. return BackgroundMaterial;
  90624. }(BABYLON.PushMaterial));
  90625. BABYLON.BackgroundMaterial = BackgroundMaterial;
  90626. })(BABYLON || (BABYLON = {}));
  90627. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  90628. "use strict";
  90629. var __assign = (this && this.__assign) || Object.assign || function(t) {
  90630. for (var s, i = 1, n = arguments.length; i < n; i++) {
  90631. s = arguments[i];
  90632. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  90633. t[p] = s[p];
  90634. }
  90635. return t;
  90636. };
  90637. var BABYLON;
  90638. (function (BABYLON) {
  90639. /**
  90640. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  90641. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  90642. * It also helps with the default setup of your imageProcessing configuration.
  90643. */
  90644. var EnvironmentHelper = /** @class */ (function () {
  90645. /**
  90646. * constructor
  90647. * @param options
  90648. * @param scene The scene to add the material to
  90649. */
  90650. function EnvironmentHelper(options, scene) {
  90651. var _this = this;
  90652. this._errorHandler = function (message, exception) {
  90653. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  90654. };
  90655. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  90656. this._scene = scene;
  90657. this.onErrorObservable = new BABYLON.Observable();
  90658. this._setupBackground();
  90659. this._setupImageProcessing();
  90660. }
  90661. /**
  90662. * Creates the default options for the helper.
  90663. */
  90664. EnvironmentHelper._getDefaultOptions = function () {
  90665. return {
  90666. createGround: true,
  90667. groundSize: 15,
  90668. groundTexture: this._groundTextureCDNUrl,
  90669. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90670. groundOpacity: 0.9,
  90671. enableGroundShadow: true,
  90672. groundShadowLevel: 0.5,
  90673. enableGroundMirror: false,
  90674. groundMirrorSizeRatio: 0.3,
  90675. groundMirrorBlurKernel: 64,
  90676. groundMirrorAmount: 1,
  90677. groundMirrorFresnelWeight: 1,
  90678. groundMirrorFallOffDistance: 0,
  90679. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  90680. groundYBias: 0.00001,
  90681. createSkybox: true,
  90682. skyboxSize: 20,
  90683. skyboxTexture: this._skyboxTextureCDNUrl,
  90684. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90685. backgroundYRotation: 0,
  90686. sizeAuto: true,
  90687. rootPosition: BABYLON.Vector3.Zero(),
  90688. setupImageProcessing: true,
  90689. environmentTexture: this._environmentTextureCDNUrl,
  90690. cameraExposure: 0.8,
  90691. cameraContrast: 1.2,
  90692. toneMappingEnabled: true,
  90693. };
  90694. };
  90695. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  90696. /**
  90697. * Gets the root mesh created by the helper.
  90698. */
  90699. get: function () {
  90700. return this._rootMesh;
  90701. },
  90702. enumerable: true,
  90703. configurable: true
  90704. });
  90705. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  90706. /**
  90707. * Gets the skybox created by the helper.
  90708. */
  90709. get: function () {
  90710. return this._skybox;
  90711. },
  90712. enumerable: true,
  90713. configurable: true
  90714. });
  90715. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  90716. /**
  90717. * Gets the skybox texture created by the helper.
  90718. */
  90719. get: function () {
  90720. return this._skyboxTexture;
  90721. },
  90722. enumerable: true,
  90723. configurable: true
  90724. });
  90725. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  90726. /**
  90727. * Gets the skybox material created by the helper.
  90728. */
  90729. get: function () {
  90730. return this._skyboxMaterial;
  90731. },
  90732. enumerable: true,
  90733. configurable: true
  90734. });
  90735. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  90736. /**
  90737. * Gets the ground mesh created by the helper.
  90738. */
  90739. get: function () {
  90740. return this._ground;
  90741. },
  90742. enumerable: true,
  90743. configurable: true
  90744. });
  90745. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  90746. /**
  90747. * Gets the ground texture created by the helper.
  90748. */
  90749. get: function () {
  90750. return this._groundTexture;
  90751. },
  90752. enumerable: true,
  90753. configurable: true
  90754. });
  90755. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  90756. /**
  90757. * Gets the ground mirror created by the helper.
  90758. */
  90759. get: function () {
  90760. return this._groundMirror;
  90761. },
  90762. enumerable: true,
  90763. configurable: true
  90764. });
  90765. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  90766. /**
  90767. * Gets the ground mirror render list to helps pushing the meshes
  90768. * you wish in the ground reflection.
  90769. */
  90770. get: function () {
  90771. if (this._groundMirror) {
  90772. return this._groundMirror.renderList;
  90773. }
  90774. return null;
  90775. },
  90776. enumerable: true,
  90777. configurable: true
  90778. });
  90779. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  90780. /**
  90781. * Gets the ground material created by the helper.
  90782. */
  90783. get: function () {
  90784. return this._groundMaterial;
  90785. },
  90786. enumerable: true,
  90787. configurable: true
  90788. });
  90789. /**
  90790. * Updates the background according to the new options
  90791. * @param options
  90792. */
  90793. EnvironmentHelper.prototype.updateOptions = function (options) {
  90794. var newOptions = __assign({}, this._options, options);
  90795. if (this._ground && !newOptions.createGround) {
  90796. this._ground.dispose();
  90797. this._ground = null;
  90798. }
  90799. if (this._groundMaterial && !newOptions.createGround) {
  90800. this._groundMaterial.dispose();
  90801. this._groundMaterial = null;
  90802. }
  90803. if (this._groundTexture) {
  90804. if (this._options.groundTexture != newOptions.groundTexture) {
  90805. this._groundTexture.dispose();
  90806. this._groundTexture = null;
  90807. }
  90808. }
  90809. if (this._skybox && !newOptions.createSkybox) {
  90810. this._skybox.dispose();
  90811. this._skybox = null;
  90812. }
  90813. if (this._skyboxMaterial && !newOptions.createSkybox) {
  90814. this._skyboxMaterial.dispose();
  90815. this._skyboxMaterial = null;
  90816. }
  90817. if (this._skyboxTexture) {
  90818. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  90819. this._skyboxTexture.dispose();
  90820. this._skyboxTexture = null;
  90821. }
  90822. }
  90823. if (this._groundMirror && !newOptions.enableGroundMirror) {
  90824. this._groundMirror.dispose();
  90825. this._groundMirror = null;
  90826. }
  90827. if (this._scene.environmentTexture) {
  90828. if (this._options.environmentTexture != newOptions.environmentTexture) {
  90829. this._scene.environmentTexture.dispose();
  90830. }
  90831. }
  90832. this._options = newOptions;
  90833. this._setupBackground();
  90834. this._setupImageProcessing();
  90835. };
  90836. /**
  90837. * Sets the primary color of all the available elements.
  90838. * @param color
  90839. */
  90840. EnvironmentHelper.prototype.setMainColor = function (color) {
  90841. if (this.groundMaterial) {
  90842. this.groundMaterial.primaryColor = color;
  90843. }
  90844. if (this.skyboxMaterial) {
  90845. this.skyboxMaterial.primaryColor = color;
  90846. }
  90847. if (this.groundMirror) {
  90848. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  90849. }
  90850. };
  90851. /**
  90852. * Setup the image processing according to the specified options.
  90853. */
  90854. EnvironmentHelper.prototype._setupImageProcessing = function () {
  90855. if (this._options.setupImageProcessing) {
  90856. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  90857. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  90858. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  90859. this._setupEnvironmentTexture();
  90860. }
  90861. };
  90862. /**
  90863. * Setup the environment texture according to the specified options.
  90864. */
  90865. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  90866. if (this._scene.environmentTexture) {
  90867. return;
  90868. }
  90869. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  90870. this._scene.environmentTexture = this._options.environmentTexture;
  90871. return;
  90872. }
  90873. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  90874. this._scene.environmentTexture = environmentTexture;
  90875. };
  90876. /**
  90877. * Setup the background according to the specified options.
  90878. */
  90879. EnvironmentHelper.prototype._setupBackground = function () {
  90880. if (!this._rootMesh) {
  90881. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  90882. }
  90883. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  90884. var sceneSize = this._getSceneSize();
  90885. if (this._options.createGround) {
  90886. this._setupGround(sceneSize);
  90887. this._setupGroundMaterial();
  90888. this._setupGroundDiffuseTexture();
  90889. if (this._options.enableGroundMirror) {
  90890. this._setupGroundMirrorTexture(sceneSize);
  90891. }
  90892. this._setupMirrorInGroundMaterial();
  90893. }
  90894. if (this._options.createSkybox) {
  90895. this._setupSkybox(sceneSize);
  90896. this._setupSkyboxMaterial();
  90897. this._setupSkyboxReflectionTexture();
  90898. }
  90899. this._rootMesh.position.x = sceneSize.rootPosition.x;
  90900. this._rootMesh.position.z = sceneSize.rootPosition.z;
  90901. this._rootMesh.position.y = sceneSize.rootPosition.y;
  90902. };
  90903. /**
  90904. * Get the scene sizes according to the setup.
  90905. */
  90906. EnvironmentHelper.prototype._getSceneSize = function () {
  90907. var _this = this;
  90908. var groundSize = this._options.groundSize;
  90909. var skyboxSize = this._options.skyboxSize;
  90910. var rootPosition = this._options.rootPosition;
  90911. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  90912. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  90913. }
  90914. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  90915. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  90916. });
  90917. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  90918. if (this._options.sizeAuto) {
  90919. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  90920. this._scene.activeCamera.upperRadiusLimit) {
  90921. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  90922. skyboxSize = groundSize;
  90923. }
  90924. var sceneDiagonalLenght = sceneDiagonal.length();
  90925. if (sceneDiagonalLenght > groundSize) {
  90926. groundSize = sceneDiagonalLenght * 2;
  90927. skyboxSize = groundSize;
  90928. }
  90929. // 10 % bigger.
  90930. groundSize *= 1.1;
  90931. skyboxSize *= 1.5;
  90932. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  90933. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  90934. }
  90935. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  90936. };
  90937. /**
  90938. * Setup the ground according to the specified options.
  90939. */
  90940. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  90941. var _this = this;
  90942. if (!this._ground) {
  90943. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  90944. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  90945. this._ground.parent = this._rootMesh;
  90946. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  90947. }
  90948. this._ground.receiveShadows = this._options.enableGroundShadow;
  90949. };
  90950. /**
  90951. * Setup the ground material according to the specified options.
  90952. */
  90953. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  90954. if (!this._groundMaterial) {
  90955. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  90956. }
  90957. this._groundMaterial.alpha = this._options.groundOpacity;
  90958. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  90959. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  90960. this._groundMaterial.primaryLevel = 1;
  90961. this._groundMaterial.primaryColor = this._options.groundColor;
  90962. this._groundMaterial.secondaryLevel = 0;
  90963. this._groundMaterial.tertiaryLevel = 0;
  90964. this._groundMaterial.useRGBColor = false;
  90965. this._groundMaterial.enableNoise = true;
  90966. if (this._ground) {
  90967. this._ground.material = this._groundMaterial;
  90968. }
  90969. };
  90970. /**
  90971. * Setup the ground diffuse texture according to the specified options.
  90972. */
  90973. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  90974. if (!this._groundMaterial) {
  90975. return;
  90976. }
  90977. if (this._groundTexture) {
  90978. return;
  90979. }
  90980. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  90981. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  90982. return;
  90983. }
  90984. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  90985. diffuseTexture.gammaSpace = false;
  90986. diffuseTexture.hasAlpha = true;
  90987. this._groundMaterial.diffuseTexture = diffuseTexture;
  90988. };
  90989. /**
  90990. * Setup the ground mirror texture according to the specified options.
  90991. */
  90992. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  90993. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90994. if (!this._groundMirror) {
  90995. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  90996. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  90997. this._groundMirror.anisotropicFilteringLevel = 1;
  90998. this._groundMirror.wrapU = wrapping;
  90999. this._groundMirror.wrapV = wrapping;
  91000. this._groundMirror.gammaSpace = false;
  91001. if (this._groundMirror.renderList) {
  91002. for (var i = 0; i < this._scene.meshes.length; i++) {
  91003. var mesh = this._scene.meshes[i];
  91004. if (mesh !== this._ground &&
  91005. mesh !== this._skybox &&
  91006. mesh !== this._rootMesh) {
  91007. this._groundMirror.renderList.push(mesh);
  91008. }
  91009. }
  91010. }
  91011. }
  91012. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  91013. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  91014. };
  91015. /**
  91016. * Setup the ground to receive the mirror texture.
  91017. */
  91018. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  91019. if (this._groundMaterial) {
  91020. this._groundMaterial.reflectionTexture = this._groundMirror;
  91021. this._groundMaterial.reflectionFresnel = true;
  91022. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  91023. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  91024. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  91025. }
  91026. };
  91027. /**
  91028. * Setup the skybox according to the specified options.
  91029. */
  91030. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  91031. var _this = this;
  91032. if (!this._skybox) {
  91033. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  91034. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  91035. }
  91036. this._skybox.parent = this._rootMesh;
  91037. };
  91038. /**
  91039. * Setup the skybox material according to the specified options.
  91040. */
  91041. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  91042. if (!this._skybox) {
  91043. return;
  91044. }
  91045. if (!this._skyboxMaterial) {
  91046. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  91047. }
  91048. this._skyboxMaterial.useRGBColor = false;
  91049. this._skyboxMaterial.primaryLevel = 1;
  91050. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  91051. this._skyboxMaterial.secondaryLevel = 0;
  91052. this._skyboxMaterial.tertiaryLevel = 0;
  91053. this._skyboxMaterial.enableNoise = true;
  91054. this._skybox.material = this._skyboxMaterial;
  91055. };
  91056. /**
  91057. * Setup the skybox reflection texture according to the specified options.
  91058. */
  91059. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  91060. if (!this._skyboxMaterial) {
  91061. return;
  91062. }
  91063. if (this._skyboxTexture) {
  91064. return;
  91065. }
  91066. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  91067. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91068. return;
  91069. }
  91070. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91071. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  91072. this._skyboxTexture.gammaSpace = false;
  91073. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91074. };
  91075. /**
  91076. * Dispose all the elements created by the Helper.
  91077. */
  91078. EnvironmentHelper.prototype.dispose = function () {
  91079. if (this._groundMaterial) {
  91080. this._groundMaterial.dispose(true, true);
  91081. }
  91082. if (this._skyboxMaterial) {
  91083. this._skyboxMaterial.dispose(true, true);
  91084. }
  91085. this._rootMesh.dispose(false);
  91086. };
  91087. /**
  91088. * Default ground texture URL.
  91089. */
  91090. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  91091. /**
  91092. * Default skybox texture URL.
  91093. */
  91094. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  91095. /**
  91096. * Default environment texture URL.
  91097. */
  91098. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  91099. return EnvironmentHelper;
  91100. }());
  91101. BABYLON.EnvironmentHelper = EnvironmentHelper;
  91102. })(BABYLON || (BABYLON = {}));
  91103. //# sourceMappingURL=babylon.environmentHelper.js.map
  91104. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\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#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\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#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb);\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\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}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\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}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(textureSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\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","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\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\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#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\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#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  91105. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\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};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,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#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\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}","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};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\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};"};
  91106. "use strict";
  91107. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  91108. var BABYLON;
  91109. (function (BABYLON) {
  91110. var GridMaterialDefines = /** @class */ (function (_super) {
  91111. __extends(GridMaterialDefines, _super);
  91112. function GridMaterialDefines() {
  91113. var _this = _super.call(this) || this;
  91114. _this.TRANSPARENT = false;
  91115. _this.FOG = false;
  91116. _this.PREMULTIPLYALPHA = false;
  91117. _this.rebuild();
  91118. return _this;
  91119. }
  91120. return GridMaterialDefines;
  91121. }(BABYLON.MaterialDefines));
  91122. /**
  91123. * The grid materials allows you to wrap any shape with a grid.
  91124. * Colors are customizable.
  91125. */
  91126. var GridMaterial = /** @class */ (function (_super) {
  91127. __extends(GridMaterial, _super);
  91128. /**
  91129. * constructor
  91130. * @param name The name given to the material in order to identify it afterwards.
  91131. * @param scene The scene the material is used in.
  91132. */
  91133. function GridMaterial(name, scene) {
  91134. var _this = _super.call(this, name, scene) || this;
  91135. /**
  91136. * Main color of the grid (e.g. between lines)
  91137. */
  91138. _this.mainColor = BABYLON.Color3.Black();
  91139. /**
  91140. * Color of the grid lines.
  91141. */
  91142. _this.lineColor = BABYLON.Color3.Teal();
  91143. /**
  91144. * The scale of the grid compared to unit.
  91145. */
  91146. _this.gridRatio = 1.0;
  91147. /**
  91148. * Allows setting an offset for the grid lines.
  91149. */
  91150. _this.gridOffset = BABYLON.Vector3.Zero();
  91151. /**
  91152. * The frequency of thicker lines.
  91153. */
  91154. _this.majorUnitFrequency = 10;
  91155. /**
  91156. * The visibility of minor units in the grid.
  91157. */
  91158. _this.minorUnitVisibility = 0.33;
  91159. /**
  91160. * The grid opacity outside of the lines.
  91161. */
  91162. _this.opacity = 1.0;
  91163. /**
  91164. * Determine RBG output is premultiplied by alpha value.
  91165. */
  91166. _this.preMultiplyAlpha = false;
  91167. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  91168. return _this;
  91169. }
  91170. /**
  91171. * Returns wehter or not the grid requires alpha blending.
  91172. */
  91173. GridMaterial.prototype.needAlphaBlending = function () {
  91174. return this.opacity < 1.0;
  91175. };
  91176. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  91177. return this.needAlphaBlending();
  91178. };
  91179. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  91180. if (this.isFrozen) {
  91181. if (this._wasPreviouslyReady && subMesh.effect) {
  91182. return true;
  91183. }
  91184. }
  91185. if (!subMesh._materialDefines) {
  91186. subMesh._materialDefines = new GridMaterialDefines();
  91187. }
  91188. var defines = subMesh._materialDefines;
  91189. var scene = this.getScene();
  91190. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  91191. if (this._renderId === scene.getRenderId()) {
  91192. return true;
  91193. }
  91194. }
  91195. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  91196. defines.TRANSPARENT = !defines.TRANSPARENT;
  91197. defines.markAsUnprocessed();
  91198. }
  91199. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  91200. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  91201. defines.markAsUnprocessed();
  91202. }
  91203. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  91204. // Get correct effect
  91205. if (defines.isDirty) {
  91206. defines.markAsProcessed();
  91207. scene.resetCachedMaterial();
  91208. // Attributes
  91209. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  91210. // Defines
  91211. var join = defines.toString();
  91212. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  91213. }
  91214. if (!subMesh.effect || !subMesh.effect.isReady()) {
  91215. return false;
  91216. }
  91217. this._renderId = scene.getRenderId();
  91218. this._wasPreviouslyReady = true;
  91219. return true;
  91220. };
  91221. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  91222. var scene = this.getScene();
  91223. var defines = subMesh._materialDefines;
  91224. if (!defines) {
  91225. return;
  91226. }
  91227. var effect = subMesh.effect;
  91228. if (!effect) {
  91229. return;
  91230. }
  91231. this._activeEffect = effect;
  91232. // Matrices
  91233. this.bindOnlyWorldMatrix(world);
  91234. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  91235. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  91236. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  91237. // Uniforms
  91238. if (this._mustRebind(scene, effect)) {
  91239. this._activeEffect.setColor3("mainColor", this.mainColor);
  91240. this._activeEffect.setColor3("lineColor", this.lineColor);
  91241. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  91242. this._gridControl.x = this.gridRatio;
  91243. this._gridControl.y = Math.round(this.majorUnitFrequency);
  91244. this._gridControl.z = this.minorUnitVisibility;
  91245. this._gridControl.w = this.opacity;
  91246. this._activeEffect.setVector4("gridControl", this._gridControl);
  91247. }
  91248. // Fog
  91249. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  91250. this._afterBind(mesh, this._activeEffect);
  91251. };
  91252. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  91253. _super.prototype.dispose.call(this, forceDisposeEffect);
  91254. };
  91255. GridMaterial.prototype.clone = function (name) {
  91256. var _this = this;
  91257. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  91258. };
  91259. GridMaterial.prototype.serialize = function () {
  91260. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91261. serializationObject.customType = "BABYLON.GridMaterial";
  91262. return serializationObject;
  91263. };
  91264. GridMaterial.prototype.getClassName = function () {
  91265. return "GridMaterial";
  91266. };
  91267. GridMaterial.Parse = function (source, scene, rootUrl) {
  91268. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  91269. };
  91270. __decorate([
  91271. BABYLON.serializeAsColor3()
  91272. ], GridMaterial.prototype, "mainColor", void 0);
  91273. __decorate([
  91274. BABYLON.serializeAsColor3()
  91275. ], GridMaterial.prototype, "lineColor", void 0);
  91276. __decorate([
  91277. BABYLON.serialize()
  91278. ], GridMaterial.prototype, "gridRatio", void 0);
  91279. __decorate([
  91280. BABYLON.serializeAsColor3()
  91281. ], GridMaterial.prototype, "gridOffset", void 0);
  91282. __decorate([
  91283. BABYLON.serialize()
  91284. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  91285. __decorate([
  91286. BABYLON.serialize()
  91287. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  91288. __decorate([
  91289. BABYLON.serialize()
  91290. ], GridMaterial.prototype, "opacity", void 0);
  91291. __decorate([
  91292. BABYLON.serialize()
  91293. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  91294. return GridMaterial;
  91295. }(BABYLON.PushMaterial));
  91296. BABYLON.GridMaterial = GridMaterial;
  91297. })(BABYLON || (BABYLON = {}));
  91298. //# sourceMappingURL=babylon.gridmaterial.js.map
  91299. 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}";
  91300. 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}";
  91301. "use strict";
  91302. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  91303. var BABYLON;
  91304. (function (BABYLON) {
  91305. var GLTFLoaderCoordinateSystemMode;
  91306. (function (GLTFLoaderCoordinateSystemMode) {
  91307. /**
  91308. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  91309. */
  91310. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  91311. /**
  91312. * Sets the useRightHandedSystem flag on the scene.
  91313. */
  91314. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  91315. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  91316. var GLTFLoaderAnimationStartMode;
  91317. (function (GLTFLoaderAnimationStartMode) {
  91318. /**
  91319. * No animation will start.
  91320. */
  91321. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  91322. /**
  91323. * The first animation will start.
  91324. */
  91325. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  91326. /**
  91327. * All animations will start.
  91328. */
  91329. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  91330. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  91331. var GLTFLoaderState;
  91332. (function (GLTFLoaderState) {
  91333. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  91334. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  91335. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  91336. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  91337. var GLTFFileLoader = /** @class */ (function () {
  91338. function GLTFFileLoader() {
  91339. // #region Common options
  91340. /**
  91341. * Raised when the asset has been parsed.
  91342. * The data.json property stores the glTF JSON.
  91343. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  91344. */
  91345. this.onParsedObservable = new BABYLON.Observable();
  91346. // #endregion
  91347. // #region V2 options
  91348. /**
  91349. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  91350. */
  91351. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  91352. /**
  91353. * The animation start mode (NONE, FIRST, ALL).
  91354. */
  91355. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  91356. /**
  91357. * Set to true to compile materials before raising the success callback.
  91358. */
  91359. this.compileMaterials = false;
  91360. /**
  91361. * Set to true to also compile materials with clip planes.
  91362. */
  91363. this.useClipPlane = false;
  91364. /**
  91365. * Set to true to compile shadow generators before raising the success callback.
  91366. */
  91367. this.compileShadowGenerators = false;
  91368. /**
  91369. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  91370. */
  91371. this.onMeshLoadedObservable = new BABYLON.Observable();
  91372. /**
  91373. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  91374. */
  91375. this.onTextureLoadedObservable = new BABYLON.Observable();
  91376. /**
  91377. * Raised when the loader creates a material after parsing the glTF properties of the material.
  91378. */
  91379. this.onMaterialLoadedObservable = new BABYLON.Observable();
  91380. /**
  91381. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  91382. */
  91383. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  91384. /**
  91385. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  91386. * For assets with LODs, raised when all of the LODs are complete.
  91387. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  91388. */
  91389. this.onCompleteObservable = new BABYLON.Observable();
  91390. /**
  91391. * Raised when the loader is disposed.
  91392. */
  91393. this.onDisposeObservable = new BABYLON.Observable();
  91394. /**
  91395. * Raised after a loader extension is created.
  91396. * Set additional options for a loader extension in this event.
  91397. */
  91398. this.onExtensionLoadedObservable = new BABYLON.Observable();
  91399. // #endregion
  91400. this._loader = null;
  91401. this.name = "gltf";
  91402. this.extensions = {
  91403. ".gltf": { isBinary: false },
  91404. ".glb": { isBinary: true }
  91405. };
  91406. }
  91407. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  91408. set: function (callback) {
  91409. if (this._onParsedObserver) {
  91410. this.onParsedObservable.remove(this._onParsedObserver);
  91411. }
  91412. this._onParsedObserver = this.onParsedObservable.add(callback);
  91413. },
  91414. enumerable: true,
  91415. configurable: true
  91416. });
  91417. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  91418. set: function (callback) {
  91419. if (this._onMeshLoadedObserver) {
  91420. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  91421. }
  91422. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  91423. },
  91424. enumerable: true,
  91425. configurable: true
  91426. });
  91427. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  91428. set: function (callback) {
  91429. if (this._onTextureLoadedObserver) {
  91430. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  91431. }
  91432. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  91433. },
  91434. enumerable: true,
  91435. configurable: true
  91436. });
  91437. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  91438. set: function (callback) {
  91439. if (this._onMaterialLoadedObserver) {
  91440. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  91441. }
  91442. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  91443. },
  91444. enumerable: true,
  91445. configurable: true
  91446. });
  91447. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  91448. set: function (callback) {
  91449. if (this._onAnimationGroupLoadedObserver) {
  91450. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  91451. }
  91452. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  91453. },
  91454. enumerable: true,
  91455. configurable: true
  91456. });
  91457. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  91458. set: function (callback) {
  91459. if (this._onCompleteObserver) {
  91460. this.onCompleteObservable.remove(this._onCompleteObserver);
  91461. }
  91462. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  91463. },
  91464. enumerable: true,
  91465. configurable: true
  91466. });
  91467. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  91468. set: function (callback) {
  91469. if (this._onDisposeObserver) {
  91470. this.onDisposeObservable.remove(this._onDisposeObserver);
  91471. }
  91472. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  91473. },
  91474. enumerable: true,
  91475. configurable: true
  91476. });
  91477. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  91478. set: function (callback) {
  91479. if (this._onExtensionLoadedObserver) {
  91480. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  91481. }
  91482. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  91483. },
  91484. enumerable: true,
  91485. configurable: true
  91486. });
  91487. /**
  91488. * Gets a promise that resolves when the asset is completely loaded.
  91489. * @returns A promise that resolves when the asset is completely loaded.
  91490. */
  91491. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  91492. var _this = this;
  91493. return new Promise(function (resolve) {
  91494. _this.onCompleteObservable.add(function () {
  91495. resolve();
  91496. }, undefined, undefined, undefined, true);
  91497. });
  91498. };
  91499. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  91500. /**
  91501. * The loader state or null if not active.
  91502. */
  91503. get: function () {
  91504. return this._loader ? this._loader.state : null;
  91505. },
  91506. enumerable: true,
  91507. configurable: true
  91508. });
  91509. /**
  91510. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  91511. */
  91512. GLTFFileLoader.prototype.dispose = function () {
  91513. if (this._loader) {
  91514. this._loader.dispose();
  91515. this._loader = null;
  91516. }
  91517. this.onMeshLoadedObservable.clear();
  91518. this.onTextureLoadedObservable.clear();
  91519. this.onMaterialLoadedObservable.clear();
  91520. this.onDisposeObservable.notifyObservers(this);
  91521. this.onDisposeObservable.clear();
  91522. };
  91523. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  91524. var _this = this;
  91525. return Promise.resolve().then(function () {
  91526. var loaderData = _this._parse(data);
  91527. _this._loader = _this._getLoader(loaderData);
  91528. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  91529. });
  91530. };
  91531. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  91532. var _this = this;
  91533. return Promise.resolve().then(function () {
  91534. var loaderData = _this._parse(data);
  91535. _this._loader = _this._getLoader(loaderData);
  91536. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  91537. });
  91538. };
  91539. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  91540. var _this = this;
  91541. return Promise.resolve().then(function () {
  91542. var loaderData = _this._parse(data);
  91543. _this._loader = _this._getLoader(loaderData);
  91544. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  91545. var container = new BABYLON.AssetContainer(scene);
  91546. Array.prototype.push.apply(container.meshes, result.meshes);
  91547. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  91548. Array.prototype.push.apply(container.skeletons, result.skeletons);
  91549. container.removeAllFromScene();
  91550. return container;
  91551. });
  91552. });
  91553. };
  91554. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  91555. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  91556. };
  91557. GLTFFileLoader.prototype.createPlugin = function () {
  91558. return new GLTFFileLoader();
  91559. };
  91560. GLTFFileLoader.prototype._parse = function (data) {
  91561. var parsedData;
  91562. if (data instanceof ArrayBuffer) {
  91563. parsedData = GLTFFileLoader._parseBinary(data);
  91564. }
  91565. else {
  91566. parsedData = {
  91567. json: JSON.parse(data),
  91568. bin: null
  91569. };
  91570. }
  91571. this.onParsedObservable.notifyObservers(parsedData);
  91572. this.onParsedObservable.clear();
  91573. return parsedData;
  91574. };
  91575. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  91576. var _this = this;
  91577. var loaderVersion = { major: 2, minor: 0 };
  91578. var asset = loaderData.json.asset || {};
  91579. var version = GLTFFileLoader._parseVersion(asset.version);
  91580. if (!version) {
  91581. throw new Error("Invalid version: " + asset.version);
  91582. }
  91583. if (asset.minVersion !== undefined) {
  91584. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  91585. if (!minVersion) {
  91586. throw new Error("Invalid minimum version: " + asset.minVersion);
  91587. }
  91588. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  91589. throw new Error("Incompatible minimum version: " + asset.minVersion);
  91590. }
  91591. }
  91592. var createLoaders = {
  91593. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  91594. 2: GLTFFileLoader.CreateGLTFLoaderV2
  91595. };
  91596. var createLoader = createLoaders[version.major];
  91597. if (!createLoader) {
  91598. throw new Error("Unsupported version: " + asset.version);
  91599. }
  91600. var loader = createLoader();
  91601. loader.coordinateSystemMode = this.coordinateSystemMode;
  91602. loader.animationStartMode = this.animationStartMode;
  91603. loader.compileMaterials = this.compileMaterials;
  91604. loader.useClipPlane = this.useClipPlane;
  91605. loader.compileShadowGenerators = this.compileShadowGenerators;
  91606. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  91607. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  91608. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  91609. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  91610. loader.onCompleteObservable.add(function () {
  91611. _this.onMeshLoadedObservable.clear();
  91612. _this.onTextureLoadedObservable.clear();
  91613. _this.onMaterialLoadedObservable.clear();
  91614. _this.onCompleteObservable.notifyObservers(_this);
  91615. _this.onCompleteObservable.clear();
  91616. });
  91617. return loader;
  91618. };
  91619. GLTFFileLoader._parseBinary = function (data) {
  91620. var Binary = {
  91621. Magic: 0x46546C67
  91622. };
  91623. var binaryReader = new BinaryReader(data);
  91624. var magic = binaryReader.readUint32();
  91625. if (magic !== Binary.Magic) {
  91626. throw new Error("Unexpected magic: " + magic);
  91627. }
  91628. var version = binaryReader.readUint32();
  91629. switch (version) {
  91630. case 1: return GLTFFileLoader._parseV1(binaryReader);
  91631. case 2: return GLTFFileLoader._parseV2(binaryReader);
  91632. }
  91633. throw new Error("Unsupported version: " + version);
  91634. };
  91635. GLTFFileLoader._parseV1 = function (binaryReader) {
  91636. var ContentFormat = {
  91637. JSON: 0
  91638. };
  91639. var length = binaryReader.readUint32();
  91640. if (length != binaryReader.getLength()) {
  91641. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  91642. }
  91643. var contentLength = binaryReader.readUint32();
  91644. var contentFormat = binaryReader.readUint32();
  91645. var content;
  91646. switch (contentFormat) {
  91647. case ContentFormat.JSON: {
  91648. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  91649. break;
  91650. }
  91651. default: {
  91652. throw new Error("Unexpected content format: " + contentFormat);
  91653. }
  91654. }
  91655. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  91656. var body = binaryReader.readUint8Array(bytesRemaining);
  91657. return {
  91658. json: content,
  91659. bin: body
  91660. };
  91661. };
  91662. GLTFFileLoader._parseV2 = function (binaryReader) {
  91663. var ChunkFormat = {
  91664. JSON: 0x4E4F534A,
  91665. BIN: 0x004E4942
  91666. };
  91667. var length = binaryReader.readUint32();
  91668. if (length !== binaryReader.getLength()) {
  91669. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  91670. }
  91671. // JSON chunk
  91672. var chunkLength = binaryReader.readUint32();
  91673. var chunkFormat = binaryReader.readUint32();
  91674. if (chunkFormat !== ChunkFormat.JSON) {
  91675. throw new Error("First chunk format is not JSON");
  91676. }
  91677. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  91678. // Look for BIN chunk
  91679. var bin = null;
  91680. while (binaryReader.getPosition() < binaryReader.getLength()) {
  91681. var chunkLength_1 = binaryReader.readUint32();
  91682. var chunkFormat_1 = binaryReader.readUint32();
  91683. switch (chunkFormat_1) {
  91684. case ChunkFormat.JSON: {
  91685. throw new Error("Unexpected JSON chunk");
  91686. }
  91687. case ChunkFormat.BIN: {
  91688. bin = binaryReader.readUint8Array(chunkLength_1);
  91689. break;
  91690. }
  91691. default: {
  91692. // ignore unrecognized chunkFormat
  91693. binaryReader.skipBytes(chunkLength_1);
  91694. break;
  91695. }
  91696. }
  91697. }
  91698. return {
  91699. json: json,
  91700. bin: bin
  91701. };
  91702. };
  91703. GLTFFileLoader._parseVersion = function (version) {
  91704. if (version === "1.0" || version === "1.0.1") {
  91705. return {
  91706. major: 1,
  91707. minor: 0
  91708. };
  91709. }
  91710. var match = (version + "").match(/^(\d+)\.(\d+)/);
  91711. if (!match) {
  91712. return null;
  91713. }
  91714. return {
  91715. major: parseInt(match[1]),
  91716. minor: parseInt(match[2])
  91717. };
  91718. };
  91719. GLTFFileLoader._compareVersion = function (a, b) {
  91720. if (a.major > b.major)
  91721. return 1;
  91722. if (a.major < b.major)
  91723. return -1;
  91724. if (a.minor > b.minor)
  91725. return 1;
  91726. if (a.minor < b.minor)
  91727. return -1;
  91728. return 0;
  91729. };
  91730. GLTFFileLoader._decodeBufferToText = function (buffer) {
  91731. var result = "";
  91732. var length = buffer.byteLength;
  91733. for (var i = 0; i < length; i++) {
  91734. result += String.fromCharCode(buffer[i]);
  91735. }
  91736. return result;
  91737. };
  91738. // #endregion
  91739. // #region V1 options
  91740. GLTFFileLoader.IncrementalLoading = true;
  91741. GLTFFileLoader.HomogeneousCoordinates = false;
  91742. return GLTFFileLoader;
  91743. }());
  91744. BABYLON.GLTFFileLoader = GLTFFileLoader;
  91745. var BinaryReader = /** @class */ (function () {
  91746. function BinaryReader(arrayBuffer) {
  91747. this._arrayBuffer = arrayBuffer;
  91748. this._dataView = new DataView(arrayBuffer);
  91749. this._byteOffset = 0;
  91750. }
  91751. BinaryReader.prototype.getPosition = function () {
  91752. return this._byteOffset;
  91753. };
  91754. BinaryReader.prototype.getLength = function () {
  91755. return this._arrayBuffer.byteLength;
  91756. };
  91757. BinaryReader.prototype.readUint32 = function () {
  91758. var value = this._dataView.getUint32(this._byteOffset, true);
  91759. this._byteOffset += 4;
  91760. return value;
  91761. };
  91762. BinaryReader.prototype.readUint8Array = function (length) {
  91763. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  91764. this._byteOffset += length;
  91765. return value;
  91766. };
  91767. BinaryReader.prototype.skipBytes = function (length) {
  91768. this._byteOffset += length;
  91769. };
  91770. return BinaryReader;
  91771. }());
  91772. if (BABYLON.SceneLoader) {
  91773. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  91774. }
  91775. })(BABYLON || (BABYLON = {}));
  91776. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  91777. "use strict";
  91778. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91779. var BABYLON;
  91780. (function (BABYLON) {
  91781. var GLTF1;
  91782. (function (GLTF1) {
  91783. /**
  91784. * Enums
  91785. */
  91786. var EComponentType;
  91787. (function (EComponentType) {
  91788. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  91789. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  91790. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  91791. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  91792. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  91793. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  91794. var EShaderType;
  91795. (function (EShaderType) {
  91796. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  91797. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  91798. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  91799. var EParameterType;
  91800. (function (EParameterType) {
  91801. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  91802. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  91803. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  91804. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  91805. EParameterType[EParameterType["INT"] = 5124] = "INT";
  91806. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  91807. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  91808. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  91809. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  91810. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  91811. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  91812. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  91813. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  91814. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  91815. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  91816. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  91817. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  91818. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  91819. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  91820. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  91821. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  91822. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  91823. var ETextureWrapMode;
  91824. (function (ETextureWrapMode) {
  91825. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  91826. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  91827. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  91828. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  91829. var ETextureFilterType;
  91830. (function (ETextureFilterType) {
  91831. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  91832. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  91833. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  91834. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  91835. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  91836. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  91837. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  91838. var ETextureFormat;
  91839. (function (ETextureFormat) {
  91840. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  91841. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  91842. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  91843. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  91844. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  91845. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  91846. var ECullingType;
  91847. (function (ECullingType) {
  91848. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  91849. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  91850. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  91851. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  91852. var EBlendingFunction;
  91853. (function (EBlendingFunction) {
  91854. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  91855. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  91856. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  91857. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  91858. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  91859. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  91860. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  91861. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  91862. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  91863. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  91864. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  91865. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  91866. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  91867. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  91868. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  91869. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  91870. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91871. })(BABYLON || (BABYLON = {}));
  91872. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  91873. "use strict";
  91874. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91875. var BABYLON;
  91876. (function (BABYLON) {
  91877. var GLTF1;
  91878. (function (GLTF1) {
  91879. /**
  91880. * Tokenizer. Used for shaders compatibility
  91881. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  91882. */
  91883. var ETokenType;
  91884. (function (ETokenType) {
  91885. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  91886. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  91887. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  91888. })(ETokenType || (ETokenType = {}));
  91889. var Tokenizer = /** @class */ (function () {
  91890. function Tokenizer(toParse) {
  91891. this._pos = 0;
  91892. this.currentToken = ETokenType.UNKNOWN;
  91893. this.currentIdentifier = "";
  91894. this.currentString = "";
  91895. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  91896. this._toParse = toParse;
  91897. this._maxPos = toParse.length;
  91898. }
  91899. Tokenizer.prototype.getNextToken = function () {
  91900. if (this.isEnd())
  91901. return ETokenType.END_OF_INPUT;
  91902. this.currentString = this.read();
  91903. this.currentToken = ETokenType.UNKNOWN;
  91904. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  91905. this.currentToken = ETokenType.IDENTIFIER;
  91906. this.currentIdentifier = this.currentString;
  91907. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  91908. this.currentIdentifier += this.currentString;
  91909. this.forward();
  91910. }
  91911. }
  91912. return this.currentToken;
  91913. };
  91914. Tokenizer.prototype.peek = function () {
  91915. return this._toParse[this._pos];
  91916. };
  91917. Tokenizer.prototype.read = function () {
  91918. return this._toParse[this._pos++];
  91919. };
  91920. Tokenizer.prototype.forward = function () {
  91921. this._pos++;
  91922. };
  91923. Tokenizer.prototype.isEnd = function () {
  91924. return this._pos >= this._maxPos;
  91925. };
  91926. return Tokenizer;
  91927. }());
  91928. /**
  91929. * Values
  91930. */
  91931. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  91932. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  91933. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  91934. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  91935. /**
  91936. * Parse
  91937. */
  91938. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  91939. for (var buf in parsedBuffers) {
  91940. var parsedBuffer = parsedBuffers[buf];
  91941. gltfRuntime.buffers[buf] = parsedBuffer;
  91942. gltfRuntime.buffersCount++;
  91943. }
  91944. };
  91945. var parseShaders = function (parsedShaders, gltfRuntime) {
  91946. for (var sha in parsedShaders) {
  91947. var parsedShader = parsedShaders[sha];
  91948. gltfRuntime.shaders[sha] = parsedShader;
  91949. gltfRuntime.shaderscount++;
  91950. }
  91951. };
  91952. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  91953. for (var object in parsedObjects) {
  91954. var parsedObject = parsedObjects[object];
  91955. gltfRuntime[runtimeProperty][object] = parsedObject;
  91956. }
  91957. };
  91958. /**
  91959. * Utils
  91960. */
  91961. var normalizeUVs = function (buffer) {
  91962. if (!buffer) {
  91963. return;
  91964. }
  91965. for (var i = 0; i < buffer.length / 2; i++) {
  91966. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  91967. }
  91968. };
  91969. var getAttribute = function (attributeParameter) {
  91970. if (attributeParameter.semantic === "NORMAL") {
  91971. return "normal";
  91972. }
  91973. else if (attributeParameter.semantic === "POSITION") {
  91974. return "position";
  91975. }
  91976. else if (attributeParameter.semantic === "JOINT") {
  91977. return "matricesIndices";
  91978. }
  91979. else if (attributeParameter.semantic === "WEIGHT") {
  91980. return "matricesWeights";
  91981. }
  91982. else if (attributeParameter.semantic === "COLOR") {
  91983. return "color";
  91984. }
  91985. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  91986. var channel = Number(attributeParameter.semantic.split("_")[1]);
  91987. return "uv" + (channel === 0 ? "" : channel + 1);
  91988. }
  91989. return null;
  91990. };
  91991. /**
  91992. * Loads and creates animations
  91993. */
  91994. var loadAnimations = function (gltfRuntime) {
  91995. for (var anim in gltfRuntime.animations) {
  91996. var animation = gltfRuntime.animations[anim];
  91997. if (!animation.channels || !animation.samplers) {
  91998. continue;
  91999. }
  92000. var lastAnimation = null;
  92001. for (var i = 0; i < animation.channels.length; i++) {
  92002. // Get parameters and load buffers
  92003. var channel = animation.channels[i];
  92004. var sampler = animation.samplers[channel.sampler];
  92005. if (!sampler) {
  92006. continue;
  92007. }
  92008. var inputData = null;
  92009. var outputData = null;
  92010. if (animation.parameters) {
  92011. inputData = animation.parameters[sampler.input];
  92012. outputData = animation.parameters[sampler.output];
  92013. }
  92014. else {
  92015. inputData = sampler.input;
  92016. outputData = sampler.output;
  92017. }
  92018. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  92019. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  92020. var targetID = channel.target.id;
  92021. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  92022. if (targetNode === null) {
  92023. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  92024. }
  92025. if (targetNode === null) {
  92026. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  92027. continue;
  92028. }
  92029. var isBone = targetNode instanceof BABYLON.Bone;
  92030. // Get target path (position, rotation or scaling)
  92031. var targetPath = channel.target.path;
  92032. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  92033. if (targetPathIndex !== -1) {
  92034. targetPath = babylonAnimationPaths[targetPathIndex];
  92035. }
  92036. // Determine animation type
  92037. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  92038. if (!isBone) {
  92039. if (targetPath === "rotationQuaternion") {
  92040. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  92041. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  92042. }
  92043. else {
  92044. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  92045. }
  92046. }
  92047. // Create animation and key frames
  92048. var babylonAnimation = null;
  92049. var keys = [];
  92050. var arrayOffset = 0;
  92051. var modifyKey = false;
  92052. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  92053. babylonAnimation = lastAnimation;
  92054. modifyKey = true;
  92055. }
  92056. if (!modifyKey) {
  92057. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  92058. }
  92059. // For each frame
  92060. for (var j = 0; j < bufferInput.length; j++) {
  92061. var value = null;
  92062. if (targetPath === "rotationQuaternion") {
  92063. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  92064. arrayOffset += 4;
  92065. }
  92066. else {
  92067. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  92068. arrayOffset += 3;
  92069. }
  92070. if (isBone) {
  92071. var bone = targetNode;
  92072. var translation = BABYLON.Vector3.Zero();
  92073. var rotationQuaternion = new BABYLON.Quaternion();
  92074. var scaling = BABYLON.Vector3.Zero();
  92075. // Warning on decompose
  92076. var mat = bone.getBaseMatrix();
  92077. if (modifyKey && lastAnimation) {
  92078. mat = lastAnimation.getKeys()[j].value;
  92079. }
  92080. mat.decompose(scaling, rotationQuaternion, translation);
  92081. if (targetPath === "position") {
  92082. translation = value;
  92083. }
  92084. else if (targetPath === "rotationQuaternion") {
  92085. rotationQuaternion = value;
  92086. }
  92087. else {
  92088. scaling = value;
  92089. }
  92090. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  92091. }
  92092. if (!modifyKey) {
  92093. keys.push({
  92094. frame: bufferInput[j],
  92095. value: value
  92096. });
  92097. }
  92098. else if (lastAnimation) {
  92099. lastAnimation.getKeys()[j].value = value;
  92100. }
  92101. }
  92102. // Finish
  92103. if (!modifyKey && babylonAnimation) {
  92104. babylonAnimation.setKeys(keys);
  92105. targetNode.animations.push(babylonAnimation);
  92106. }
  92107. lastAnimation = babylonAnimation;
  92108. gltfRuntime.scene.stopAnimation(targetNode);
  92109. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  92110. }
  92111. }
  92112. };
  92113. /**
  92114. * Returns the bones transformation matrix
  92115. */
  92116. var configureBoneTransformation = function (node) {
  92117. var mat = null;
  92118. if (node.translation || node.rotation || node.scale) {
  92119. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  92120. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  92121. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  92122. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  92123. }
  92124. else {
  92125. mat = BABYLON.Matrix.FromArray(node.matrix);
  92126. }
  92127. return mat;
  92128. };
  92129. /**
  92130. * Returns the parent bone
  92131. */
  92132. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  92133. // Try to find
  92134. for (var i = 0; i < newSkeleton.bones.length; i++) {
  92135. if (newSkeleton.bones[i].name === jointName) {
  92136. return newSkeleton.bones[i];
  92137. }
  92138. }
  92139. // Not found, search in gltf nodes
  92140. var nodes = gltfRuntime.nodes;
  92141. for (var nde in nodes) {
  92142. var node = nodes[nde];
  92143. if (!node.jointName) {
  92144. continue;
  92145. }
  92146. var children = node.children;
  92147. for (var i = 0; i < children.length; i++) {
  92148. var child = gltfRuntime.nodes[children[i]];
  92149. if (!child.jointName) {
  92150. continue;
  92151. }
  92152. if (child.jointName === jointName) {
  92153. var mat = configureBoneTransformation(node);
  92154. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  92155. bone.id = nde;
  92156. return bone;
  92157. }
  92158. }
  92159. }
  92160. return null;
  92161. };
  92162. /**
  92163. * Returns the appropriate root node
  92164. */
  92165. var getNodeToRoot = function (nodesToRoot, id) {
  92166. for (var i = 0; i < nodesToRoot.length; i++) {
  92167. var nodeToRoot = nodesToRoot[i];
  92168. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  92169. var child = nodeToRoot.node.children[j];
  92170. if (child === id) {
  92171. return nodeToRoot.bone;
  92172. }
  92173. }
  92174. }
  92175. return null;
  92176. };
  92177. /**
  92178. * Returns the node with the joint name
  92179. */
  92180. var getJointNode = function (gltfRuntime, jointName) {
  92181. var nodes = gltfRuntime.nodes;
  92182. var node = nodes[jointName];
  92183. if (node) {
  92184. return {
  92185. node: node,
  92186. id: jointName
  92187. };
  92188. }
  92189. for (var nde in nodes) {
  92190. node = nodes[nde];
  92191. if (node.jointName === jointName) {
  92192. return {
  92193. node: node,
  92194. id: nde
  92195. };
  92196. }
  92197. }
  92198. return null;
  92199. };
  92200. /**
  92201. * Checks if a nodes is in joints
  92202. */
  92203. var nodeIsInJoints = function (skins, id) {
  92204. for (var i = 0; i < skins.jointNames.length; i++) {
  92205. if (skins.jointNames[i] === id) {
  92206. return true;
  92207. }
  92208. }
  92209. return false;
  92210. };
  92211. /**
  92212. * Fills the nodes to root for bones and builds hierarchy
  92213. */
  92214. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  92215. // Creates nodes for root
  92216. for (var nde in gltfRuntime.nodes) {
  92217. var node = gltfRuntime.nodes[nde];
  92218. var id = nde;
  92219. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  92220. continue;
  92221. }
  92222. // Create node to root bone
  92223. var mat = configureBoneTransformation(node);
  92224. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  92225. bone.id = id;
  92226. nodesToRoot.push({ bone: bone, node: node, id: id });
  92227. }
  92228. // Parenting
  92229. for (var i = 0; i < nodesToRoot.length; i++) {
  92230. var nodeToRoot = nodesToRoot[i];
  92231. var children = nodeToRoot.node.children;
  92232. for (var j = 0; j < children.length; j++) {
  92233. var child = null;
  92234. for (var k = 0; k < nodesToRoot.length; k++) {
  92235. if (nodesToRoot[k].id === children[j]) {
  92236. child = nodesToRoot[k];
  92237. break;
  92238. }
  92239. }
  92240. if (child) {
  92241. child.bone._parent = nodeToRoot.bone;
  92242. nodeToRoot.bone.children.push(child.bone);
  92243. }
  92244. }
  92245. }
  92246. };
  92247. /**
  92248. * Imports a skeleton
  92249. */
  92250. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  92251. if (!newSkeleton) {
  92252. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  92253. }
  92254. if (!skins.babylonSkeleton) {
  92255. return newSkeleton;
  92256. }
  92257. // Find the root bones
  92258. var nodesToRoot = [];
  92259. var nodesToRootToAdd = [];
  92260. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  92261. newSkeleton.bones = [];
  92262. // Joints
  92263. for (var i = 0; i < skins.jointNames.length; i++) {
  92264. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  92265. if (!jointNode) {
  92266. continue;
  92267. }
  92268. var node = jointNode.node;
  92269. if (!node) {
  92270. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  92271. continue;
  92272. }
  92273. var id = jointNode.id;
  92274. // Optimize, if the bone already exists...
  92275. var existingBone = gltfRuntime.scene.getBoneByID(id);
  92276. if (existingBone) {
  92277. newSkeleton.bones.push(existingBone);
  92278. continue;
  92279. }
  92280. // Search for parent bone
  92281. var foundBone = false;
  92282. var parentBone = null;
  92283. for (var j = 0; j < i; j++) {
  92284. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  92285. if (!jointNode_1) {
  92286. continue;
  92287. }
  92288. var joint = jointNode_1.node;
  92289. if (!joint) {
  92290. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  92291. continue;
  92292. }
  92293. var children = joint.children;
  92294. if (!children) {
  92295. continue;
  92296. }
  92297. foundBone = false;
  92298. for (var k = 0; k < children.length; k++) {
  92299. if (children[k] === id) {
  92300. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  92301. foundBone = true;
  92302. break;
  92303. }
  92304. }
  92305. if (foundBone) {
  92306. break;
  92307. }
  92308. }
  92309. // Create bone
  92310. var mat = configureBoneTransformation(node);
  92311. if (!parentBone && nodesToRoot.length > 0) {
  92312. parentBone = getNodeToRoot(nodesToRoot, id);
  92313. if (parentBone) {
  92314. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  92315. nodesToRootToAdd.push(parentBone);
  92316. }
  92317. }
  92318. }
  92319. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  92320. bone.id = id;
  92321. }
  92322. // Polish
  92323. var bones = newSkeleton.bones;
  92324. newSkeleton.bones = [];
  92325. for (var i = 0; i < skins.jointNames.length; i++) {
  92326. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  92327. if (!jointNode) {
  92328. continue;
  92329. }
  92330. for (var j = 0; j < bones.length; j++) {
  92331. if (bones[j].id === jointNode.id) {
  92332. newSkeleton.bones.push(bones[j]);
  92333. break;
  92334. }
  92335. }
  92336. }
  92337. newSkeleton.prepare();
  92338. // Finish
  92339. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  92340. newSkeleton.bones.push(nodesToRootToAdd[i]);
  92341. }
  92342. return newSkeleton;
  92343. };
  92344. /**
  92345. * Imports a mesh and its geometries
  92346. */
  92347. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  92348. if (!newMesh) {
  92349. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  92350. newMesh.id = id;
  92351. }
  92352. if (!node.babylonNode) {
  92353. return newMesh;
  92354. }
  92355. var subMaterials = [];
  92356. var vertexData = null;
  92357. var verticesStarts = new Array();
  92358. var verticesCounts = new Array();
  92359. var indexStarts = new Array();
  92360. var indexCounts = new Array();
  92361. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  92362. var meshID = meshes[meshIndex];
  92363. var mesh = gltfRuntime.meshes[meshID];
  92364. if (!mesh) {
  92365. continue;
  92366. }
  92367. // Positions, normals and UVs
  92368. for (var i = 0; i < mesh.primitives.length; i++) {
  92369. // Temporary vertex data
  92370. var tempVertexData = new BABYLON.VertexData();
  92371. var primitive = mesh.primitives[i];
  92372. if (primitive.mode !== 4) {
  92373. // continue;
  92374. }
  92375. var attributes = primitive.attributes;
  92376. var accessor = null;
  92377. var buffer = null;
  92378. // Set positions, normal and uvs
  92379. for (var semantic in attributes) {
  92380. // Link accessor and buffer view
  92381. accessor = gltfRuntime.accessors[attributes[semantic]];
  92382. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  92383. if (semantic === "NORMAL") {
  92384. tempVertexData.normals = new Float32Array(buffer.length);
  92385. tempVertexData.normals.set(buffer);
  92386. }
  92387. else if (semantic === "POSITION") {
  92388. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  92389. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  92390. for (var j = 0; j < buffer.length; j += 4) {
  92391. tempVertexData.positions[j] = buffer[j];
  92392. tempVertexData.positions[j + 1] = buffer[j + 1];
  92393. tempVertexData.positions[j + 2] = buffer[j + 2];
  92394. }
  92395. }
  92396. else {
  92397. tempVertexData.positions = new Float32Array(buffer.length);
  92398. tempVertexData.positions.set(buffer);
  92399. }
  92400. verticesCounts.push(tempVertexData.positions.length);
  92401. }
  92402. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  92403. var channel = Number(semantic.split("_")[1]);
  92404. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  92405. var uvs = new Float32Array(buffer.length);
  92406. uvs.set(buffer);
  92407. normalizeUVs(uvs);
  92408. tempVertexData.set(uvs, uvKind);
  92409. }
  92410. else if (semantic === "JOINT") {
  92411. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  92412. tempVertexData.matricesIndices.set(buffer);
  92413. }
  92414. else if (semantic === "WEIGHT") {
  92415. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  92416. tempVertexData.matricesWeights.set(buffer);
  92417. }
  92418. else if (semantic === "COLOR") {
  92419. tempVertexData.colors = new Float32Array(buffer.length);
  92420. tempVertexData.colors.set(buffer);
  92421. }
  92422. }
  92423. // Indices
  92424. accessor = gltfRuntime.accessors[primitive.indices];
  92425. if (accessor) {
  92426. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  92427. tempVertexData.indices = new Int32Array(buffer.length);
  92428. tempVertexData.indices.set(buffer);
  92429. indexCounts.push(tempVertexData.indices.length);
  92430. }
  92431. else {
  92432. // Set indices on the fly
  92433. var indices = [];
  92434. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  92435. indices.push(j);
  92436. }
  92437. tempVertexData.indices = new Int32Array(indices);
  92438. indexCounts.push(tempVertexData.indices.length);
  92439. }
  92440. if (!vertexData) {
  92441. vertexData = tempVertexData;
  92442. }
  92443. else {
  92444. vertexData.merge(tempVertexData);
  92445. }
  92446. // Sub material
  92447. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  92448. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  92449. // Update vertices start and index start
  92450. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  92451. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  92452. }
  92453. }
  92454. var material;
  92455. if (subMaterials.length > 1) {
  92456. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  92457. material.subMaterials = subMaterials;
  92458. }
  92459. else {
  92460. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  92461. }
  92462. if (subMaterials.length === 1) {
  92463. material = subMaterials[0];
  92464. }
  92465. if (!newMesh.material) {
  92466. newMesh.material = material;
  92467. }
  92468. // Apply geometry
  92469. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  92470. newMesh.computeWorldMatrix(true);
  92471. // Apply submeshes
  92472. newMesh.subMeshes = [];
  92473. var index = 0;
  92474. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  92475. var meshID = meshes[meshIndex];
  92476. var mesh = gltfRuntime.meshes[meshID];
  92477. if (!mesh) {
  92478. continue;
  92479. }
  92480. for (var i = 0; i < mesh.primitives.length; i++) {
  92481. if (mesh.primitives[i].mode !== 4) {
  92482. //continue;
  92483. }
  92484. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  92485. index++;
  92486. }
  92487. }
  92488. // Finish
  92489. return newMesh;
  92490. };
  92491. /**
  92492. * Configure node transformation from position, rotation and scaling
  92493. */
  92494. var configureNode = function (newNode, position, rotation, scaling) {
  92495. if (newNode.position) {
  92496. newNode.position = position;
  92497. }
  92498. if (newNode.rotationQuaternion || newNode.rotation) {
  92499. newNode.rotationQuaternion = rotation;
  92500. }
  92501. if (newNode.scaling) {
  92502. newNode.scaling = scaling;
  92503. }
  92504. };
  92505. /**
  92506. * Configures node from transformation matrix
  92507. */
  92508. var configureNodeFromMatrix = function (newNode, node, parent) {
  92509. if (node.matrix) {
  92510. var position = new BABYLON.Vector3(0, 0, 0);
  92511. var rotation = new BABYLON.Quaternion();
  92512. var scaling = new BABYLON.Vector3(0, 0, 0);
  92513. var mat = BABYLON.Matrix.FromArray(node.matrix);
  92514. mat.decompose(scaling, rotation, position);
  92515. configureNode(newNode, position, rotation, scaling);
  92516. }
  92517. else if (node.translation && node.rotation && node.scale) {
  92518. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  92519. }
  92520. newNode.computeWorldMatrix(true);
  92521. };
  92522. /**
  92523. * Imports a node
  92524. */
  92525. var importNode = function (gltfRuntime, node, id, parent) {
  92526. var lastNode = null;
  92527. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  92528. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  92529. return null;
  92530. }
  92531. }
  92532. // Meshes
  92533. if (node.skin) {
  92534. if (node.meshes) {
  92535. var skin = gltfRuntime.skins[node.skin];
  92536. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  92537. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  92538. if (newMesh.skeleton === null) {
  92539. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  92540. if (!skin.babylonSkeleton) {
  92541. skin.babylonSkeleton = newMesh.skeleton;
  92542. }
  92543. }
  92544. lastNode = newMesh;
  92545. }
  92546. }
  92547. else if (node.meshes) {
  92548. /**
  92549. * Improve meshes property
  92550. */
  92551. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  92552. lastNode = newMesh;
  92553. }
  92554. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  92555. var light = gltfRuntime.lights[node.light];
  92556. if (light) {
  92557. if (light.type === "ambient") {
  92558. var ambienLight = light[light.type];
  92559. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  92560. hemiLight.name = node.name || "";
  92561. if (ambienLight.color) {
  92562. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  92563. }
  92564. lastNode = hemiLight;
  92565. }
  92566. else if (light.type === "directional") {
  92567. var directionalLight = light[light.type];
  92568. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  92569. dirLight.name = node.name || "";
  92570. if (directionalLight.color) {
  92571. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  92572. }
  92573. lastNode = dirLight;
  92574. }
  92575. else if (light.type === "point") {
  92576. var pointLight = light[light.type];
  92577. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  92578. ptLight.name = node.name || "";
  92579. if (pointLight.color) {
  92580. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  92581. }
  92582. lastNode = ptLight;
  92583. }
  92584. else if (light.type === "spot") {
  92585. var spotLight = light[light.type];
  92586. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  92587. spLight.name = node.name || "";
  92588. if (spotLight.color) {
  92589. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  92590. }
  92591. if (spotLight.fallOfAngle) {
  92592. spLight.angle = spotLight.fallOfAngle;
  92593. }
  92594. if (spotLight.fallOffExponent) {
  92595. spLight.exponent = spotLight.fallOffExponent;
  92596. }
  92597. lastNode = spLight;
  92598. }
  92599. }
  92600. }
  92601. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  92602. var camera = gltfRuntime.cameras[node.camera];
  92603. if (camera) {
  92604. if (camera.type === "orthographic") {
  92605. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  92606. orthoCamera.name = node.name || "";
  92607. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  92608. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  92609. lastNode = orthoCamera;
  92610. }
  92611. else if (camera.type === "perspective") {
  92612. var perspectiveCamera = camera[camera.type];
  92613. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  92614. persCamera.name = node.name || "";
  92615. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  92616. if (!perspectiveCamera.aspectRatio) {
  92617. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  92618. }
  92619. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  92620. persCamera.maxZ = perspectiveCamera.zfar;
  92621. persCamera.minZ = perspectiveCamera.znear;
  92622. }
  92623. lastNode = persCamera;
  92624. }
  92625. }
  92626. }
  92627. // Empty node
  92628. if (!node.jointName) {
  92629. if (node.babylonNode) {
  92630. return node.babylonNode;
  92631. }
  92632. else if (lastNode === null) {
  92633. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  92634. node.babylonNode = dummy;
  92635. lastNode = dummy;
  92636. }
  92637. }
  92638. if (lastNode !== null) {
  92639. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  92640. configureNodeFromMatrix(lastNode, node, parent);
  92641. }
  92642. else {
  92643. var translation = node.translation || [0, 0, 0];
  92644. var rotation = node.rotation || [0, 0, 0, 1];
  92645. var scale = node.scale || [1, 1, 1];
  92646. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  92647. }
  92648. lastNode.updateCache(true);
  92649. node.babylonNode = lastNode;
  92650. }
  92651. return lastNode;
  92652. };
  92653. /**
  92654. * Traverses nodes and creates them
  92655. */
  92656. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  92657. if (meshIncluded === void 0) { meshIncluded = false; }
  92658. var node = gltfRuntime.nodes[id];
  92659. var newNode = null;
  92660. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  92661. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  92662. meshIncluded = true;
  92663. }
  92664. else {
  92665. meshIncluded = false;
  92666. }
  92667. }
  92668. else {
  92669. meshIncluded = true;
  92670. }
  92671. if (!node.jointName && meshIncluded) {
  92672. newNode = importNode(gltfRuntime, node, id, parent);
  92673. if (newNode !== null) {
  92674. newNode.id = id;
  92675. newNode.parent = parent;
  92676. }
  92677. }
  92678. if (node.children) {
  92679. for (var i = 0; i < node.children.length; i++) {
  92680. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  92681. }
  92682. }
  92683. };
  92684. /**
  92685. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  92686. */
  92687. var postLoad = function (gltfRuntime) {
  92688. // Nodes
  92689. var currentScene = gltfRuntime.currentScene;
  92690. if (currentScene) {
  92691. for (var i = 0; i < currentScene.nodes.length; i++) {
  92692. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  92693. }
  92694. }
  92695. else {
  92696. for (var thing in gltfRuntime.scenes) {
  92697. currentScene = gltfRuntime.scenes[thing];
  92698. for (var i = 0; i < currentScene.nodes.length; i++) {
  92699. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  92700. }
  92701. }
  92702. }
  92703. // Set animations
  92704. loadAnimations(gltfRuntime);
  92705. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  92706. var skeleton = gltfRuntime.scene.skeletons[i];
  92707. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  92708. }
  92709. };
  92710. /**
  92711. * onBind shaderrs callback to set uniforms and matrices
  92712. */
  92713. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  92714. var materialValues = material.values || technique.parameters;
  92715. for (var unif in unTreatedUniforms) {
  92716. var uniform = unTreatedUniforms[unif];
  92717. var type = uniform.type;
  92718. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  92719. if (uniform.semantic && !uniform.source && !uniform.node) {
  92720. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  92721. }
  92722. else if (uniform.semantic && (uniform.source || uniform.node)) {
  92723. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  92724. if (source === null) {
  92725. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  92726. }
  92727. if (source === null) {
  92728. continue;
  92729. }
  92730. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  92731. }
  92732. }
  92733. else {
  92734. var value = materialValues[technique.uniforms[unif]];
  92735. if (!value) {
  92736. continue;
  92737. }
  92738. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  92739. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  92740. if (texture === null || texture === undefined) {
  92741. continue;
  92742. }
  92743. shaderMaterial.getEffect().setTexture(unif, texture);
  92744. }
  92745. else {
  92746. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  92747. }
  92748. }
  92749. }
  92750. onSuccess(shaderMaterial);
  92751. };
  92752. /**
  92753. * Prepare uniforms to send the only one time
  92754. * Loads the appropriate textures
  92755. */
  92756. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  92757. var materialValues = material.values || technique.parameters;
  92758. var techniqueUniforms = technique.uniforms;
  92759. /**
  92760. * Prepare values here (not matrices)
  92761. */
  92762. for (var unif in unTreatedUniforms) {
  92763. var uniform = unTreatedUniforms[unif];
  92764. var type = uniform.type;
  92765. var value = materialValues[techniqueUniforms[unif]];
  92766. if (value === undefined) {
  92767. // In case the value is the same for all materials
  92768. value = uniform.value;
  92769. }
  92770. if (!value) {
  92771. continue;
  92772. }
  92773. var onLoadTexture = function (uniformName) {
  92774. return function (texture) {
  92775. if (uniform.value && uniformName) {
  92776. // Static uniform
  92777. shaderMaterial.setTexture(uniformName, texture);
  92778. delete unTreatedUniforms[uniformName];
  92779. }
  92780. };
  92781. };
  92782. // Texture (sampler2D)
  92783. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  92784. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  92785. }
  92786. else {
  92787. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  92788. // Static uniform
  92789. delete unTreatedUniforms[unif];
  92790. }
  92791. }
  92792. }
  92793. };
  92794. /**
  92795. * Shader compilation failed
  92796. */
  92797. var onShaderCompileError = function (program, shaderMaterial, onError) {
  92798. return function (effect, error) {
  92799. shaderMaterial.dispose(true);
  92800. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  92801. };
  92802. };
  92803. /**
  92804. * Shader compilation success
  92805. */
  92806. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  92807. return function (_) {
  92808. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  92809. shaderMaterial.onBind = function (mesh) {
  92810. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  92811. };
  92812. };
  92813. };
  92814. /**
  92815. * Returns the appropriate uniform if already handled by babylon
  92816. */
  92817. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  92818. for (var unif in technique.uniforms) {
  92819. var uniform = technique.uniforms[unif];
  92820. var uniformParameter = technique.parameters[uniform];
  92821. if (tokenizer.currentIdentifier === unif) {
  92822. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  92823. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  92824. if (transformIndex !== -1) {
  92825. delete unTreatedUniforms[unif];
  92826. return babylonTransforms[transformIndex];
  92827. }
  92828. }
  92829. }
  92830. }
  92831. return tokenizer.currentIdentifier;
  92832. };
  92833. /**
  92834. * All shaders loaded. Create materials one by one
  92835. */
  92836. var importMaterials = function (gltfRuntime) {
  92837. // Create materials
  92838. for (var mat in gltfRuntime.materials) {
  92839. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  92840. }
  92841. };
  92842. /**
  92843. * Implementation of the base glTF spec
  92844. */
  92845. var GLTFLoaderBase = /** @class */ (function () {
  92846. function GLTFLoaderBase() {
  92847. }
  92848. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  92849. var gltfRuntime = {
  92850. extensions: {},
  92851. accessors: {},
  92852. buffers: {},
  92853. bufferViews: {},
  92854. meshes: {},
  92855. lights: {},
  92856. cameras: {},
  92857. nodes: {},
  92858. images: {},
  92859. textures: {},
  92860. shaders: {},
  92861. programs: {},
  92862. samplers: {},
  92863. techniques: {},
  92864. materials: {},
  92865. animations: {},
  92866. skins: {},
  92867. extensionsUsed: [],
  92868. scenes: {},
  92869. buffersCount: 0,
  92870. shaderscount: 0,
  92871. scene: scene,
  92872. rootUrl: rootUrl,
  92873. loadedBufferCount: 0,
  92874. loadedBufferViews: {},
  92875. loadedShaderCount: 0,
  92876. importOnlyMeshes: false,
  92877. dummyNodes: []
  92878. };
  92879. // Parse
  92880. if (parsedData.extensions) {
  92881. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  92882. }
  92883. if (parsedData.extensionsUsed) {
  92884. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  92885. }
  92886. if (parsedData.buffers) {
  92887. parseBuffers(parsedData.buffers, gltfRuntime);
  92888. }
  92889. if (parsedData.bufferViews) {
  92890. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  92891. }
  92892. if (parsedData.accessors) {
  92893. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  92894. }
  92895. if (parsedData.meshes) {
  92896. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  92897. }
  92898. if (parsedData.lights) {
  92899. parseObject(parsedData.lights, "lights", gltfRuntime);
  92900. }
  92901. if (parsedData.cameras) {
  92902. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  92903. }
  92904. if (parsedData.nodes) {
  92905. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  92906. }
  92907. if (parsedData.images) {
  92908. parseObject(parsedData.images, "images", gltfRuntime);
  92909. }
  92910. if (parsedData.textures) {
  92911. parseObject(parsedData.textures, "textures", gltfRuntime);
  92912. }
  92913. if (parsedData.shaders) {
  92914. parseShaders(parsedData.shaders, gltfRuntime);
  92915. }
  92916. if (parsedData.programs) {
  92917. parseObject(parsedData.programs, "programs", gltfRuntime);
  92918. }
  92919. if (parsedData.samplers) {
  92920. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  92921. }
  92922. if (parsedData.techniques) {
  92923. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  92924. }
  92925. if (parsedData.materials) {
  92926. parseObject(parsedData.materials, "materials", gltfRuntime);
  92927. }
  92928. if (parsedData.animations) {
  92929. parseObject(parsedData.animations, "animations", gltfRuntime);
  92930. }
  92931. if (parsedData.skins) {
  92932. parseObject(parsedData.skins, "skins", gltfRuntime);
  92933. }
  92934. if (parsedData.scenes) {
  92935. gltfRuntime.scenes = parsedData.scenes;
  92936. }
  92937. if (parsedData.scene && parsedData.scenes) {
  92938. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  92939. }
  92940. return gltfRuntime;
  92941. };
  92942. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  92943. var buffer = gltfRuntime.buffers[id];
  92944. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  92945. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  92946. }
  92947. else {
  92948. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  92949. if (request) {
  92950. onError(request.status + " " + request.statusText);
  92951. }
  92952. });
  92953. }
  92954. };
  92955. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92956. var texture = gltfRuntime.textures[id];
  92957. if (!texture || !texture.source) {
  92958. onError("");
  92959. return;
  92960. }
  92961. if (texture.babylonTexture) {
  92962. onSuccess(null);
  92963. return;
  92964. }
  92965. var source = gltfRuntime.images[texture.source];
  92966. if (BABYLON.Tools.IsBase64(source.uri)) {
  92967. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  92968. }
  92969. else {
  92970. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  92971. if (request) {
  92972. onError(request.status + " " + request.statusText);
  92973. }
  92974. });
  92975. }
  92976. };
  92977. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  92978. var texture = gltfRuntime.textures[id];
  92979. if (texture.babylonTexture) {
  92980. onSuccess(texture.babylonTexture);
  92981. return;
  92982. }
  92983. var sampler = gltfRuntime.samplers[texture.sampler];
  92984. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  92985. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  92986. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  92987. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  92988. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  92989. var blob = new Blob([buffer]);
  92990. var blobURL = URL.createObjectURL(blob);
  92991. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  92992. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  92993. if (sampler.wrapS !== undefined) {
  92994. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  92995. }
  92996. if (sampler.wrapT !== undefined) {
  92997. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  92998. }
  92999. newTexture.name = id;
  93000. texture.babylonTexture = newTexture;
  93001. onSuccess(newTexture);
  93002. };
  93003. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  93004. var shader = gltfRuntime.shaders[id];
  93005. if (BABYLON.Tools.IsBase64(shader.uri)) {
  93006. var shaderString = atob(shader.uri.split(",")[1]);
  93007. if (onSuccess) {
  93008. onSuccess(shaderString);
  93009. }
  93010. }
  93011. else {
  93012. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  93013. if (request && onError) {
  93014. onError(request.status + " " + request.statusText);
  93015. }
  93016. });
  93017. }
  93018. };
  93019. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  93020. var material = gltfRuntime.materials[id];
  93021. if (!material.technique) {
  93022. if (onError) {
  93023. onError("No technique found.");
  93024. }
  93025. return;
  93026. }
  93027. var technique = gltfRuntime.techniques[material.technique];
  93028. if (!technique) {
  93029. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  93030. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  93031. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  93032. onSuccess(defaultMaterial);
  93033. return;
  93034. }
  93035. var program = gltfRuntime.programs[technique.program];
  93036. var states = technique.states;
  93037. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  93038. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  93039. var newVertexShader = "";
  93040. var newPixelShader = "";
  93041. var vertexTokenizer = new Tokenizer(vertexShader);
  93042. var pixelTokenizer = new Tokenizer(pixelShader);
  93043. var unTreatedUniforms = {};
  93044. var uniforms = [];
  93045. var attributes = [];
  93046. var samplers = [];
  93047. // Fill uniform, sampler2D and attributes
  93048. for (var unif in technique.uniforms) {
  93049. var uniform = technique.uniforms[unif];
  93050. var uniformParameter = technique.parameters[uniform];
  93051. unTreatedUniforms[unif] = uniformParameter;
  93052. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  93053. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  93054. if (transformIndex !== -1) {
  93055. uniforms.push(babylonTransforms[transformIndex]);
  93056. delete unTreatedUniforms[unif];
  93057. }
  93058. else {
  93059. uniforms.push(unif);
  93060. }
  93061. }
  93062. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  93063. samplers.push(unif);
  93064. }
  93065. else {
  93066. uniforms.push(unif);
  93067. }
  93068. }
  93069. for (var attr in technique.attributes) {
  93070. var attribute = technique.attributes[attr];
  93071. var attributeParameter = technique.parameters[attribute];
  93072. if (attributeParameter.semantic) {
  93073. attributes.push(getAttribute(attributeParameter));
  93074. }
  93075. }
  93076. // Configure vertex shader
  93077. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  93078. var tokenType = vertexTokenizer.currentToken;
  93079. if (tokenType !== ETokenType.IDENTIFIER) {
  93080. newVertexShader += vertexTokenizer.currentString;
  93081. continue;
  93082. }
  93083. var foundAttribute = false;
  93084. for (var attr in technique.attributes) {
  93085. var attribute = technique.attributes[attr];
  93086. var attributeParameter = technique.parameters[attribute];
  93087. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  93088. newVertexShader += getAttribute(attributeParameter);
  93089. foundAttribute = true;
  93090. break;
  93091. }
  93092. }
  93093. if (foundAttribute) {
  93094. continue;
  93095. }
  93096. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  93097. }
  93098. // Configure pixel shader
  93099. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  93100. var tokenType = pixelTokenizer.currentToken;
  93101. if (tokenType !== ETokenType.IDENTIFIER) {
  93102. newPixelShader += pixelTokenizer.currentString;
  93103. continue;
  93104. }
  93105. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  93106. }
  93107. // Create shader material
  93108. var shaderPath = {
  93109. vertex: program.vertexShader + id,
  93110. fragment: program.fragmentShader + id
  93111. };
  93112. var options = {
  93113. attributes: attributes,
  93114. uniforms: uniforms,
  93115. samplers: samplers,
  93116. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  93117. };
  93118. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  93119. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  93120. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  93121. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  93122. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  93123. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  93124. if (states && states.functions) {
  93125. var functions = states.functions;
  93126. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  93127. shaderMaterial.backFaceCulling = false;
  93128. }
  93129. var blendFunc = functions.blendFuncSeparate;
  93130. if (blendFunc) {
  93131. 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) {
  93132. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  93133. }
  93134. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  93135. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  93136. }
  93137. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  93138. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  93139. }
  93140. 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) {
  93141. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  93142. }
  93143. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  93144. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  93145. }
  93146. 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) {
  93147. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  93148. }
  93149. }
  93150. }
  93151. };
  93152. return GLTFLoaderBase;
  93153. }());
  93154. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  93155. /**
  93156. * glTF V1 Loader
  93157. */
  93158. var GLTFLoader = /** @class */ (function () {
  93159. function GLTFLoader() {
  93160. // #region Stubs for IGLTFLoader interface
  93161. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  93162. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  93163. this.compileMaterials = false;
  93164. this.useClipPlane = false;
  93165. this.compileShadowGenerators = false;
  93166. this.onDisposeObservable = new BABYLON.Observable();
  93167. this.onMeshLoadedObservable = new BABYLON.Observable();
  93168. this.onTextureLoadedObservable = new BABYLON.Observable();
  93169. this.onMaterialLoadedObservable = new BABYLON.Observable();
  93170. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  93171. this.onCompleteObservable = new BABYLON.Observable();
  93172. this.onExtensionLoadedObservable = new BABYLON.Observable();
  93173. this.state = null;
  93174. }
  93175. GLTFLoader.RegisterExtension = function (extension) {
  93176. if (GLTFLoader.Extensions[extension.name]) {
  93177. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  93178. return;
  93179. }
  93180. GLTFLoader.Extensions[extension.name] = extension;
  93181. };
  93182. GLTFLoader.prototype.dispose = function () { };
  93183. // #endregion
  93184. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  93185. var _this = this;
  93186. scene.useRightHandedSystem = true;
  93187. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  93188. gltfRuntime.importOnlyMeshes = true;
  93189. if (meshesNames === "") {
  93190. gltfRuntime.importMeshesNames = [];
  93191. }
  93192. else if (typeof meshesNames === "string") {
  93193. gltfRuntime.importMeshesNames = [meshesNames];
  93194. }
  93195. else if (meshesNames && !(meshesNames instanceof Array)) {
  93196. gltfRuntime.importMeshesNames = [meshesNames];
  93197. }
  93198. else {
  93199. gltfRuntime.importMeshesNames = [];
  93200. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  93201. }
  93202. // Create nodes
  93203. _this._createNodes(gltfRuntime);
  93204. var meshes = new Array();
  93205. var skeletons = new Array();
  93206. // Fill arrays of meshes and skeletons
  93207. for (var nde in gltfRuntime.nodes) {
  93208. var node = gltfRuntime.nodes[nde];
  93209. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  93210. meshes.push(node.babylonNode);
  93211. }
  93212. }
  93213. for (var skl in gltfRuntime.skins) {
  93214. var skin = gltfRuntime.skins[skl];
  93215. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  93216. skeletons.push(skin.babylonSkeleton);
  93217. }
  93218. }
  93219. // Load buffers, shaders, materials, etc.
  93220. _this._loadBuffersAsync(gltfRuntime, function () {
  93221. _this._loadShadersAsync(gltfRuntime, function () {
  93222. importMaterials(gltfRuntime);
  93223. postLoad(gltfRuntime);
  93224. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  93225. onSuccess(meshes, [], skeletons);
  93226. }
  93227. });
  93228. }, onProgress);
  93229. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  93230. onSuccess(meshes, [], skeletons);
  93231. }
  93232. }, onError);
  93233. return true;
  93234. };
  93235. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  93236. var _this = this;
  93237. return new Promise(function (resolve, reject) {
  93238. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  93239. resolve({
  93240. meshes: meshes,
  93241. particleSystems: particleSystems,
  93242. skeletons: skeletons
  93243. });
  93244. }, onProgress, function (message) {
  93245. reject(new Error(message));
  93246. });
  93247. });
  93248. };
  93249. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  93250. var _this = this;
  93251. scene.useRightHandedSystem = true;
  93252. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  93253. // Load runtime extensios
  93254. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  93255. // Create nodes
  93256. _this._createNodes(gltfRuntime);
  93257. // Load buffers, shaders, materials, etc.
  93258. _this._loadBuffersAsync(gltfRuntime, function () {
  93259. _this._loadShadersAsync(gltfRuntime, function () {
  93260. importMaterials(gltfRuntime);
  93261. postLoad(gltfRuntime);
  93262. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  93263. onSuccess();
  93264. }
  93265. });
  93266. });
  93267. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  93268. onSuccess();
  93269. }
  93270. }, onError);
  93271. }, onError);
  93272. };
  93273. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  93274. var _this = this;
  93275. return new Promise(function (resolve, reject) {
  93276. _this._loadAsync(scene, data, rootUrl, function () {
  93277. resolve();
  93278. }, onProgress, function (message) {
  93279. reject(new Error(message));
  93280. });
  93281. });
  93282. };
  93283. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  93284. var hasShaders = false;
  93285. var processShader = function (sha, shader) {
  93286. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  93287. if (shaderString instanceof ArrayBuffer) {
  93288. return;
  93289. }
  93290. gltfRuntime.loadedShaderCount++;
  93291. if (shaderString) {
  93292. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  93293. }
  93294. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  93295. onload();
  93296. }
  93297. }, function () {
  93298. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  93299. });
  93300. };
  93301. for (var sha in gltfRuntime.shaders) {
  93302. hasShaders = true;
  93303. var shader = gltfRuntime.shaders[sha];
  93304. if (shader) {
  93305. processShader.bind(this, sha, shader)();
  93306. }
  93307. else {
  93308. BABYLON.Tools.Error("No shader named: " + sha);
  93309. }
  93310. }
  93311. if (!hasShaders) {
  93312. onload();
  93313. }
  93314. };
  93315. ;
  93316. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  93317. var hasBuffers = false;
  93318. var processBuffer = function (buf, buffer) {
  93319. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  93320. gltfRuntime.loadedBufferCount++;
  93321. if (bufferView) {
  93322. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  93323. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  93324. }
  93325. gltfRuntime.loadedBufferViews[buf] = bufferView;
  93326. }
  93327. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  93328. onLoad();
  93329. }
  93330. }, function () {
  93331. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  93332. });
  93333. };
  93334. for (var buf in gltfRuntime.buffers) {
  93335. hasBuffers = true;
  93336. var buffer = gltfRuntime.buffers[buf];
  93337. if (buffer) {
  93338. processBuffer.bind(this, buf, buffer)();
  93339. }
  93340. else {
  93341. BABYLON.Tools.Error("No buffer named: " + buf);
  93342. }
  93343. }
  93344. if (!hasBuffers) {
  93345. onLoad();
  93346. }
  93347. };
  93348. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  93349. var currentScene = gltfRuntime.currentScene;
  93350. if (currentScene) {
  93351. // Only one scene even if multiple scenes are defined
  93352. for (var i = 0; i < currentScene.nodes.length; i++) {
  93353. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  93354. }
  93355. }
  93356. else {
  93357. // Load all scenes
  93358. for (var thing in gltfRuntime.scenes) {
  93359. currentScene = gltfRuntime.scenes[thing];
  93360. for (var i = 0; i < currentScene.nodes.length; i++) {
  93361. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  93362. }
  93363. }
  93364. }
  93365. };
  93366. GLTFLoader.Extensions = {};
  93367. return GLTFLoader;
  93368. }());
  93369. GLTF1.GLTFLoader = GLTFLoader;
  93370. ;
  93371. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  93372. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  93373. })(BABYLON || (BABYLON = {}));
  93374. //# sourceMappingURL=babylon.glTFLoader.js.map
  93375. "use strict";
  93376. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93377. var BABYLON;
  93378. (function (BABYLON) {
  93379. var GLTF1;
  93380. (function (GLTF1) {
  93381. /**
  93382. * Utils functions for GLTF
  93383. */
  93384. var GLTFUtils = /** @class */ (function () {
  93385. function GLTFUtils() {
  93386. }
  93387. /**
  93388. * Sets the given "parameter" matrix
  93389. * @param scene: the {BABYLON.Scene} object
  93390. * @param source: the source node where to pick the matrix
  93391. * @param parameter: the GLTF technique parameter
  93392. * @param uniformName: the name of the shader's uniform
  93393. * @param shaderMaterial: the shader material
  93394. */
  93395. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  93396. var mat = null;
  93397. if (parameter.semantic === "MODEL") {
  93398. mat = source.getWorldMatrix();
  93399. }
  93400. else if (parameter.semantic === "PROJECTION") {
  93401. mat = scene.getProjectionMatrix();
  93402. }
  93403. else if (parameter.semantic === "VIEW") {
  93404. mat = scene.getViewMatrix();
  93405. }
  93406. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  93407. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  93408. }
  93409. else if (parameter.semantic === "MODELVIEW") {
  93410. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  93411. }
  93412. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  93413. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  93414. }
  93415. else if (parameter.semantic === "MODELINVERSE") {
  93416. mat = source.getWorldMatrix().invert();
  93417. }
  93418. else if (parameter.semantic === "VIEWINVERSE") {
  93419. mat = scene.getViewMatrix().invert();
  93420. }
  93421. else if (parameter.semantic === "PROJECTIONINVERSE") {
  93422. mat = scene.getProjectionMatrix().invert();
  93423. }
  93424. else if (parameter.semantic === "MODELVIEWINVERSE") {
  93425. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  93426. }
  93427. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  93428. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  93429. }
  93430. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  93431. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  93432. }
  93433. else {
  93434. debugger;
  93435. }
  93436. if (mat) {
  93437. switch (parameter.type) {
  93438. case GLTF1.EParameterType.FLOAT_MAT2:
  93439. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  93440. break;
  93441. case GLTF1.EParameterType.FLOAT_MAT3:
  93442. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  93443. break;
  93444. case GLTF1.EParameterType.FLOAT_MAT4:
  93445. shaderMaterial.setMatrix(uniformName, mat);
  93446. break;
  93447. default: break;
  93448. }
  93449. }
  93450. };
  93451. /**
  93452. * Sets the given "parameter" matrix
  93453. * @param shaderMaterial: the shader material
  93454. * @param uniform: the name of the shader's uniform
  93455. * @param value: the value of the uniform
  93456. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  93457. */
  93458. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  93459. switch (type) {
  93460. case GLTF1.EParameterType.FLOAT:
  93461. shaderMaterial.setFloat(uniform, value);
  93462. return true;
  93463. case GLTF1.EParameterType.FLOAT_VEC2:
  93464. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  93465. return true;
  93466. case GLTF1.EParameterType.FLOAT_VEC3:
  93467. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  93468. return true;
  93469. case GLTF1.EParameterType.FLOAT_VEC4:
  93470. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  93471. return true;
  93472. default: return false;
  93473. }
  93474. };
  93475. /**
  93476. * Returns the wrap mode of the texture
  93477. * @param mode: the mode value
  93478. */
  93479. GLTFUtils.GetWrapMode = function (mode) {
  93480. switch (mode) {
  93481. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  93482. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  93483. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  93484. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  93485. }
  93486. };
  93487. /**
  93488. * Returns the byte stride giving an accessor
  93489. * @param accessor: the GLTF accessor objet
  93490. */
  93491. GLTFUtils.GetByteStrideFromType = function (accessor) {
  93492. // Needs this function since "byteStride" isn't requiered in glTF format
  93493. var type = accessor.type;
  93494. switch (type) {
  93495. case "VEC2": return 2;
  93496. case "VEC3": return 3;
  93497. case "VEC4": return 4;
  93498. case "MAT2": return 4;
  93499. case "MAT3": return 9;
  93500. case "MAT4": return 16;
  93501. default: return 1;
  93502. }
  93503. };
  93504. /**
  93505. * Returns the texture filter mode giving a mode value
  93506. * @param mode: the filter mode value
  93507. */
  93508. GLTFUtils.GetTextureFilterMode = function (mode) {
  93509. switch (mode) {
  93510. case GLTF1.ETextureFilterType.LINEAR:
  93511. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  93512. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  93513. case GLTF1.ETextureFilterType.NEAREST:
  93514. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  93515. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  93516. }
  93517. };
  93518. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  93519. var byteOffset = bufferView.byteOffset + byteOffset;
  93520. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  93521. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  93522. throw new Error("Buffer access is out of range");
  93523. }
  93524. var buffer = loadedBufferView.buffer;
  93525. byteOffset += loadedBufferView.byteOffset;
  93526. switch (componentType) {
  93527. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  93528. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  93529. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  93530. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  93531. default: return new Float32Array(buffer, byteOffset, byteLength);
  93532. }
  93533. };
  93534. /**
  93535. * Returns a buffer from its accessor
  93536. * @param gltfRuntime: the GLTF runtime
  93537. * @param accessor: the GLTF accessor
  93538. */
  93539. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  93540. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  93541. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  93542. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  93543. };
  93544. /**
  93545. * Decodes a buffer view into a string
  93546. * @param view: the buffer view
  93547. */
  93548. GLTFUtils.DecodeBufferToText = function (view) {
  93549. var result = "";
  93550. var length = view.byteLength;
  93551. for (var i = 0; i < length; ++i) {
  93552. result += String.fromCharCode(view[i]);
  93553. }
  93554. return result;
  93555. };
  93556. /**
  93557. * Returns the default material of gltf. Related to
  93558. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  93559. * @param scene: the Babylon.js scene
  93560. */
  93561. GLTFUtils.GetDefaultMaterial = function (scene) {
  93562. if (!GLTFUtils._DefaultMaterial) {
  93563. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  93564. "precision highp float;",
  93565. "",
  93566. "uniform mat4 worldView;",
  93567. "uniform mat4 projection;",
  93568. "",
  93569. "attribute vec3 position;",
  93570. "",
  93571. "void main(void)",
  93572. "{",
  93573. " gl_Position = projection * worldView * vec4(position, 1.0);",
  93574. "}"
  93575. ].join("\n");
  93576. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  93577. "precision highp float;",
  93578. "",
  93579. "uniform vec4 u_emission;",
  93580. "",
  93581. "void main(void)",
  93582. "{",
  93583. " gl_FragColor = u_emission;",
  93584. "}"
  93585. ].join("\n");
  93586. var shaderPath = {
  93587. vertex: "GLTFDefaultMaterial",
  93588. fragment: "GLTFDefaultMaterial"
  93589. };
  93590. var options = {
  93591. attributes: ["position"],
  93592. uniforms: ["worldView", "projection", "u_emission"],
  93593. samplers: new Array(),
  93594. needAlphaBlending: false
  93595. };
  93596. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  93597. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  93598. }
  93599. return GLTFUtils._DefaultMaterial;
  93600. };
  93601. // The GLTF default material
  93602. GLTFUtils._DefaultMaterial = null;
  93603. return GLTFUtils;
  93604. }());
  93605. GLTF1.GLTFUtils = GLTFUtils;
  93606. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  93607. })(BABYLON || (BABYLON = {}));
  93608. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  93609. "use strict";
  93610. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93611. var BABYLON;
  93612. (function (BABYLON) {
  93613. var GLTF1;
  93614. (function (GLTF1) {
  93615. var GLTFLoaderExtension = /** @class */ (function () {
  93616. function GLTFLoaderExtension(name) {
  93617. this._name = name;
  93618. }
  93619. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  93620. get: function () {
  93621. return this._name;
  93622. },
  93623. enumerable: true,
  93624. configurable: true
  93625. });
  93626. /**
  93627. * Defines an override for loading the runtime
  93628. * Return true to stop further extensions from loading the runtime
  93629. */
  93630. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  93631. return false;
  93632. };
  93633. /**
  93634. * Defines an onverride for creating gltf runtime
  93635. * Return true to stop further extensions from creating the runtime
  93636. */
  93637. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  93638. return false;
  93639. };
  93640. /**
  93641. * Defines an override for loading buffers
  93642. * Return true to stop further extensions from loading this buffer
  93643. */
  93644. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  93645. return false;
  93646. };
  93647. /**
  93648. * Defines an override for loading texture buffers
  93649. * Return true to stop further extensions from loading this texture data
  93650. */
  93651. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  93652. return false;
  93653. };
  93654. /**
  93655. * Defines an override for creating textures
  93656. * Return true to stop further extensions from loading this texture
  93657. */
  93658. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  93659. return false;
  93660. };
  93661. /**
  93662. * Defines an override for loading shader strings
  93663. * Return true to stop further extensions from loading this shader data
  93664. */
  93665. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  93666. return false;
  93667. };
  93668. /**
  93669. * Defines an override for loading materials
  93670. * Return true to stop further extensions from loading this material
  93671. */
  93672. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  93673. return false;
  93674. };
  93675. // ---------
  93676. // Utilities
  93677. // ---------
  93678. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  93679. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93680. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  93681. }, function () {
  93682. setTimeout(function () {
  93683. if (!onSuccess) {
  93684. return;
  93685. }
  93686. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  93687. });
  93688. });
  93689. };
  93690. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  93691. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93692. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  93693. }, function () {
  93694. setTimeout(function () {
  93695. onSuccess();
  93696. });
  93697. });
  93698. };
  93699. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  93700. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93701. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  93702. }, function () {
  93703. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  93704. });
  93705. };
  93706. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  93707. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  93708. if (buffer) {
  93709. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  93710. }
  93711. }, onError);
  93712. };
  93713. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  93714. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93715. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  93716. }, function () {
  93717. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  93718. });
  93719. };
  93720. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  93721. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93722. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  93723. }, function () {
  93724. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  93725. });
  93726. };
  93727. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  93728. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93729. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  93730. }, function () {
  93731. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  93732. });
  93733. };
  93734. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  93735. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93736. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  93737. }, function () {
  93738. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  93739. });
  93740. };
  93741. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  93742. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  93743. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  93744. if (func(loaderExtension)) {
  93745. return;
  93746. }
  93747. }
  93748. defaultFunc();
  93749. };
  93750. return GLTFLoaderExtension;
  93751. }());
  93752. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  93753. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  93754. })(BABYLON || (BABYLON = {}));
  93755. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  93756. "use strict";
  93757. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93758. var BABYLON;
  93759. (function (BABYLON) {
  93760. var GLTF1;
  93761. (function (GLTF1) {
  93762. var BinaryExtensionBufferName = "binary_glTF";
  93763. ;
  93764. ;
  93765. var GLTFBinaryExtension = /** @class */ (function (_super) {
  93766. __extends(GLTFBinaryExtension, _super);
  93767. function GLTFBinaryExtension() {
  93768. return _super.call(this, "KHR_binary_glTF") || this;
  93769. }
  93770. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  93771. var extensionsUsed = data.json.extensionsUsed;
  93772. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  93773. return false;
  93774. }
  93775. this._bin = data.bin;
  93776. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  93777. return true;
  93778. };
  93779. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  93780. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  93781. return false;
  93782. }
  93783. if (id !== BinaryExtensionBufferName) {
  93784. return false;
  93785. }
  93786. onSuccess(this._bin);
  93787. return true;
  93788. };
  93789. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  93790. var texture = gltfRuntime.textures[id];
  93791. var source = gltfRuntime.images[texture.source];
  93792. if (!source.extensions || !(this.name in source.extensions)) {
  93793. return false;
  93794. }
  93795. var sourceExt = source.extensions[this.name];
  93796. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  93797. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  93798. onSuccess(buffer);
  93799. return true;
  93800. };
  93801. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  93802. var shader = gltfRuntime.shaders[id];
  93803. if (!shader.extensions || !(this.name in shader.extensions)) {
  93804. return false;
  93805. }
  93806. var binaryExtensionShader = shader.extensions[this.name];
  93807. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  93808. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  93809. setTimeout(function () {
  93810. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  93811. onSuccess(shaderString);
  93812. });
  93813. return true;
  93814. };
  93815. return GLTFBinaryExtension;
  93816. }(GLTF1.GLTFLoaderExtension));
  93817. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  93818. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  93819. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  93820. })(BABYLON || (BABYLON = {}));
  93821. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  93822. "use strict";
  93823. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93824. var BABYLON;
  93825. (function (BABYLON) {
  93826. var GLTF1;
  93827. (function (GLTF1) {
  93828. ;
  93829. ;
  93830. ;
  93831. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  93832. __extends(GLTFMaterialsCommonExtension, _super);
  93833. function GLTFMaterialsCommonExtension() {
  93834. return _super.call(this, "KHR_materials_common") || this;
  93835. }
  93836. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  93837. if (!gltfRuntime.extensions)
  93838. return false;
  93839. var extension = gltfRuntime.extensions[this.name];
  93840. if (!extension)
  93841. return false;
  93842. // Create lights
  93843. var lights = extension.lights;
  93844. if (lights) {
  93845. for (var thing in lights) {
  93846. var light = lights[thing];
  93847. switch (light.type) {
  93848. case "ambient":
  93849. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  93850. var ambient = light.ambient;
  93851. if (ambient) {
  93852. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  93853. }
  93854. break;
  93855. case "point":
  93856. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  93857. var point = light.point;
  93858. if (point) {
  93859. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  93860. }
  93861. break;
  93862. case "directional":
  93863. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  93864. var directional = light.directional;
  93865. if (directional) {
  93866. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  93867. }
  93868. break;
  93869. case "spot":
  93870. var spot = light.spot;
  93871. if (spot) {
  93872. 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);
  93873. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  93874. }
  93875. break;
  93876. default:
  93877. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  93878. break;
  93879. }
  93880. }
  93881. }
  93882. return false;
  93883. };
  93884. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  93885. var material = gltfRuntime.materials[id];
  93886. if (!material || !material.extensions)
  93887. return false;
  93888. var extension = material.extensions[this.name];
  93889. if (!extension)
  93890. return false;
  93891. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  93892. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  93893. if (extension.technique === "CONSTANT") {
  93894. standardMaterial.disableLighting = true;
  93895. }
  93896. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  93897. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  93898. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  93899. // Ambient
  93900. if (typeof extension.values.ambient === "string") {
  93901. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  93902. }
  93903. else {
  93904. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  93905. }
  93906. // Diffuse
  93907. if (typeof extension.values.diffuse === "string") {
  93908. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  93909. }
  93910. else {
  93911. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  93912. }
  93913. // Emission
  93914. if (typeof extension.values.emission === "string") {
  93915. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  93916. }
  93917. else {
  93918. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  93919. }
  93920. // Specular
  93921. if (typeof extension.values.specular === "string") {
  93922. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  93923. }
  93924. else {
  93925. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  93926. }
  93927. return true;
  93928. };
  93929. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  93930. // Create buffer from texture url
  93931. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  93932. // Create texture from buffer
  93933. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  93934. }, onError);
  93935. };
  93936. return GLTFMaterialsCommonExtension;
  93937. }(GLTF1.GLTFLoaderExtension));
  93938. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  93939. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  93940. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  93941. })(BABYLON || (BABYLON = {}));
  93942. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  93943. "use strict";
  93944. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93945. var BABYLON;
  93946. (function (BABYLON) {
  93947. var GLTF2;
  93948. (function (GLTF2) {
  93949. var ArrayItem = /** @class */ (function () {
  93950. function ArrayItem() {
  93951. }
  93952. ArrayItem.Assign = function (values) {
  93953. if (values) {
  93954. for (var index = 0; index < values.length; index++) {
  93955. values[index]._index = index;
  93956. }
  93957. }
  93958. };
  93959. return ArrayItem;
  93960. }());
  93961. GLTF2.ArrayItem = ArrayItem;
  93962. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93963. })(BABYLON || (BABYLON = {}));
  93964. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  93965. "use strict";
  93966. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93967. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  93968. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  93969. "use strict";
  93970. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93971. var BABYLON;
  93972. (function (BABYLON) {
  93973. var GLTF2;
  93974. (function (GLTF2) {
  93975. var GLTFLoader = /** @class */ (function () {
  93976. function GLTFLoader() {
  93977. this._completePromises = new Array();
  93978. this._disposed = false;
  93979. this._state = null;
  93980. this._extensions = {};
  93981. this._defaultSampler = {};
  93982. this._defaultBabylonMaterials = {};
  93983. this._requests = new Array();
  93984. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  93985. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  93986. this.compileMaterials = false;
  93987. this.useClipPlane = false;
  93988. this.compileShadowGenerators = false;
  93989. this.onDisposeObservable = new BABYLON.Observable();
  93990. this.onMeshLoadedObservable = new BABYLON.Observable();
  93991. this.onTextureLoadedObservable = new BABYLON.Observable();
  93992. this.onMaterialLoadedObservable = new BABYLON.Observable();
  93993. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  93994. this.onExtensionLoadedObservable = new BABYLON.Observable();
  93995. this.onCompleteObservable = new BABYLON.Observable();
  93996. }
  93997. GLTFLoader._Register = function (name, factory) {
  93998. if (GLTFLoader._Factories[name]) {
  93999. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  94000. return;
  94001. }
  94002. GLTFLoader._Factories[name] = factory;
  94003. // Keep the order of registration so that extensions registered first are called first.
  94004. GLTFLoader._Names.push(name);
  94005. };
  94006. Object.defineProperty(GLTFLoader.prototype, "state", {
  94007. get: function () {
  94008. return this._state;
  94009. },
  94010. enumerable: true,
  94011. configurable: true
  94012. });
  94013. GLTFLoader.prototype.dispose = function () {
  94014. if (this._disposed) {
  94015. return;
  94016. }
  94017. this._disposed = true;
  94018. this.onDisposeObservable.notifyObservers(this);
  94019. this.onDisposeObservable.clear();
  94020. this._clear();
  94021. };
  94022. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  94023. var _this = this;
  94024. return Promise.resolve().then(function () {
  94025. var nodes = null;
  94026. if (meshesNames) {
  94027. var nodeMap_1 = {};
  94028. if (_this._gltf.nodes) {
  94029. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  94030. var node = _a[_i];
  94031. if (node.name) {
  94032. nodeMap_1[node.name] = node;
  94033. }
  94034. }
  94035. }
  94036. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  94037. nodes = names.map(function (name) {
  94038. var node = nodeMap_1[name];
  94039. if (!node) {
  94040. throw new Error("Failed to find node '" + name + "'");
  94041. }
  94042. return node;
  94043. });
  94044. }
  94045. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  94046. return {
  94047. meshes: _this._getMeshes(),
  94048. particleSystems: [],
  94049. skeletons: _this._getSkeletons(),
  94050. };
  94051. });
  94052. });
  94053. };
  94054. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  94055. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  94056. };
  94057. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  94058. var _this = this;
  94059. return Promise.resolve().then(function () {
  94060. _this._loadExtensions();
  94061. _this._babylonScene = scene;
  94062. _this._rootUrl = rootUrl;
  94063. _this._progressCallback = onProgress;
  94064. _this._state = BABYLON.GLTFLoaderState.Loading;
  94065. _this._loadData(data);
  94066. _this._checkExtensions();
  94067. var promises = new Array();
  94068. if (nodes) {
  94069. promises.push(_this._loadNodesAsync(nodes));
  94070. }
  94071. else {
  94072. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  94073. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  94074. }
  94075. if (_this.compileMaterials) {
  94076. promises.push(_this._compileMaterialsAsync());
  94077. }
  94078. if (_this.compileShadowGenerators) {
  94079. promises.push(_this._compileShadowGeneratorsAsync());
  94080. }
  94081. var resultPromise = Promise.all(promises).then(function () {
  94082. _this._state = BABYLON.GLTFLoaderState.Ready;
  94083. _this._startAnimations();
  94084. });
  94085. resultPromise.then(function () {
  94086. _this._rootBabylonMesh.setEnabled(true);
  94087. BABYLON.Tools.SetImmediate(function () {
  94088. if (!_this._disposed) {
  94089. Promise.all(_this._completePromises).then(function () {
  94090. _this._state = BABYLON.GLTFLoaderState.Complete;
  94091. _this.onCompleteObservable.notifyObservers(_this);
  94092. _this.onCompleteObservable.clear();
  94093. _this._clear();
  94094. }).catch(function (error) {
  94095. BABYLON.Tools.Error("glTF Loader: " + error.message);
  94096. _this._clear();
  94097. });
  94098. }
  94099. });
  94100. });
  94101. return resultPromise;
  94102. }).catch(function (error) {
  94103. BABYLON.Tools.Error("glTF Loader: " + error.message);
  94104. _this._clear();
  94105. throw error;
  94106. });
  94107. };
  94108. GLTFLoader.prototype._loadExtensions = function () {
  94109. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  94110. var name_1 = _a[_i];
  94111. var extension = GLTFLoader._Factories[name_1](this);
  94112. this._extensions[name_1] = extension;
  94113. this.onExtensionLoadedObservable.notifyObservers(extension);
  94114. }
  94115. this.onExtensionLoadedObservable.clear();
  94116. };
  94117. GLTFLoader.prototype._loadData = function (data) {
  94118. this._gltf = data.json;
  94119. this._setupData();
  94120. if (data.bin) {
  94121. var buffers = this._gltf.buffers;
  94122. if (buffers && buffers[0] && !buffers[0].uri) {
  94123. var binaryBuffer = buffers[0];
  94124. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  94125. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  94126. }
  94127. binaryBuffer._data = Promise.resolve(data.bin);
  94128. }
  94129. else {
  94130. BABYLON.Tools.Warn("Unexpected BIN chunk");
  94131. }
  94132. }
  94133. };
  94134. GLTFLoader.prototype._setupData = function () {
  94135. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  94136. GLTF2.ArrayItem.Assign(this._gltf.animations);
  94137. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  94138. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  94139. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  94140. GLTF2.ArrayItem.Assign(this._gltf.images);
  94141. GLTF2.ArrayItem.Assign(this._gltf.materials);
  94142. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  94143. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  94144. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  94145. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  94146. GLTF2.ArrayItem.Assign(this._gltf.skins);
  94147. GLTF2.ArrayItem.Assign(this._gltf.textures);
  94148. if (this._gltf.nodes) {
  94149. var nodeParents = {};
  94150. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  94151. var node = _a[_i];
  94152. if (node.children) {
  94153. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  94154. var index = _c[_b];
  94155. nodeParents[index] = node._index;
  94156. }
  94157. }
  94158. }
  94159. var rootNode = this._createRootNode();
  94160. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  94161. var node = _e[_d];
  94162. var parentIndex = nodeParents[node._index];
  94163. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  94164. }
  94165. }
  94166. };
  94167. GLTFLoader.prototype._checkExtensions = function () {
  94168. if (this._gltf.extensionsRequired) {
  94169. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  94170. var name_2 = _a[_i];
  94171. var extension = this._extensions[name_2];
  94172. if (!extension || !extension.enabled) {
  94173. throw new Error("Require extension " + name_2 + " is not available");
  94174. }
  94175. }
  94176. }
  94177. };
  94178. GLTFLoader.prototype._createRootNode = function () {
  94179. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  94180. this._rootBabylonMesh.setEnabled(false);
  94181. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  94182. switch (this.coordinateSystemMode) {
  94183. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  94184. if (!this._babylonScene.useRightHandedSystem) {
  94185. rootNode.rotation = [0, 1, 0, 0];
  94186. rootNode.scale = [1, 1, -1];
  94187. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  94188. }
  94189. break;
  94190. }
  94191. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  94192. this._babylonScene.useRightHandedSystem = true;
  94193. break;
  94194. }
  94195. default: {
  94196. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  94197. }
  94198. }
  94199. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  94200. return rootNode;
  94201. };
  94202. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  94203. var promises = new Array();
  94204. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  94205. var node = nodes_1[_i];
  94206. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  94207. }
  94208. promises.push(this._loadAnimationsAsync());
  94209. return Promise.all(promises).then(function () { });
  94210. };
  94211. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  94212. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  94213. if (promise) {
  94214. return promise;
  94215. }
  94216. var promises = new Array();
  94217. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  94218. var index = _a[_i];
  94219. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  94220. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  94221. }
  94222. promises.push(this._loadAnimationsAsync());
  94223. return Promise.all(promises).then(function () { });
  94224. };
  94225. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  94226. if (node._primitiveBabylonMeshes) {
  94227. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  94228. var babylonMesh = _a[_i];
  94229. callback(babylonMesh);
  94230. }
  94231. }
  94232. else {
  94233. callback(node._babylonMesh);
  94234. }
  94235. };
  94236. GLTFLoader.prototype._getMeshes = function () {
  94237. var meshes = new Array();
  94238. // Root mesh is always first.
  94239. meshes.push(this._rootBabylonMesh);
  94240. var nodes = this._gltf.nodes;
  94241. if (nodes) {
  94242. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  94243. var node = nodes_2[_i];
  94244. if (node._babylonMesh) {
  94245. meshes.push(node._babylonMesh);
  94246. }
  94247. if (node._primitiveBabylonMeshes) {
  94248. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  94249. var babylonMesh = _b[_a];
  94250. meshes.push(babylonMesh);
  94251. }
  94252. }
  94253. }
  94254. }
  94255. return meshes;
  94256. };
  94257. GLTFLoader.prototype._getSkeletons = function () {
  94258. var skeletons = new Array();
  94259. var skins = this._gltf.skins;
  94260. if (skins) {
  94261. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  94262. var skin = skins_1[_i];
  94263. if (skin._babylonSkeleton) {
  94264. skeletons.push(skin._babylonSkeleton);
  94265. }
  94266. }
  94267. }
  94268. return skeletons;
  94269. };
  94270. GLTFLoader.prototype._startAnimations = function () {
  94271. var animations = this._gltf.animations;
  94272. if (!animations) {
  94273. return;
  94274. }
  94275. switch (this.animationStartMode) {
  94276. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  94277. // do nothing
  94278. break;
  94279. }
  94280. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  94281. var animation = animations[0];
  94282. animation._babylonAnimationGroup.start(true);
  94283. break;
  94284. }
  94285. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  94286. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  94287. var animation = animations_1[_i];
  94288. animation._babylonAnimationGroup.start(true);
  94289. }
  94290. break;
  94291. }
  94292. default: {
  94293. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  94294. return;
  94295. }
  94296. }
  94297. };
  94298. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  94299. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  94300. if (promise) {
  94301. return promise;
  94302. }
  94303. if (node._babylonMesh) {
  94304. throw new Error(context + ": Invalid recursive node hierarchy");
  94305. }
  94306. var promises = new Array();
  94307. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  94308. node._babylonMesh = babylonMesh;
  94309. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  94310. node._babylonAnimationTargets.push(babylonMesh);
  94311. GLTFLoader._LoadTransform(node, babylonMesh);
  94312. if (node.mesh != undefined) {
  94313. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  94314. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  94315. }
  94316. if (node.children) {
  94317. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  94318. var index = _a[_i];
  94319. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  94320. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  94321. }
  94322. }
  94323. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  94324. return Promise.all(promises).then(function () { });
  94325. };
  94326. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  94327. // TODO: instancing
  94328. var _this = this;
  94329. var promises = new Array();
  94330. var primitives = mesh.primitives;
  94331. if (!primitives || primitives.length === 0) {
  94332. throw new Error(context + ": Primitives are missing");
  94333. }
  94334. GLTF2.ArrayItem.Assign(primitives);
  94335. if (primitives.length === 1) {
  94336. var primitive = primitives[0];
  94337. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  94338. }
  94339. else {
  94340. node._primitiveBabylonMeshes = [];
  94341. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  94342. var primitive = primitives_1[_i];
  94343. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  94344. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  94345. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  94346. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  94347. }
  94348. }
  94349. if (node.skin != undefined) {
  94350. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  94351. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  94352. }
  94353. return Promise.all(promises).then(function () {
  94354. _this._forEachPrimitive(node, function (babylonMesh) {
  94355. babylonMesh._refreshBoundingInfo(true);
  94356. });
  94357. });
  94358. };
  94359. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  94360. var _this = this;
  94361. var promises = new Array();
  94362. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  94363. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  94364. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  94365. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  94366. }));
  94367. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  94368. if (primitive.material == undefined) {
  94369. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  94370. }
  94371. else {
  94372. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  94373. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  94374. babylonMesh.material = babylonMaterial;
  94375. }));
  94376. }
  94377. return Promise.all(promises).then(function () { });
  94378. };
  94379. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  94380. var _this = this;
  94381. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  94382. if (promise) {
  94383. return promise;
  94384. }
  94385. var attributes = primitive.attributes;
  94386. if (!attributes) {
  94387. throw new Error(context + ": Attributes are missing");
  94388. }
  94389. var promises = new Array();
  94390. var babylonVertexData = new BABYLON.VertexData();
  94391. if (primitive.indices == undefined) {
  94392. var positionAccessorIndex = attributes["POSITION"];
  94393. if (positionAccessorIndex != undefined) {
  94394. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  94395. babylonVertexData.indices = new Uint32Array(accessor.count);
  94396. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  94397. babylonVertexData.indices[i] = i;
  94398. }
  94399. }
  94400. }
  94401. else {
  94402. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  94403. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  94404. babylonVertexData.indices = data;
  94405. }));
  94406. }
  94407. var loadAttribute = function (attribute, kind) {
  94408. if (attributes[attribute] == undefined) {
  94409. return;
  94410. }
  94411. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  94412. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  94413. babylonMesh._delayInfo.push(kind);
  94414. }
  94415. if (attribute === "COLOR_0") {
  94416. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  94417. babylonMesh.hasVertexAlpha = true;
  94418. }
  94419. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  94420. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  94421. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  94422. if (attribute === "COLOR_0" && accessor.type === "VEC3") {
  94423. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  94424. }
  94425. babylonVertexData.set(attributeData, kind);
  94426. }));
  94427. };
  94428. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  94429. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  94430. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  94431. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  94432. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  94433. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  94434. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  94435. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  94436. return Promise.all(promises).then(function () {
  94437. return babylonVertexData;
  94438. });
  94439. };
  94440. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  94441. if (!primitive.targets) {
  94442. return;
  94443. }
  94444. if (node._numMorphTargets == undefined) {
  94445. node._numMorphTargets = primitive.targets.length;
  94446. }
  94447. else if (primitive.targets.length !== node._numMorphTargets) {
  94448. throw new Error(context + ": Primitives do not have the same number of targets");
  94449. }
  94450. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  94451. for (var index = 0; index < primitive.targets.length; index++) {
  94452. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  94453. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  94454. // TODO: tell the target whether it has positions, normals, tangents
  94455. }
  94456. };
  94457. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  94458. if (!primitive.targets) {
  94459. return Promise.resolve();
  94460. }
  94461. var promises = new Array();
  94462. var morphTargetManager = babylonMesh.morphTargetManager;
  94463. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  94464. var babylonMorphTarget = morphTargetManager.getTarget(index);
  94465. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  94466. }
  94467. return Promise.all(promises).then(function () { });
  94468. };
  94469. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  94470. var _this = this;
  94471. var promises = new Array();
  94472. var loadAttribute = function (attribute, setData) {
  94473. if (attributes[attribute] == undefined) {
  94474. return;
  94475. }
  94476. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  94477. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  94478. setData(data);
  94479. }));
  94480. };
  94481. loadAttribute("POSITION", function (data) {
  94482. if (babylonVertexData.positions) {
  94483. for (var i = 0; i < data.length; i++) {
  94484. data[i] += babylonVertexData.positions[i];
  94485. }
  94486. babylonMorphTarget.setPositions(data);
  94487. }
  94488. });
  94489. loadAttribute("NORMAL", function (data) {
  94490. if (babylonVertexData.normals) {
  94491. for (var i = 0; i < data.length; i++) {
  94492. data[i] += babylonVertexData.normals[i];
  94493. }
  94494. babylonMorphTarget.setNormals(data);
  94495. }
  94496. });
  94497. loadAttribute("TANGENT", function (data) {
  94498. if (babylonVertexData.tangents) {
  94499. // Tangent data for morph targets is stored as xyz delta.
  94500. // The vertexData.tangent is stored as xyzw.
  94501. // So we need to skip every fourth vertexData.tangent.
  94502. for (var i = 0, j = 0; i < data.length; i++) {
  94503. data[i] += babylonVertexData.tangents[j++];
  94504. if ((i + 1) % 3 == 0) {
  94505. j++;
  94506. }
  94507. }
  94508. babylonMorphTarget.setTangents(data);
  94509. }
  94510. });
  94511. return Promise.all(promises).then(function () { });
  94512. };
  94513. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  94514. if (accessor.componentType == 5126 /* FLOAT */) {
  94515. return data;
  94516. }
  94517. var factor = 1;
  94518. if (accessor.normalized) {
  94519. switch (accessor.componentType) {
  94520. case 5121 /* UNSIGNED_BYTE */: {
  94521. factor = 1 / 255;
  94522. break;
  94523. }
  94524. case 5123 /* UNSIGNED_SHORT */: {
  94525. factor = 1 / 65535;
  94526. break;
  94527. }
  94528. default: {
  94529. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  94530. }
  94531. }
  94532. }
  94533. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  94534. for (var i = 0; i < result.length; i++) {
  94535. result[i] = data[i] * factor;
  94536. }
  94537. return result;
  94538. };
  94539. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  94540. var result = new Float32Array(data.length / 3 * 4);
  94541. var offset = 0;
  94542. for (var i = 0; i < result.length; i++) {
  94543. if ((i + 1) % 4 === 0) {
  94544. result[i] = 1;
  94545. }
  94546. else {
  94547. result[i] = data[offset++];
  94548. }
  94549. }
  94550. return result;
  94551. };
  94552. GLTFLoader._LoadTransform = function (node, babylonNode) {
  94553. var position = BABYLON.Vector3.Zero();
  94554. var rotation = BABYLON.Quaternion.Identity();
  94555. var scaling = BABYLON.Vector3.One();
  94556. if (node.matrix) {
  94557. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  94558. matrix.decompose(scaling, rotation, position);
  94559. }
  94560. else {
  94561. if (node.translation)
  94562. position = BABYLON.Vector3.FromArray(node.translation);
  94563. if (node.rotation)
  94564. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  94565. if (node.scale)
  94566. scaling = BABYLON.Vector3.FromArray(node.scale);
  94567. }
  94568. babylonNode.position = position;
  94569. babylonNode.rotationQuaternion = rotation;
  94570. babylonNode.scaling = scaling;
  94571. };
  94572. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  94573. var _this = this;
  94574. var assignSkeleton = function () {
  94575. _this._forEachPrimitive(node, function (babylonMesh) {
  94576. babylonMesh.skeleton = skin._babylonSkeleton;
  94577. });
  94578. node._babylonMesh.parent = _this._rootBabylonMesh;
  94579. node._babylonMesh.position = BABYLON.Vector3.Zero();
  94580. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  94581. node._babylonMesh.scaling = BABYLON.Vector3.One();
  94582. };
  94583. if (skin._loaded) {
  94584. return skin._loaded.then(function () {
  94585. assignSkeleton();
  94586. });
  94587. }
  94588. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  94589. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  94590. var skeletonId = "skeleton" + skin._index;
  94591. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  94592. skin._babylonSkeleton = babylonSkeleton;
  94593. _this._loadBones(context, skin, inverseBindMatricesData);
  94594. assignSkeleton();
  94595. }));
  94596. };
  94597. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  94598. if (skin.inverseBindMatrices == undefined) {
  94599. return Promise.resolve(null);
  94600. }
  94601. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  94602. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  94603. return data;
  94604. });
  94605. };
  94606. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  94607. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  94608. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  94609. node._babylonAnimationTargets.push(babylonBone);
  94610. return babylonBone;
  94611. };
  94612. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  94613. var babylonBones = {};
  94614. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  94615. var index = _a[_i];
  94616. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  94617. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  94618. }
  94619. };
  94620. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  94621. var babylonBone = babylonBones[node._index];
  94622. if (babylonBone) {
  94623. return babylonBone;
  94624. }
  94625. var boneIndex = skin.joints.indexOf(node._index);
  94626. var baseMatrix = BABYLON.Matrix.Identity();
  94627. if (inverseBindMatricesData && boneIndex !== -1) {
  94628. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  94629. baseMatrix.invertToRef(baseMatrix);
  94630. }
  94631. var babylonParentBone = null;
  94632. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  94633. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  94634. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  94635. }
  94636. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  94637. babylonBones[node._index] = babylonBone;
  94638. return babylonBone;
  94639. };
  94640. GLTFLoader.prototype._getNodeMatrix = function (node) {
  94641. return node.matrix ?
  94642. BABYLON.Matrix.FromArray(node.matrix) :
  94643. 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());
  94644. };
  94645. GLTFLoader.prototype._loadAnimationsAsync = function () {
  94646. var animations = this._gltf.animations;
  94647. if (!animations) {
  94648. return Promise.resolve();
  94649. }
  94650. var promises = new Array();
  94651. for (var index = 0; index < animations.length; index++) {
  94652. var animation = animations[index];
  94653. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  94654. }
  94655. return Promise.all(promises).then(function () { });
  94656. };
  94657. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  94658. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  94659. animation._babylonAnimationGroup = babylonAnimationGroup;
  94660. var promises = new Array();
  94661. GLTF2.ArrayItem.Assign(animation.channels);
  94662. GLTF2.ArrayItem.Assign(animation.samplers);
  94663. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  94664. var channel = _a[_i];
  94665. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  94666. }
  94667. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  94668. return Promise.all(promises).then(function () {
  94669. babylonAnimationGroup.normalize();
  94670. });
  94671. };
  94672. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  94673. var _this = this;
  94674. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  94675. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  94676. return Promise.resolve();
  94677. }
  94678. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  94679. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  94680. var targetPath;
  94681. var animationType;
  94682. switch (channel.target.path) {
  94683. case "translation" /* TRANSLATION */: {
  94684. targetPath = "position";
  94685. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  94686. break;
  94687. }
  94688. case "rotation" /* ROTATION */: {
  94689. targetPath = "rotationQuaternion";
  94690. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  94691. break;
  94692. }
  94693. case "scale" /* SCALE */: {
  94694. targetPath = "scaling";
  94695. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  94696. break;
  94697. }
  94698. case "weights" /* WEIGHTS */: {
  94699. targetPath = "influence";
  94700. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  94701. break;
  94702. }
  94703. default: {
  94704. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  94705. }
  94706. }
  94707. var outputBufferOffset = 0;
  94708. var getNextOutputValue;
  94709. switch (targetPath) {
  94710. case "position": {
  94711. getNextOutputValue = function () {
  94712. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  94713. outputBufferOffset += 3;
  94714. return value;
  94715. };
  94716. break;
  94717. }
  94718. case "rotationQuaternion": {
  94719. getNextOutputValue = function () {
  94720. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  94721. outputBufferOffset += 4;
  94722. return value;
  94723. };
  94724. break;
  94725. }
  94726. case "scaling": {
  94727. getNextOutputValue = function () {
  94728. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  94729. outputBufferOffset += 3;
  94730. return value;
  94731. };
  94732. break;
  94733. }
  94734. case "influence": {
  94735. getNextOutputValue = function () {
  94736. var value = new Array(targetNode._numMorphTargets);
  94737. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  94738. value[i] = data.output[outputBufferOffset++];
  94739. }
  94740. return value;
  94741. };
  94742. break;
  94743. }
  94744. }
  94745. var getNextKey;
  94746. switch (data.interpolation) {
  94747. case "STEP" /* STEP */: {
  94748. getNextKey = function (frameIndex) { return ({
  94749. frame: data.input[frameIndex],
  94750. value: getNextOutputValue(),
  94751. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  94752. }); };
  94753. break;
  94754. }
  94755. case "LINEAR" /* LINEAR */: {
  94756. getNextKey = function (frameIndex) { return ({
  94757. frame: data.input[frameIndex],
  94758. value: getNextOutputValue()
  94759. }); };
  94760. break;
  94761. }
  94762. case "CUBICSPLINE" /* CUBICSPLINE */: {
  94763. getNextKey = function (frameIndex) { return ({
  94764. frame: data.input[frameIndex],
  94765. inTangent: getNextOutputValue(),
  94766. value: getNextOutputValue(),
  94767. outTangent: getNextOutputValue()
  94768. }); };
  94769. break;
  94770. }
  94771. }
  94772. var keys = new Array(data.input.length);
  94773. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  94774. keys[frameIndex] = getNextKey(frameIndex);
  94775. }
  94776. if (targetPath === "influence") {
  94777. var _loop_1 = function (targetIndex) {
  94778. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  94779. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  94780. babylonAnimation.setKeys(keys.map(function (key) { return ({
  94781. frame: key.frame,
  94782. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  94783. value: key.value[targetIndex],
  94784. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  94785. }); }));
  94786. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  94787. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  94788. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  94789. });
  94790. };
  94791. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  94792. _loop_1(targetIndex);
  94793. }
  94794. }
  94795. else {
  94796. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  94797. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  94798. babylonAnimation.setKeys(keys);
  94799. if (targetNode._babylonAnimationTargets) {
  94800. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  94801. var target = _a[_i];
  94802. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  94803. }
  94804. }
  94805. }
  94806. });
  94807. };
  94808. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  94809. if (sampler._data) {
  94810. return sampler._data;
  94811. }
  94812. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  94813. switch (interpolation) {
  94814. case "STEP" /* STEP */:
  94815. case "LINEAR" /* LINEAR */:
  94816. case "CUBICSPLINE" /* CUBICSPLINE */: {
  94817. break;
  94818. }
  94819. default: {
  94820. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  94821. }
  94822. }
  94823. var inputData;
  94824. var outputData;
  94825. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  94826. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  94827. sampler._data = Promise.all([
  94828. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  94829. inputData = data;
  94830. }),
  94831. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  94832. outputData = data;
  94833. })
  94834. ]).then(function () {
  94835. return {
  94836. input: inputData,
  94837. interpolation: interpolation,
  94838. output: outputData,
  94839. };
  94840. });
  94841. return sampler._data;
  94842. };
  94843. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  94844. if (buffer._data) {
  94845. return buffer._data;
  94846. }
  94847. if (!buffer.uri) {
  94848. throw new Error(context + ": Uri is missing");
  94849. }
  94850. buffer._data = this._loadUriAsync(context, buffer.uri);
  94851. return buffer._data;
  94852. };
  94853. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  94854. if (bufferView._data) {
  94855. return bufferView._data;
  94856. }
  94857. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  94858. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  94859. try {
  94860. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  94861. }
  94862. catch (e) {
  94863. throw new Error(context + ": " + e.message);
  94864. }
  94865. });
  94866. return bufferView._data;
  94867. };
  94868. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  94869. var _this = this;
  94870. if (accessor.sparse) {
  94871. throw new Error(context + ": Sparse accessors are not currently supported");
  94872. }
  94873. if (accessor._data) {
  94874. return accessor._data;
  94875. }
  94876. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  94877. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  94878. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  94879. var byteOffset = accessor.byteOffset || 0;
  94880. var byteStride = bufferView.byteStride;
  94881. if (byteStride === 0) {
  94882. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  94883. }
  94884. try {
  94885. switch (accessor.componentType) {
  94886. case 5120 /* BYTE */: {
  94887. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  94888. }
  94889. case 5121 /* UNSIGNED_BYTE */: {
  94890. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  94891. }
  94892. case 5122 /* SHORT */: {
  94893. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  94894. }
  94895. case 5123 /* UNSIGNED_SHORT */: {
  94896. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  94897. }
  94898. case 5125 /* UNSIGNED_INT */: {
  94899. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  94900. }
  94901. case 5126 /* FLOAT */: {
  94902. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  94903. }
  94904. default: {
  94905. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  94906. }
  94907. }
  94908. }
  94909. catch (e) {
  94910. throw new Error(context + ": " + e.messsage);
  94911. }
  94912. });
  94913. return accessor._data;
  94914. };
  94915. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  94916. byteOffset += data.byteOffset;
  94917. var targetLength = count * numComponents;
  94918. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  94919. return new typedArray(data.buffer, byteOffset, targetLength);
  94920. }
  94921. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  94922. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  94923. var targetBuffer = new typedArray(targetLength);
  94924. var sourceIndex = 0;
  94925. var targetIndex = 0;
  94926. while (targetIndex < targetLength) {
  94927. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  94928. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  94929. targetIndex++;
  94930. }
  94931. sourceIndex += elementStride;
  94932. }
  94933. return targetBuffer;
  94934. };
  94935. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  94936. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  94937. if (!babylonMaterial) {
  94938. babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, "__gltf_default", drawMode);
  94939. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  94940. babylonMaterial.metallic = 1;
  94941. babylonMaterial.roughness = 1;
  94942. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  94943. }
  94944. return babylonMaterial;
  94945. };
  94946. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  94947. var promises = new Array();
  94948. // Ensure metallic workflow
  94949. babylonMaterial.metallic = 1;
  94950. babylonMaterial.roughness = 1;
  94951. var properties = material.pbrMetallicRoughness;
  94952. if (properties) {
  94953. if (properties.baseColorFactor) {
  94954. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  94955. babylonMaterial.alpha = properties.baseColorFactor[3];
  94956. }
  94957. else {
  94958. babylonMaterial.albedoColor = BABYLON.Color3.White();
  94959. }
  94960. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  94961. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  94962. if (properties.baseColorTexture) {
  94963. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  94964. babylonMaterial.albedoTexture = texture;
  94965. }));
  94966. }
  94967. if (properties.metallicRoughnessTexture) {
  94968. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  94969. babylonMaterial.metallicTexture = texture;
  94970. }));
  94971. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  94972. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  94973. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  94974. }
  94975. }
  94976. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  94977. return Promise.all(promises).then(function () { });
  94978. };
  94979. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  94980. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  94981. if (promise) {
  94982. return promise;
  94983. }
  94984. material._babylonData = material._babylonData || {};
  94985. var babylonData = material._babylonData[babylonDrawMode];
  94986. if (!babylonData) {
  94987. var promises = new Array();
  94988. var name_3 = material.name || "materialSG_" + material._index;
  94989. var babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, name_3, babylonDrawMode);
  94990. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  94991. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  94992. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  94993. babylonData = {
  94994. material: babylonMaterial,
  94995. meshes: [],
  94996. loaded: Promise.all(promises).then(function () { })
  94997. };
  94998. material._babylonData[babylonDrawMode] = babylonData;
  94999. }
  95000. babylonData.meshes.push(babylonMesh);
  95001. assign(babylonData.material);
  95002. return babylonData.loaded;
  95003. };
  95004. GLTFLoader.prototype._createMaterial = function (type, name, drawMode) {
  95005. var babylonMaterial = new type(name, this._babylonScene);
  95006. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  95007. babylonMaterial.fillMode = drawMode;
  95008. return babylonMaterial;
  95009. };
  95010. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  95011. var promises = new Array();
  95012. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  95013. if (material.doubleSided) {
  95014. babylonMaterial.backFaceCulling = false;
  95015. babylonMaterial.twoSidedLighting = true;
  95016. }
  95017. if (material.normalTexture) {
  95018. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  95019. babylonMaterial.bumpTexture = texture;
  95020. }));
  95021. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  95022. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  95023. if (material.normalTexture.scale != undefined) {
  95024. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  95025. }
  95026. }
  95027. if (material.occlusionTexture) {
  95028. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  95029. babylonMaterial.ambientTexture = texture;
  95030. }));
  95031. babylonMaterial.useAmbientInGrayScale = true;
  95032. if (material.occlusionTexture.strength != undefined) {
  95033. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  95034. }
  95035. }
  95036. if (material.emissiveTexture) {
  95037. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  95038. babylonMaterial.emissiveTexture = texture;
  95039. }));
  95040. }
  95041. return Promise.all(promises).then(function () { });
  95042. };
  95043. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  95044. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  95045. switch (alphaMode) {
  95046. case "OPAQUE" /* OPAQUE */: {
  95047. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  95048. break;
  95049. }
  95050. case "MASK" /* MASK */: {
  95051. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  95052. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  95053. if (babylonMaterial.albedoTexture) {
  95054. babylonMaterial.albedoTexture.hasAlpha = true;
  95055. }
  95056. break;
  95057. }
  95058. case "BLEND" /* BLEND */: {
  95059. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  95060. if (babylonMaterial.albedoTexture) {
  95061. babylonMaterial.albedoTexture.hasAlpha = true;
  95062. babylonMaterial.useAlphaFromAlbedoTexture = true;
  95063. }
  95064. break;
  95065. }
  95066. default: {
  95067. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  95068. }
  95069. }
  95070. };
  95071. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  95072. var _this = this;
  95073. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  95074. context = "#/textures/" + textureInfo.index;
  95075. var promises = new Array();
  95076. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  95077. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  95078. var deferred = new BABYLON.Deferred();
  95079. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  95080. if (!_this._disposed) {
  95081. deferred.resolve();
  95082. }
  95083. }, function (message, exception) {
  95084. if (!_this._disposed) {
  95085. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  95086. }
  95087. });
  95088. promises.push(deferred.promise);
  95089. babylonTexture.name = texture.name || "texture" + texture._index;
  95090. babylonTexture.wrapU = samplerData.wrapU;
  95091. babylonTexture.wrapV = samplerData.wrapV;
  95092. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  95093. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  95094. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  95095. babylonTexture.updateURL(objectURL);
  95096. }));
  95097. assign(babylonTexture);
  95098. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  95099. return Promise.all(promises).then(function () { });
  95100. };
  95101. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  95102. if (!sampler._data) {
  95103. sampler._data = {
  95104. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  95105. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  95106. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  95107. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  95108. };
  95109. }
  95110. ;
  95111. return sampler._data;
  95112. };
  95113. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  95114. if (image._objectURL) {
  95115. return image._objectURL;
  95116. }
  95117. var promise;
  95118. if (image.uri) {
  95119. promise = this._loadUriAsync(context, image.uri);
  95120. }
  95121. else {
  95122. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  95123. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  95124. }
  95125. image._objectURL = promise.then(function (data) {
  95126. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  95127. });
  95128. return image._objectURL;
  95129. };
  95130. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  95131. var _this = this;
  95132. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  95133. if (promise) {
  95134. return promise;
  95135. }
  95136. if (!GLTFLoader._ValidateUri(uri)) {
  95137. throw new Error(context + ": Uri '" + uri + "' is invalid");
  95138. }
  95139. if (BABYLON.Tools.IsBase64(uri)) {
  95140. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  95141. }
  95142. return new Promise(function (resolve, reject) {
  95143. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  95144. if (!_this._disposed) {
  95145. resolve(new Uint8Array(data));
  95146. }
  95147. }, function (event) {
  95148. if (!_this._disposed) {
  95149. try {
  95150. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  95151. request._lengthComputable = event.lengthComputable;
  95152. request._loaded = event.loaded;
  95153. request._total = event.total;
  95154. _this._onProgress();
  95155. }
  95156. }
  95157. catch (e) {
  95158. reject(e);
  95159. }
  95160. }
  95161. }, _this._babylonScene.database, true, function (request, exception) {
  95162. if (!_this._disposed) {
  95163. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  95164. }
  95165. });
  95166. _this._requests.push(request);
  95167. });
  95168. };
  95169. GLTFLoader.prototype._onProgress = function () {
  95170. if (!this._progressCallback) {
  95171. return;
  95172. }
  95173. var lengthComputable = true;
  95174. var loaded = 0;
  95175. var total = 0;
  95176. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  95177. var request = _a[_i];
  95178. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  95179. return;
  95180. }
  95181. lengthComputable = lengthComputable && request._lengthComputable;
  95182. loaded += request._loaded;
  95183. total += request._total;
  95184. }
  95185. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  95186. };
  95187. GLTFLoader._GetProperty = function (context, array, index) {
  95188. if (!array || index == undefined || !array[index]) {
  95189. throw new Error(context + ": Failed to find index (" + index + ")");
  95190. }
  95191. return array[index];
  95192. };
  95193. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  95194. // Set defaults if undefined
  95195. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  95196. switch (mode) {
  95197. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  95198. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  95199. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  95200. default:
  95201. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  95202. return BABYLON.Texture.WRAP_ADDRESSMODE;
  95203. }
  95204. };
  95205. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  95206. // Set defaults if undefined
  95207. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  95208. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  95209. if (magFilter === 9729 /* LINEAR */) {
  95210. switch (minFilter) {
  95211. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  95212. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  95213. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  95214. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  95215. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  95216. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  95217. default:
  95218. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  95219. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  95220. }
  95221. }
  95222. else {
  95223. if (magFilter !== 9728 /* NEAREST */) {
  95224. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  95225. }
  95226. switch (minFilter) {
  95227. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  95228. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  95229. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  95230. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  95231. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  95232. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  95233. default:
  95234. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  95235. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  95236. }
  95237. }
  95238. };
  95239. GLTFLoader._GetNumComponents = function (context, type) {
  95240. switch (type) {
  95241. case "SCALAR": return 1;
  95242. case "VEC2": return 2;
  95243. case "VEC3": return 3;
  95244. case "VEC4": return 4;
  95245. case "MAT2": return 4;
  95246. case "MAT3": return 9;
  95247. case "MAT4": return 16;
  95248. }
  95249. throw new Error(context + ": Invalid type (" + type + ")");
  95250. };
  95251. GLTFLoader._ValidateUri = function (uri) {
  95252. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  95253. };
  95254. GLTFLoader._GetDrawMode = function (context, mode) {
  95255. mode = mode || 4 /* TRIANGLES */;
  95256. switch (mode) {
  95257. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  95258. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  95259. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  95260. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  95261. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  95262. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  95263. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  95264. }
  95265. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  95266. };
  95267. GLTFLoader.prototype._compileMaterialsAsync = function () {
  95268. var promises = new Array();
  95269. if (this._gltf.materials) {
  95270. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  95271. var material = _a[_i];
  95272. if (material._babylonData) {
  95273. for (var babylonDrawMode in material._babylonData) {
  95274. var babylonData = material._babylonData[babylonDrawMode];
  95275. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  95276. var babylonMesh = _c[_b];
  95277. // Ensure nonUniformScaling is set if necessary.
  95278. babylonMesh.computeWorldMatrix(true);
  95279. var babylonMaterial = babylonData.material;
  95280. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  95281. if (this.useClipPlane) {
  95282. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  95283. }
  95284. }
  95285. }
  95286. }
  95287. }
  95288. }
  95289. return Promise.all(promises).then(function () { });
  95290. };
  95291. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  95292. var promises = new Array();
  95293. var lights = this._babylonScene.lights;
  95294. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  95295. var light = lights_1[_i];
  95296. var generator = light.getShadowGenerator();
  95297. if (generator) {
  95298. promises.push(generator.forceCompilationAsync());
  95299. }
  95300. }
  95301. return Promise.all(promises).then(function () { });
  95302. };
  95303. GLTFLoader.prototype._clear = function () {
  95304. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  95305. var request = _a[_i];
  95306. request.abort();
  95307. }
  95308. this._requests.length = 0;
  95309. if (this._gltf && this._gltf.images) {
  95310. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  95311. var image = _c[_b];
  95312. if (image._objectURL) {
  95313. image._objectURL.then(function (value) {
  95314. URL.revokeObjectURL(value);
  95315. });
  95316. image._objectURL = undefined;
  95317. }
  95318. }
  95319. }
  95320. delete this._gltf;
  95321. delete this._babylonScene;
  95322. this._completePromises.length = 0;
  95323. for (var name_4 in this._extensions) {
  95324. this._extensions[name_4].dispose();
  95325. }
  95326. this._extensions = {};
  95327. delete this._rootBabylonMesh;
  95328. delete this._progressCallback;
  95329. this.onMeshLoadedObservable.clear();
  95330. this.onTextureLoadedObservable.clear();
  95331. this.onMaterialLoadedObservable.clear();
  95332. };
  95333. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  95334. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  95335. var name_5 = _a[_i];
  95336. var extension = this._extensions[name_5];
  95337. if (extension.enabled) {
  95338. var promise = actionAsync(extension);
  95339. if (promise) {
  95340. return promise;
  95341. }
  95342. }
  95343. }
  95344. return null;
  95345. };
  95346. GLTFLoader._Names = new Array();
  95347. GLTFLoader._Factories = {};
  95348. return GLTFLoader;
  95349. }());
  95350. GLTF2.GLTFLoader = GLTFLoader;
  95351. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  95352. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  95353. })(BABYLON || (BABYLON = {}));
  95354. //# sourceMappingURL=babylon.glTFLoader.js.map
  95355. "use strict";
  95356. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  95357. var BABYLON;
  95358. (function (BABYLON) {
  95359. var GLTF2;
  95360. (function (GLTF2) {
  95361. var GLTFLoaderExtension = /** @class */ (function () {
  95362. function GLTFLoaderExtension(loader) {
  95363. this.enabled = true;
  95364. this._loader = loader;
  95365. }
  95366. GLTFLoaderExtension.prototype.dispose = function () {
  95367. delete this._loader;
  95368. };
  95369. // #region Overridable Methods
  95370. /** Override this method to modify the default behavior for loading scenes. */
  95371. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  95372. /** Override this method to modify the default behavior for loading nodes. */
  95373. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  95374. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  95375. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  95376. /** Override this method to modify the default behavior for loading materials. */
  95377. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  95378. /** Override this method to modify the default behavior for loading uris. */
  95379. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  95380. // #endregion
  95381. /** Helper method called by a loader extension to load an glTF extension. */
  95382. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  95383. if (!property.extensions) {
  95384. return null;
  95385. }
  95386. var extensions = property.extensions;
  95387. var extension = extensions[this.name];
  95388. if (!extension) {
  95389. return null;
  95390. }
  95391. // Clear out the extension before executing the action to avoid recursing into the same property.
  95392. delete extensions[this.name];
  95393. try {
  95394. return actionAsync(context + "/extensions/" + this.name, extension);
  95395. }
  95396. finally {
  95397. // Restore the extension after executing the action.
  95398. extensions[this.name] = extension;
  95399. }
  95400. };
  95401. /** Helper method called by the loader to allow extensions to override loading scenes. */
  95402. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  95403. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  95404. };
  95405. /** Helper method called by the loader to allow extensions to override loading nodes. */
  95406. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  95407. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  95408. };
  95409. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  95410. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  95411. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  95412. };
  95413. /** Helper method called by the loader to allow extensions to override loading materials. */
  95414. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  95415. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  95416. };
  95417. /** Helper method called by the loader to allow extensions to override loading uris. */
  95418. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  95419. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  95420. };
  95421. return GLTFLoaderExtension;
  95422. }());
  95423. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  95424. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  95425. })(BABYLON || (BABYLON = {}));
  95426. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  95427. "use strict";
  95428. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  95429. var BABYLON;
  95430. (function (BABYLON) {
  95431. var GLTF2;
  95432. (function (GLTF2) {
  95433. var Extensions;
  95434. (function (Extensions) {
  95435. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  95436. var NAME = "MSFT_lod";
  95437. var MSFT_lod = /** @class */ (function (_super) {
  95438. __extends(MSFT_lod, _super);
  95439. function MSFT_lod() {
  95440. var _this = _super !== null && _super.apply(this, arguments) || this;
  95441. _this.name = NAME;
  95442. /**
  95443. * Maximum number of LODs to load, starting from the lowest LOD.
  95444. */
  95445. _this.maxLODsToLoad = Number.MAX_VALUE;
  95446. _this._loadingNodeLOD = null;
  95447. _this._loadNodeSignals = {};
  95448. _this._loadingMaterialLOD = null;
  95449. _this._loadMaterialSignals = {};
  95450. return _this;
  95451. }
  95452. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  95453. var _this = this;
  95454. return this._loadExtensionAsync(context, node, function (context, extension) {
  95455. var firstPromise;
  95456. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  95457. var _loop_1 = function (indexLOD) {
  95458. var nodeLOD = nodeLODs[indexLOD];
  95459. if (indexLOD !== 0) {
  95460. _this._loadingNodeLOD = nodeLOD;
  95461. if (!_this._loadNodeSignals[nodeLOD._index]) {
  95462. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  95463. }
  95464. }
  95465. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  95466. if (indexLOD !== 0) {
  95467. var previousNodeLOD = nodeLODs[indexLOD - 1];
  95468. if (previousNodeLOD._babylonMesh) {
  95469. previousNodeLOD._babylonMesh.dispose();
  95470. delete previousNodeLOD._babylonMesh;
  95471. }
  95472. }
  95473. if (indexLOD !== nodeLODs.length - 1) {
  95474. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  95475. if (_this._loadNodeSignals[nodeIndex]) {
  95476. _this._loadNodeSignals[nodeIndex].resolve();
  95477. delete _this._loadNodeSignals[nodeIndex];
  95478. }
  95479. }
  95480. });
  95481. if (indexLOD === 0) {
  95482. firstPromise = promise;
  95483. }
  95484. else {
  95485. _this._loader._completePromises.push(promise);
  95486. _this._loadingNodeLOD = null;
  95487. }
  95488. };
  95489. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  95490. _loop_1(indexLOD);
  95491. }
  95492. return firstPromise;
  95493. });
  95494. };
  95495. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  95496. var _this = this;
  95497. // Don't load material LODs if already loading a node LOD.
  95498. if (this._loadingNodeLOD) {
  95499. return null;
  95500. }
  95501. return this._loadExtensionAsync(context, material, function (context, extension) {
  95502. var firstPromise;
  95503. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  95504. var _loop_2 = function (indexLOD) {
  95505. var materialLOD = materialLODs[indexLOD];
  95506. if (indexLOD !== 0) {
  95507. _this._loadingMaterialLOD = materialLOD;
  95508. if (!_this._loadMaterialSignals[materialLOD._index]) {
  95509. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  95510. }
  95511. }
  95512. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  95513. if (indexLOD !== 0) {
  95514. var babylonDataLOD = materialLOD._babylonData;
  95515. assign(babylonDataLOD[babylonDrawMode].material);
  95516. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  95517. if (previousBabylonDataLOD[babylonDrawMode]) {
  95518. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  95519. delete previousBabylonDataLOD[babylonDrawMode];
  95520. }
  95521. }
  95522. if (indexLOD !== materialLODs.length - 1) {
  95523. var materialIndex = materialLODs[indexLOD + 1]._index;
  95524. if (_this._loadMaterialSignals[materialIndex]) {
  95525. _this._loadMaterialSignals[materialIndex].resolve();
  95526. delete _this._loadMaterialSignals[materialIndex];
  95527. }
  95528. }
  95529. });
  95530. if (indexLOD === 0) {
  95531. firstPromise = promise;
  95532. }
  95533. else {
  95534. _this._loader._completePromises.push(promise);
  95535. _this._loadingMaterialLOD = null;
  95536. }
  95537. };
  95538. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  95539. _loop_2(indexLOD);
  95540. }
  95541. return firstPromise;
  95542. });
  95543. };
  95544. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  95545. var _this = this;
  95546. // Defer the loading of uris if loading a material or node LOD.
  95547. if (this._loadingMaterialLOD) {
  95548. var index = this._loadingMaterialLOD._index;
  95549. return this._loadMaterialSignals[index].promise.then(function () {
  95550. return _this._loader._loadUriAsync(context, uri);
  95551. });
  95552. }
  95553. else if (this._loadingNodeLOD) {
  95554. var index = this._loadingNodeLOD._index;
  95555. return this._loadNodeSignals[index].promise.then(function () {
  95556. return _this._loader._loadUriAsync(context, uri);
  95557. });
  95558. }
  95559. return null;
  95560. };
  95561. /**
  95562. * Gets an array of LOD properties from lowest to highest.
  95563. */
  95564. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  95565. if (this.maxLODsToLoad <= 0) {
  95566. throw new Error("maxLODsToLoad must be greater than zero");
  95567. }
  95568. var properties = new Array();
  95569. for (var i = ids.length - 1; i >= 0; i--) {
  95570. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  95571. if (properties.length === this.maxLODsToLoad) {
  95572. return properties;
  95573. }
  95574. }
  95575. properties.push(property);
  95576. return properties;
  95577. };
  95578. return MSFT_lod;
  95579. }(GLTF2.GLTFLoaderExtension));
  95580. Extensions.MSFT_lod = MSFT_lod;
  95581. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  95582. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  95583. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  95584. })(BABYLON || (BABYLON = {}));
  95585. //# sourceMappingURL=MSFT_lod.js.map
  95586. "use strict";
  95587. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  95588. var BABYLON;
  95589. (function (BABYLON) {
  95590. var GLTF2;
  95591. (function (GLTF2) {
  95592. var Extensions;
  95593. (function (Extensions) {
  95594. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  95595. var NAME = "KHR_draco_mesh_compression";
  95596. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  95597. __extends(KHR_draco_mesh_compression, _super);
  95598. function KHR_draco_mesh_compression(loader) {
  95599. var _this = _super.call(this, loader) || this;
  95600. _this.name = NAME;
  95601. _this._dracoCompression = null;
  95602. // Disable extension if decoder is not available.
  95603. if (!BABYLON.DracoCompression.DecoderUrl) {
  95604. _this.enabled = false;
  95605. }
  95606. return _this;
  95607. }
  95608. KHR_draco_mesh_compression.prototype.dispose = function () {
  95609. if (this._dracoCompression) {
  95610. this._dracoCompression.dispose();
  95611. }
  95612. _super.prototype.dispose.call(this);
  95613. };
  95614. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  95615. var _this = this;
  95616. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  95617. if (primitive.mode != undefined) {
  95618. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  95619. primitive.mode !== 4 /* TRIANGLES */) {
  95620. throw new Error(context + ": Unsupported mode " + primitive.mode);
  95621. }
  95622. // TODO: handle triangle strips
  95623. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  95624. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  95625. }
  95626. }
  95627. var attributes = {};
  95628. var loadAttribute = function (name, kind) {
  95629. var uniqueId = extension.attributes[name];
  95630. if (uniqueId == undefined) {
  95631. return;
  95632. }
  95633. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  95634. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  95635. babylonMesh._delayInfo.push(kind);
  95636. }
  95637. attributes[kind] = uniqueId;
  95638. };
  95639. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  95640. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  95641. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  95642. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  95643. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  95644. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  95645. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  95646. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  95647. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  95648. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  95649. try {
  95650. if (!_this._dracoCompression) {
  95651. _this._dracoCompression = new BABYLON.DracoCompression();
  95652. }
  95653. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  95654. }
  95655. catch (e) {
  95656. throw new Error(context + ": " + e.message);
  95657. }
  95658. });
  95659. });
  95660. };
  95661. return KHR_draco_mesh_compression;
  95662. }(GLTF2.GLTFLoaderExtension));
  95663. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  95664. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  95665. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  95666. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  95667. })(BABYLON || (BABYLON = {}));
  95668. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  95669. "use strict";
  95670. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  95671. var BABYLON;
  95672. (function (BABYLON) {
  95673. var GLTF2;
  95674. (function (GLTF2) {
  95675. var Extensions;
  95676. (function (Extensions) {
  95677. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  95678. var NAME = "KHR_materials_pbrSpecularGlossiness";
  95679. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  95680. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  95681. function KHR_materials_pbrSpecularGlossiness() {
  95682. var _this = _super !== null && _super.apply(this, arguments) || this;
  95683. _this.name = NAME;
  95684. return _this;
  95685. }
  95686. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  95687. var _this = this;
  95688. return this._loadExtensionAsync(context, material, function (context, extension) {
  95689. material._babylonData = material._babylonData || {};
  95690. var babylonData = material._babylonData[babylonDrawMode];
  95691. if (!babylonData) {
  95692. var promises = new Array();
  95693. var name_1 = material.name || "materialSG_" + material._index;
  95694. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  95695. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  95696. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension, babylonMaterial));
  95697. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  95698. babylonData = {
  95699. material: babylonMaterial,
  95700. meshes: [],
  95701. loaded: Promise.all(promises).then(function () { })
  95702. };
  95703. material._babylonData[babylonDrawMode] = babylonData;
  95704. }
  95705. babylonData.meshes.push(babylonMesh);
  95706. assign(babylonData.material);
  95707. return babylonData.loaded;
  95708. });
  95709. };
  95710. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  95711. var promises = new Array();
  95712. if (properties.diffuseFactor) {
  95713. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  95714. babylonMaterial.alpha = properties.diffuseFactor[3];
  95715. }
  95716. else {
  95717. babylonMaterial.albedoColor = BABYLON.Color3.White();
  95718. }
  95719. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  95720. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  95721. if (properties.diffuseTexture) {
  95722. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  95723. babylonMaterial.albedoTexture = texture;
  95724. }));
  95725. }
  95726. if (properties.specularGlossinessTexture) {
  95727. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  95728. babylonMaterial.reflectivityTexture = texture;
  95729. }));
  95730. babylonMaterial.reflectivityTexture.hasAlpha = true;
  95731. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  95732. }
  95733. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  95734. return Promise.all(promises).then(function () { });
  95735. };
  95736. return KHR_materials_pbrSpecularGlossiness;
  95737. }(GLTF2.GLTFLoaderExtension));
  95738. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  95739. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  95740. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  95741. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  95742. })(BABYLON || (BABYLON = {}));
  95743. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  95744. "use strict";
  95745. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  95746. var BABYLON;
  95747. (function (BABYLON) {
  95748. var GLTF2;
  95749. (function (GLTF2) {
  95750. var Extensions;
  95751. (function (Extensions) {
  95752. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  95753. var NAME = "KHR_lights";
  95754. var LightType;
  95755. (function (LightType) {
  95756. LightType["AMBIENT"] = "ambient";
  95757. LightType["DIRECTIONAL"] = "directional";
  95758. LightType["POINT"] = "point";
  95759. LightType["SPOT"] = "spot";
  95760. })(LightType || (LightType = {}));
  95761. var KHR_lights = /** @class */ (function (_super) {
  95762. __extends(KHR_lights, _super);
  95763. function KHR_lights() {
  95764. var _this = _super !== null && _super.apply(this, arguments) || this;
  95765. _this.name = NAME;
  95766. return _this;
  95767. }
  95768. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  95769. var _this = this;
  95770. return this._loadExtensionAsync(context, scene, function (context, extension) {
  95771. var promise = _this._loader._loadSceneAsync(context, scene);
  95772. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  95773. if (light.type !== LightType.AMBIENT) {
  95774. throw new Error(context + ": Only ambient lights are allowed on a scene");
  95775. }
  95776. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  95777. return promise;
  95778. });
  95779. };
  95780. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  95781. var _this = this;
  95782. return this._loadExtensionAsync(context, node, function (context, extension) {
  95783. var promise = _this._loader._loadNodeAsync(context, node);
  95784. var babylonLight;
  95785. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  95786. var name = node._babylonMesh.name;
  95787. switch (light.type) {
  95788. case LightType.AMBIENT: {
  95789. throw new Error(context + ": Ambient lights are not allowed on a node");
  95790. }
  95791. case LightType.DIRECTIONAL: {
  95792. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  95793. break;
  95794. }
  95795. case LightType.POINT: {
  95796. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  95797. break;
  95798. }
  95799. case LightType.SPOT: {
  95800. var spotLight = light;
  95801. // TODO: support inner and outer cone angles
  95802. //const innerConeAngle = spotLight.innerConeAngle || 0;
  95803. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  95804. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  95805. break;
  95806. }
  95807. default: {
  95808. throw new Error(context + ": Invalid light type (" + light.type + ")");
  95809. }
  95810. }
  95811. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  95812. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  95813. babylonLight.parent = node._babylonMesh;
  95814. return promise;
  95815. });
  95816. };
  95817. Object.defineProperty(KHR_lights.prototype, "_lights", {
  95818. get: function () {
  95819. var extensions = this._loader._gltf.extensions;
  95820. if (!extensions || !extensions[this.name]) {
  95821. throw new Error("#/extensions: '" + this.name + "' not found");
  95822. }
  95823. var extension = extensions[this.name];
  95824. return extension.lights;
  95825. },
  95826. enumerable: true,
  95827. configurable: true
  95828. });
  95829. return KHR_lights;
  95830. }(GLTF2.GLTFLoaderExtension));
  95831. Extensions.KHR_lights = KHR_lights;
  95832. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  95833. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  95834. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  95835. })(BABYLON || (BABYLON = {}));
  95836. //# sourceMappingURL=KHR_lights.js.map
  95837. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  95838. globalObject["BABYLON"] = BABYLON;
  95839. 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 WorkerPool = BABYLON.WorkerPool;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var DepthTextureCreationOptions = BABYLON.DepthTextureCreationOptions;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 AnimationPropertiesOverride = BABYLON.AnimationPropertiesOverride;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 DracoCompression = BABYLON.DracoCompression;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 DaydreamController = BABYLON.DaydreamController;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 ChromaticAberrationPostProcess = BABYLON.ChromaticAberrationPostProcess;var SharpenPostProcess = BABYLON.SharpenPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;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 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;var Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;var Xbox360Button = BABYLON.Xbox360Button ;var Xbox360Dpad = BABYLON.Xbox360Dpad ;var PoseEnabledControllerType = BABYLON.PoseEnabledControllerType ;var DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel ;var TonemappingOperator = BABYLON.TonemappingOperator ;var PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff ;var PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;var GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode ;var GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode ;var GLTFLoaderState = BABYLON.GLTFLoaderState ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;
  95840. 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,WorkerPool,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,DepthTextureCreationOptions,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,AnimationPropertiesOverride,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,DracoCompression,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,DaydreamController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,ChromaticAberrationPostProcess,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,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,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,JoystickAxis ,SimplificationType ,AssetTaskState ,GLTFLoaderCoordinateSystemMode ,GLTFLoaderAnimationStartMode ,GLTFLoaderState ,GLTF1 ,GLTF1 ,GLTF1 ,GLTF1 ,GLTF1 ,GLTF1 ,GLTF2 ,GLTF2 ,GLTF2 ,GLTF2 ,GLTF2 ,GLTF2 ,GLTF2 };