babylon.no-module.max.js 4.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559935609356193562935639356493565935669356793568935699357093571935729357393574935759357693577935789357993580935819358293583935849358593586935879358893589935909359193592935939359493595935969359793598935999360093601936029360393604936059360693607936089360993610936119361293613936149361593616936179361893619936209362193622936239362493625936269362793628936299363093631936329363393634936359363693637936389363993640936419364293643936449364593646936479364893649936509365193652936539365493655936569365793658936599366093661936629366393664936659366693667936689366993670936719367293673936749367593676936779367893679936809368193682936839368493685936869368793688936899369093691936929369393694936959369693697936989369993700937019370293703937049370593706937079370893709937109371193712937139371493715937169371793718937199372093721937229372393724937259372693727937289372993730937319373293733937349373593736937379373893739937409374193742937439374493745937469374793748937499375093751937529375393754937559375693757937589375993760937619376293763937649376593766937679376893769937709377193772937739377493775937769377793778937799378093781937829378393784937859378693787937889378993790937919379293793937949379593796937979379893799938009380193802938039380493805938069380793808938099381093811938129381393814938159381693817938189381993820938219382293823938249382593826938279382893829938309383193832938339383493835938369383793838938399384093841938429384393844938459384693847938489384993850938519385293853938549385593856938579385893859938609386193862938639386493865938669386793868938699387093871938729387393874938759387693877938789387993880938819388293883938849388593886938879388893889938909389193892938939389493895938969389793898938999390093901939029390393904939059390693907939089390993910939119391293913939149391593916939179391893919939209392193922939239392493925939269392793928939299393093931939329393393934939359393693937939389393993940939419394293943939449394593946939479394893949939509395193952939539395493955939569395793958939599396093961939629396393964939659396693967939689396993970939719397293973939749397593976939779397893979939809398193982939839398493985939869398793988939899399093991939929399393994939959399693997939989399994000940019400294003940049400594006940079400894009940109401194012940139401494015940169401794018940199402094021940229402394024940259402694027940289402994030940319403294033940349403594036940379403894039940409404194042940439404494045940469404794048940499405094051940529405394054940559405694057940589405994060940619406294063940649406594066940679406894069940709407194072940739407494075940769407794078940799408094081940829408394084940859408694087940889408994090940919409294093940949409594096940979409894099941009410194102941039410494105941069410794108941099411094111941129411394114941159411694117941189411994120941219412294123941249412594126941279412894129941309413194132941339413494135941369413794138941399414094141941429414394144941459414694147941489414994150941519415294153941549415594156941579415894159941609416194162941639416494165941669416794168941699417094171941729417394174941759417694177941789417994180941819418294183941849418594186941879418894189941909419194192941939419494195941969419794198941999420094201942029420394204942059420694207942089420994210942119421294213942149421594216942179421894219942209422194222942239422494225942269422794228942299423094231942329423394234942359423694237942389423994240942419424294243942449424594246942479424894249942509425194252942539425494255942569425794258942599426094261942629426394264942659426694267942689426994270942719427294273942749427594276942779427894279942809428194282942839428494285942869428794288942899429094291942929429394294942959429694297942989429994300943019430294303943049430594306943079430894309943109431194312943139431494315943169431794318943199432094321943229432394324943259432694327943289432994330943319433294333943349433594336943379433894339943409434194342943439434494345943469434794348943499435094351943529435394354943559435694357943589435994360943619436294363943649436594366943679436894369943709437194372943739437494375943769437794378943799438094381943829438394384943859438694387943889438994390943919439294393943949439594396943979439894399944009440194402944039440494405944069440794408944099441094411944129441394414944159441694417944189441994420944219442294423944249442594426944279442894429944309443194432944339443494435944369443794438944399444094441944429444394444944459444694447944489444994450944519445294453944549445594456944579445894459944609446194462944639446494465944669446794468944699447094471944729447394474944759447694477944789447994480944819448294483944849448594486944879448894489944909449194492944939449494495944969449794498944999450094501945029450394504945059450694507945089450994510945119451294513945149451594516945179451894519945209452194522945239452494525945269452794528945299453094531945329453394534945359453694537945389453994540945419454294543945449454594546945479454894549945509455194552945539455494555945569455794558945599456094561945629456394564945659456694567945689456994570945719457294573945749457594576945779457894579945809458194582945839458494585945869458794588945899459094591945929459394594945959459694597945989459994600946019460294603946049460594606946079460894609946109461194612946139461494615946169461794618946199462094621946229462394624946259462694627946289462994630946319463294633946349463594636946379463894639946409464194642946439464494645946469464794648946499465094651946529465394654946559465694657946589465994660946619466294663946649466594666946679466894669946709467194672946739467494675946769467794678946799468094681946829468394684946859468694687946889468994690946919469294693946949469594696946979469894699947009470194702947039470494705947069470794708947099471094711947129471394714947159471694717947189471994720947219472294723947249472594726947279472894729947309473194732947339473494735947369473794738947399474094741947429474394744947459474694747947489474994750947519475294753947549475594756947579475894759947609476194762947639476494765947669476794768947699477094771947729477394774947759477694777947789477994780947819478294783947849478594786947879478894789947909479194792947939479494795947969479794798947999480094801948029480394804948059480694807948089480994810948119481294813948149481594816948179481894819948209482194822948239482494825948269482794828948299483094831948329483394834948359483694837948389483994840948419484294843948449484594846948479484894849948509485194852948539485494855948569485794858948599486094861948629486394864948659486694867948689486994870948719487294873948749487594876948779487894879948809488194882948839488494885948869488794888948899489094891948929489394894948959489694897948989489994900949019490294903949049490594906949079490894909949109491194912949139491494915949169491794918949199492094921949229492394924949259492694927949289492994930949319493294933949349493594936949379493894939949409494194942949439494494945949469494794948949499495094951949529495394954949559495694957949589495994960949619496294963949649496594966949679496894969949709497194972949739497494975949769497794978949799498094981949829498394984949859498694987949889498994990949919499294993949949499594996949979499894999950009500195002950039500495005950069500795008950099501095011950129501395014950159501695017950189501995020950219502295023950249502595026950279502895029950309503195032950339503495035950369503795038950399504095041950429504395044950459504695047950489504995050950519505295053950549505595056950579505895059950609506195062950639506495065950669506795068950699507095071950729507395074950759507695077950789507995080950819508295083950849508595086950879508895089950909509195092950939509495095950969509795098950999510095101951029510395104951059510695107951089510995110951119511295113951149511595116951179511895119951209512195122951239512495125951269512795128951299513095131951329513395134951359513695137951389513995140951419514295143951449514595146951479514895149951509515195152951539515495155951569515795158951599516095161951629516395164951659516695167951689516995170951719517295173951749517595176951779517895179951809518195182951839518495185951869518795188951899519095191951929519395194951959519695197951989519995200952019520295203952049520595206952079520895209952109521195212952139521495215952169521795218952199522095221952229522395224952259522695227952289522995230952319523295233952349523595236952379523895239952409524195242952439524495245952469524795248952499525095251952529525395254952559525695257952589525995260952619526295263952649526595266952679526895269952709527195272952739527495275952769527795278952799528095281952829528395284952859528695287952889528995290952919529295293952949529595296952979529895299953009530195302953039530495305953069530795308953099531095311953129531395314953159531695317953189531995320953219532295323953249532595326953279532895329953309533195332953339533495335953369533795338953399534095341953429534395344953459534695347953489534995350953519535295353953549535595356953579535895359953609536195362953639536495365953669536795368953699537095371953729537395374953759537695377953789537995380953819538295383953849538595386953879538895389953909539195392953939539495395953969539795398953999540095401954029540395404954059540695407954089540995410954119541295413954149541595416954179541895419954209542195422954239542495425954269542795428954299543095431954329543395434954359543695437954389543995440954419544295443954449544595446954479544895449954509545195452954539545495455954569545795458954599546095461954629546395464954659546695467954689546995470954719547295473954749547595476954779547895479954809548195482954839548495485954869548795488954899549095491954929549395494954959549695497954989549995500955019550295503955049550595506955079550895509955109551195512955139551495515955169551795518955199552095521955229552395524955259552695527955289552995530955319553295533955349553595536955379553895539955409554195542955439554495545955469554795548955499555095551955529555395554955559555695557955589555995560955619556295563955649556595566955679556895569955709557195572955739557495575955769557795578955799558095581955829558395584955859558695587955889558995590955919559295593955949559595596955979559895599956009560195602956039560495605956069560795608956099561095611956129561395614956159561695617956189561995620956219562295623956249562595626956279562895629956309563195632956339563495635956369563795638956399564095641956429564395644956459564695647956489564995650956519565295653956549565595656956579565895659956609566195662956639566495665956669566795668956699567095671956729567395674956759567695677956789567995680956819568295683956849568595686956879568895689956909569195692956939569495695956969569795698956999570095701957029570395704957059570695707957089570995710957119571295713957149571595716957179571895719957209572195722957239572495725957269572795728957299573095731957329573395734957359573695737957389573995740957419574295743957449574595746957479574895749957509575195752957539575495755957569575795758957599576095761957629576395764957659576695767957689576995770957719577295773957749577595776957779577895779957809578195782957839578495785957869578795788957899579095791957929579395794957959579695797957989579995800958019580295803958049580595806958079580895809958109581195812958139581495815958169581795818958199582095821958229582395824958259582695827958289582995830958319583295833958349583595836958379583895839958409584195842958439584495845958469584795848958499585095851958529585395854958559585695857958589585995860958619586295863958649586595866958679586895869958709587195872958739587495875958769587795878958799588095881958829588395884958859588695887958889588995890958919589295893958949589595896958979589895899959009590195902959039590495905959069590795908959099591095911959129591395914959159591695917959189591995920959219592295923959249592595926959279592895929959309593195932959339593495935959369593795938959399594095941959429594395944959459594695947959489594995950959519595295953959549595595956959579595895959959609596195962959639596495965959669596795968959699597095971959729597395974959759597695977959789597995980959819598295983959849598595986959879598895989959909599195992959939599495995959969599795998959999600096001960029600396004960059600696007960089600996010960119601296013960149601596016960179601896019960209602196022960239602496025960269602796028960299603096031960329603396034960359603696037960389603996040960419604296043960449604596046960479604896049960509605196052960539605496055960569605796058960599606096061960629606396064960659606696067960689606996070960719607296073960749607596076960779607896079960809608196082960839608496085960869608796088960899609096091960929609396094960959609696097960989609996100961019610296103961049610596106961079610896109961109611196112961139611496115961169611796118961199612096121961229612396124961259612696127961289612996130961319613296133961349613596136961379613896139961409614196142961439614496145961469614796148961499615096151961529615396154961559615696157961589615996160961619616296163961649616596166961679616896169961709617196172961739617496175961769617796178961799618096181961829618396184961859618696187961889618996190961919619296193961949619596196961979619896199962009620196202962039620496205962069620796208962099621096211962129621396214962159621696217962189621996220962219622296223962249622596226962279622896229962309623196232962339623496235962369623796238962399624096241962429624396244962459624696247962489624996250962519625296253962549625596256962579625896259962609626196262962639626496265962669626796268962699627096271962729627396274962759627696277962789627996280962819628296283962849628596286962879628896289962909629196292962939629496295962969629796298962999630096301963029630396304963059630696307963089630996310963119631296313963149631596316963179631896319963209632196322963239632496325963269632796328963299633096331963329633396334963359633696337963389633996340963419634296343963449634596346963479634896349963509635196352963539635496355963569635796358963599636096361963629636396364963659636696367963689636996370963719637296373963749637596376963779637896379963809638196382963839638496385963869638796388963899639096391963929639396394963959639696397963989639996400964019640296403964049640596406964079640896409964109641196412964139641496415964169641796418964199642096421964229642396424964259642696427964289642996430964319643296433964349643596436964379643896439964409644196442964439644496445964469644796448964499645096451964529645396454964559645696457964589645996460964619646296463964649646596466964679646896469964709647196472964739647496475964769647796478964799648096481964829648396484964859648696487964889648996490964919649296493964949649596496964979649896499965009650196502965039650496505965069650796508965099651096511965129651396514965159651696517965189651996520965219652296523965249652596526965279652896529965309653196532965339653496535965369653796538965399654096541965429654396544965459654696547965489654996550965519655296553965549655596556965579655896559965609656196562965639656496565965669656796568965699657096571965729657396574965759657696577965789657996580965819658296583965849658596586965879658896589965909659196592965939659496595965969659796598965999660096601966029660396604966059660696607966089660996610966119661296613966149661596616966179661896619966209662196622966239662496625966269662796628966299663096631966329663396634966359663696637966389663996640966419664296643966449664596646966479664896649966509665196652966539665496655966569665796658966599666096661966629666396664966659666696667966689666996670966719667296673966749667596676966779667896679966809668196682966839668496685966869668796688966899669096691966929669396694966959669696697966989669996700967019670296703967049670596706967079670896709967109671196712967139671496715967169671796718967199672096721967229672396724967259672696727967289672996730967319673296733967349673596736967379673896739967409674196742967439674496745967469674796748967499675096751967529675396754967559675696757967589675996760967619676296763967649676596766967679676896769967709677196772967739677496775967769677796778967799678096781967829678396784967859678696787967889678996790967919679296793967949679596796967979679896799968009680196802968039680496805968069680796808968099681096811968129681396814968159681696817968189681996820968219682296823968249682596826968279682896829968309683196832968339683496835968369683796838968399684096841968429684396844968459684696847968489684996850968519685296853968549685596856968579685896859968609686196862968639686496865968669686796868968699687096871968729687396874968759687696877968789687996880968819688296883968849688596886968879688896889968909689196892968939689496895968969689796898968999690096901969029690396904969059690696907969089690996910969119691296913969149691596916969179691896919969209692196922969239692496925969269692796928969299693096931969329693396934969359693696937969389693996940969419694296943969449694596946969479694896949969509695196952969539695496955969569695796958969599696096961969629696396964969659696696967969689696996970969719697296973969749697596976969779697896979969809698196982969839698496985969869698796988969899699096991969929699396994969959699696997969989699997000970019700297003970049700597006970079700897009970109701197012970139701497015970169701797018970199702097021970229702397024970259702697027970289702997030970319703297033970349703597036970379703897039970409704197042970439704497045970469704797048970499705097051970529705397054970559705697057970589705997060970619706297063970649706597066970679706897069970709707197072970739707497075970769707797078970799708097081970829708397084970859708697087970889708997090970919709297093970949709597096970979709897099971009710197102971039710497105971069710797108971099711097111971129711397114971159711697117971189711997120971219712297123971249712597126971279712897129971309713197132971339713497135971369713797138971399714097141971429714397144971459714697147971489714997150971519715297153971549715597156971579715897159971609716197162971639716497165971669716797168971699717097171971729717397174971759717697177971789717997180971819718297183971849718597186971879718897189971909719197192971939719497195971969719797198971999720097201972029720397204972059720697207972089720997210972119721297213972149721597216972179721897219972209722197222972239722497225972269722797228972299723097231972329723397234972359723697237972389723997240972419724297243972449724597246972479724897249972509725197252972539725497255972569725797258972599726097261972629726397264972659726697267972689726997270972719727297273972749727597276972779727897279972809728197282972839728497285972869728797288972899729097291972929729397294972959729697297972989729997300973019730297303973049730597306973079730897309973109731197312973139731497315973169731797318973199732097321973229732397324973259732697327973289732997330973319733297333973349733597336973379733897339973409734197342973439734497345973469734797348973499735097351973529735397354973559735697357973589735997360973619736297363973649736597366973679736897369973709737197372973739737497375973769737797378973799738097381973829738397384973859738697387973889738997390973919739297393973949739597396973979739897399974009740197402974039740497405974069740797408974099741097411974129741397414974159741697417974189741997420974219742297423974249742597426974279742897429974309743197432974339743497435974369743797438974399744097441974429744397444974459744697447974489744997450974519745297453974549745597456974579745897459974609746197462974639746497465974669746797468974699747097471974729747397474974759747697477974789747997480974819748297483974849748597486974879748897489974909749197492974939749497495974969749797498974999750097501975029750397504975059750697507975089750997510975119751297513975149751597516975179751897519975209752197522975239752497525975269752797528975299753097531975329753397534975359753697537975389753997540975419754297543975449754597546975479754897549975509755197552975539755497555975569755797558975599756097561975629756397564975659756697567975689756997570975719757297573975749757597576975779757897579975809758197582975839758497585975869758797588975899759097591975929759397594975959759697597975989759997600976019760297603976049760597606976079760897609976109761197612976139761497615976169761797618976199762097621976229762397624976259762697627976289762997630976319763297633976349763597636976379763897639976409764197642976439764497645976469764797648976499765097651976529765397654976559765697657976589765997660976619766297663976649766597666976679766897669976709767197672976739767497675976769767797678976799768097681976829768397684976859768697687976889768997690976919769297693976949769597696976979769897699977009770197702977039770497705977069770797708977099771097711977129771397714977159771697717977189771997720977219772297723977249772597726977279772897729977309773197732977339773497735977369773797738977399774097741977429774397744977459774697747977489774997750977519775297753977549775597756977579775897759977609776197762977639776497765977669776797768977699777097771977729777397774977759777697777977789777997780977819778297783977849778597786977879778897789977909779197792977939779497795977969779797798977999780097801978029780397804978059780697807978089780997810978119781297813978149781597816978179781897819978209782197822978239782497825978269782797828978299783097831978329783397834978359783697837978389783997840978419784297843978449784597846978479784897849978509785197852978539785497855978569785797858978599786097861978629786397864978659786697867978689786997870978719787297873978749787597876978779787897879978809788197882978839788497885978869788797888978899789097891978929789397894978959789697897978989789997900979019790297903979049790597906979079790897909979109791197912979139791497915979169791797918979199792097921979229792397924979259792697927979289792997930979319793297933979349793597936979379793897939979409794197942979439794497945979469794797948979499795097951979529795397954979559795697957979589795997960979619796297963979649796597966979679796897969979709797197972979739797497975979769797797978979799798097981979829798397984979859798697987979889798997990979919799297993979949799597996979979799897999980009800198002980039800498005980069800798008980099801098011980129801398014980159801698017980189801998020980219802298023980249802598026980279802898029980309803198032980339803498035980369803798038980399804098041980429804398044980459804698047980489804998050980519805298053980549805598056980579805898059980609806198062980639806498065980669806798068980699807098071980729807398074980759807698077980789807998080980819808298083980849808598086980879808898089980909809198092980939809498095980969809798098980999810098101981029810398104981059810698107981089810998110981119811298113981149811598116981179811898119981209812198122981239812498125981269812798128981299813098131981329813398134981359813698137981389813998140981419814298143981449814598146981479814898149981509815198152981539815498155981569815798158981599816098161981629816398164981659816698167981689816998170981719817298173981749817598176981779817898179981809818198182981839818498185981869818798188981899819098191981929819398194981959819698197981989819998200982019820298203982049820598206982079820898209982109821198212982139821498215982169821798218982199822098221982229822398224982259822698227982289822998230982319823298233982349823598236982379823898239982409824198242982439824498245982469824798248982499825098251982529825398254982559825698257982589825998260982619826298263982649826598266982679826898269982709827198272982739827498275982769827798278982799828098281982829828398284982859828698287982889828998290982919829298293982949829598296982979829898299983009830198302983039830498305983069830798308983099831098311983129831398314983159831698317983189831998320983219832298323983249832598326983279832898329983309833198332983339833498335983369833798338983399834098341983429834398344983459834698347983489834998350983519835298353983549835598356983579835898359983609836198362983639836498365983669836798368983699837098371983729837398374983759837698377983789837998380983819838298383983849838598386983879838898389983909839198392983939839498395983969839798398983999840098401984029840398404984059840698407984089840998410984119841298413984149841598416984179841898419984209842198422984239842498425984269842798428984299843098431984329843398434984359843698437984389843998440984419844298443984449844598446984479844898449984509845198452984539845498455984569845798458984599846098461984629846398464984659846698467984689846998470984719847298473984749847598476984779847898479984809848198482984839848498485984869848798488984899849098491984929849398494984959849698497984989849998500985019850298503985049850598506985079850898509985109851198512985139851498515985169851798518985199852098521985229852398524985259852698527985289852998530985319853298533985349853598536985379853898539985409854198542985439854498545985469854798548985499855098551985529855398554985559855698557985589855998560985619856298563985649856598566985679856898569985709857198572985739857498575985769857798578985799858098581985829858398584985859858698587985889858998590985919859298593985949859598596985979859898599986009860198602986039860498605986069860798608986099861098611986129861398614986159861698617986189861998620986219862298623986249862598626986279862898629986309863198632986339863498635986369863798638986399864098641986429864398644986459864698647986489864998650986519865298653986549865598656986579865898659986609866198662986639866498665986669866798668986699867098671
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  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 if (otherMesh.subMeshes) {
  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. /** @hidden */
  163. this._bonesComputationForcedToCPU = false;
  164. this._uniformBuffersNames = {};
  165. this._isReady = false;
  166. this._compilationError = "";
  167. this.name = baseName;
  168. if (attributesNamesOrOptions.attributes) {
  169. var options = attributesNamesOrOptions;
  170. this._engine = uniformsNamesOrEngine;
  171. this._attributesNames = options.attributes;
  172. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  173. this._samplers = options.samplers.slice();
  174. this.defines = options.defines;
  175. this.onError = options.onError;
  176. this.onCompiled = options.onCompiled;
  177. this._fallbacks = options.fallbacks;
  178. this._indexParameters = options.indexParameters;
  179. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  180. if (options.uniformBuffersNames) {
  181. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  182. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  183. }
  184. }
  185. }
  186. else {
  187. this._engine = engine;
  188. this.defines = defines;
  189. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  190. this._samplers = samplers ? samplers.slice() : [];
  191. this._attributesNames = attributesNamesOrOptions;
  192. this.onError = onError;
  193. this.onCompiled = onCompiled;
  194. this._indexParameters = indexParameters;
  195. this._fallbacks = fallbacks;
  196. }
  197. this.uniqueId = Effect._uniqueIdSeed++;
  198. var vertexSource;
  199. var fragmentSource;
  200. if (baseName.vertexElement) {
  201. vertexSource = document.getElementById(baseName.vertexElement);
  202. if (!vertexSource) {
  203. vertexSource = baseName.vertexElement;
  204. }
  205. }
  206. else {
  207. vertexSource = baseName.vertex || baseName;
  208. }
  209. if (baseName.fragmentElement) {
  210. fragmentSource = document.getElementById(baseName.fragmentElement);
  211. if (!fragmentSource) {
  212. fragmentSource = baseName.fragmentElement;
  213. }
  214. }
  215. else {
  216. fragmentSource = baseName.fragment || baseName;
  217. }
  218. this._loadVertexShader(vertexSource, function (vertexCode) {
  219. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  220. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  221. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  222. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  223. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  224. if (baseName) {
  225. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  226. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  227. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  228. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  229. }
  230. else {
  231. _this._vertexSourceCode = migratedVertexCode;
  232. _this._fragmentSourceCode = migratedFragmentCode;
  233. }
  234. _this._prepareEffect();
  235. });
  236. });
  237. });
  238. });
  239. });
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @hidden */
  348. Effect.prototype._loadVertexShader = function (vertex, callback) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. callback(vertexCode);
  354. return;
  355. }
  356. }
  357. // Base64 encoded ?
  358. if (vertex.substr(0, 7) === "base64:") {
  359. var vertexBinary = window.atob(vertex.substr(7));
  360. callback(vertexBinary);
  361. return;
  362. }
  363. // Is in local store ?
  364. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  365. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  366. return;
  367. }
  368. var vertexShaderUrl;
  369. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  370. vertexShaderUrl = vertex;
  371. }
  372. else {
  373. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  374. }
  375. // Vertex shader
  376. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  377. };
  378. /** @hidden */
  379. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  380. if (BABYLON.Tools.IsWindowObjectExist()) {
  381. // DOM element ?
  382. if (fragment instanceof HTMLElement) {
  383. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  384. callback(fragmentCode);
  385. return;
  386. }
  387. }
  388. // Base64 encoded ?
  389. if (fragment.substr(0, 7) === "base64:") {
  390. var fragmentBinary = window.atob(fragment.substr(7));
  391. callback(fragmentBinary);
  392. return;
  393. }
  394. // Is in local store ?
  395. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  396. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  397. return;
  398. }
  399. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  400. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  401. return;
  402. }
  403. var fragmentShaderUrl;
  404. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  405. fragmentShaderUrl = fragment;
  406. }
  407. else {
  408. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  409. }
  410. // Fragment shader
  411. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  412. };
  413. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  414. // Rebuild shaders source code
  415. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  416. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  417. vertexCode = prefix + vertexCode;
  418. fragmentCode = prefix + fragmentCode;
  419. // Number lines of shaders source code
  420. var i = 2;
  421. var regex = /\n/gm;
  422. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. i = 2;
  424. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  425. // Dump shaders name and formatted source code
  426. if (this.name.vertexElement) {
  427. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  428. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  429. }
  430. else if (this.name.vertex) {
  431. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  432. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  433. }
  434. else {
  435. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  436. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  437. }
  438. };
  439. ;
  440. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  441. var preparedSourceCode = this._processPrecision(sourceCode);
  442. if (this._engine.webGLVersion == 1) {
  443. callback(preparedSourceCode);
  444. return;
  445. }
  446. // Already converted
  447. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  448. callback(preparedSourceCode.replace("#version 300 es", ""));
  449. return;
  450. }
  451. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  452. // Remove extensions
  453. // #extension GL_OES_standard_derivatives : enable
  454. // #extension GL_EXT_shader_texture_lod : enable
  455. // #extension GL_EXT_frag_depth : enable
  456. // #extension GL_EXT_draw_buffers : require
  457. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  458. var result = preparedSourceCode.replace(regex, "");
  459. // Migrate to GLSL v300
  460. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  461. result = result.replace(/attribute[ \t]/g, "in ");
  462. result = result.replace(/[ \t]attribute/g, " in");
  463. if (isFragment) {
  464. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  465. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  466. result = result.replace(/texture2D\s*\(/g, "texture(");
  467. result = result.replace(/textureCube\s*\(/g, "texture(");
  468. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  469. result = result.replace(/gl_FragColor/g, "glFragColor");
  470. result = result.replace(/gl_FragData/g, "glFragData");
  471. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  472. }
  473. callback(result);
  474. };
  475. Effect.prototype._processIncludes = function (sourceCode, callback) {
  476. var _this = this;
  477. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  478. var match = regex.exec(sourceCode);
  479. var returnValue = new String(sourceCode);
  480. while (match != null) {
  481. var includeFile = match[1];
  482. // Uniform declaration
  483. if (includeFile.indexOf("__decl__") !== -1) {
  484. includeFile = includeFile.replace(/__decl__/, "");
  485. if (this._engine.supportsUniformBuffers) {
  486. includeFile = includeFile.replace(/Vertex/, "Ubo");
  487. includeFile = includeFile.replace(/Fragment/, "Ubo");
  488. }
  489. includeFile = includeFile + "Declaration";
  490. }
  491. if (Effect.IncludesShadersStore[includeFile]) {
  492. // Substitution
  493. var includeContent = Effect.IncludesShadersStore[includeFile];
  494. if (match[2]) {
  495. var splits = match[3].split(",");
  496. for (var index = 0; index < splits.length; index += 2) {
  497. var source = new RegExp(splits[index], "g");
  498. var dest = splits[index + 1];
  499. includeContent = includeContent.replace(source, dest);
  500. }
  501. }
  502. if (match[4]) {
  503. var indexString = match[5];
  504. if (indexString.indexOf("..") !== -1) {
  505. var indexSplits = indexString.split("..");
  506. var minIndex = parseInt(indexSplits[0]);
  507. var maxIndex = parseInt(indexSplits[1]);
  508. var sourceIncludeContent = includeContent.slice(0);
  509. includeContent = "";
  510. if (isNaN(maxIndex)) {
  511. maxIndex = this._indexParameters[indexSplits[1]];
  512. }
  513. for (var i = minIndex; i < maxIndex; i++) {
  514. if (!this._engine.supportsUniformBuffers) {
  515. // Ubo replacement
  516. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  517. return p1 + "{X}";
  518. });
  519. }
  520. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  521. }
  522. }
  523. else {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent = includeContent.replace(/\{X\}/g, indexString);
  531. }
  532. }
  533. // Replace
  534. returnValue = returnValue.replace(match[0], includeContent);
  535. }
  536. else {
  537. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  538. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  539. Effect.IncludesShadersStore[includeFile] = fileContent;
  540. _this._processIncludes(returnValue, callback);
  541. });
  542. return;
  543. }
  544. match = regex.exec(sourceCode);
  545. }
  546. callback(returnValue);
  547. };
  548. Effect.prototype._processPrecision = function (source) {
  549. if (source.indexOf("precision highp float") === -1) {
  550. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  551. source = "precision mediump float;\n" + source;
  552. }
  553. else {
  554. source = "precision highp float;\n" + source;
  555. }
  556. }
  557. else {
  558. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  559. source = source.replace("precision highp float", "precision mediump float");
  560. }
  561. }
  562. return source;
  563. };
  564. /**
  565. * Recompiles the webGL program
  566. * @param vertexSourceCode The source code for the vertex shader.
  567. * @param fragmentSourceCode The source code for the fragment shader.
  568. * @param onCompiled Callback called when completed.
  569. * @param onError Callback called on error.
  570. */
  571. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  572. var _this = this;
  573. this._isReady = false;
  574. this._vertexSourceCodeOverride = vertexSourceCode;
  575. this._fragmentSourceCodeOverride = fragmentSourceCode;
  576. this.onError = function (effect, error) {
  577. if (onError) {
  578. onError(error);
  579. }
  580. };
  581. this.onCompiled = function () {
  582. var scenes = _this.getEngine().scenes;
  583. for (var i = 0; i < scenes.length; i++) {
  584. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  585. }
  586. if (onCompiled) {
  587. onCompiled(_this._program);
  588. }
  589. };
  590. this._fallbacks = null;
  591. this._prepareEffect();
  592. };
  593. /**
  594. * Gets the uniform locations of the the specified variable names
  595. * @param names THe names of the variables to lookup.
  596. * @returns Array of locations in the same order as variable names.
  597. */
  598. Effect.prototype.getSpecificUniformLocations = function (names) {
  599. var engine = this._engine;
  600. return engine.getUniforms(this._program, names);
  601. };
  602. /**
  603. * Prepares the effect
  604. */
  605. Effect.prototype._prepareEffect = function () {
  606. var attributesNames = this._attributesNames;
  607. var defines = this.defines;
  608. var fallbacks = this._fallbacks;
  609. this._valueCache = {};
  610. var previousProgram = this._program;
  611. try {
  612. var engine = this._engine;
  613. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  614. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  615. }
  616. else {
  617. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  618. }
  619. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  620. if (engine.supportsUniformBuffers) {
  621. for (var name in this._uniformBuffersNames) {
  622. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  623. }
  624. }
  625. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  626. this._attributes = engine.getAttributes(this._program, attributesNames);
  627. var index;
  628. for (index = 0; index < this._samplers.length; index++) {
  629. var sampler = this.getUniform(this._samplers[index]);
  630. if (sampler == null) {
  631. this._samplers.splice(index, 1);
  632. index--;
  633. }
  634. }
  635. engine.bindSamplers(this);
  636. this._compilationError = "";
  637. this._isReady = true;
  638. if (this.onCompiled) {
  639. this.onCompiled(this);
  640. }
  641. this.onCompileObservable.notifyObservers(this);
  642. this.onCompileObservable.clear();
  643. // Unbind mesh reference in fallbacks
  644. if (this._fallbacks) {
  645. this._fallbacks.unBindMesh();
  646. }
  647. if (previousProgram) {
  648. this.getEngine()._deleteProgram(previousProgram);
  649. }
  650. }
  651. catch (e) {
  652. this._compilationError = e.message;
  653. // Let's go through fallbacks then
  654. BABYLON.Tools.Error("Unable to compile effect:");
  655. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  656. return " " + uniform;
  657. }));
  658. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  659. return " " + attribute;
  660. }));
  661. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  662. BABYLON.Tools.Error("Error: " + this._compilationError);
  663. if (previousProgram) {
  664. this._program = previousProgram;
  665. this._isReady = true;
  666. if (this.onError) {
  667. this.onError(this, this._compilationError);
  668. }
  669. this.onErrorObservable.notifyObservers(this);
  670. }
  671. if (fallbacks && fallbacks.isMoreFallbacks) {
  672. BABYLON.Tools.Error("Trying next fallback.");
  673. this.defines = fallbacks.reduce(this.defines, this);
  674. this._prepareEffect();
  675. }
  676. else { // Sorry we did everything we can
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. this.onErrorObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. }
  687. }
  688. };
  689. Object.defineProperty(Effect.prototype, "isSupported", {
  690. /**
  691. * Checks if the effect is supported. (Must be called after compilation)
  692. */
  693. get: function () {
  694. return this._compilationError === "";
  695. },
  696. enumerable: true,
  697. configurable: true
  698. });
  699. /**
  700. * Binds a texture to the engine to be used as output of the shader.
  701. * @param channel Name of the output variable.
  702. * @param texture Texture to bind.
  703. */
  704. Effect.prototype._bindTexture = function (channel, texture) {
  705. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  706. };
  707. /**
  708. * Sets a texture on the engine to be used in the shader.
  709. * @param channel Name of the sampler variable.
  710. * @param texture Texture to set.
  711. */
  712. Effect.prototype.setTexture = function (channel, texture) {
  713. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  714. };
  715. /**
  716. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  717. * @param channel Name of the sampler variable.
  718. * @param texture Texture to set.
  719. */
  720. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  721. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  722. };
  723. /**
  724. * Sets an array of textures on the engine to be used in the shader.
  725. * @param channel Name of the variable.
  726. * @param textures Textures to set.
  727. */
  728. Effect.prototype.setTextureArray = function (channel, textures) {
  729. if (this._samplers.indexOf(channel + "Ex") === -1) {
  730. var initialPos = this._samplers.indexOf(channel);
  731. for (var index = 1; index < textures.length; index++) {
  732. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  733. }
  734. }
  735. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  736. };
  737. /**
  738. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  739. * @param channel Name of the sampler variable.
  740. * @param postProcess Post process to get the input texture from.
  741. */
  742. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  743. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  744. };
  745. /**
  746. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  747. * 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)
  748. * @param channel Name of the sampler variable.
  749. * @param postProcess Post process to get the output texture from.
  750. */
  751. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  752. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  753. };
  754. /** @hidden */
  755. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  756. var cache = this._valueCache[uniformName];
  757. var flag = matrix.updateFlag;
  758. if (cache !== undefined && cache === flag) {
  759. return false;
  760. }
  761. this._valueCache[uniformName] = flag;
  762. return true;
  763. };
  764. /** @hidden */
  765. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  766. var cache = this._valueCache[uniformName];
  767. if (!cache) {
  768. cache = [x, y];
  769. this._valueCache[uniformName] = cache;
  770. return true;
  771. }
  772. var changed = false;
  773. if (cache[0] !== x) {
  774. cache[0] = x;
  775. changed = true;
  776. }
  777. if (cache[1] !== y) {
  778. cache[1] = y;
  779. changed = true;
  780. }
  781. return changed;
  782. };
  783. /** @hidden */
  784. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  785. var cache = this._valueCache[uniformName];
  786. if (!cache) {
  787. cache = [x, y, z];
  788. this._valueCache[uniformName] = cache;
  789. return true;
  790. }
  791. var changed = false;
  792. if (cache[0] !== x) {
  793. cache[0] = x;
  794. changed = true;
  795. }
  796. if (cache[1] !== y) {
  797. cache[1] = y;
  798. changed = true;
  799. }
  800. if (cache[2] !== z) {
  801. cache[2] = z;
  802. changed = true;
  803. }
  804. return changed;
  805. };
  806. /** @hidden */
  807. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  808. var cache = this._valueCache[uniformName];
  809. if (!cache) {
  810. cache = [x, y, z, w];
  811. this._valueCache[uniformName] = cache;
  812. return true;
  813. }
  814. var changed = false;
  815. if (cache[0] !== x) {
  816. cache[0] = x;
  817. changed = true;
  818. }
  819. if (cache[1] !== y) {
  820. cache[1] = y;
  821. changed = true;
  822. }
  823. if (cache[2] !== z) {
  824. cache[2] = z;
  825. changed = true;
  826. }
  827. if (cache[3] !== w) {
  828. cache[3] = w;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /**
  834. * Binds a buffer to a uniform.
  835. * @param buffer Buffer to bind.
  836. * @param name Name of the uniform variable to bind to.
  837. */
  838. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  839. var bufferName = this._uniformBuffersNames[name];
  840. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  841. return;
  842. }
  843. Effect._baseCache[bufferName] = buffer;
  844. this._engine.bindUniformBufferBase(buffer, bufferName);
  845. };
  846. /**
  847. * Binds block to a uniform.
  848. * @param blockName Name of the block to bind.
  849. * @param index Index to bind.
  850. */
  851. Effect.prototype.bindUniformBlock = function (blockName, index) {
  852. this._engine.bindUniformBlock(this._program, blockName, index);
  853. };
  854. /**
  855. * Sets an interger value on a uniform variable.
  856. * @param uniformName Name of the variable.
  857. * @param value Value to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setInt = function (uniformName, value) {
  861. var cache = this._valueCache[uniformName];
  862. if (cache !== undefined && cache === value)
  863. return this;
  864. this._valueCache[uniformName] = value;
  865. this._engine.setInt(this.getUniform(uniformName), value);
  866. return this;
  867. };
  868. /**
  869. * Sets an int array on a uniform variable.
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * 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)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray2 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray2(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * 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)
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray3 = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray3(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * 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)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray4 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray4(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * Sets an float array on a uniform variable.
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * 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)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * 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)
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * 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)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * Sets an array on a uniform variable.
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * 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)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray2 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray2(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * 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)
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray3 = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray3(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * 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)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray4 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray4(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * Sets matrices on a uniform variable.
  1002. * @param uniformName Name of the variable.
  1003. * @param matrices matrices to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1007. if (!matrices) {
  1008. return this;
  1009. }
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets matrix on a uniform variable.
  1016. * @param uniformName Name of the variable.
  1017. * @param matrix matrix to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1021. if (this._cacheMatrix(uniformName, matrix)) {
  1022. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1023. }
  1024. return this;
  1025. };
  1026. /**
  1027. * 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)
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1039. * @param uniformName Name of the variable.
  1040. * @param matrix matrix to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1044. this._valueCache[uniformName] = null;
  1045. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1046. return this;
  1047. };
  1048. /**
  1049. * Sets a float on a uniform variable.
  1050. * @param uniformName Name of the variable.
  1051. * @param value value to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setFloat = function (uniformName, value) {
  1055. var cache = this._valueCache[uniformName];
  1056. if (cache !== undefined && cache === value)
  1057. return this;
  1058. this._valueCache[uniformName] = value;
  1059. this._engine.setFloat(this.getUniform(uniformName), value);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a boolean on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param bool value to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setBool = function (uniformName, bool) {
  1069. var cache = this._valueCache[uniformName];
  1070. if (cache !== undefined && cache === bool)
  1071. return this;
  1072. this._valueCache[uniformName] = bool;
  1073. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a Vector2 on a uniform variable.
  1078. * @param uniformName Name of the variable.
  1079. * @param vector2 vector2 to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1083. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1084. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1085. }
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param x First float in float2.
  1092. * @param y Second float in float2.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1096. if (this._cacheFloat2(uniformName, x, y)) {
  1097. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1098. }
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector3 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector3 Value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1108. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1109. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float3.
  1117. * @param y Second float in float3.
  1118. * @param z Third float in float3.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1122. if (this._cacheFloat3(uniformName, x, y, z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a Vector4 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param vector4 Value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1134. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1135. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a float4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param x First float in float4.
  1143. * @param y Second float in float4.
  1144. * @param z Third float in float4.
  1145. * @param w Fourth float in float4.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1149. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1150. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Color3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param color3 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setColor3 = function (uniformName, color3) {
  1161. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1162. this._engine.setColor3(this.getUniform(uniformName), color3);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @param alpha Alpha value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1174. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1175. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color4 on a uniform variable
  1181. * @param uniformName defines the name of the variable
  1182. * @param color4 defines the value to be set
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1186. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1187. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Resets the cache of effects.
  1193. */
  1194. Effect.ResetCache = function () {
  1195. Effect._baseCache = {};
  1196. };
  1197. Effect._uniqueIdSeed = 0;
  1198. Effect._baseCache = {};
  1199. /**
  1200. * Store of each shader (The can be looked up using effect.key)
  1201. */
  1202. Effect.ShadersStore = {};
  1203. /**
  1204. * Store of each included file for a shader (The can be looked up using effect.key)
  1205. */
  1206. Effect.IncludesShadersStore = {};
  1207. return Effect;
  1208. }());
  1209. BABYLON.Effect = Effect;
  1210. })(BABYLON || (BABYLON = {}));
  1211. //# sourceMappingURL=babylon.effect.js.map
  1212. //# sourceMappingURL=babylon.types.js.map
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. var BABYLON;
  1262. (function (BABYLON) {
  1263. var PointerEventTypes = /** @class */ (function () {
  1264. function PointerEventTypes() {
  1265. }
  1266. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1267. get: function () {
  1268. return PointerEventTypes._POINTERDOWN;
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1274. get: function () {
  1275. return PointerEventTypes._POINTERUP;
  1276. },
  1277. enumerable: true,
  1278. configurable: true
  1279. });
  1280. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1281. get: function () {
  1282. return PointerEventTypes._POINTERMOVE;
  1283. },
  1284. enumerable: true,
  1285. configurable: true
  1286. });
  1287. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1288. get: function () {
  1289. return PointerEventTypes._POINTERWHEEL;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERPICK;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERTAP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERDOUBLETAP;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. PointerEventTypes._POINTERDOWN = 0x01;
  1316. PointerEventTypes._POINTERUP = 0x02;
  1317. PointerEventTypes._POINTERMOVE = 0x04;
  1318. PointerEventTypes._POINTERWHEEL = 0x08;
  1319. PointerEventTypes._POINTERPICK = 0x10;
  1320. PointerEventTypes._POINTERTAP = 0x20;
  1321. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1322. return PointerEventTypes;
  1323. }());
  1324. BABYLON.PointerEventTypes = PointerEventTypes;
  1325. var PointerInfoBase = /** @class */ (function () {
  1326. function PointerInfoBase(type, event) {
  1327. this.type = type;
  1328. this.event = event;
  1329. }
  1330. return PointerInfoBase;
  1331. }());
  1332. BABYLON.PointerInfoBase = PointerInfoBase;
  1333. /**
  1334. * This class is used to store pointer related info for the onPrePointerObservable event.
  1335. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1336. */
  1337. var PointerInfoPre = /** @class */ (function (_super) {
  1338. __extends(PointerInfoPre, _super);
  1339. function PointerInfoPre(type, event, localX, localY) {
  1340. var _this = _super.call(this, type, event) || this;
  1341. _this.skipOnPointerObservable = false;
  1342. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1343. return _this;
  1344. }
  1345. return PointerInfoPre;
  1346. }(PointerInfoBase));
  1347. BABYLON.PointerInfoPre = PointerInfoPre;
  1348. /**
  1349. * This type contains all the data related to a pointer event in Babylon.js.
  1350. * 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.
  1351. */
  1352. var PointerInfo = /** @class */ (function (_super) {
  1353. __extends(PointerInfo, _super);
  1354. function PointerInfo(type, event, pickInfo) {
  1355. var _this = _super.call(this, type, event) || this;
  1356. _this.pickInfo = pickInfo;
  1357. return _this;
  1358. }
  1359. return PointerInfo;
  1360. }(PointerInfoBase));
  1361. BABYLON.PointerInfo = PointerInfo;
  1362. })(BABYLON || (BABYLON = {}));
  1363. //# sourceMappingURL=babylon.pointerEvents.js.map
  1364. var BABYLON;
  1365. (function (BABYLON) {
  1366. BABYLON.ToGammaSpace = 1 / 2.2;
  1367. BABYLON.ToLinearSpace = 2.2;
  1368. BABYLON.Epsilon = 0.001;
  1369. /**
  1370. * Class used to hold a RBG color
  1371. */
  1372. var Color3 = /** @class */ (function () {
  1373. /**
  1374. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1375. * @param r defines the red component (between 0 and 1, default is 0)
  1376. * @param g defines the green component (between 0 and 1, default is 0)
  1377. * @param b defines the blue component (between 0 and 1, default is 0)
  1378. */
  1379. function Color3(
  1380. /**
  1381. * Defines the red component (between 0 and 1, default is 0)
  1382. */
  1383. r,
  1384. /**
  1385. * Defines the green component (between 0 and 1, default is 0)
  1386. */
  1387. g,
  1388. /**
  1389. * Defines the blue component (between 0 and 1, default is 0)
  1390. */
  1391. b) {
  1392. if (r === void 0) { r = 0; }
  1393. if (g === void 0) { g = 0; }
  1394. if (b === void 0) { b = 0; }
  1395. this.r = r;
  1396. this.g = g;
  1397. this.b = b;
  1398. }
  1399. /**
  1400. * Creates a string with the Color3 current values
  1401. * @returns the string representation of the Color3 object
  1402. */
  1403. Color3.prototype.toString = function () {
  1404. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1405. };
  1406. /**
  1407. * Returns the string "Color3"
  1408. * @returns "Color3"
  1409. */
  1410. Color3.prototype.getClassName = function () {
  1411. return "Color3";
  1412. };
  1413. /**
  1414. * Compute the Color3 hash code
  1415. * @returns an unique number that can be used to hash Color3 objects
  1416. */
  1417. Color3.prototype.getHashCode = function () {
  1418. var hash = this.r || 0;
  1419. hash = (hash * 397) ^ (this.g || 0);
  1420. hash = (hash * 397) ^ (this.b || 0);
  1421. return hash;
  1422. };
  1423. // Operators
  1424. /**
  1425. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1426. * @param array defines the array where to store the r,g,b components
  1427. * @param index defines an optional index in the target array to define where to start storing values
  1428. * @returns the current Color3 object
  1429. */
  1430. Color3.prototype.toArray = function (array, index) {
  1431. if (index === undefined) {
  1432. index = 0;
  1433. }
  1434. array[index] = this.r;
  1435. array[index + 1] = this.g;
  1436. array[index + 2] = this.b;
  1437. return this;
  1438. };
  1439. /**
  1440. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1441. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1442. * @returns a new {BABYLON.Color4} object
  1443. */
  1444. Color3.prototype.toColor4 = function (alpha) {
  1445. if (alpha === void 0) { alpha = 1; }
  1446. return new Color4(this.r, this.g, this.b, alpha);
  1447. };
  1448. /**
  1449. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1450. * @returns the new array
  1451. */
  1452. Color3.prototype.asArray = function () {
  1453. var result = new Array();
  1454. this.toArray(result, 0);
  1455. return result;
  1456. };
  1457. /**
  1458. * Returns the luminance value
  1459. * @returns a float value
  1460. */
  1461. Color3.prototype.toLuminance = function () {
  1462. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1463. };
  1464. /**
  1465. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1466. * @param otherColor defines the second operand
  1467. * @returns the new Color3 object
  1468. */
  1469. Color3.prototype.multiply = function (otherColor) {
  1470. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1471. };
  1472. /**
  1473. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1474. * @param otherColor defines the second operand
  1475. * @param result defines the Color3 object where to store the result
  1476. * @returns the current Color3
  1477. */
  1478. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1479. result.r = this.r * otherColor.r;
  1480. result.g = this.g * otherColor.g;
  1481. result.b = this.b * otherColor.b;
  1482. return this;
  1483. };
  1484. /**
  1485. * Determines equality between Color3 objects
  1486. * @param otherColor defines the second operand
  1487. * @returns true if the rgb values are equal to the given ones
  1488. */
  1489. Color3.prototype.equals = function (otherColor) {
  1490. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1491. };
  1492. /**
  1493. * Determines equality between the current Color3 object and a set of r,b,g values
  1494. * @param r defines the red component to check
  1495. * @param g defines the green component to check
  1496. * @param b defines the blue component to check
  1497. * @returns true if the rgb values are equal to the given ones
  1498. */
  1499. Color3.prototype.equalsFloats = function (r, g, b) {
  1500. return this.r === r && this.g === g && this.b === b;
  1501. };
  1502. /**
  1503. * Multiplies in place each rgb value by scale
  1504. * @param scale defines the scaling factor
  1505. * @returns the updated Color3
  1506. */
  1507. Color3.prototype.scale = function (scale) {
  1508. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1509. };
  1510. /**
  1511. * Multiplies the rgb values by scale and stores the result into "result"
  1512. * @param scale defines the scaling factor
  1513. * @param result defines the Color3 object where to store the result
  1514. * @returns the unmodified current Color3
  1515. */
  1516. Color3.prototype.scaleToRef = function (scale, result) {
  1517. result.r = this.r * scale;
  1518. result.g = this.g * scale;
  1519. result.b = this.b * scale;
  1520. return this;
  1521. };
  1522. /**
  1523. * Scale the current Color3 values by a factor and add the result to a given Color3
  1524. * @param scale defines the scale factor
  1525. * @param result defines color to store the result into
  1526. * @returns the unmodified current Color3
  1527. */
  1528. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1529. result.r += this.r * scale;
  1530. result.g += this.g * scale;
  1531. result.b += this.b * scale;
  1532. return this;
  1533. };
  1534. /**
  1535. * Clamps the rgb values by the min and max values and stores the result into "result"
  1536. * @param min defines minimum clamping value (default is 0)
  1537. * @param max defines maximum clamping value (default is 1)
  1538. * @param result defines color to store the result into
  1539. * @returns the original Color3
  1540. */
  1541. Color3.prototype.clampToRef = function (min, max, result) {
  1542. if (min === void 0) { min = 0; }
  1543. if (max === void 0) { max = 1; }
  1544. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1545. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1546. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1547. return this;
  1548. };
  1549. /**
  1550. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1551. * @param otherColor defines the second operand
  1552. * @returns the new Color3
  1553. */
  1554. Color3.prototype.add = function (otherColor) {
  1555. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1556. };
  1557. /**
  1558. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1559. * @param otherColor defines the second operand
  1560. * @param result defines Color3 object to store the result into
  1561. * @returns the unmodified current Color3
  1562. */
  1563. Color3.prototype.addToRef = function (otherColor, result) {
  1564. result.r = this.r + otherColor.r;
  1565. result.g = this.g + otherColor.g;
  1566. result.b = this.b + otherColor.b;
  1567. return this;
  1568. };
  1569. /**
  1570. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1571. * @param otherColor defines the second operand
  1572. * @returns the new Color3
  1573. */
  1574. Color3.prototype.subtract = function (otherColor) {
  1575. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1576. };
  1577. /**
  1578. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1579. * @param otherColor defines the second operand
  1580. * @param result defines Color3 object to store the result into
  1581. * @returns the unmodified current Color3
  1582. */
  1583. Color3.prototype.subtractToRef = function (otherColor, result) {
  1584. result.r = this.r - otherColor.r;
  1585. result.g = this.g - otherColor.g;
  1586. result.b = this.b - otherColor.b;
  1587. return this;
  1588. };
  1589. /**
  1590. * Copy the current object
  1591. * @returns a new Color3 copied the current one
  1592. */
  1593. Color3.prototype.clone = function () {
  1594. return new Color3(this.r, this.g, this.b);
  1595. };
  1596. /**
  1597. * Copies the rgb values from the source in the current Color3
  1598. * @param source defines the source Color3 object
  1599. * @returns the updated Color3 object
  1600. */
  1601. Color3.prototype.copyFrom = function (source) {
  1602. this.r = source.r;
  1603. this.g = source.g;
  1604. this.b = source.b;
  1605. return this;
  1606. };
  1607. /**
  1608. * Updates the Color3 rgb values from the given floats
  1609. * @param r defines the red component to read from
  1610. * @param g defines the green component to read from
  1611. * @param b defines the blue component to read from
  1612. * @returns the current Color3 object
  1613. */
  1614. Color3.prototype.copyFromFloats = function (r, g, b) {
  1615. this.r = r;
  1616. this.g = g;
  1617. this.b = b;
  1618. return this;
  1619. };
  1620. /**
  1621. * Updates the Color3 rgb values from the given floats
  1622. * @param r defines the red component to read from
  1623. * @param g defines the green component to read from
  1624. * @param b defines the blue component to read from
  1625. * @returns the current Color3 object
  1626. */
  1627. Color3.prototype.set = function (r, g, b) {
  1628. return this.copyFromFloats(r, g, b);
  1629. };
  1630. /**
  1631. * Compute the Color3 hexadecimal code as a string
  1632. * @returns a string containing the hexadecimal representation of the Color3 object
  1633. */
  1634. Color3.prototype.toHexString = function () {
  1635. var intR = (this.r * 255) | 0;
  1636. var intG = (this.g * 255) | 0;
  1637. var intB = (this.b * 255) | 0;
  1638. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1639. };
  1640. /**
  1641. * Computes a new Color3 converted from the current one to linear space
  1642. * @returns a new Color3 object
  1643. */
  1644. Color3.prototype.toLinearSpace = function () {
  1645. var convertedColor = new Color3();
  1646. this.toLinearSpaceToRef(convertedColor);
  1647. return convertedColor;
  1648. };
  1649. /**
  1650. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1651. * @param convertedColor defines the Color3 object where to store the linear space version
  1652. * @returns the unmodified Color3
  1653. */
  1654. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1655. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1656. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1657. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1658. return this;
  1659. };
  1660. /**
  1661. * Computes a new Color3 converted from the current one to gamma space
  1662. * @returns a new Color3 object
  1663. */
  1664. Color3.prototype.toGammaSpace = function () {
  1665. var convertedColor = new Color3();
  1666. this.toGammaSpaceToRef(convertedColor);
  1667. return convertedColor;
  1668. };
  1669. /**
  1670. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1671. * @param convertedColor defines the Color3 object where to store the gamma space version
  1672. * @returns the unmodified Color3
  1673. */
  1674. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1675. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1676. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1677. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1678. return this;
  1679. };
  1680. // Statics
  1681. /**
  1682. * Creates a new Color3 from the string containing valid hexadecimal values
  1683. * @param hex defines a string containing valid hexadecimal values
  1684. * @returns a new Color3 object
  1685. */
  1686. Color3.FromHexString = function (hex) {
  1687. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1688. return new Color3(0, 0, 0);
  1689. }
  1690. var r = parseInt(hex.substring(1, 3), 16);
  1691. var g = parseInt(hex.substring(3, 5), 16);
  1692. var b = parseInt(hex.substring(5, 7), 16);
  1693. return Color3.FromInts(r, g, b);
  1694. };
  1695. /**
  1696. * Creates a new Vector3 from the starting index of the given array
  1697. * @param array defines the source array
  1698. * @param offset defines an offset in the source array
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.FromArray = function (array, offset) {
  1702. if (offset === void 0) { offset = 0; }
  1703. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1704. };
  1705. /**
  1706. * Creates a new Color3 from integer values (< 256)
  1707. * @param r defines the red component to read from (value between 0 and 255)
  1708. * @param g defines the green component to read from (value between 0 and 255)
  1709. * @param b defines the blue component to read from (value between 0 and 255)
  1710. * @returns a new Color3 object
  1711. */
  1712. Color3.FromInts = function (r, g, b) {
  1713. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1714. };
  1715. /**
  1716. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1717. * @param start defines the start Color3 value
  1718. * @param end defines the end Color3 value
  1719. * @param amount defines the gradient value between start and end
  1720. * @returns a new Color3 object
  1721. */
  1722. Color3.Lerp = function (start, end, amount) {
  1723. var r = start.r + ((end.r - start.r) * amount);
  1724. var g = start.g + ((end.g - start.g) * amount);
  1725. var b = start.b + ((end.b - start.b) * amount);
  1726. return new Color3(r, g, b);
  1727. };
  1728. /**
  1729. * Returns a Color3 value containing a red color
  1730. * @returns a new Color3 object
  1731. */
  1732. Color3.Red = function () { return new Color3(1, 0, 0); };
  1733. /**
  1734. * Returns a Color3 value containing a green color
  1735. * @returns a new Color3 object
  1736. */
  1737. Color3.Green = function () { return new Color3(0, 1, 0); };
  1738. /**
  1739. * Returns a Color3 value containing a blue color
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1743. /**
  1744. * Returns a Color3 value containing a black color
  1745. * @returns a new Color3 object
  1746. */
  1747. Color3.Black = function () { return new Color3(0, 0, 0); };
  1748. /**
  1749. * Returns a Color3 value containing a white color
  1750. * @returns a new Color3 object
  1751. */
  1752. Color3.White = function () { return new Color3(1, 1, 1); };
  1753. /**
  1754. * Returns a Color3 value containing a purple color
  1755. * @returns a new Color3 object
  1756. */
  1757. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1758. /**
  1759. * Returns a Color3 value containing a magenta color
  1760. * @returns a new Color3 object
  1761. */
  1762. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1763. /**
  1764. * Returns a Color3 value containing a yellow color
  1765. * @returns a new Color3 object
  1766. */
  1767. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1768. /**
  1769. * Returns a Color3 value containing a gray color
  1770. * @returns a new Color3 object
  1771. */
  1772. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1773. /**
  1774. * Returns a Color3 value containing a teal color
  1775. * @returns a new Color3 object
  1776. */
  1777. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1778. /**
  1779. * Returns a Color3 value containing a random color
  1780. * @returns a new Color3 object
  1781. */
  1782. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1783. return Color3;
  1784. }());
  1785. BABYLON.Color3 = Color3;
  1786. /**
  1787. * Class used to hold a RBGA color
  1788. */
  1789. var Color4 = /** @class */ (function () {
  1790. /**
  1791. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1792. * @param r defines the red component (between 0 and 1, default is 0)
  1793. * @param g defines the green component (between 0 and 1, default is 0)
  1794. * @param b defines the blue component (between 0 and 1, default is 0)
  1795. * @param a defines the alpha component (between 0 and 1, default is 1)
  1796. */
  1797. function Color4(
  1798. /**
  1799. * Defines the red component (between 0 and 1, default is 0)
  1800. */
  1801. r,
  1802. /**
  1803. * Defines the green component (between 0 and 1, default is 0)
  1804. */
  1805. g,
  1806. /**
  1807. * Defines the blue component (between 0 and 1, default is 0)
  1808. */
  1809. b,
  1810. /**
  1811. * Defines the alpha component (between 0 and 1, default is 1)
  1812. */
  1813. a) {
  1814. if (r === void 0) { r = 0; }
  1815. if (g === void 0) { g = 0; }
  1816. if (b === void 0) { b = 0; }
  1817. if (a === void 0) { a = 1; }
  1818. this.r = r;
  1819. this.g = g;
  1820. this.b = b;
  1821. this.a = a;
  1822. }
  1823. // Operators
  1824. /**
  1825. * Adds in place the given Color4 values to the current Color4 object
  1826. * @param right defines the second operand
  1827. * @returns the current updated Color4 object
  1828. */
  1829. Color4.prototype.addInPlace = function (right) {
  1830. this.r += right.r;
  1831. this.g += right.g;
  1832. this.b += right.b;
  1833. this.a += right.a;
  1834. return this;
  1835. };
  1836. /**
  1837. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1838. * @returns the new array
  1839. */
  1840. Color4.prototype.asArray = function () {
  1841. var result = new Array();
  1842. this.toArray(result, 0);
  1843. return result;
  1844. };
  1845. /**
  1846. * Stores from the starting index in the given array the Color4 successive values
  1847. * @param array defines the array where to store the r,g,b components
  1848. * @param index defines an optional index in the target array to define where to start storing values
  1849. * @returns the current Color4 object
  1850. */
  1851. Color4.prototype.toArray = function (array, index) {
  1852. if (index === undefined) {
  1853. index = 0;
  1854. }
  1855. array[index] = this.r;
  1856. array[index + 1] = this.g;
  1857. array[index + 2] = this.b;
  1858. array[index + 3] = this.a;
  1859. return this;
  1860. };
  1861. /**
  1862. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1863. * @param right defines the second operand
  1864. * @returns a new Color4 object
  1865. */
  1866. Color4.prototype.add = function (right) {
  1867. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1868. };
  1869. /**
  1870. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1871. * @param right defines the second operand
  1872. * @returns a new Color4 object
  1873. */
  1874. Color4.prototype.subtract = function (right) {
  1875. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1876. };
  1877. /**
  1878. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1879. * @param right defines the second operand
  1880. * @param result defines the Color4 object where to store the result
  1881. * @returns the current Color4 object
  1882. */
  1883. Color4.prototype.subtractToRef = function (right, result) {
  1884. result.r = this.r - right.r;
  1885. result.g = this.g - right.g;
  1886. result.b = this.b - right.b;
  1887. result.a = this.a - right.a;
  1888. return this;
  1889. };
  1890. /**
  1891. * Creates a new Color4 with the current Color4 values multiplied by scale
  1892. * @param scale defines the scaling factor to apply
  1893. * @returns a new Color4 object
  1894. */
  1895. Color4.prototype.scale = function (scale) {
  1896. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1897. };
  1898. /**
  1899. * Multiplies the current Color4 values by scale and stores the result in "result"
  1900. * @param scale defines the scaling factor to apply
  1901. * @param result defines the Color4 object where to store the result
  1902. * @returns the current unmodified Color4
  1903. */
  1904. Color4.prototype.scaleToRef = function (scale, result) {
  1905. result.r = this.r * scale;
  1906. result.g = this.g * scale;
  1907. result.b = this.b * scale;
  1908. result.a = this.a * scale;
  1909. return this;
  1910. };
  1911. /**
  1912. * Scale the current Color4 values by a factor and add the result to a given Color4
  1913. * @param scale defines the scale factor
  1914. * @param result defines the Color4 object where to store the result
  1915. * @returns the unmodified current Color4
  1916. */
  1917. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1918. result.r += this.r * scale;
  1919. result.g += this.g * scale;
  1920. result.b += this.b * scale;
  1921. result.a += this.a * scale;
  1922. return this;
  1923. };
  1924. /**
  1925. * Clamps the rgb values by the min and max values and stores the result into "result"
  1926. * @param min defines minimum clamping value (default is 0)
  1927. * @param max defines maximum clamping value (default is 1)
  1928. * @param result defines color to store the result into.
  1929. * @returns the cuurent Color4
  1930. */
  1931. Color4.prototype.clampToRef = function (min, max, result) {
  1932. if (min === void 0) { min = 0; }
  1933. if (max === void 0) { max = 1; }
  1934. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1935. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1936. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1937. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1938. return this;
  1939. };
  1940. /**
  1941. * Multipy an Color4 value by another and return a new Color4 object
  1942. * @param color defines the Color4 value to multiply by
  1943. * @returns a new Color4 object
  1944. */
  1945. Color4.prototype.multiply = function (color) {
  1946. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1947. };
  1948. /**
  1949. * Multipy a Color4 value by another and push the result in a reference value
  1950. * @param color defines the Color4 value to multiply by
  1951. * @param result defines the Color4 to fill the result in
  1952. * @returns the result Color4
  1953. */
  1954. Color4.prototype.multiplyToRef = function (color, result) {
  1955. result.r = this.r * color.r;
  1956. result.g = this.g * color.g;
  1957. result.b = this.b * color.b;
  1958. result.a = this.a * color.a;
  1959. return result;
  1960. };
  1961. /**
  1962. * Creates a string with the Color4 current values
  1963. * @returns the string representation of the Color4 object
  1964. */
  1965. Color4.prototype.toString = function () {
  1966. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1967. };
  1968. /**
  1969. * Returns the string "Color4"
  1970. * @returns "Color4"
  1971. */
  1972. Color4.prototype.getClassName = function () {
  1973. return "Color4";
  1974. };
  1975. /**
  1976. * Compute the Color4 hash code
  1977. * @returns an unique number that can be used to hash Color4 objects
  1978. */
  1979. Color4.prototype.getHashCode = function () {
  1980. var hash = this.r || 0;
  1981. hash = (hash * 397) ^ (this.g || 0);
  1982. hash = (hash * 397) ^ (this.b || 0);
  1983. hash = (hash * 397) ^ (this.a || 0);
  1984. return hash;
  1985. };
  1986. /**
  1987. * Creates a new Color4 copied from the current one
  1988. * @returns a new Color4 object
  1989. */
  1990. Color4.prototype.clone = function () {
  1991. return new Color4(this.r, this.g, this.b, this.a);
  1992. };
  1993. /**
  1994. * Copies the given Color4 values into the current one
  1995. * @param source defines the source Color4 object
  1996. * @returns the current updated Color4 object
  1997. */
  1998. Color4.prototype.copyFrom = function (source) {
  1999. this.r = source.r;
  2000. this.g = source.g;
  2001. this.b = source.b;
  2002. this.a = source.a;
  2003. return this;
  2004. };
  2005. /**
  2006. * Copies the given float values into the current one
  2007. * @param r defines the red component to read from
  2008. * @param g defines the green component to read from
  2009. * @param b defines the blue component to read from
  2010. * @param a defines the alpha component to read from
  2011. * @returns the current updated Color4 object
  2012. */
  2013. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2014. this.r = r;
  2015. this.g = g;
  2016. this.b = b;
  2017. this.a = a;
  2018. return this;
  2019. };
  2020. /**
  2021. * Copies the given float values into the current one
  2022. * @param r defines the red component to read from
  2023. * @param g defines the green component to read from
  2024. * @param b defines the blue component to read from
  2025. * @param a defines the alpha component to read from
  2026. * @returns the current updated Color4 object
  2027. */
  2028. Color4.prototype.set = function (r, g, b, a) {
  2029. return this.copyFromFloats(r, g, b, a);
  2030. };
  2031. /**
  2032. * Compute the Color4 hexadecimal code as a string
  2033. * @returns a string containing the hexadecimal representation of the Color4 object
  2034. */
  2035. Color4.prototype.toHexString = function () {
  2036. var intR = (this.r * 255) | 0;
  2037. var intG = (this.g * 255) | 0;
  2038. var intB = (this.b * 255) | 0;
  2039. var intA = (this.a * 255) | 0;
  2040. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2041. };
  2042. /**
  2043. * Computes a new Color4 converted from the current one to linear space
  2044. * @returns a new Color4 object
  2045. */
  2046. Color4.prototype.toLinearSpace = function () {
  2047. var convertedColor = new Color4();
  2048. this.toLinearSpaceToRef(convertedColor);
  2049. return convertedColor;
  2050. };
  2051. /**
  2052. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2053. * @param convertedColor defines the Color4 object where to store the linear space version
  2054. * @returns the unmodified Color4
  2055. */
  2056. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2057. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2058. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2059. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2060. convertedColor.a = this.a;
  2061. return this;
  2062. };
  2063. /**
  2064. * Computes a new Color4 converted from the current one to gamma space
  2065. * @returns a new Color4 object
  2066. */
  2067. Color4.prototype.toGammaSpace = function () {
  2068. var convertedColor = new Color4();
  2069. this.toGammaSpaceToRef(convertedColor);
  2070. return convertedColor;
  2071. };
  2072. /**
  2073. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2074. * @param convertedColor defines the Color4 object where to store the gamma space version
  2075. * @returns the unmodified Color4
  2076. */
  2077. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2078. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2079. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2080. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2081. convertedColor.a = this.a;
  2082. return this;
  2083. };
  2084. // Statics
  2085. /**
  2086. * Creates a new Color4 from the string containing valid hexadecimal values
  2087. * @param hex defines a string containing valid hexadecimal values
  2088. * @returns a new Color4 object
  2089. */
  2090. Color4.FromHexString = function (hex) {
  2091. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2092. return new Color4(0.0, 0.0, 0.0, 0.0);
  2093. }
  2094. var r = parseInt(hex.substring(1, 3), 16);
  2095. var g = parseInt(hex.substring(3, 5), 16);
  2096. var b = parseInt(hex.substring(5, 7), 16);
  2097. var a = parseInt(hex.substring(7, 9), 16);
  2098. return Color4.FromInts(r, g, b, a);
  2099. };
  2100. /**
  2101. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2102. * @param left defines the start value
  2103. * @param right defines the end value
  2104. * @param amount defines the gradient factor
  2105. * @returns a new Color4 object
  2106. */
  2107. Color4.Lerp = function (left, right, amount) {
  2108. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2109. Color4.LerpToRef(left, right, amount, result);
  2110. return result;
  2111. };
  2112. /**
  2113. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2114. * @param left defines the start value
  2115. * @param right defines the end value
  2116. * @param amount defines the gradient factor
  2117. * @param result defines the Color4 object where to store data
  2118. */
  2119. Color4.LerpToRef = function (left, right, amount, result) {
  2120. result.r = left.r + (right.r - left.r) * amount;
  2121. result.g = left.g + (right.g - left.g) * amount;
  2122. result.b = left.b + (right.b - left.b) * amount;
  2123. result.a = left.a + (right.a - left.a) * amount;
  2124. };
  2125. /**
  2126. * Creates a new Color4 from the starting index element of the given array
  2127. * @param array defines the source array to read from
  2128. * @param offset defines the offset in the source array
  2129. * @returns a new Color4 object
  2130. */
  2131. Color4.FromArray = function (array, offset) {
  2132. if (offset === void 0) { offset = 0; }
  2133. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2134. };
  2135. /**
  2136. * Creates a new Color3 from integer values (< 256)
  2137. * @param r defines the red component to read from (value between 0 and 255)
  2138. * @param g defines the green component to read from (value between 0 and 255)
  2139. * @param b defines the blue component to read from (value between 0 and 255)
  2140. * @param a defines the alpha component to read from (value between 0 and 255)
  2141. * @returns a new Color3 object
  2142. */
  2143. Color4.FromInts = function (r, g, b, a) {
  2144. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2145. };
  2146. /**
  2147. * Check the content of a given array and convert it to an array containing RGBA data
  2148. * If the original array was already containing count * 4 values then it is returned directly
  2149. * @param colors defines the array to check
  2150. * @param count defines the number of RGBA data to expect
  2151. * @returns an array containing count * 4 values (RGBA)
  2152. */
  2153. Color4.CheckColors4 = function (colors, count) {
  2154. // Check if color3 was used
  2155. if (colors.length === count * 3) {
  2156. var colors4 = [];
  2157. for (var index = 0; index < colors.length; index += 3) {
  2158. var newIndex = (index / 3) * 4;
  2159. colors4[newIndex] = colors[index];
  2160. colors4[newIndex + 1] = colors[index + 1];
  2161. colors4[newIndex + 2] = colors[index + 2];
  2162. colors4[newIndex + 3] = 1.0;
  2163. }
  2164. return colors4;
  2165. }
  2166. return colors;
  2167. };
  2168. return Color4;
  2169. }());
  2170. BABYLON.Color4 = Color4;
  2171. /**
  2172. * Class representing a vector containing 2 coordinates
  2173. */
  2174. var Vector2 = /** @class */ (function () {
  2175. /**
  2176. * Creates a new Vector2 from the given x and y coordinates
  2177. * @param x defines the first coordinate
  2178. * @param y defines the second coordinate
  2179. */
  2180. function Vector2(
  2181. /** defines the first coordinate */
  2182. x,
  2183. /** defines the second coordinate */
  2184. y) {
  2185. this.x = x;
  2186. this.y = y;
  2187. }
  2188. /**
  2189. * Gets a string with the Vector2 coordinates
  2190. * @returns a string with the Vector2 coordinates
  2191. */
  2192. Vector2.prototype.toString = function () {
  2193. return "{X: " + this.x + " Y:" + this.y + "}";
  2194. };
  2195. /**
  2196. * Gets class name
  2197. * @returns the string "Vector2"
  2198. */
  2199. Vector2.prototype.getClassName = function () {
  2200. return "Vector2";
  2201. };
  2202. /**
  2203. * Gets current vector hash code
  2204. * @returns the Vector2 hash code as a number
  2205. */
  2206. Vector2.prototype.getHashCode = function () {
  2207. var hash = this.x || 0;
  2208. hash = (hash * 397) ^ (this.y || 0);
  2209. return hash;
  2210. };
  2211. // Operators
  2212. /**
  2213. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2214. * @param array defines the source array
  2215. * @param index defines the offset in source array
  2216. * @returns the current Vector2
  2217. */
  2218. Vector2.prototype.toArray = function (array, index) {
  2219. if (index === void 0) { index = 0; }
  2220. array[index] = this.x;
  2221. array[index + 1] = this.y;
  2222. return this;
  2223. };
  2224. /**
  2225. * Copy the current vector to an array
  2226. * @returns a new array with 2 elements: the Vector2 coordinates.
  2227. */
  2228. Vector2.prototype.asArray = function () {
  2229. var result = new Array();
  2230. this.toArray(result, 0);
  2231. return result;
  2232. };
  2233. /**
  2234. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2235. * @param source defines the source Vector2
  2236. * @returns the current updated Vector2
  2237. */
  2238. Vector2.prototype.copyFrom = function (source) {
  2239. this.x = source.x;
  2240. this.y = source.y;
  2241. return this;
  2242. };
  2243. /**
  2244. * Sets the Vector2 coordinates with the given floats
  2245. * @param x defines the first coordinate
  2246. * @param y defines the second coordinate
  2247. * @returns the current updated Vector2
  2248. */
  2249. Vector2.prototype.copyFromFloats = function (x, y) {
  2250. this.x = x;
  2251. this.y = y;
  2252. return this;
  2253. };
  2254. /**
  2255. * Sets the Vector2 coordinates with the given floats
  2256. * @param x defines the first coordinate
  2257. * @param y defines the second coordinate
  2258. * @returns the current updated Vector2
  2259. */
  2260. Vector2.prototype.set = function (x, y) {
  2261. return this.copyFromFloats(x, y);
  2262. };
  2263. /**
  2264. * Add another vector with the current one
  2265. * @param otherVector defines the other vector
  2266. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2267. */
  2268. Vector2.prototype.add = function (otherVector) {
  2269. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2270. };
  2271. /**
  2272. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2273. * @param otherVector defines the other vector
  2274. * @param result defines the target vector
  2275. * @returns the unmodified current Vector2
  2276. */
  2277. Vector2.prototype.addToRef = function (otherVector, result) {
  2278. result.x = this.x + otherVector.x;
  2279. result.y = this.y + otherVector.y;
  2280. return this;
  2281. };
  2282. /**
  2283. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2284. * @param otherVector defines the other vector
  2285. * @returns the current updated Vector2
  2286. */
  2287. Vector2.prototype.addInPlace = function (otherVector) {
  2288. this.x += otherVector.x;
  2289. this.y += otherVector.y;
  2290. return this;
  2291. };
  2292. /**
  2293. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2294. * @param otherVector defines the other vector
  2295. * @returns a new Vector2
  2296. */
  2297. Vector2.prototype.addVector3 = function (otherVector) {
  2298. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2299. };
  2300. /**
  2301. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2302. * @param otherVector defines the other vector
  2303. * @returns a new Vector2
  2304. */
  2305. Vector2.prototype.subtract = function (otherVector) {
  2306. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2307. };
  2308. /**
  2309. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2310. * @param otherVector defines the other vector
  2311. * @param result defines the target vector
  2312. * @returns the unmodified current Vector2
  2313. */
  2314. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2315. result.x = this.x - otherVector.x;
  2316. result.y = this.y - otherVector.y;
  2317. return this;
  2318. };
  2319. /**
  2320. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2321. * @param otherVector defines the other vector
  2322. * @returns the current updated Vector2
  2323. */
  2324. Vector2.prototype.subtractInPlace = function (otherVector) {
  2325. this.x -= otherVector.x;
  2326. this.y -= otherVector.y;
  2327. return this;
  2328. };
  2329. /**
  2330. * Multiplies in place the current Vector2 coordinates by the given ones
  2331. * @param otherVector defines the other vector
  2332. * @returns the current updated Vector2
  2333. */
  2334. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2335. this.x *= otherVector.x;
  2336. this.y *= otherVector.y;
  2337. return this;
  2338. };
  2339. /**
  2340. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2341. * @param otherVector defines the other vector
  2342. * @returns a new Vector2
  2343. */
  2344. Vector2.prototype.multiply = function (otherVector) {
  2345. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2346. };
  2347. /**
  2348. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2349. * @param otherVector defines the other vector
  2350. * @param result defines the target vector
  2351. * @returns the unmodified current Vector2
  2352. */
  2353. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2354. result.x = this.x * otherVector.x;
  2355. result.y = this.y * otherVector.y;
  2356. return this;
  2357. };
  2358. /**
  2359. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2360. * @param x defines the first coordinate
  2361. * @param y defines the second coordinate
  2362. * @returns a new Vector2
  2363. */
  2364. Vector2.prototype.multiplyByFloats = function (x, y) {
  2365. return new Vector2(this.x * x, this.y * y);
  2366. };
  2367. /**
  2368. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2369. * @param otherVector defines the other vector
  2370. * @returns a new Vector2
  2371. */
  2372. Vector2.prototype.divide = function (otherVector) {
  2373. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2374. };
  2375. /**
  2376. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2377. * @param otherVector defines the other vector
  2378. * @param result defines the target vector
  2379. * @returns the unmodified current Vector2
  2380. */
  2381. Vector2.prototype.divideToRef = function (otherVector, result) {
  2382. result.x = this.x / otherVector.x;
  2383. result.y = this.y / otherVector.y;
  2384. return this;
  2385. };
  2386. /**
  2387. * Divides the current Vector3 coordinates by the given ones
  2388. * @param otherVector defines the other vector
  2389. * @returns the current updated Vector2
  2390. */
  2391. Vector2.prototype.divideInPlace = function (otherVector) {
  2392. return this.divideToRef(otherVector, this);
  2393. };
  2394. /**
  2395. * Gets a new Vector2 with current Vector2 negated coordinates
  2396. * @returns a new Vector2
  2397. */
  2398. Vector2.prototype.negate = function () {
  2399. return new Vector2(-this.x, -this.y);
  2400. };
  2401. /**
  2402. * Multiply the Vector2 coordinates by scale
  2403. * @param scale defines the scaling factor
  2404. * @returns the current updated Vector2
  2405. */
  2406. Vector2.prototype.scaleInPlace = function (scale) {
  2407. this.x *= scale;
  2408. this.y *= scale;
  2409. return this;
  2410. };
  2411. /**
  2412. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2413. * @param scale defines the scaling factor
  2414. * @returns a new Vector2
  2415. */
  2416. Vector2.prototype.scale = function (scale) {
  2417. var result = new Vector2(0, 0);
  2418. this.scaleToRef(scale, result);
  2419. return result;
  2420. };
  2421. /**
  2422. * Scale the current Vector2 values by a factor to a given Vector2
  2423. * @param scale defines the scale factor
  2424. * @param result defines the Vector2 object where to store the result
  2425. * @returns the unmodified current Vector2
  2426. */
  2427. Vector2.prototype.scaleToRef = function (scale, result) {
  2428. result.x = this.x * scale;
  2429. result.y = this.y * scale;
  2430. return this;
  2431. };
  2432. /**
  2433. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2434. * @param scale defines the scale factor
  2435. * @param result defines the Vector2 object where to store the result
  2436. * @returns the unmodified current Vector2
  2437. */
  2438. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2439. result.x += this.x * scale;
  2440. result.y += this.y * scale;
  2441. return this;
  2442. };
  2443. /**
  2444. * Gets a boolean if two vectors are equals
  2445. * @param otherVector defines the other vector
  2446. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2447. */
  2448. Vector2.prototype.equals = function (otherVector) {
  2449. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2450. };
  2451. /**
  2452. * Gets a boolean if two vectors are equals (using an epsilon value)
  2453. * @param otherVector defines the other vector
  2454. * @param epsilon defines the minimal distance to consider equality
  2455. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2456. */
  2457. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2458. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2459. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2460. };
  2461. // Properties
  2462. /**
  2463. * Gets the length of the vector
  2464. * @returns the vector length (float)
  2465. */
  2466. Vector2.prototype.length = function () {
  2467. return Math.sqrt(this.x * this.x + this.y * this.y);
  2468. };
  2469. /**
  2470. * Gets the vector squared length
  2471. * @returns the vector squared length (float)
  2472. */
  2473. Vector2.prototype.lengthSquared = function () {
  2474. return (this.x * this.x + this.y * this.y);
  2475. };
  2476. // Methods
  2477. /**
  2478. * Normalize the vector
  2479. * @returns the current updated Vector2
  2480. */
  2481. Vector2.prototype.normalize = function () {
  2482. var len = this.length();
  2483. if (len === 0)
  2484. return this;
  2485. var num = 1.0 / len;
  2486. this.x *= num;
  2487. this.y *= num;
  2488. return this;
  2489. };
  2490. /**
  2491. * Gets a new Vector2 copied from the Vector2
  2492. * @returns a new Vector2
  2493. */
  2494. Vector2.prototype.clone = function () {
  2495. return new Vector2(this.x, this.y);
  2496. };
  2497. // Statics
  2498. /**
  2499. * Gets a new Vector2(0, 0)
  2500. * @returns a new Vector2
  2501. */
  2502. Vector2.Zero = function () {
  2503. return new Vector2(0, 0);
  2504. };
  2505. /**
  2506. * Gets a new Vector2(1, 1)
  2507. * @returns a new Vector2
  2508. */
  2509. Vector2.One = function () {
  2510. return new Vector2(1, 1);
  2511. };
  2512. /**
  2513. * Gets a new Vector2 set from the given index element of the given array
  2514. * @param array defines the data source
  2515. * @param offset defines the offset in the data source
  2516. * @returns a new Vector2
  2517. */
  2518. Vector2.FromArray = function (array, offset) {
  2519. if (offset === void 0) { offset = 0; }
  2520. return new Vector2(array[offset], array[offset + 1]);
  2521. };
  2522. /**
  2523. * Sets "result" from the given index element of the given array
  2524. * @param array defines the data source
  2525. * @param offset defines the offset in the data source
  2526. * @param result defines the target vector
  2527. */
  2528. Vector2.FromArrayToRef = function (array, offset, result) {
  2529. result.x = array[offset];
  2530. result.y = array[offset + 1];
  2531. };
  2532. /**
  2533. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2534. * @param value1 defines 1st point of control
  2535. * @param value2 defines 2nd point of control
  2536. * @param value3 defines 3rd point of control
  2537. * @param value4 defines 4th point of control
  2538. * @param amount defines the interpolation factor
  2539. * @returns a new Vector2
  2540. */
  2541. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2542. var squared = amount * amount;
  2543. var cubed = amount * squared;
  2544. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2545. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2546. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2547. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2548. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2549. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2550. return new Vector2(x, y);
  2551. };
  2552. /**
  2553. * 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".
  2554. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2555. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2556. * @param value defines the value to clamp
  2557. * @param min defines the lower limit
  2558. * @param max defines the upper limit
  2559. * @returns a new Vector2
  2560. */
  2561. Vector2.Clamp = function (value, min, max) {
  2562. var x = value.x;
  2563. x = (x > max.x) ? max.x : x;
  2564. x = (x < min.x) ? min.x : x;
  2565. var y = value.y;
  2566. y = (y > max.y) ? max.y : y;
  2567. y = (y < min.y) ? min.y : y;
  2568. return new Vector2(x, y);
  2569. };
  2570. /**
  2571. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2572. * @param value1 defines the 1st control point
  2573. * @param tangent1 defines the outgoing tangent
  2574. * @param value2 defines the 2nd control point
  2575. * @param tangent2 defines the incoming tangent
  2576. * @param amount defines the interpolation factor
  2577. * @returns a new Vector2
  2578. */
  2579. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2580. var squared = amount * amount;
  2581. var cubed = amount * squared;
  2582. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2583. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2584. var part3 = (cubed - (2.0 * squared)) + amount;
  2585. var part4 = cubed - squared;
  2586. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2587. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2588. return new Vector2(x, y);
  2589. };
  2590. /**
  2591. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2592. * @param start defines the start vector
  2593. * @param end defines the end vector
  2594. * @param amount defines the interpolation factor
  2595. * @returns a new Vector2
  2596. */
  2597. Vector2.Lerp = function (start, end, amount) {
  2598. var x = start.x + ((end.x - start.x) * amount);
  2599. var y = start.y + ((end.y - start.y) * amount);
  2600. return new Vector2(x, y);
  2601. };
  2602. /**
  2603. * Gets the dot product of the vector "left" and the vector "right"
  2604. * @param left defines first vector
  2605. * @param right defines second vector
  2606. * @returns the dot product (float)
  2607. */
  2608. Vector2.Dot = function (left, right) {
  2609. return left.x * right.x + left.y * right.y;
  2610. };
  2611. /**
  2612. * Returns a new Vector2 equal to the normalized given vector
  2613. * @param vector defines the vector to normalize
  2614. * @returns a new Vector2
  2615. */
  2616. Vector2.Normalize = function (vector) {
  2617. var newVector = vector.clone();
  2618. newVector.normalize();
  2619. return newVector;
  2620. };
  2621. /**
  2622. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2623. * @param left defines 1st vector
  2624. * @param right defines 2nd vector
  2625. * @returns a new Vector2
  2626. */
  2627. Vector2.Minimize = function (left, right) {
  2628. var x = (left.x < right.x) ? left.x : right.x;
  2629. var y = (left.y < right.y) ? left.y : right.y;
  2630. return new Vector2(x, y);
  2631. };
  2632. /**
  2633. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2634. * @param left defines 1st vector
  2635. * @param right defines 2nd vector
  2636. * @returns a new Vector2
  2637. */
  2638. Vector2.Maximize = function (left, right) {
  2639. var x = (left.x > right.x) ? left.x : right.x;
  2640. var y = (left.y > right.y) ? left.y : right.y;
  2641. return new Vector2(x, y);
  2642. };
  2643. /**
  2644. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2645. * @param vector defines the vector to transform
  2646. * @param transformation defines the matrix to apply
  2647. * @returns a new Vector2
  2648. */
  2649. Vector2.Transform = function (vector, transformation) {
  2650. var r = Vector2.Zero();
  2651. Vector2.TransformToRef(vector, transformation, r);
  2652. return r;
  2653. };
  2654. /**
  2655. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2656. * @param vector defines the vector to transform
  2657. * @param transformation defines the matrix to apply
  2658. * @param result defines the target vector
  2659. */
  2660. Vector2.TransformToRef = function (vector, transformation, result) {
  2661. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2662. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2663. result.x = x;
  2664. result.y = y;
  2665. };
  2666. /**
  2667. * Determines if a given vector is included in a triangle
  2668. * @param p defines the vector to test
  2669. * @param p0 defines 1st triangle point
  2670. * @param p1 defines 2nd triangle point
  2671. * @param p2 defines 3rd triangle point
  2672. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2673. */
  2674. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2675. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2676. var sign = a < 0 ? -1 : 1;
  2677. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2678. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2679. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2680. };
  2681. /**
  2682. * Gets the distance between the vectors "value1" and "value2"
  2683. * @param value1 defines first vector
  2684. * @param value2 defines second vector
  2685. * @returns the distance between vectors
  2686. */
  2687. Vector2.Distance = function (value1, value2) {
  2688. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2689. };
  2690. /**
  2691. * Returns the squared distance between the vectors "value1" and "value2"
  2692. * @param value1 defines first vector
  2693. * @param value2 defines second vector
  2694. * @returns the squared distance between vectors
  2695. */
  2696. Vector2.DistanceSquared = function (value1, value2) {
  2697. var x = value1.x - value2.x;
  2698. var y = value1.y - value2.y;
  2699. return (x * x) + (y * y);
  2700. };
  2701. /**
  2702. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2703. * @param value1 defines first vector
  2704. * @param value2 defines second vector
  2705. * @returns a new Vector2
  2706. */
  2707. Vector2.Center = function (value1, value2) {
  2708. var center = value1.add(value2);
  2709. center.scaleInPlace(0.5);
  2710. return center;
  2711. };
  2712. /**
  2713. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2714. * @param p defines the middle point
  2715. * @param segA defines one point of the segment
  2716. * @param segB defines the other point of the segment
  2717. * @returns the shortest distance
  2718. */
  2719. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2720. var l2 = Vector2.DistanceSquared(segA, segB);
  2721. if (l2 === 0.0) {
  2722. return Vector2.Distance(p, segA);
  2723. }
  2724. var v = segB.subtract(segA);
  2725. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2726. var proj = segA.add(v.multiplyByFloats(t, t));
  2727. return Vector2.Distance(p, proj);
  2728. };
  2729. return Vector2;
  2730. }());
  2731. BABYLON.Vector2 = Vector2;
  2732. /**
  2733. * Classed used to store (x,y,z) vector representation
  2734. * A Vector3 is the main object used in 3D geometry
  2735. * It can represent etiher the coordinates of a point the space, either a direction
  2736. * Reminder: Babylon.js uses a left handed forward facing system
  2737. */
  2738. var Vector3 = /** @class */ (function () {
  2739. /**
  2740. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2741. * @param x defines the first coordinates (on X axis)
  2742. * @param y defines the second coordinates (on Y axis)
  2743. * @param z defines the third coordinates (on Z axis)
  2744. */
  2745. function Vector3(
  2746. /**
  2747. * Defines the first coordinates (on X axis)
  2748. */
  2749. x,
  2750. /**
  2751. * Defines the second coordinates (on Y axis)
  2752. */
  2753. y,
  2754. /**
  2755. * Defines the third coordinates (on Z axis)
  2756. */
  2757. z) {
  2758. this.x = x;
  2759. this.y = y;
  2760. this.z = z;
  2761. }
  2762. /**
  2763. * Creates a string representation of the Vector3
  2764. * @returns a string with the Vector3 coordinates.
  2765. */
  2766. Vector3.prototype.toString = function () {
  2767. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2768. };
  2769. /**
  2770. * Gets the class name
  2771. * @returns the string "Vector3"
  2772. */
  2773. Vector3.prototype.getClassName = function () {
  2774. return "Vector3";
  2775. };
  2776. /**
  2777. * Creates the Vector3 hash code
  2778. * @returns a number which tends to be unique between Vector3 instances
  2779. */
  2780. Vector3.prototype.getHashCode = function () {
  2781. var hash = this.x || 0;
  2782. hash = (hash * 397) ^ (this.y || 0);
  2783. hash = (hash * 397) ^ (this.z || 0);
  2784. return hash;
  2785. };
  2786. // Operators
  2787. /**
  2788. * Creates an array containing three elements : the coordinates of the Vector3
  2789. * @returns a new array of numbers
  2790. */
  2791. Vector3.prototype.asArray = function () {
  2792. var result = [];
  2793. this.toArray(result, 0);
  2794. return result;
  2795. };
  2796. /**
  2797. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2798. * @param array defines the destination array
  2799. * @param index defines the offset in the destination array
  2800. * @returns the current Vector3
  2801. */
  2802. Vector3.prototype.toArray = function (array, index) {
  2803. if (index === void 0) { index = 0; }
  2804. array[index] = this.x;
  2805. array[index + 1] = this.y;
  2806. array[index + 2] = this.z;
  2807. return this;
  2808. };
  2809. /**
  2810. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2811. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2812. */
  2813. Vector3.prototype.toQuaternion = function () {
  2814. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2815. };
  2816. /**
  2817. * Adds the given vector to the current Vector3
  2818. * @param otherVector defines the second operand
  2819. * @returns the current updated Vector3
  2820. */
  2821. Vector3.prototype.addInPlace = function (otherVector) {
  2822. this.x += otherVector.x;
  2823. this.y += otherVector.y;
  2824. this.z += otherVector.z;
  2825. return this;
  2826. };
  2827. /**
  2828. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2829. * @param otherVector defines the second operand
  2830. * @returns the resulting Vector3
  2831. */
  2832. Vector3.prototype.add = function (otherVector) {
  2833. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2834. };
  2835. /**
  2836. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2837. * @param otherVector defines the second operand
  2838. * @param result defines the Vector3 object where to store the result
  2839. * @returns the current Vector3
  2840. */
  2841. Vector3.prototype.addToRef = function (otherVector, result) {
  2842. result.x = this.x + otherVector.x;
  2843. result.y = this.y + otherVector.y;
  2844. result.z = this.z + otherVector.z;
  2845. return this;
  2846. };
  2847. /**
  2848. * Subtract the given vector from the current Vector3
  2849. * @param otherVector defines the second operand
  2850. * @returns the current updated Vector3
  2851. */
  2852. Vector3.prototype.subtractInPlace = function (otherVector) {
  2853. this.x -= otherVector.x;
  2854. this.y -= otherVector.y;
  2855. this.z -= otherVector.z;
  2856. return this;
  2857. };
  2858. /**
  2859. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2860. * @param otherVector defines the second operand
  2861. * @returns the resulting Vector3
  2862. */
  2863. Vector3.prototype.subtract = function (otherVector) {
  2864. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2865. };
  2866. /**
  2867. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2868. * @param otherVector defines the second operand
  2869. * @param result defines the Vector3 object where to store the result
  2870. * @returns the current Vector3
  2871. */
  2872. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2873. result.x = this.x - otherVector.x;
  2874. result.y = this.y - otherVector.y;
  2875. result.z = this.z - otherVector.z;
  2876. return this;
  2877. };
  2878. /**
  2879. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2880. * @param x defines the x coordinate of the operand
  2881. * @param y defines the y coordinate of the operand
  2882. * @param z defines the z coordinate of the operand
  2883. * @returns the resulting Vector3
  2884. */
  2885. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2886. return new Vector3(this.x - x, this.y - y, this.z - z);
  2887. };
  2888. /**
  2889. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2890. * @param x defines the x coordinate of the operand
  2891. * @param y defines the y coordinate of the operand
  2892. * @param z defines the z coordinate of the operand
  2893. * @param result defines the Vector3 object where to store the result
  2894. * @returns the current Vector3
  2895. */
  2896. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2897. result.x = this.x - x;
  2898. result.y = this.y - y;
  2899. result.z = this.z - z;
  2900. return this;
  2901. };
  2902. /**
  2903. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2904. * @returns a new Vector3
  2905. */
  2906. Vector3.prototype.negate = function () {
  2907. return new Vector3(-this.x, -this.y, -this.z);
  2908. };
  2909. /**
  2910. * Multiplies the Vector3 coordinates by the float "scale"
  2911. * @param scale defines the multiplier factor
  2912. * @returns the current updated Vector3
  2913. */
  2914. Vector3.prototype.scaleInPlace = function (scale) {
  2915. this.x *= scale;
  2916. this.y *= scale;
  2917. this.z *= scale;
  2918. return this;
  2919. };
  2920. /**
  2921. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2922. * @param scale defines the multiplier factor
  2923. * @returns a new Vector3
  2924. */
  2925. Vector3.prototype.scale = function (scale) {
  2926. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2927. };
  2928. /**
  2929. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2930. * @param scale defines the multiplier factor
  2931. * @param result defines the Vector3 object where to store the result
  2932. * @returns the current Vector3
  2933. */
  2934. Vector3.prototype.scaleToRef = function (scale, result) {
  2935. result.x = this.x * scale;
  2936. result.y = this.y * scale;
  2937. result.z = this.z * scale;
  2938. return this;
  2939. };
  2940. /**
  2941. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2942. * @param scale defines the scale factor
  2943. * @param result defines the Vector3 object where to store the result
  2944. * @returns the unmodified current Vector3
  2945. */
  2946. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2947. result.x += this.x * scale;
  2948. result.y += this.y * scale;
  2949. result.z += this.z * scale;
  2950. return this;
  2951. };
  2952. /**
  2953. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2954. * @param otherVector defines the second operand
  2955. * @returns true if both vectors are equals
  2956. */
  2957. Vector3.prototype.equals = function (otherVector) {
  2958. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2959. };
  2960. /**
  2961. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2962. * @param otherVector defines the second operand
  2963. * @param epsilon defines the minimal distance to define values as equals
  2964. * @returns true if both vectors are distant less than epsilon
  2965. */
  2966. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2967. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2968. 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);
  2969. };
  2970. /**
  2971. * Returns true if the current Vector3 coordinates equals the given floats
  2972. * @param x defines the x coordinate of the operand
  2973. * @param y defines the y coordinate of the operand
  2974. * @param z defines the z coordinate of the operand
  2975. * @returns true if both vectors are equals
  2976. */
  2977. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2978. return this.x === x && this.y === y && this.z === z;
  2979. };
  2980. /**
  2981. * Multiplies the current Vector3 coordinates by the given ones
  2982. * @param otherVector defines the second operand
  2983. * @returns the current updated Vector3
  2984. */
  2985. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2986. this.x *= otherVector.x;
  2987. this.y *= otherVector.y;
  2988. this.z *= otherVector.z;
  2989. return this;
  2990. };
  2991. /**
  2992. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  2993. * @param otherVector defines the second operand
  2994. * @returns the new Vector3
  2995. */
  2996. Vector3.prototype.multiply = function (otherVector) {
  2997. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2998. };
  2999. /**
  3000. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3001. * @param otherVector defines the second operand
  3002. * @param result defines the Vector3 object where to store the result
  3003. * @returns the current Vector3
  3004. */
  3005. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3006. result.x = this.x * otherVector.x;
  3007. result.y = this.y * otherVector.y;
  3008. result.z = this.z * otherVector.z;
  3009. return this;
  3010. };
  3011. /**
  3012. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3013. * @param x defines the x coordinate of the operand
  3014. * @param y defines the y coordinate of the operand
  3015. * @param z defines the z coordinate of the operand
  3016. * @returns the new Vector3
  3017. */
  3018. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3019. return new Vector3(this.x * x, this.y * y, this.z * z);
  3020. };
  3021. /**
  3022. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3023. * @param otherVector defines the second operand
  3024. * @returns the new Vector3
  3025. */
  3026. Vector3.prototype.divide = function (otherVector) {
  3027. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3028. };
  3029. /**
  3030. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3031. * @param otherVector defines the second operand
  3032. * @param result defines the Vector3 object where to store the result
  3033. * @returns the current Vector3
  3034. */
  3035. Vector3.prototype.divideToRef = function (otherVector, result) {
  3036. result.x = this.x / otherVector.x;
  3037. result.y = this.y / otherVector.y;
  3038. result.z = this.z / otherVector.z;
  3039. return this;
  3040. };
  3041. /**
  3042. * Divides the current Vector3 coordinates by the given ones.
  3043. * @param otherVector defines the second operand
  3044. * @returns the current updated Vector3
  3045. */
  3046. Vector3.prototype.divideInPlace = function (otherVector) {
  3047. return this.divideToRef(otherVector, this);
  3048. };
  3049. /**
  3050. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3051. * @param other defines the second operand
  3052. * @returns the current updated Vector3
  3053. */
  3054. Vector3.prototype.minimizeInPlace = function (other) {
  3055. if (other.x < this.x)
  3056. this.x = other.x;
  3057. if (other.y < this.y)
  3058. this.y = other.y;
  3059. if (other.z < this.z)
  3060. this.z = other.z;
  3061. return this;
  3062. };
  3063. /**
  3064. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3065. * @param other defines the second operand
  3066. * @returns the current updated Vector3
  3067. */
  3068. Vector3.prototype.maximizeInPlace = function (other) {
  3069. if (other.x > this.x)
  3070. this.x = other.x;
  3071. if (other.y > this.y)
  3072. this.y = other.y;
  3073. if (other.z > this.z)
  3074. this.z = other.z;
  3075. return this;
  3076. };
  3077. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3078. /**
  3079. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3080. */
  3081. get: function () {
  3082. var absX = Math.abs(this.x);
  3083. var absY = Math.abs(this.y);
  3084. if (absX !== absY) {
  3085. return true;
  3086. }
  3087. var absZ = Math.abs(this.z);
  3088. if (absX !== absZ) {
  3089. return true;
  3090. }
  3091. if (absY !== absZ) {
  3092. return true;
  3093. }
  3094. return false;
  3095. },
  3096. enumerable: true,
  3097. configurable: true
  3098. });
  3099. // Properties
  3100. /**
  3101. * Gets the length of the Vector3
  3102. * @returns the length of the Vecto3
  3103. */
  3104. Vector3.prototype.length = function () {
  3105. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3106. };
  3107. /**
  3108. * Gets the squared length of the Vector3
  3109. * @returns squared length of the Vector3
  3110. */
  3111. Vector3.prototype.lengthSquared = function () {
  3112. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3113. };
  3114. /**
  3115. * Normalize the current Vector3.
  3116. * Please note that this is an in place operation.
  3117. * @returns the current updated Vector3
  3118. */
  3119. Vector3.prototype.normalize = function () {
  3120. var len = this.length();
  3121. if (len === 0 || len === 1.0)
  3122. return this;
  3123. var num = 1.0 / len;
  3124. this.x *= num;
  3125. this.y *= num;
  3126. this.z *= num;
  3127. return this;
  3128. };
  3129. /**
  3130. * Normalize the current Vector3 to a new vector
  3131. * @returns the new Vector3
  3132. */
  3133. Vector3.prototype.normalizeToNew = function () {
  3134. var normalized = new Vector3(0, 0, 0);
  3135. this.normalizeToRef(normalized);
  3136. return normalized;
  3137. };
  3138. /**
  3139. * Normalize the current Vector3 to the reference
  3140. * @param reference define the Vector3 to update
  3141. * @returns the updated Vector3
  3142. */
  3143. Vector3.prototype.normalizeToRef = function (reference) {
  3144. var len = this.length();
  3145. if (len === 0 || len === 1.0) {
  3146. reference.set(this.x, this.y, this.z);
  3147. return reference;
  3148. }
  3149. var scale = 1.0 / len;
  3150. this.scaleToRef(scale, reference);
  3151. return reference;
  3152. };
  3153. /**
  3154. * Creates a new Vector3 copied from the current Vector3
  3155. * @returns the new Vector3
  3156. */
  3157. Vector3.prototype.clone = function () {
  3158. return new Vector3(this.x, this.y, this.z);
  3159. };
  3160. /**
  3161. * Copies the given vector coordinates to the current Vector3 ones
  3162. * @param source defines the source Vector3
  3163. * @returns the current updated Vector3
  3164. */
  3165. Vector3.prototype.copyFrom = function (source) {
  3166. this.x = source.x;
  3167. this.y = source.y;
  3168. this.z = source.z;
  3169. return this;
  3170. };
  3171. /**
  3172. * Copies the given floats to the current Vector3 coordinates
  3173. * @param x defines the x coordinate of the operand
  3174. * @param y defines the y coordinate of the operand
  3175. * @param z defines the z coordinate of the operand
  3176. * @returns the current updated Vector3
  3177. */
  3178. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3179. this.x = x;
  3180. this.y = y;
  3181. this.z = z;
  3182. return this;
  3183. };
  3184. /**
  3185. * Copies the given floats to the current Vector3 coordinates
  3186. * @param x defines the x coordinate of the operand
  3187. * @param y defines the y coordinate of the operand
  3188. * @param z defines the z coordinate of the operand
  3189. * @returns the current updated Vector3
  3190. */
  3191. Vector3.prototype.set = function (x, y, z) {
  3192. return this.copyFromFloats(x, y, z);
  3193. };
  3194. // Statics
  3195. /**
  3196. * Get the clip factor between two vectors
  3197. * @param vector0 defines the first operand
  3198. * @param vector1 defines the second operand
  3199. * @param axis defines the axis to use
  3200. * @param size defines the size along the axis
  3201. * @returns the clip factor
  3202. */
  3203. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3204. var d0 = Vector3.Dot(vector0, axis) - size;
  3205. var d1 = Vector3.Dot(vector1, axis) - size;
  3206. var s = d0 / (d0 - d1);
  3207. return s;
  3208. };
  3209. /**
  3210. * Get angle between two vectors
  3211. * @param vector0 angle between vector0 and vector1
  3212. * @param vector1 angle between vector0 and vector1
  3213. * @param normal direction of the normal
  3214. * @return the angle between vector0 and vector1
  3215. */
  3216. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3217. var v0 = vector0.clone().normalize();
  3218. var v1 = vector1.clone().normalize();
  3219. var dot = Vector3.Dot(v0, v1);
  3220. var n = Vector3.Cross(v0, v1);
  3221. if (Vector3.Dot(n, normal) > 0) {
  3222. return Math.acos(dot);
  3223. }
  3224. return -Math.acos(dot);
  3225. };
  3226. /**
  3227. * Returns a new Vector3 set from the index "offset" of the given array
  3228. * @param array defines the source array
  3229. * @param offset defines the offset in the source array
  3230. * @returns the new Vector3
  3231. */
  3232. Vector3.FromArray = function (array, offset) {
  3233. if (!offset) {
  3234. offset = 0;
  3235. }
  3236. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3237. };
  3238. /**
  3239. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3240. * This function is deprecated. Use FromArray instead
  3241. * @param array defines the source array
  3242. * @param offset defines the offset in the source array
  3243. * @returns the new Vector3
  3244. */
  3245. Vector3.FromFloatArray = function (array, offset) {
  3246. return Vector3.FromArray(array, offset);
  3247. };
  3248. /**
  3249. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3250. * @param array defines the source array
  3251. * @param offset defines the offset in the source array
  3252. * @param result defines the Vector3 where to store the result
  3253. */
  3254. Vector3.FromArrayToRef = function (array, offset, result) {
  3255. result.x = array[offset];
  3256. result.y = array[offset + 1];
  3257. result.z = array[offset + 2];
  3258. };
  3259. /**
  3260. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3261. * This function is deprecated. Use FromArrayToRef instead.
  3262. * @param array defines the source array
  3263. * @param offset defines the offset in the source array
  3264. * @param result defines the Vector3 where to store the result
  3265. */
  3266. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3267. return Vector3.FromArrayToRef(array, offset, result);
  3268. };
  3269. /**
  3270. * Sets the given vector "result" with the given floats.
  3271. * @param x defines the x coordinate of the source
  3272. * @param y defines the y coordinate of the source
  3273. * @param z defines the z coordinate of the source
  3274. * @param result defines the Vector3 where to store the result
  3275. */
  3276. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3277. result.x = x;
  3278. result.y = y;
  3279. result.z = z;
  3280. };
  3281. /**
  3282. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3283. * @returns a new empty Vector3
  3284. */
  3285. Vector3.Zero = function () {
  3286. return new Vector3(0.0, 0.0, 0.0);
  3287. };
  3288. /**
  3289. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3290. * @returns a new unit Vector3
  3291. */
  3292. Vector3.One = function () {
  3293. return new Vector3(1.0, 1.0, 1.0);
  3294. };
  3295. /**
  3296. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3297. * @returns a new up Vector3
  3298. */
  3299. Vector3.Up = function () {
  3300. return new Vector3(0.0, 1.0, 0.0);
  3301. };
  3302. /**
  3303. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3304. * @returns a new forward Vector3
  3305. */
  3306. Vector3.Forward = function () {
  3307. return new Vector3(0.0, 0.0, 1.0);
  3308. };
  3309. /**
  3310. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3311. * @returns a new right Vector3
  3312. */
  3313. Vector3.Right = function () {
  3314. return new Vector3(1.0, 0.0, 0.0);
  3315. };
  3316. /**
  3317. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3318. * @returns a new left Vector3
  3319. */
  3320. Vector3.Left = function () {
  3321. return new Vector3(-1.0, 0.0, 0.0);
  3322. };
  3323. /**
  3324. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3325. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3326. * @param vector defines the Vector3 to transform
  3327. * @param transformation defines the transformation matrix
  3328. * @returns the transformed Vector3
  3329. */
  3330. Vector3.TransformCoordinates = function (vector, transformation) {
  3331. var result = Vector3.Zero();
  3332. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3333. return result;
  3334. };
  3335. /**
  3336. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3337. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3338. * @param vector defines the Vector3 to transform
  3339. * @param transformation defines the transformation matrix
  3340. * @param result defines the Vector3 where to store the result
  3341. */
  3342. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3343. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3344. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3345. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3346. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3347. result.x = x / w;
  3348. result.y = y / w;
  3349. result.z = z / w;
  3350. };
  3351. /**
  3352. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3353. * This method computes tranformed coordinates only, not transformed direction vectors
  3354. * @param x define the x coordinate of the source vector
  3355. * @param y define the y coordinate of the source vector
  3356. * @param z define the z coordinate of the source vector
  3357. * @param transformation defines the transformation matrix
  3358. * @param result defines the Vector3 where to store the result
  3359. */
  3360. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3361. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3362. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3363. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3364. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3365. result.x = rx / rw;
  3366. result.y = ry / rw;
  3367. result.z = rz / rw;
  3368. };
  3369. /**
  3370. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3371. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3372. * @param vector defines the Vector3 to transform
  3373. * @param transformation defines the transformation matrix
  3374. * @returns the new Vector3
  3375. */
  3376. Vector3.TransformNormal = function (vector, transformation) {
  3377. var result = Vector3.Zero();
  3378. Vector3.TransformNormalToRef(vector, transformation, result);
  3379. return result;
  3380. };
  3381. /**
  3382. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3383. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3384. * @param vector defines the Vector3 to transform
  3385. * @param transformation defines the transformation matrix
  3386. * @param result defines the Vector3 where to store the result
  3387. */
  3388. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3389. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3390. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3391. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3392. result.x = x;
  3393. result.y = y;
  3394. result.z = z;
  3395. };
  3396. /**
  3397. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3398. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3399. * @param x define the x coordinate of the source vector
  3400. * @param y define the y coordinate of the source vector
  3401. * @param z define the z coordinate of the source vector
  3402. * @param transformation defines the transformation matrix
  3403. * @param result defines the Vector3 where to store the result
  3404. */
  3405. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3406. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3407. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3408. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3409. };
  3410. /**
  3411. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3412. * @param value1 defines the first control point
  3413. * @param value2 defines the second control point
  3414. * @param value3 defines the third control point
  3415. * @param value4 defines the fourth control point
  3416. * @param amount defines the amount on the spline to use
  3417. * @returns the new Vector3
  3418. */
  3419. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3420. var squared = amount * amount;
  3421. var cubed = amount * squared;
  3422. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3423. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3424. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3425. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3426. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3427. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3428. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3429. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3430. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3431. return new Vector3(x, y, z);
  3432. };
  3433. /**
  3434. * 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"
  3435. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3436. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3437. * @param value defines the current value
  3438. * @param min defines the lower range value
  3439. * @param max defines the upper range value
  3440. * @returns the new Vector3
  3441. */
  3442. Vector3.Clamp = function (value, min, max) {
  3443. var x = value.x;
  3444. x = (x > max.x) ? max.x : x;
  3445. x = (x < min.x) ? min.x : x;
  3446. var y = value.y;
  3447. y = (y > max.y) ? max.y : y;
  3448. y = (y < min.y) ? min.y : y;
  3449. var z = value.z;
  3450. z = (z > max.z) ? max.z : z;
  3451. z = (z < min.z) ? min.z : z;
  3452. return new Vector3(x, y, z);
  3453. };
  3454. /**
  3455. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3456. * @param value1 defines the first control point
  3457. * @param tangent1 defines the first tangent vector
  3458. * @param value2 defines the second control point
  3459. * @param tangent2 defines the second tangent vector
  3460. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3461. * @returns the new Vector3
  3462. */
  3463. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3464. var squared = amount * amount;
  3465. var cubed = amount * squared;
  3466. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3467. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3468. var part3 = (cubed - (2.0 * squared)) + amount;
  3469. var part4 = cubed - squared;
  3470. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3471. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3472. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3473. return new Vector3(x, y, z);
  3474. };
  3475. /**
  3476. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3477. * @param start defines the start value
  3478. * @param end defines the end value
  3479. * @param amount max defines amount between both (between 0 and 1)
  3480. * @returns the new Vector3
  3481. */
  3482. Vector3.Lerp = function (start, end, amount) {
  3483. var result = new Vector3(0, 0, 0);
  3484. Vector3.LerpToRef(start, end, amount, result);
  3485. return result;
  3486. };
  3487. /**
  3488. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3489. * @param start defines the start value
  3490. * @param end defines the end value
  3491. * @param amount max defines amount between both (between 0 and 1)
  3492. * @param result defines the Vector3 where to store the result
  3493. */
  3494. Vector3.LerpToRef = function (start, end, amount, result) {
  3495. result.x = start.x + ((end.x - start.x) * amount);
  3496. result.y = start.y + ((end.y - start.y) * amount);
  3497. result.z = start.z + ((end.z - start.z) * amount);
  3498. };
  3499. /**
  3500. * Returns the dot product (float) between the vectors "left" and "right"
  3501. * @param left defines the left operand
  3502. * @param right defines the right operand
  3503. * @returns the dot product
  3504. */
  3505. Vector3.Dot = function (left, right) {
  3506. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3507. };
  3508. /**
  3509. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3510. * The cross product is then orthogonal to both "left" and "right"
  3511. * @param left defines the left operand
  3512. * @param right defines the right operand
  3513. * @returns the cross product
  3514. */
  3515. Vector3.Cross = function (left, right) {
  3516. var result = Vector3.Zero();
  3517. Vector3.CrossToRef(left, right, result);
  3518. return result;
  3519. };
  3520. /**
  3521. * Sets the given vector "result" with the cross product of "left" and "right"
  3522. * The cross product is then orthogonal to both "left" and "right"
  3523. * @param left defines the left operand
  3524. * @param right defines the right operand
  3525. * @param result defines the Vector3 where to store the result
  3526. */
  3527. Vector3.CrossToRef = function (left, right, result) {
  3528. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3529. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3530. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3531. result.copyFrom(MathTmp.Vector3[0]);
  3532. };
  3533. /**
  3534. * Returns a new Vector3 as the normalization of the given vector
  3535. * @param vector defines the Vector3 to normalize
  3536. * @returns the new Vector3
  3537. */
  3538. Vector3.Normalize = function (vector) {
  3539. var result = Vector3.Zero();
  3540. Vector3.NormalizeToRef(vector, result);
  3541. return result;
  3542. };
  3543. /**
  3544. * Sets the given vector "result" with the normalization of the given first vector
  3545. * @param vector defines the Vector3 to normalize
  3546. * @param result defines the Vector3 where to store the result
  3547. */
  3548. Vector3.NormalizeToRef = function (vector, result) {
  3549. result.copyFrom(vector);
  3550. result.normalize();
  3551. };
  3552. /**
  3553. * Project a Vector3 onto screen space
  3554. * @param vector defines the Vector3 to project
  3555. * @param world defines the world matrix to use
  3556. * @param transform defines the transform (view x projection) matrix to use
  3557. * @param viewport defines the screen viewport to use
  3558. * @returns the new Vector3
  3559. */
  3560. Vector3.Project = function (vector, world, transform, viewport) {
  3561. var cw = viewport.width;
  3562. var ch = viewport.height;
  3563. var cx = viewport.x;
  3564. var cy = viewport.y;
  3565. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3566. 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);
  3567. var matrix = MathTmp.Matrix[0];
  3568. world.multiplyToRef(transform, matrix);
  3569. matrix.multiplyToRef(viewportMatrix, matrix);
  3570. return Vector3.TransformCoordinates(vector, matrix);
  3571. };
  3572. /**
  3573. * Unproject from screen space to object space
  3574. * @param source defines the screen space Vector3 to use
  3575. * @param viewportWidth defines the current width of the viewport
  3576. * @param viewportHeight defines the current height of the viewport
  3577. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3578. * @param transform defines the transform (view x projection) matrix to use
  3579. * @returns the new Vector3
  3580. */
  3581. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3582. var matrix = MathTmp.Matrix[0];
  3583. world.multiplyToRef(transform, matrix);
  3584. matrix.invert();
  3585. source.x = source.x / viewportWidth * 2 - 1;
  3586. source.y = -(source.y / viewportHeight * 2 - 1);
  3587. var vector = Vector3.TransformCoordinates(source, matrix);
  3588. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3589. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3590. vector = vector.scale(1.0 / num);
  3591. }
  3592. return vector;
  3593. };
  3594. /**
  3595. * Unproject from screen space to object space
  3596. * @param source defines the screen space Vector3 to use
  3597. * @param viewportWidth defines the current width of the viewport
  3598. * @param viewportHeight defines the current height of the viewport
  3599. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3600. * @param view defines the view matrix to use
  3601. * @param projection defines the projection matrix to use
  3602. * @returns the new Vector3
  3603. */
  3604. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3605. var result = Vector3.Zero();
  3606. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3607. return result;
  3608. };
  3609. /**
  3610. * Unproject from screen space to object space
  3611. * @param source defines the screen space Vector3 to use
  3612. * @param viewportWidth defines the current width of the viewport
  3613. * @param viewportHeight defines the current height of the viewport
  3614. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3615. * @param view defines the view matrix to use
  3616. * @param projection defines the projection matrix to use
  3617. * @param result defines the Vector3 where to store the result
  3618. */
  3619. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3620. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3621. };
  3622. /**
  3623. * Unproject from screen space to object space
  3624. * @param sourceX defines the screen space x coordinate to use
  3625. * @param sourceY defines the screen space y coordinate to use
  3626. * @param sourceZ defines the screen space z coordinate to use
  3627. * @param viewportWidth defines the current width of the viewport
  3628. * @param viewportHeight defines the current height of the viewport
  3629. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3630. * @param view defines the view matrix to use
  3631. * @param projection defines the projection matrix to use
  3632. * @param result defines the Vector3 where to store the result
  3633. */
  3634. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3635. var matrix = MathTmp.Matrix[0];
  3636. world.multiplyToRef(view, matrix);
  3637. matrix.multiplyToRef(projection, matrix);
  3638. matrix.invert();
  3639. var screenSource = MathTmp.Vector3[0];
  3640. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3641. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3642. screenSource.z = 2 * sourceZ - 1.0;
  3643. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3644. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3645. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3646. result.scaleInPlace(1.0 / num);
  3647. }
  3648. };
  3649. /**
  3650. * Gets the minimal coordinate values between two Vector3
  3651. * @param left defines the first operand
  3652. * @param right defines the second operand
  3653. * @returns the new Vector3
  3654. */
  3655. Vector3.Minimize = function (left, right) {
  3656. var min = left.clone();
  3657. min.minimizeInPlace(right);
  3658. return min;
  3659. };
  3660. /**
  3661. * Gets the maximal coordinate values between two Vector3
  3662. * @param left defines the first operand
  3663. * @param right defines the second operand
  3664. * @returns the new Vector3
  3665. */
  3666. Vector3.Maximize = function (left, right) {
  3667. var max = left.clone();
  3668. max.maximizeInPlace(right);
  3669. return max;
  3670. };
  3671. /**
  3672. * Returns the distance between the vectors "value1" and "value2"
  3673. * @param value1 defines the first operand
  3674. * @param value2 defines the second operand
  3675. * @returns the distance
  3676. */
  3677. Vector3.Distance = function (value1, value2) {
  3678. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3679. };
  3680. /**
  3681. * Returns the squared distance between the vectors "value1" and "value2"
  3682. * @param value1 defines the first operand
  3683. * @param value2 defines the second operand
  3684. * @returns the squared distance
  3685. */
  3686. Vector3.DistanceSquared = function (value1, value2) {
  3687. var x = value1.x - value2.x;
  3688. var y = value1.y - value2.y;
  3689. var z = value1.z - value2.z;
  3690. return (x * x) + (y * y) + (z * z);
  3691. };
  3692. /**
  3693. * Returns a new Vector3 located at the center between "value1" and "value2"
  3694. * @param value1 defines the first operand
  3695. * @param value2 defines the second operand
  3696. * @returns the new Vector3
  3697. */
  3698. Vector3.Center = function (value1, value2) {
  3699. var center = value1.add(value2);
  3700. center.scaleInPlace(0.5);
  3701. return center;
  3702. };
  3703. /**
  3704. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3705. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3706. * to something in order to rotate it from its local system to the given target system
  3707. * Note: axis1, axis2 and axis3 are normalized during this operation
  3708. * @param axis1 defines the first axis
  3709. * @param axis2 defines the second axis
  3710. * @param axis3 defines the third axis
  3711. * @returns a new Vector3
  3712. */
  3713. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3714. var rotation = Vector3.Zero();
  3715. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3716. return rotation;
  3717. };
  3718. /**
  3719. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3720. * @param axis1 defines the first axis
  3721. * @param axis2 defines the second axis
  3722. * @param axis3 defines the third axis
  3723. * @param ref defines the Vector3 where to store the result
  3724. */
  3725. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3726. var quat = MathTmp.Quaternion[0];
  3727. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3728. quat.toEulerAnglesToRef(ref);
  3729. };
  3730. return Vector3;
  3731. }());
  3732. BABYLON.Vector3 = Vector3;
  3733. //Vector4 class created for EulerAngle class conversion to Quaternion
  3734. var Vector4 = /** @class */ (function () {
  3735. /**
  3736. * Creates a Vector4 object from the given floats.
  3737. */
  3738. function Vector4(x, y, z, w) {
  3739. this.x = x;
  3740. this.y = y;
  3741. this.z = z;
  3742. this.w = w;
  3743. }
  3744. /**
  3745. * Returns the string with the Vector4 coordinates.
  3746. */
  3747. Vector4.prototype.toString = function () {
  3748. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3749. };
  3750. /**
  3751. * Returns the string "Vector4".
  3752. */
  3753. Vector4.prototype.getClassName = function () {
  3754. return "Vector4";
  3755. };
  3756. /**
  3757. * Returns the Vector4 hash code.
  3758. */
  3759. Vector4.prototype.getHashCode = function () {
  3760. var hash = this.x || 0;
  3761. hash = (hash * 397) ^ (this.y || 0);
  3762. hash = (hash * 397) ^ (this.z || 0);
  3763. hash = (hash * 397) ^ (this.w || 0);
  3764. return hash;
  3765. };
  3766. // Operators
  3767. /**
  3768. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3769. */
  3770. Vector4.prototype.asArray = function () {
  3771. var result = new Array();
  3772. this.toArray(result, 0);
  3773. return result;
  3774. };
  3775. /**
  3776. * Populates the given array from the given index with the Vector4 coordinates.
  3777. * Returns the Vector4.
  3778. */
  3779. Vector4.prototype.toArray = function (array, index) {
  3780. if (index === undefined) {
  3781. index = 0;
  3782. }
  3783. array[index] = this.x;
  3784. array[index + 1] = this.y;
  3785. array[index + 2] = this.z;
  3786. array[index + 3] = this.w;
  3787. return this;
  3788. };
  3789. /**
  3790. * Adds the given vector to the current Vector4.
  3791. * Returns the updated Vector4.
  3792. */
  3793. Vector4.prototype.addInPlace = function (otherVector) {
  3794. this.x += otherVector.x;
  3795. this.y += otherVector.y;
  3796. this.z += otherVector.z;
  3797. this.w += otherVector.w;
  3798. return this;
  3799. };
  3800. /**
  3801. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3802. */
  3803. Vector4.prototype.add = function (otherVector) {
  3804. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3805. };
  3806. /**
  3807. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3808. * Returns the current Vector4.
  3809. */
  3810. Vector4.prototype.addToRef = function (otherVector, result) {
  3811. result.x = this.x + otherVector.x;
  3812. result.y = this.y + otherVector.y;
  3813. result.z = this.z + otherVector.z;
  3814. result.w = this.w + otherVector.w;
  3815. return this;
  3816. };
  3817. /**
  3818. * Subtract in place the given vector from the current Vector4.
  3819. * Returns the updated Vector4.
  3820. */
  3821. Vector4.prototype.subtractInPlace = function (otherVector) {
  3822. this.x -= otherVector.x;
  3823. this.y -= otherVector.y;
  3824. this.z -= otherVector.z;
  3825. this.w -= otherVector.w;
  3826. return this;
  3827. };
  3828. /**
  3829. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3830. */
  3831. Vector4.prototype.subtract = function (otherVector) {
  3832. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3833. };
  3834. /**
  3835. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3836. * Returns the current Vector4.
  3837. */
  3838. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3839. result.x = this.x - otherVector.x;
  3840. result.y = this.y - otherVector.y;
  3841. result.z = this.z - otherVector.z;
  3842. result.w = this.w - otherVector.w;
  3843. return this;
  3844. };
  3845. /**
  3846. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3847. */
  3848. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3849. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3850. };
  3851. /**
  3852. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3853. * Returns the current Vector4.
  3854. */
  3855. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3856. result.x = this.x - x;
  3857. result.y = this.y - y;
  3858. result.z = this.z - z;
  3859. result.w = this.w - w;
  3860. return this;
  3861. };
  3862. /**
  3863. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3864. */
  3865. Vector4.prototype.negate = function () {
  3866. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3867. };
  3868. /**
  3869. * Multiplies the current Vector4 coordinates by scale (float).
  3870. * Returns the updated Vector4.
  3871. */
  3872. Vector4.prototype.scaleInPlace = function (scale) {
  3873. this.x *= scale;
  3874. this.y *= scale;
  3875. this.z *= scale;
  3876. this.w *= scale;
  3877. return this;
  3878. };
  3879. /**
  3880. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3881. */
  3882. Vector4.prototype.scale = function (scale) {
  3883. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3884. };
  3885. /**
  3886. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3887. * Returns the current Vector4.
  3888. */
  3889. Vector4.prototype.scaleToRef = function (scale, result) {
  3890. result.x = this.x * scale;
  3891. result.y = this.y * scale;
  3892. result.z = this.z * scale;
  3893. result.w = this.w * scale;
  3894. return this;
  3895. };
  3896. /**
  3897. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3898. * @param scale defines the scale factor
  3899. * @param result defines the Vector4 object where to store the result
  3900. * @returns the unmodified current Vector4
  3901. */
  3902. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3903. result.x += this.x * scale;
  3904. result.y += this.y * scale;
  3905. result.z += this.z * scale;
  3906. result.w += this.w * scale;
  3907. return this;
  3908. };
  3909. /**
  3910. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3911. */
  3912. Vector4.prototype.equals = function (otherVector) {
  3913. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3914. };
  3915. /**
  3916. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3917. */
  3918. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3919. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3920. return otherVector
  3921. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3922. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3923. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3924. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3925. };
  3926. /**
  3927. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3928. */
  3929. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3930. return this.x === x && this.y === y && this.z === z && this.w === w;
  3931. };
  3932. /**
  3933. * Multiplies in place the current Vector4 by the given one.
  3934. * Returns the updated Vector4.
  3935. */
  3936. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3937. this.x *= otherVector.x;
  3938. this.y *= otherVector.y;
  3939. this.z *= otherVector.z;
  3940. this.w *= otherVector.w;
  3941. return this;
  3942. };
  3943. /**
  3944. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3945. */
  3946. Vector4.prototype.multiply = function (otherVector) {
  3947. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3948. };
  3949. /**
  3950. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3951. * Returns the current Vector4.
  3952. */
  3953. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3954. result.x = this.x * otherVector.x;
  3955. result.y = this.y * otherVector.y;
  3956. result.z = this.z * otherVector.z;
  3957. result.w = this.w * otherVector.w;
  3958. return this;
  3959. };
  3960. /**
  3961. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3962. */
  3963. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3964. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3965. };
  3966. /**
  3967. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3968. */
  3969. Vector4.prototype.divide = function (otherVector) {
  3970. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3971. };
  3972. /**
  3973. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3974. * Returns the current Vector4.
  3975. */
  3976. Vector4.prototype.divideToRef = function (otherVector, result) {
  3977. result.x = this.x / otherVector.x;
  3978. result.y = this.y / otherVector.y;
  3979. result.z = this.z / otherVector.z;
  3980. result.w = this.w / otherVector.w;
  3981. return this;
  3982. };
  3983. /**
  3984. * Divides the current Vector3 coordinates by the given ones.
  3985. * @returns the updated Vector3.
  3986. */
  3987. Vector4.prototype.divideInPlace = function (otherVector) {
  3988. return this.divideToRef(otherVector, this);
  3989. };
  3990. /**
  3991. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  3992. * @param other defines the second operand
  3993. * @returns the current updated Vector4
  3994. */
  3995. Vector4.prototype.minimizeInPlace = function (other) {
  3996. if (other.x < this.x)
  3997. this.x = other.x;
  3998. if (other.y < this.y)
  3999. this.y = other.y;
  4000. if (other.z < this.z)
  4001. this.z = other.z;
  4002. if (other.w < this.w)
  4003. this.w = other.w;
  4004. return this;
  4005. };
  4006. /**
  4007. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4008. * @param other defines the second operand
  4009. * @returns the current updated Vector4
  4010. */
  4011. Vector4.prototype.maximizeInPlace = function (other) {
  4012. if (other.x > this.x)
  4013. this.x = other.x;
  4014. if (other.y > this.y)
  4015. this.y = other.y;
  4016. if (other.z > this.z)
  4017. this.z = other.z;
  4018. if (other.w > this.w)
  4019. this.w = other.w;
  4020. return this;
  4021. };
  4022. // Properties
  4023. /**
  4024. * Returns the Vector4 length (float).
  4025. */
  4026. Vector4.prototype.length = function () {
  4027. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4028. };
  4029. /**
  4030. * Returns the Vector4 squared length (float).
  4031. */
  4032. Vector4.prototype.lengthSquared = function () {
  4033. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4034. };
  4035. // Methods
  4036. /**
  4037. * Normalizes in place the Vector4.
  4038. * Returns the updated Vector4.
  4039. */
  4040. Vector4.prototype.normalize = function () {
  4041. var len = this.length();
  4042. if (len === 0)
  4043. return this;
  4044. var num = 1.0 / len;
  4045. this.x *= num;
  4046. this.y *= num;
  4047. this.z *= num;
  4048. this.w *= num;
  4049. return this;
  4050. };
  4051. /**
  4052. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4053. */
  4054. Vector4.prototype.toVector3 = function () {
  4055. return new Vector3(this.x, this.y, this.z);
  4056. };
  4057. /**
  4058. * Returns a new Vector4 copied from the current one.
  4059. */
  4060. Vector4.prototype.clone = function () {
  4061. return new Vector4(this.x, this.y, this.z, this.w);
  4062. };
  4063. /**
  4064. * Updates the current Vector4 with the given one coordinates.
  4065. * Returns the updated Vector4.
  4066. */
  4067. Vector4.prototype.copyFrom = function (source) {
  4068. this.x = source.x;
  4069. this.y = source.y;
  4070. this.z = source.z;
  4071. this.w = source.w;
  4072. return this;
  4073. };
  4074. /**
  4075. * Updates the current Vector4 coordinates with the given floats.
  4076. * Returns the updated Vector4.
  4077. */
  4078. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4079. this.x = x;
  4080. this.y = y;
  4081. this.z = z;
  4082. this.w = w;
  4083. return this;
  4084. };
  4085. /**
  4086. * Updates the current Vector4 coordinates with the given floats.
  4087. * Returns the updated Vector4.
  4088. */
  4089. Vector4.prototype.set = function (x, y, z, w) {
  4090. return this.copyFromFloats(x, y, z, w);
  4091. };
  4092. // Statics
  4093. /**
  4094. * Returns a new Vector4 set from the starting index of the given array.
  4095. */
  4096. Vector4.FromArray = function (array, offset) {
  4097. if (!offset) {
  4098. offset = 0;
  4099. }
  4100. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4101. };
  4102. /**
  4103. * Updates the given vector "result" from the starting index of the given array.
  4104. */
  4105. Vector4.FromArrayToRef = function (array, offset, result) {
  4106. result.x = array[offset];
  4107. result.y = array[offset + 1];
  4108. result.z = array[offset + 2];
  4109. result.w = array[offset + 3];
  4110. };
  4111. /**
  4112. * Updates the given vector "result" from the starting index of the given Float32Array.
  4113. */
  4114. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4115. Vector4.FromArrayToRef(array, offset, result);
  4116. };
  4117. /**
  4118. * Updates the given vector "result" coordinates from the given floats.
  4119. */
  4120. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4121. result.x = x;
  4122. result.y = y;
  4123. result.z = z;
  4124. result.w = w;
  4125. };
  4126. /**
  4127. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4128. */
  4129. Vector4.Zero = function () {
  4130. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4131. };
  4132. /**
  4133. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4134. */
  4135. Vector4.One = function () {
  4136. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4137. };
  4138. /**
  4139. * Returns a new normalized Vector4 from the given one.
  4140. */
  4141. Vector4.Normalize = function (vector) {
  4142. var result = Vector4.Zero();
  4143. Vector4.NormalizeToRef(vector, result);
  4144. return result;
  4145. };
  4146. /**
  4147. * Updates the given vector "result" from the normalization of the given one.
  4148. */
  4149. Vector4.NormalizeToRef = function (vector, result) {
  4150. result.copyFrom(vector);
  4151. result.normalize();
  4152. };
  4153. Vector4.Minimize = function (left, right) {
  4154. var min = left.clone();
  4155. min.minimizeInPlace(right);
  4156. return min;
  4157. };
  4158. Vector4.Maximize = function (left, right) {
  4159. var max = left.clone();
  4160. max.maximizeInPlace(right);
  4161. return max;
  4162. };
  4163. /**
  4164. * Returns the distance (float) between the vectors "value1" and "value2".
  4165. */
  4166. Vector4.Distance = function (value1, value2) {
  4167. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4168. };
  4169. /**
  4170. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4171. */
  4172. Vector4.DistanceSquared = function (value1, value2) {
  4173. var x = value1.x - value2.x;
  4174. var y = value1.y - value2.y;
  4175. var z = value1.z - value2.z;
  4176. var w = value1.w - value2.w;
  4177. return (x * x) + (y * y) + (z * z) + (w * w);
  4178. };
  4179. /**
  4180. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4181. */
  4182. Vector4.Center = function (value1, value2) {
  4183. var center = value1.add(value2);
  4184. center.scaleInPlace(0.5);
  4185. return center;
  4186. };
  4187. /**
  4188. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4189. * This methods computes transformed normalized direction vectors only.
  4190. */
  4191. Vector4.TransformNormal = function (vector, transformation) {
  4192. var result = Vector4.Zero();
  4193. Vector4.TransformNormalToRef(vector, transformation, result);
  4194. return result;
  4195. };
  4196. /**
  4197. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4198. * This methods computes transformed normalized direction vectors only.
  4199. */
  4200. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4201. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4202. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4203. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4204. result.x = x;
  4205. result.y = y;
  4206. result.z = z;
  4207. result.w = vector.w;
  4208. };
  4209. /**
  4210. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4211. * This methods computes transformed normalized direction vectors only.
  4212. */
  4213. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4214. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4215. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4216. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4217. result.w = w;
  4218. };
  4219. return Vector4;
  4220. }());
  4221. BABYLON.Vector4 = Vector4;
  4222. var Size = /** @class */ (function () {
  4223. /**
  4224. * Creates a Size object from the given width and height (floats).
  4225. */
  4226. function Size(width, height) {
  4227. this.width = width;
  4228. this.height = height;
  4229. }
  4230. // Returns a string with the Size width and height.
  4231. Size.prototype.toString = function () {
  4232. return "{W: " + this.width + ", H: " + this.height + "}";
  4233. };
  4234. /**
  4235. * Returns the string "Size"
  4236. */
  4237. Size.prototype.getClassName = function () {
  4238. return "Size";
  4239. };
  4240. /**
  4241. * Returns the Size hash code.
  4242. */
  4243. Size.prototype.getHashCode = function () {
  4244. var hash = this.width || 0;
  4245. hash = (hash * 397) ^ (this.height || 0);
  4246. return hash;
  4247. };
  4248. /**
  4249. * Updates the current size from the given one.
  4250. * Returns the updated Size.
  4251. */
  4252. Size.prototype.copyFrom = function (src) {
  4253. this.width = src.width;
  4254. this.height = src.height;
  4255. };
  4256. /**
  4257. * Updates in place the current Size from the given floats.
  4258. * Returns the updated Size.
  4259. */
  4260. Size.prototype.copyFromFloats = function (width, height) {
  4261. this.width = width;
  4262. this.height = height;
  4263. return this;
  4264. };
  4265. /**
  4266. * Updates in place the current Size from the given floats.
  4267. * Returns the updated Size.
  4268. */
  4269. Size.prototype.set = function (width, height) {
  4270. return this.copyFromFloats(width, height);
  4271. };
  4272. /**
  4273. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4274. */
  4275. Size.prototype.multiplyByFloats = function (w, h) {
  4276. return new Size(this.width * w, this.height * h);
  4277. };
  4278. /**
  4279. * Returns a new Size copied from the given one.
  4280. */
  4281. Size.prototype.clone = function () {
  4282. return new Size(this.width, this.height);
  4283. };
  4284. /**
  4285. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4286. */
  4287. Size.prototype.equals = function (other) {
  4288. if (!other) {
  4289. return false;
  4290. }
  4291. return (this.width === other.width) && (this.height === other.height);
  4292. };
  4293. Object.defineProperty(Size.prototype, "surface", {
  4294. /**
  4295. * Returns the surface of the Size : width * height (float).
  4296. */
  4297. get: function () {
  4298. return this.width * this.height;
  4299. },
  4300. enumerable: true,
  4301. configurable: true
  4302. });
  4303. /**
  4304. * Returns a new Size set to (0.0, 0.0)
  4305. */
  4306. Size.Zero = function () {
  4307. return new Size(0.0, 0.0);
  4308. };
  4309. /**
  4310. * Returns a new Size set as the addition result of the current Size and the given one.
  4311. */
  4312. Size.prototype.add = function (otherSize) {
  4313. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4314. return r;
  4315. };
  4316. /**
  4317. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4318. */
  4319. Size.prototype.subtract = function (otherSize) {
  4320. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4321. return r;
  4322. };
  4323. /**
  4324. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4325. */
  4326. Size.Lerp = function (start, end, amount) {
  4327. var w = start.width + ((end.width - start.width) * amount);
  4328. var h = start.height + ((end.height - start.height) * amount);
  4329. return new Size(w, h);
  4330. };
  4331. return Size;
  4332. }());
  4333. BABYLON.Size = Size;
  4334. /**
  4335. * Class used to store quaternion data
  4336. * @see https://en.wikipedia.org/wiki/Quaternion
  4337. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4338. */
  4339. var Quaternion = /** @class */ (function () {
  4340. /**
  4341. * Creates a new Quaternion from the given floats
  4342. * @param x defines the first component (0 by default)
  4343. * @param y defines the second component (0 by default)
  4344. * @param z defines the third component (0 by default)
  4345. * @param w defines the fourth component (1.0 by default)
  4346. */
  4347. function Quaternion(
  4348. /** defines the first component (0 by default) */
  4349. x,
  4350. /** defines the second component (0 by default) */
  4351. y,
  4352. /** defines the third component (0 by default) */
  4353. z,
  4354. /** defines the fourth component (1.0 by default) */
  4355. w) {
  4356. if (x === void 0) { x = 0.0; }
  4357. if (y === void 0) { y = 0.0; }
  4358. if (z === void 0) { z = 0.0; }
  4359. if (w === void 0) { w = 1.0; }
  4360. this.x = x;
  4361. this.y = y;
  4362. this.z = z;
  4363. this.w = w;
  4364. }
  4365. /**
  4366. * Gets a string representation for the current quaternion
  4367. * @returns a string with the Quaternion coordinates
  4368. */
  4369. Quaternion.prototype.toString = function () {
  4370. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4371. };
  4372. /**
  4373. * Gets the class name of the quaternion
  4374. * @returns the string "Quaternion"
  4375. */
  4376. Quaternion.prototype.getClassName = function () {
  4377. return "Quaternion";
  4378. };
  4379. /**
  4380. * Gets a hash code for this quaternion
  4381. * @returns the quaternion hash code
  4382. */
  4383. Quaternion.prototype.getHashCode = function () {
  4384. var hash = this.x || 0;
  4385. hash = (hash * 397) ^ (this.y || 0);
  4386. hash = (hash * 397) ^ (this.z || 0);
  4387. hash = (hash * 397) ^ (this.w || 0);
  4388. return hash;
  4389. };
  4390. /**
  4391. * Copy the quaternion to an array
  4392. * @returns a new array populated with 4 elements from the quaternion coordinates
  4393. */
  4394. Quaternion.prototype.asArray = function () {
  4395. return [this.x, this.y, this.z, this.w];
  4396. };
  4397. /**
  4398. * Check if two quaternions are equals
  4399. * @param otherQuaternion defines the second operand
  4400. * @return true if the current quaternion and the given one coordinates are strictly equals
  4401. */
  4402. Quaternion.prototype.equals = function (otherQuaternion) {
  4403. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4404. };
  4405. /**
  4406. * Clone the current quaternion
  4407. * @returns a new quaternion copied from the current one
  4408. */
  4409. Quaternion.prototype.clone = function () {
  4410. return new Quaternion(this.x, this.y, this.z, this.w);
  4411. };
  4412. /**
  4413. * Copy a quaternion to the current one
  4414. * @param other defines the other quaternion
  4415. * @returns the updated current quaternion
  4416. */
  4417. Quaternion.prototype.copyFrom = function (other) {
  4418. this.x = other.x;
  4419. this.y = other.y;
  4420. this.z = other.z;
  4421. this.w = other.w;
  4422. return this;
  4423. };
  4424. /**
  4425. * Updates the current quaternion with the given float coordinates
  4426. * @param x defines the x coordinate
  4427. * @param y defines the y coordinate
  4428. * @param z defines the z coordinate
  4429. * @param w defines the w coordinate
  4430. * @returns the updated current quaternion
  4431. */
  4432. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4433. this.x = x;
  4434. this.y = y;
  4435. this.z = z;
  4436. this.w = w;
  4437. return this;
  4438. };
  4439. /**
  4440. * Updates the current quaternion from the given float coordinates
  4441. * @param x defines the x coordinate
  4442. * @param y defines the y coordinate
  4443. * @param z defines the z coordinate
  4444. * @param w defines the w coordinate
  4445. * @returns the updated current quaternion
  4446. */
  4447. Quaternion.prototype.set = function (x, y, z, w) {
  4448. return this.copyFromFloats(x, y, z, w);
  4449. };
  4450. /**
  4451. * Adds two quaternions
  4452. * @param other defines the second operand
  4453. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4454. */
  4455. Quaternion.prototype.add = function (other) {
  4456. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4457. };
  4458. /**
  4459. * Add a quaternion to the current one
  4460. * @param other defines the quaternion to add
  4461. * @returns the current quaternion
  4462. */
  4463. Quaternion.prototype.addInPlace = function (other) {
  4464. this.x += other.x;
  4465. this.y += other.y;
  4466. this.z += other.z;
  4467. this.w += other.w;
  4468. return this;
  4469. };
  4470. /**
  4471. * Subtract two quaternions
  4472. * @param other defines the second operand
  4473. * @returns a new quaternion as the subtraction result of the given one from the current one
  4474. */
  4475. Quaternion.prototype.subtract = function (other) {
  4476. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4477. };
  4478. /**
  4479. * Multiplies the current quaternion by a scale factor
  4480. * @param value defines the scale factor
  4481. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4482. */
  4483. Quaternion.prototype.scale = function (value) {
  4484. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4485. };
  4486. /**
  4487. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4488. * @param scale defines the scale factor
  4489. * @param result defines the Quaternion object where to store the result
  4490. * @returns the unmodified current quaternion
  4491. */
  4492. Quaternion.prototype.scaleToRef = function (scale, result) {
  4493. result.x = this.x * scale;
  4494. result.y = this.y * scale;
  4495. result.z = this.z * scale;
  4496. result.w = this.w * scale;
  4497. return this;
  4498. };
  4499. /**
  4500. * Multiplies in place the current quaternion by a scale factor
  4501. * @param value defines the scale factor
  4502. * @returns the current modified quaternion
  4503. */
  4504. Quaternion.prototype.scaleInPlace = function (value) {
  4505. this.x *= value;
  4506. this.y *= value;
  4507. this.z *= value;
  4508. this.w *= value;
  4509. return this;
  4510. };
  4511. /**
  4512. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4513. * @param scale defines the scale factor
  4514. * @param result defines the Quaternion object where to store the result
  4515. * @returns the unmodified current quaternion
  4516. */
  4517. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4518. result.x += this.x * scale;
  4519. result.y += this.y * scale;
  4520. result.z += this.z * scale;
  4521. result.w += this.w * scale;
  4522. return this;
  4523. };
  4524. /**
  4525. * Multiplies two quaternions
  4526. * @param q1 defines the second operand
  4527. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4528. */
  4529. Quaternion.prototype.multiply = function (q1) {
  4530. var result = new Quaternion(0, 0, 0, 1.0);
  4531. this.multiplyToRef(q1, result);
  4532. return result;
  4533. };
  4534. /**
  4535. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4536. * @param q1 defines the second operand
  4537. * @param result defines the target quaternion
  4538. * @returns the current quaternion
  4539. */
  4540. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4541. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4542. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4543. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4544. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4545. result.copyFromFloats(x, y, z, w);
  4546. return this;
  4547. };
  4548. /**
  4549. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4550. * @param q1 defines the second operand
  4551. * @returns the currentupdated quaternion
  4552. */
  4553. Quaternion.prototype.multiplyInPlace = function (q1) {
  4554. this.multiplyToRef(q1, this);
  4555. return this;
  4556. };
  4557. /**
  4558. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4559. * @param ref defines the target quaternion
  4560. * @returns the current quaternion
  4561. */
  4562. Quaternion.prototype.conjugateToRef = function (ref) {
  4563. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4564. return this;
  4565. };
  4566. /**
  4567. * Conjugates in place (1-q) the current quaternion
  4568. * @returns the current updated quaternion
  4569. */
  4570. Quaternion.prototype.conjugateInPlace = function () {
  4571. this.x *= -1;
  4572. this.y *= -1;
  4573. this.z *= -1;
  4574. return this;
  4575. };
  4576. /**
  4577. * Conjugates in place (1-q) the current quaternion
  4578. * @returns a new quaternion
  4579. */
  4580. Quaternion.prototype.conjugate = function () {
  4581. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4582. return result;
  4583. };
  4584. /**
  4585. * Gets length of current quaternion
  4586. * @returns the quaternion length (float)
  4587. */
  4588. Quaternion.prototype.length = function () {
  4589. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4590. };
  4591. /**
  4592. * Normalize in place the current quaternion
  4593. * @returns the current updated quaternion
  4594. */
  4595. Quaternion.prototype.normalize = function () {
  4596. var length = 1.0 / this.length();
  4597. this.x *= length;
  4598. this.y *= length;
  4599. this.z *= length;
  4600. this.w *= length;
  4601. return this;
  4602. };
  4603. /**
  4604. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4605. * @param order is a reserved parameter and is ignore for now
  4606. * @returns a new Vector3 containing the Euler angles
  4607. */
  4608. Quaternion.prototype.toEulerAngles = function (order) {
  4609. if (order === void 0) { order = "YZX"; }
  4610. var result = Vector3.Zero();
  4611. this.toEulerAnglesToRef(result, order);
  4612. return result;
  4613. };
  4614. /**
  4615. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4616. * @param result defines the vector which will be filled with the Euler angles
  4617. * @param order is a reserved parameter and is ignore for now
  4618. * @returns the current unchanged quaternion
  4619. */
  4620. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4621. if (order === void 0) { order = "YZX"; }
  4622. var qz = this.z;
  4623. var qx = this.x;
  4624. var qy = this.y;
  4625. var qw = this.w;
  4626. var sqw = qw * qw;
  4627. var sqz = qz * qz;
  4628. var sqx = qx * qx;
  4629. var sqy = qy * qy;
  4630. var zAxisY = qy * qz - qx * qw;
  4631. var limit = .4999999;
  4632. if (zAxisY < -limit) {
  4633. result.y = 2 * Math.atan2(qy, qw);
  4634. result.x = Math.PI / 2;
  4635. result.z = 0;
  4636. }
  4637. else if (zAxisY > limit) {
  4638. result.y = 2 * Math.atan2(qy, qw);
  4639. result.x = -Math.PI / 2;
  4640. result.z = 0;
  4641. }
  4642. else {
  4643. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4644. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4645. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4646. }
  4647. return this;
  4648. };
  4649. /**
  4650. * Updates the given rotation matrix with the current quaternion values
  4651. * @param result defines the target matrix
  4652. * @returns the current unchanged quaternion
  4653. */
  4654. Quaternion.prototype.toRotationMatrix = function (result) {
  4655. var xx = this.x * this.x;
  4656. var yy = this.y * this.y;
  4657. var zz = this.z * this.z;
  4658. var xy = this.x * this.y;
  4659. var zw = this.z * this.w;
  4660. var zx = this.z * this.x;
  4661. var yw = this.y * this.w;
  4662. var yz = this.y * this.z;
  4663. var xw = this.x * this.w;
  4664. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4665. result.m[1] = 2.0 * (xy + zw);
  4666. result.m[2] = 2.0 * (zx - yw);
  4667. result.m[3] = 0;
  4668. result.m[4] = 2.0 * (xy - zw);
  4669. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4670. result.m[6] = 2.0 * (yz + xw);
  4671. result.m[7] = 0;
  4672. result.m[8] = 2.0 * (zx + yw);
  4673. result.m[9] = 2.0 * (yz - xw);
  4674. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4675. result.m[11] = 0;
  4676. result.m[12] = 0;
  4677. result.m[13] = 0;
  4678. result.m[14] = 0;
  4679. result.m[15] = 1.0;
  4680. result._markAsUpdated();
  4681. return this;
  4682. };
  4683. /**
  4684. * Updates the current quaternion from the given rotation matrix values
  4685. * @param matrix defines the source matrix
  4686. * @returns the current updated quaternion
  4687. */
  4688. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4689. Quaternion.FromRotationMatrixToRef(matrix, this);
  4690. return this;
  4691. };
  4692. // Statics
  4693. /**
  4694. * Creates a new quaternion from a rotation matrix
  4695. * @param matrix defines the source matrix
  4696. * @returns a new quaternion created from the given rotation matrix values
  4697. */
  4698. Quaternion.FromRotationMatrix = function (matrix) {
  4699. var result = new Quaternion();
  4700. Quaternion.FromRotationMatrixToRef(matrix, result);
  4701. return result;
  4702. };
  4703. /**
  4704. * Updates the given quaternion with the given rotation matrix values
  4705. * @param matrix defines the source matrix
  4706. * @param result defines the target quaternion
  4707. */
  4708. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4709. var data = matrix.m;
  4710. var m11 = data[0], m12 = data[4], m13 = data[8];
  4711. var m21 = data[1], m22 = data[5], m23 = data[9];
  4712. var m31 = data[2], m32 = data[6], m33 = data[10];
  4713. var trace = m11 + m22 + m33;
  4714. var s;
  4715. if (trace > 0) {
  4716. s = 0.5 / Math.sqrt(trace + 1.0);
  4717. result.w = 0.25 / s;
  4718. result.x = (m32 - m23) * s;
  4719. result.y = (m13 - m31) * s;
  4720. result.z = (m21 - m12) * s;
  4721. }
  4722. else if (m11 > m22 && m11 > m33) {
  4723. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4724. result.w = (m32 - m23) / s;
  4725. result.x = 0.25 * s;
  4726. result.y = (m12 + m21) / s;
  4727. result.z = (m13 + m31) / s;
  4728. }
  4729. else if (m22 > m33) {
  4730. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4731. result.w = (m13 - m31) / s;
  4732. result.x = (m12 + m21) / s;
  4733. result.y = 0.25 * s;
  4734. result.z = (m23 + m32) / s;
  4735. }
  4736. else {
  4737. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4738. result.w = (m21 - m12) / s;
  4739. result.x = (m13 + m31) / s;
  4740. result.y = (m23 + m32) / s;
  4741. result.z = 0.25 * s;
  4742. }
  4743. };
  4744. /**
  4745. * Returns the dot product (float) between the quaternions "left" and "right"
  4746. * @param left defines the left operand
  4747. * @param right defines the right operand
  4748. * @returns the dot product
  4749. */
  4750. Quaternion.Dot = function (left, right) {
  4751. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4752. };
  4753. /**
  4754. * Checks if the two quaternions are close to each other
  4755. * @param quat0 defines the first quaternion to check
  4756. * @param quat1 defines the second quaternion to check
  4757. * @returns true if the two quaternions are close to each other
  4758. */
  4759. Quaternion.AreClose = function (quat0, quat1) {
  4760. var dot = Quaternion.Dot(quat0, quat1);
  4761. return dot >= 0;
  4762. };
  4763. /**
  4764. * Creates an empty quaternion
  4765. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4766. */
  4767. Quaternion.Zero = function () {
  4768. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4769. };
  4770. /**
  4771. * Inverse a given quaternion
  4772. * @param q defines the source quaternion
  4773. * @returns a new quaternion as the inverted current quaternion
  4774. */
  4775. Quaternion.Inverse = function (q) {
  4776. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4777. };
  4778. /**
  4779. * Creates an identity quaternion
  4780. * @returns the identity quaternion
  4781. */
  4782. Quaternion.Identity = function () {
  4783. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4784. };
  4785. /**
  4786. * Gets a boolean indicating if the given quaternion is identity
  4787. * @param quaternion defines the quaternion to check
  4788. * @returns true if the quaternion is identity
  4789. */
  4790. Quaternion.IsIdentity = function (quaternion) {
  4791. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4792. };
  4793. /**
  4794. * Creates a quaternion from a rotation around an axis
  4795. * @param axis defines the axis to use
  4796. * @param angle defines the angle to use
  4797. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4798. */
  4799. Quaternion.RotationAxis = function (axis, angle) {
  4800. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4801. };
  4802. /**
  4803. * Creates a rotation around an axis and stores it into the given quaternion
  4804. * @param axis defines the axis to use
  4805. * @param angle defines the angle to use
  4806. * @param result defines the target quaternion
  4807. * @returns the target quaternion
  4808. */
  4809. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4810. var sin = Math.sin(angle / 2);
  4811. axis.normalize();
  4812. result.w = Math.cos(angle / 2);
  4813. result.x = axis.x * sin;
  4814. result.y = axis.y * sin;
  4815. result.z = axis.z * sin;
  4816. return result;
  4817. };
  4818. /**
  4819. * Creates a new quaternion from data stored into an array
  4820. * @param array defines the data source
  4821. * @param offset defines the offset in the source array where the data starts
  4822. * @returns a new quaternion
  4823. */
  4824. Quaternion.FromArray = function (array, offset) {
  4825. if (!offset) {
  4826. offset = 0;
  4827. }
  4828. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4829. };
  4830. /**
  4831. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4832. * @param yaw defines the rotation around Y axis
  4833. * @param pitch defines the rotation around X axis
  4834. * @param roll defines the rotation around Z axis
  4835. * @returns the new quaternion
  4836. */
  4837. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4838. var q = new Quaternion();
  4839. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4840. return q;
  4841. };
  4842. /**
  4843. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4844. * @param yaw defines the rotation around Y axis
  4845. * @param pitch defines the rotation around X axis
  4846. * @param roll defines the rotation around Z axis
  4847. * @param result defines the target quaternion
  4848. */
  4849. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4850. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4851. var halfRoll = roll * 0.5;
  4852. var halfPitch = pitch * 0.5;
  4853. var halfYaw = yaw * 0.5;
  4854. var sinRoll = Math.sin(halfRoll);
  4855. var cosRoll = Math.cos(halfRoll);
  4856. var sinPitch = Math.sin(halfPitch);
  4857. var cosPitch = Math.cos(halfPitch);
  4858. var sinYaw = Math.sin(halfYaw);
  4859. var cosYaw = Math.cos(halfYaw);
  4860. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4861. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4862. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4863. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4864. };
  4865. /**
  4866. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4867. * @param alpha defines the rotation around first axis
  4868. * @param beta defines the rotation around second axis
  4869. * @param gamma defines the rotation around third axis
  4870. * @returns the new quaternion
  4871. */
  4872. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4873. var result = new Quaternion();
  4874. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4875. return result;
  4876. };
  4877. /**
  4878. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4879. * @param alpha defines the rotation around first axis
  4880. * @param beta defines the rotation around second axis
  4881. * @param gamma defines the rotation around third axis
  4882. * @param result defines the target quaternion
  4883. */
  4884. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4885. // Produces a quaternion from Euler angles in the z-x-z orientation
  4886. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4887. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4888. var halfBeta = beta * 0.5;
  4889. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4890. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4891. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4892. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4893. };
  4894. /**
  4895. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4896. * @param axis1 defines the first axis
  4897. * @param axis2 defines the second axis
  4898. * @param axis3 defines the third axis
  4899. * @returns the new quaternion
  4900. */
  4901. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4902. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4903. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4904. return quat;
  4905. };
  4906. /**
  4907. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4908. * @param axis1 defines the first axis
  4909. * @param axis2 defines the second axis
  4910. * @param axis3 defines the third axis
  4911. * @param ref defines the target quaternion
  4912. */
  4913. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4914. var rotMat = MathTmp.Matrix[0];
  4915. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4916. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4917. };
  4918. /**
  4919. * Interpolates between two quaternions
  4920. * @param left defines first quaternion
  4921. * @param right defines second quaternion
  4922. * @param amount defines the gradient to use
  4923. * @returns the new interpolated quaternion
  4924. */
  4925. Quaternion.Slerp = function (left, right, amount) {
  4926. var result = Quaternion.Identity();
  4927. Quaternion.SlerpToRef(left, right, amount, result);
  4928. return result;
  4929. };
  4930. /**
  4931. * Interpolates between two quaternions and stores it into a target quaternion
  4932. * @param left defines first quaternion
  4933. * @param right defines second quaternion
  4934. * @param amount defines the gradient to use
  4935. * @param result defines the target quaternion
  4936. */
  4937. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4938. var num2;
  4939. var num3;
  4940. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4941. var flag = false;
  4942. if (num4 < 0) {
  4943. flag = true;
  4944. num4 = -num4;
  4945. }
  4946. if (num4 > 0.999999) {
  4947. num3 = 1 - amount;
  4948. num2 = flag ? -amount : amount;
  4949. }
  4950. else {
  4951. var num5 = Math.acos(num4);
  4952. var num6 = (1.0 / Math.sin(num5));
  4953. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4954. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4955. }
  4956. result.x = (num3 * left.x) + (num2 * right.x);
  4957. result.y = (num3 * left.y) + (num2 * right.y);
  4958. result.z = (num3 * left.z) + (num2 * right.z);
  4959. result.w = (num3 * left.w) + (num2 * right.w);
  4960. };
  4961. /**
  4962. * Interpolate between two quaternions using Hermite interpolation
  4963. * @param value1 defines first quaternion
  4964. * @param tangent1 defines the incoming tangent
  4965. * @param value2 defines second quaternion
  4966. * @param tangent2 defines the outgoing tangent
  4967. * @param amount defines the target quaternion
  4968. * @returns the new interpolated quaternion
  4969. */
  4970. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4971. var squared = amount * amount;
  4972. var cubed = amount * squared;
  4973. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4974. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4975. var part3 = (cubed - (2.0 * squared)) + amount;
  4976. var part4 = cubed - squared;
  4977. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4978. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4979. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4980. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4981. return new Quaternion(x, y, z, w);
  4982. };
  4983. return Quaternion;
  4984. }());
  4985. BABYLON.Quaternion = Quaternion;
  4986. /**
  4987. * Class used to store matrix data (4x4)
  4988. */
  4989. var Matrix = /** @class */ (function () {
  4990. /**
  4991. * Creates an empty matrix (filled with zeros)
  4992. */
  4993. function Matrix() {
  4994. this._isIdentity = false;
  4995. this._isIdentityDirty = true;
  4996. /**
  4997. * Gets or sets the internal data of the matrix
  4998. */
  4999. this.m = new Float32Array(16);
  5000. this._markAsUpdated();
  5001. }
  5002. /** @hidden */
  5003. Matrix.prototype._markAsUpdated = function () {
  5004. this.updateFlag = Matrix._updateFlagSeed++;
  5005. this._isIdentityDirty = true;
  5006. };
  5007. // Properties
  5008. /**
  5009. * Check if the current matrix is indentity
  5010. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5011. * @returns true is the matrix is the identity matrix
  5012. */
  5013. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5014. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5015. if (this._isIdentityDirty) {
  5016. this._isIdentityDirty = false;
  5017. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5018. this._isIdentity = false;
  5019. }
  5020. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5021. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5022. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5023. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5024. this._isIdentity = false;
  5025. }
  5026. else {
  5027. this._isIdentity = true;
  5028. }
  5029. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5030. this._isIdentity = false;
  5031. }
  5032. }
  5033. return this._isIdentity;
  5034. };
  5035. /**
  5036. * Gets the determinant of the matrix
  5037. * @returns the matrix determinant
  5038. */
  5039. Matrix.prototype.determinant = function () {
  5040. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5041. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5042. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5043. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5044. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5045. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5046. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5047. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5048. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5049. };
  5050. // Methods
  5051. /**
  5052. * Returns the matrix as a Float32Array
  5053. * @returns the matrix underlying array
  5054. */
  5055. Matrix.prototype.toArray = function () {
  5056. return this.m;
  5057. };
  5058. /**
  5059. * Returns the matrix as a Float32Array
  5060. * @returns the matrix underlying array.
  5061. */
  5062. Matrix.prototype.asArray = function () {
  5063. return this.toArray();
  5064. };
  5065. /**
  5066. * Inverts the current matrix in place
  5067. * @returns the current inverted matrix
  5068. */
  5069. Matrix.prototype.invert = function () {
  5070. this.invertToRef(this);
  5071. return this;
  5072. };
  5073. /**
  5074. * Sets all the matrix elements to zero
  5075. * @returns the current matrix
  5076. */
  5077. Matrix.prototype.reset = function () {
  5078. for (var index = 0; index < 16; index++) {
  5079. this.m[index] = 0.0;
  5080. }
  5081. this._markAsUpdated();
  5082. return this;
  5083. };
  5084. /**
  5085. * Adds the current matrix with a second one
  5086. * @param other defines the matrix to add
  5087. * @returns a new matrix as the addition of the current matrix and the given one
  5088. */
  5089. Matrix.prototype.add = function (other) {
  5090. var result = new Matrix();
  5091. this.addToRef(other, result);
  5092. return result;
  5093. };
  5094. /**
  5095. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5096. * @param other defines the matrix to add
  5097. * @param result defines the target matrix
  5098. * @returns the current matrix
  5099. */
  5100. Matrix.prototype.addToRef = function (other, result) {
  5101. for (var index = 0; index < 16; index++) {
  5102. result.m[index] = this.m[index] + other.m[index];
  5103. }
  5104. result._markAsUpdated();
  5105. return this;
  5106. };
  5107. /**
  5108. * Adds in place the given matrix to the current matrix
  5109. * @param other defines the second operand
  5110. * @returns the current updated matrix
  5111. */
  5112. Matrix.prototype.addToSelf = function (other) {
  5113. for (var index = 0; index < 16; index++) {
  5114. this.m[index] += other.m[index];
  5115. }
  5116. this._markAsUpdated();
  5117. return this;
  5118. };
  5119. /**
  5120. * Sets the given matrix to the current inverted Matrix
  5121. * @param other defines the target matrix
  5122. * @returns the unmodified current matrix
  5123. */
  5124. Matrix.prototype.invertToRef = function (other) {
  5125. var l1 = this.m[0];
  5126. var l2 = this.m[1];
  5127. var l3 = this.m[2];
  5128. var l4 = this.m[3];
  5129. var l5 = this.m[4];
  5130. var l6 = this.m[5];
  5131. var l7 = this.m[6];
  5132. var l8 = this.m[7];
  5133. var l9 = this.m[8];
  5134. var l10 = this.m[9];
  5135. var l11 = this.m[10];
  5136. var l12 = this.m[11];
  5137. var l13 = this.m[12];
  5138. var l14 = this.m[13];
  5139. var l15 = this.m[14];
  5140. var l16 = this.m[15];
  5141. var l17 = (l11 * l16) - (l12 * l15);
  5142. var l18 = (l10 * l16) - (l12 * l14);
  5143. var l19 = (l10 * l15) - (l11 * l14);
  5144. var l20 = (l9 * l16) - (l12 * l13);
  5145. var l21 = (l9 * l15) - (l11 * l13);
  5146. var l22 = (l9 * l14) - (l10 * l13);
  5147. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5148. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5149. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5150. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5151. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5152. var l28 = (l7 * l16) - (l8 * l15);
  5153. var l29 = (l6 * l16) - (l8 * l14);
  5154. var l30 = (l6 * l15) - (l7 * l14);
  5155. var l31 = (l5 * l16) - (l8 * l13);
  5156. var l32 = (l5 * l15) - (l7 * l13);
  5157. var l33 = (l5 * l14) - (l6 * l13);
  5158. var l34 = (l7 * l12) - (l8 * l11);
  5159. var l35 = (l6 * l12) - (l8 * l10);
  5160. var l36 = (l6 * l11) - (l7 * l10);
  5161. var l37 = (l5 * l12) - (l8 * l9);
  5162. var l38 = (l5 * l11) - (l7 * l9);
  5163. var l39 = (l5 * l10) - (l6 * l9);
  5164. other.m[0] = l23 * l27;
  5165. other.m[4] = l24 * l27;
  5166. other.m[8] = l25 * l27;
  5167. other.m[12] = l26 * l27;
  5168. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5169. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5170. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5171. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5172. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5173. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5174. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5175. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5176. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5177. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5178. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5179. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5180. other._markAsUpdated();
  5181. return this;
  5182. };
  5183. /**
  5184. * Inserts the translation vector (using 3 floats) in the current matrix
  5185. * @param x defines the 1st component of the translation
  5186. * @param y defines the 2nd component of the translation
  5187. * @param z defines the 3rd component of the translation
  5188. * @returns the current updated matrix
  5189. */
  5190. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5191. this.m[12] = x;
  5192. this.m[13] = y;
  5193. this.m[14] = z;
  5194. this._markAsUpdated();
  5195. return this;
  5196. };
  5197. /**
  5198. * Inserts the translation vector in the current matrix
  5199. * @param vector3 defines the translation to insert
  5200. * @returns the current updated matrix
  5201. */
  5202. Matrix.prototype.setTranslation = function (vector3) {
  5203. this.m[12] = vector3.x;
  5204. this.m[13] = vector3.y;
  5205. this.m[14] = vector3.z;
  5206. this._markAsUpdated();
  5207. return this;
  5208. };
  5209. /**
  5210. * Gets the translation value of the current matrix
  5211. * @returns a new Vector3 as the extracted translation from the matrix
  5212. */
  5213. Matrix.prototype.getTranslation = function () {
  5214. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5215. };
  5216. /**
  5217. * Fill a Vector3 with the extracted translation from the matrix
  5218. * @param result defines the Vector3 where to store the translation
  5219. * @returns the current matrix
  5220. */
  5221. Matrix.prototype.getTranslationToRef = function (result) {
  5222. result.x = this.m[12];
  5223. result.y = this.m[13];
  5224. result.z = this.m[14];
  5225. return this;
  5226. };
  5227. /**
  5228. * Remove rotation and scaling part from the matrix
  5229. * @returns the updated matrix
  5230. */
  5231. Matrix.prototype.removeRotationAndScaling = function () {
  5232. this.setRowFromFloats(0, 1, 0, 0, 0);
  5233. this.setRowFromFloats(1, 0, 1, 0, 0);
  5234. this.setRowFromFloats(2, 0, 0, 1, 0);
  5235. return this;
  5236. };
  5237. /**
  5238. * Multiply two matrices
  5239. * @param other defines the second operand
  5240. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5241. */
  5242. Matrix.prototype.multiply = function (other) {
  5243. var result = new Matrix();
  5244. this.multiplyToRef(other, result);
  5245. return result;
  5246. };
  5247. /**
  5248. * Copy the current matrix from the given one
  5249. * @param other defines the source matrix
  5250. * @returns the current updated matrix
  5251. */
  5252. Matrix.prototype.copyFrom = function (other) {
  5253. for (var index = 0; index < 16; index++) {
  5254. this.m[index] = other.m[index];
  5255. }
  5256. this._markAsUpdated();
  5257. return this;
  5258. };
  5259. /**
  5260. * Populates the given array from the starting index with the current matrix values
  5261. * @param array defines the target array
  5262. * @param offset defines the offset in the target array where to start storing values
  5263. * @returns the current matrix
  5264. */
  5265. Matrix.prototype.copyToArray = function (array, offset) {
  5266. if (offset === void 0) { offset = 0; }
  5267. for (var index = 0; index < 16; index++) {
  5268. array[offset + index] = this.m[index];
  5269. }
  5270. return this;
  5271. };
  5272. /**
  5273. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5274. * @param other defines the second operand
  5275. * @param result defines the matrix where to store the multiplication
  5276. * @returns the current matrix
  5277. */
  5278. Matrix.prototype.multiplyToRef = function (other, result) {
  5279. this.multiplyToArray(other, result.m, 0);
  5280. result._markAsUpdated();
  5281. return this;
  5282. };
  5283. /**
  5284. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5285. * @param other defines the second operand
  5286. * @param result defines the array where to store the multiplication
  5287. * @param offset defines the offset in the target array where to start storing values
  5288. * @returns the current matrix
  5289. */
  5290. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5291. var tm0 = this.m[0];
  5292. var tm1 = this.m[1];
  5293. var tm2 = this.m[2];
  5294. var tm3 = this.m[3];
  5295. var tm4 = this.m[4];
  5296. var tm5 = this.m[5];
  5297. var tm6 = this.m[6];
  5298. var tm7 = this.m[7];
  5299. var tm8 = this.m[8];
  5300. var tm9 = this.m[9];
  5301. var tm10 = this.m[10];
  5302. var tm11 = this.m[11];
  5303. var tm12 = this.m[12];
  5304. var tm13 = this.m[13];
  5305. var tm14 = this.m[14];
  5306. var tm15 = this.m[15];
  5307. var om0 = other.m[0];
  5308. var om1 = other.m[1];
  5309. var om2 = other.m[2];
  5310. var om3 = other.m[3];
  5311. var om4 = other.m[4];
  5312. var om5 = other.m[5];
  5313. var om6 = other.m[6];
  5314. var om7 = other.m[7];
  5315. var om8 = other.m[8];
  5316. var om9 = other.m[9];
  5317. var om10 = other.m[10];
  5318. var om11 = other.m[11];
  5319. var om12 = other.m[12];
  5320. var om13 = other.m[13];
  5321. var om14 = other.m[14];
  5322. var om15 = other.m[15];
  5323. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5324. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5325. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5326. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5327. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5328. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5329. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5330. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5331. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5332. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5333. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5334. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5335. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5336. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5337. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5338. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5339. return this;
  5340. };
  5341. /**
  5342. * Check equality between this matrix and a second one
  5343. * @param value defines the second matrix to compare
  5344. * @returns true is the current matrix and the given one values are strictly equal
  5345. */
  5346. Matrix.prototype.equals = function (value) {
  5347. return value &&
  5348. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5349. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5350. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5351. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5352. };
  5353. /**
  5354. * Clone the current matrix
  5355. * @returns a new matrix from the current matrix
  5356. */
  5357. Matrix.prototype.clone = function () {
  5358. 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]);
  5359. };
  5360. /**
  5361. * Returns the name of the current matrix class
  5362. * @returns the string "Matrix"
  5363. */
  5364. Matrix.prototype.getClassName = function () {
  5365. return "Matrix";
  5366. };
  5367. /**
  5368. * Gets the hash code of the current matrix
  5369. * @returns the hash code
  5370. */
  5371. Matrix.prototype.getHashCode = function () {
  5372. var hash = this.m[0] || 0;
  5373. for (var i = 1; i < 16; i++) {
  5374. hash = (hash * 397) ^ (this.m[i] || 0);
  5375. }
  5376. return hash;
  5377. };
  5378. /**
  5379. * Decomposes the current Matrix into a translation, rotation and scaling components
  5380. * @param scale defines the scale vector3 given as a reference to update
  5381. * @param rotation defines the rotation quaternion given as a reference to update
  5382. * @param translation defines the translation vector3 given as a reference to update
  5383. * @returns true if operation was successful
  5384. */
  5385. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5386. if (translation) {
  5387. translation.x = this.m[12];
  5388. translation.y = this.m[13];
  5389. translation.z = this.m[14];
  5390. }
  5391. scale = scale || MathTmp.Vector3[0];
  5392. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5393. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5394. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5395. if (this.determinant() <= 0) {
  5396. scale.y *= -1;
  5397. }
  5398. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5399. if (rotation) {
  5400. rotation.x = 0;
  5401. rotation.y = 0;
  5402. rotation.z = 0;
  5403. rotation.w = 1;
  5404. }
  5405. return false;
  5406. }
  5407. if (rotation) {
  5408. 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]);
  5409. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5410. }
  5411. return true;
  5412. };
  5413. /**
  5414. * Gets specific row of the matrix
  5415. * @param index defines the number of the row to get
  5416. * @returns the index-th row of the current matrix as a new Vector4
  5417. */
  5418. Matrix.prototype.getRow = function (index) {
  5419. if (index < 0 || index > 3) {
  5420. return null;
  5421. }
  5422. var i = index * 4;
  5423. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5424. };
  5425. /**
  5426. * Sets the index-th row of the current matrix to the vector4 values
  5427. * @param index defines the number of the row to set
  5428. * @param row defines the target vector4
  5429. * @returns the updated current matrix
  5430. */
  5431. Matrix.prototype.setRow = function (index, row) {
  5432. if (index < 0 || index > 3) {
  5433. return this;
  5434. }
  5435. var i = index * 4;
  5436. this.m[i + 0] = row.x;
  5437. this.m[i + 1] = row.y;
  5438. this.m[i + 2] = row.z;
  5439. this.m[i + 3] = row.w;
  5440. this._markAsUpdated();
  5441. return this;
  5442. };
  5443. /**
  5444. * Compute the transpose of the matrix
  5445. * @returns the new transposed matrix
  5446. */
  5447. Matrix.prototype.transpose = function () {
  5448. return Matrix.Transpose(this);
  5449. };
  5450. /**
  5451. * Compute the transpose of the matrix and store it in a given matrix
  5452. * @param result defines the target matrix
  5453. * @returns the current matrix
  5454. */
  5455. Matrix.prototype.transposeToRef = function (result) {
  5456. Matrix.TransposeToRef(this, result);
  5457. return this;
  5458. };
  5459. /**
  5460. * Sets the index-th row of the current matrix with the given 4 x float values
  5461. * @param index defines the row index
  5462. * @param x defines the x component to set
  5463. * @param y defines the y component to set
  5464. * @param z defines the z component to set
  5465. * @param w defines the w component to set
  5466. * @returns the updated current matrix
  5467. */
  5468. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5469. if (index < 0 || index > 3) {
  5470. return this;
  5471. }
  5472. var i = index * 4;
  5473. this.m[i + 0] = x;
  5474. this.m[i + 1] = y;
  5475. this.m[i + 2] = z;
  5476. this.m[i + 3] = w;
  5477. this._markAsUpdated();
  5478. return this;
  5479. };
  5480. /**
  5481. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5482. * @param scale defines the scale factor
  5483. * @returns a new matrix
  5484. */
  5485. Matrix.prototype.scale = function (scale) {
  5486. var result = new Matrix();
  5487. this.scaleToRef(scale, result);
  5488. return result;
  5489. };
  5490. /**
  5491. * Scale the current matrix values by a factor to a given result matrix
  5492. * @param scale defines the scale factor
  5493. * @param result defines the matrix to store the result
  5494. * @returns the current matrix
  5495. */
  5496. Matrix.prototype.scaleToRef = function (scale, result) {
  5497. for (var index = 0; index < 16; index++) {
  5498. result.m[index] = this.m[index] * scale;
  5499. }
  5500. result._markAsUpdated();
  5501. return this;
  5502. };
  5503. /**
  5504. * Scale the current matrix values by a factor and add the result to a given matrix
  5505. * @param scale defines the scale factor
  5506. * @param result defines the Matrix to store the result
  5507. * @returns the current matrix
  5508. */
  5509. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5510. for (var index = 0; index < 16; index++) {
  5511. result.m[index] += this.m[index] * scale;
  5512. }
  5513. result._markAsUpdated();
  5514. return this;
  5515. };
  5516. /**
  5517. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5518. * @param ref matrix to store the result
  5519. */
  5520. Matrix.prototype.toNormalMatrix = function (ref) {
  5521. this.invertToRef(ref);
  5522. ref.transpose();
  5523. var m = ref.m;
  5524. 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);
  5525. };
  5526. /**
  5527. * Gets only rotation part of the current matrix
  5528. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5529. */
  5530. Matrix.prototype.getRotationMatrix = function () {
  5531. var result = Matrix.Identity();
  5532. this.getRotationMatrixToRef(result);
  5533. return result;
  5534. };
  5535. /**
  5536. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5537. * @param result defines the target matrix to store data to
  5538. * @returns the current matrix
  5539. */
  5540. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5541. var m = this.m;
  5542. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5543. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5544. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5545. if (this.determinant() <= 0) {
  5546. sy *= -1;
  5547. }
  5548. if (sx === 0 || sy === 0 || sz === 0) {
  5549. Matrix.IdentityToRef(result);
  5550. }
  5551. else {
  5552. 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);
  5553. }
  5554. return this;
  5555. };
  5556. // Statics
  5557. /**
  5558. * Creates a matrix from an array
  5559. * @param array defines the source array
  5560. * @param offset defines an offset in the source array
  5561. * @returns a new Matrix set from the starting index of the given array
  5562. */
  5563. Matrix.FromArray = function (array, offset) {
  5564. var result = new Matrix();
  5565. if (!offset) {
  5566. offset = 0;
  5567. }
  5568. Matrix.FromArrayToRef(array, offset, result);
  5569. return result;
  5570. };
  5571. /**
  5572. * Copy the content of an array into a given matrix
  5573. * @param array defines the source array
  5574. * @param offset defines an offset in the source array
  5575. * @param result defines the target matrix
  5576. */
  5577. Matrix.FromArrayToRef = function (array, offset, result) {
  5578. for (var index = 0; index < 16; index++) {
  5579. result.m[index] = array[index + offset];
  5580. }
  5581. result._markAsUpdated();
  5582. };
  5583. /**
  5584. * Stores an array into a matrix after having multiplied each component by a given factor
  5585. * @param array defines the source array
  5586. * @param offset defines the offset in the source array
  5587. * @param scale defines the scaling factor
  5588. * @param result defines the target matrix
  5589. */
  5590. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5591. for (var index = 0; index < 16; index++) {
  5592. result.m[index] = array[index + offset] * scale;
  5593. }
  5594. result._markAsUpdated();
  5595. };
  5596. /**
  5597. * Stores a list of values (16) inside a given matrix
  5598. * @param initialM11 defines 1st value of 1st row
  5599. * @param initialM12 defines 2nd value of 1st row
  5600. * @param initialM13 defines 3rd value of 1st row
  5601. * @param initialM14 defines 4th value of 1st row
  5602. * @param initialM21 defines 1st value of 2nd row
  5603. * @param initialM22 defines 2nd value of 2nd row
  5604. * @param initialM23 defines 3rd value of 2nd row
  5605. * @param initialM24 defines 4th value of 2nd row
  5606. * @param initialM31 defines 1st value of 3rd row
  5607. * @param initialM32 defines 2nd value of 3rd row
  5608. * @param initialM33 defines 3rd value of 3rd row
  5609. * @param initialM34 defines 4th value of 3rd row
  5610. * @param initialM41 defines 1st value of 4th row
  5611. * @param initialM42 defines 2nd value of 4th row
  5612. * @param initialM43 defines 3rd value of 4th row
  5613. * @param initialM44 defines 4th value of 4th row
  5614. * @param result defines the target matrix
  5615. */
  5616. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5617. result.m[0] = initialM11;
  5618. result.m[1] = initialM12;
  5619. result.m[2] = initialM13;
  5620. result.m[3] = initialM14;
  5621. result.m[4] = initialM21;
  5622. result.m[5] = initialM22;
  5623. result.m[6] = initialM23;
  5624. result.m[7] = initialM24;
  5625. result.m[8] = initialM31;
  5626. result.m[9] = initialM32;
  5627. result.m[10] = initialM33;
  5628. result.m[11] = initialM34;
  5629. result.m[12] = initialM41;
  5630. result.m[13] = initialM42;
  5631. result.m[14] = initialM43;
  5632. result.m[15] = initialM44;
  5633. result._markAsUpdated();
  5634. };
  5635. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5636. /**
  5637. * Gets an identity matrix that must not be updated
  5638. */
  5639. get: function () {
  5640. return Matrix._identityReadOnly;
  5641. },
  5642. enumerable: true,
  5643. configurable: true
  5644. });
  5645. /**
  5646. * Creates new matrix from a list of values (16)
  5647. * @param initialM11 defines 1st value of 1st row
  5648. * @param initialM12 defines 2nd value of 1st row
  5649. * @param initialM13 defines 3rd value of 1st row
  5650. * @param initialM14 defines 4th value of 1st row
  5651. * @param initialM21 defines 1st value of 2nd row
  5652. * @param initialM22 defines 2nd value of 2nd row
  5653. * @param initialM23 defines 3rd value of 2nd row
  5654. * @param initialM24 defines 4th value of 2nd row
  5655. * @param initialM31 defines 1st value of 3rd row
  5656. * @param initialM32 defines 2nd value of 3rd row
  5657. * @param initialM33 defines 3rd value of 3rd row
  5658. * @param initialM34 defines 4th value of 3rd row
  5659. * @param initialM41 defines 1st value of 4th row
  5660. * @param initialM42 defines 2nd value of 4th row
  5661. * @param initialM43 defines 3rd value of 4th row
  5662. * @param initialM44 defines 4th value of 4th row
  5663. * @returns the new matrix
  5664. */
  5665. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5666. var result = new Matrix();
  5667. result.m[0] = initialM11;
  5668. result.m[1] = initialM12;
  5669. result.m[2] = initialM13;
  5670. result.m[3] = initialM14;
  5671. result.m[4] = initialM21;
  5672. result.m[5] = initialM22;
  5673. result.m[6] = initialM23;
  5674. result.m[7] = initialM24;
  5675. result.m[8] = initialM31;
  5676. result.m[9] = initialM32;
  5677. result.m[10] = initialM33;
  5678. result.m[11] = initialM34;
  5679. result.m[12] = initialM41;
  5680. result.m[13] = initialM42;
  5681. result.m[14] = initialM43;
  5682. result.m[15] = initialM44;
  5683. return result;
  5684. };
  5685. /**
  5686. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5687. * @param scale defines the scale vector3
  5688. * @param rotation defines the rotation quaternion
  5689. * @param translation defines the translation vector3
  5690. * @returns a new matrix
  5691. */
  5692. Matrix.Compose = function (scale, rotation, translation) {
  5693. var result = Matrix.Identity();
  5694. Matrix.ComposeToRef(scale, rotation, translation, result);
  5695. return result;
  5696. };
  5697. /**
  5698. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5699. * @param scale defines the scale vector3
  5700. * @param rotation defines the rotation quaternion
  5701. * @param translation defines the translation vector3
  5702. * @param result defines the target matrix
  5703. */
  5704. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5705. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5706. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5707. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5708. result.setTranslation(translation);
  5709. };
  5710. /**
  5711. * Creates a new identity matrix
  5712. * @returns a new identity matrix
  5713. */
  5714. Matrix.Identity = function () {
  5715. 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);
  5716. };
  5717. /**
  5718. * Creates a new identity matrix and stores the result in a given matrix
  5719. * @param result defines the target matrix
  5720. */
  5721. Matrix.IdentityToRef = function (result) {
  5722. 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);
  5723. };
  5724. /**
  5725. * Creates a new zero matrix
  5726. * @returns a new zero matrix
  5727. */
  5728. Matrix.Zero = function () {
  5729. 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);
  5730. };
  5731. /**
  5732. * Creates a new rotation matrix for "angle" radians around the X axis
  5733. * @param angle defines the angle (in radians) to use
  5734. * @return the new matrix
  5735. */
  5736. Matrix.RotationX = function (angle) {
  5737. var result = new Matrix();
  5738. Matrix.RotationXToRef(angle, result);
  5739. return result;
  5740. };
  5741. /**
  5742. * Creates a new matrix as the invert of a given matrix
  5743. * @param source defines the source matrix
  5744. * @returns the new matrix
  5745. */
  5746. Matrix.Invert = function (source) {
  5747. var result = new Matrix();
  5748. source.invertToRef(result);
  5749. return result;
  5750. };
  5751. /**
  5752. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5753. * @param angle defines the angle (in radians) to use
  5754. * @param result defines the target matrix
  5755. */
  5756. Matrix.RotationXToRef = function (angle, result) {
  5757. var s = Math.sin(angle);
  5758. var c = Math.cos(angle);
  5759. result.m[0] = 1.0;
  5760. result.m[15] = 1.0;
  5761. result.m[5] = c;
  5762. result.m[10] = c;
  5763. result.m[9] = -s;
  5764. result.m[6] = s;
  5765. result.m[1] = 0.0;
  5766. result.m[2] = 0.0;
  5767. result.m[3] = 0.0;
  5768. result.m[4] = 0.0;
  5769. result.m[7] = 0.0;
  5770. result.m[8] = 0.0;
  5771. result.m[11] = 0.0;
  5772. result.m[12] = 0.0;
  5773. result.m[13] = 0.0;
  5774. result.m[14] = 0.0;
  5775. result._markAsUpdated();
  5776. };
  5777. /**
  5778. * Creates a new rotation matrix for "angle" radians around the Y axis
  5779. * @param angle defines the angle (in radians) to use
  5780. * @return the new matrix
  5781. */
  5782. Matrix.RotationY = function (angle) {
  5783. var result = new Matrix();
  5784. Matrix.RotationYToRef(angle, result);
  5785. return result;
  5786. };
  5787. /**
  5788. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5789. * @param angle defines the angle (in radians) to use
  5790. * @param result defines the target matrix
  5791. */
  5792. Matrix.RotationYToRef = function (angle, result) {
  5793. var s = Math.sin(angle);
  5794. var c = Math.cos(angle);
  5795. result.m[5] = 1.0;
  5796. result.m[15] = 1.0;
  5797. result.m[0] = c;
  5798. result.m[2] = -s;
  5799. result.m[8] = s;
  5800. result.m[10] = c;
  5801. result.m[1] = 0.0;
  5802. result.m[3] = 0.0;
  5803. result.m[4] = 0.0;
  5804. result.m[6] = 0.0;
  5805. result.m[7] = 0.0;
  5806. result.m[9] = 0.0;
  5807. result.m[11] = 0.0;
  5808. result.m[12] = 0.0;
  5809. result.m[13] = 0.0;
  5810. result.m[14] = 0.0;
  5811. result._markAsUpdated();
  5812. };
  5813. /**
  5814. * Creates a new rotation matrix for "angle" radians around the Z axis
  5815. * @param angle defines the angle (in radians) to use
  5816. * @return the new matrix
  5817. */
  5818. Matrix.RotationZ = function (angle) {
  5819. var result = new Matrix();
  5820. Matrix.RotationZToRef(angle, result);
  5821. return result;
  5822. };
  5823. /**
  5824. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5825. * @param angle defines the angle (in radians) to use
  5826. * @param result defines the target matrix
  5827. */
  5828. Matrix.RotationZToRef = function (angle, result) {
  5829. var s = Math.sin(angle);
  5830. var c = Math.cos(angle);
  5831. result.m[10] = 1.0;
  5832. result.m[15] = 1.0;
  5833. result.m[0] = c;
  5834. result.m[1] = s;
  5835. result.m[4] = -s;
  5836. result.m[5] = c;
  5837. result.m[2] = 0.0;
  5838. result.m[3] = 0.0;
  5839. result.m[6] = 0.0;
  5840. result.m[7] = 0.0;
  5841. result.m[8] = 0.0;
  5842. result.m[9] = 0.0;
  5843. result.m[11] = 0.0;
  5844. result.m[12] = 0.0;
  5845. result.m[13] = 0.0;
  5846. result.m[14] = 0.0;
  5847. result._markAsUpdated();
  5848. };
  5849. /**
  5850. * Creates a new rotation matrix for "angle" radians around the given axis
  5851. * @param axis defines the axis to use
  5852. * @param angle defines the angle (in radians) to use
  5853. * @return the new matrix
  5854. */
  5855. Matrix.RotationAxis = function (axis, angle) {
  5856. var result = Matrix.Zero();
  5857. Matrix.RotationAxisToRef(axis, angle, result);
  5858. return result;
  5859. };
  5860. /**
  5861. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5862. * @param axis defines the axis to use
  5863. * @param angle defines the angle (in radians) to use
  5864. * @param result defines the target matrix
  5865. */
  5866. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5867. var s = Math.sin(-angle);
  5868. var c = Math.cos(-angle);
  5869. var c1 = 1 - c;
  5870. axis.normalize();
  5871. result.m[0] = (axis.x * axis.x) * c1 + c;
  5872. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5873. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5874. result.m[3] = 0.0;
  5875. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5876. result.m[5] = (axis.y * axis.y) * c1 + c;
  5877. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5878. result.m[7] = 0.0;
  5879. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5880. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5881. result.m[10] = (axis.z * axis.z) * c1 + c;
  5882. result.m[11] = 0.0;
  5883. result.m[15] = 1.0;
  5884. result._markAsUpdated();
  5885. };
  5886. /**
  5887. * Creates a rotation matrix
  5888. * @param yaw defines the yaw angle in radians (Y axis)
  5889. * @param pitch defines the pitch angle in radians (X axis)
  5890. * @param roll defines the roll angle in radians (X axis)
  5891. * @returns the new rotation matrix
  5892. */
  5893. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5894. var result = new Matrix();
  5895. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5896. return result;
  5897. };
  5898. /**
  5899. * Creates a rotation matrix and stores it in a given matrix
  5900. * @param yaw defines the yaw angle in radians (Y axis)
  5901. * @param pitch defines the pitch angle in radians (X axis)
  5902. * @param roll defines the roll angle in radians (X axis)
  5903. * @param result defines the target matrix
  5904. */
  5905. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5906. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5907. this._tempQuaternion.toRotationMatrix(result);
  5908. };
  5909. /**
  5910. * Creates a scaling matrix
  5911. * @param x defines the scale factor on X axis
  5912. * @param y defines the scale factor on Y axis
  5913. * @param z defines the scale factor on Z axis
  5914. * @returns the new matrix
  5915. */
  5916. Matrix.Scaling = function (x, y, z) {
  5917. var result = Matrix.Zero();
  5918. Matrix.ScalingToRef(x, y, z, result);
  5919. return result;
  5920. };
  5921. /**
  5922. * Creates a scaling matrix and stores it in a given matrix
  5923. * @param x defines the scale factor on X axis
  5924. * @param y defines the scale factor on Y axis
  5925. * @param z defines the scale factor on Z axis
  5926. * @param result defines the target matrix
  5927. */
  5928. Matrix.ScalingToRef = function (x, y, z, result) {
  5929. result.m[0] = x;
  5930. result.m[1] = 0.0;
  5931. result.m[2] = 0.0;
  5932. result.m[3] = 0.0;
  5933. result.m[4] = 0.0;
  5934. result.m[5] = y;
  5935. result.m[6] = 0.0;
  5936. result.m[7] = 0.0;
  5937. result.m[8] = 0.0;
  5938. result.m[9] = 0.0;
  5939. result.m[10] = z;
  5940. result.m[11] = 0.0;
  5941. result.m[12] = 0.0;
  5942. result.m[13] = 0.0;
  5943. result.m[14] = 0.0;
  5944. result.m[15] = 1.0;
  5945. result._markAsUpdated();
  5946. };
  5947. /**
  5948. * Creates a translation matrix
  5949. * @param x defines the translation on X axis
  5950. * @param y defines the translation on Y axis
  5951. * @param z defines the translationon Z axis
  5952. * @returns the new matrix
  5953. */
  5954. Matrix.Translation = function (x, y, z) {
  5955. var result = Matrix.Identity();
  5956. Matrix.TranslationToRef(x, y, z, result);
  5957. return result;
  5958. };
  5959. /**
  5960. * Creates a translation matrix and stores it in a given matrix
  5961. * @param x defines the translation on X axis
  5962. * @param y defines the translation on Y axis
  5963. * @param z defines the translationon Z axis
  5964. * @param result defines the target matrix
  5965. */
  5966. Matrix.TranslationToRef = function (x, y, z, result) {
  5967. 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);
  5968. };
  5969. /**
  5970. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5971. * @param startValue defines the start value
  5972. * @param endValue defines the end value
  5973. * @param gradient defines the gradient factor
  5974. * @returns the new matrix
  5975. */
  5976. Matrix.Lerp = function (startValue, endValue, gradient) {
  5977. var result = Matrix.Zero();
  5978. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5979. return result;
  5980. };
  5981. /**
  5982. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5983. * @param startValue defines the start value
  5984. * @param endValue defines the end value
  5985. * @param gradient defines the gradient factor
  5986. * @param result defines the Matrix object where to store data
  5987. */
  5988. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5989. for (var index = 0; index < 16; index++) {
  5990. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5991. }
  5992. result._markAsUpdated();
  5993. };
  5994. /**
  5995. * Builds a new matrix whose values are computed by:
  5996. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5997. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5998. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5999. * @param startValue defines the first matrix
  6000. * @param endValue defines the second matrix
  6001. * @param gradient defines the gradient between the two matrices
  6002. * @returns the new matrix
  6003. */
  6004. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6005. var result = Matrix.Zero();
  6006. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6007. return result;
  6008. };
  6009. /**
  6010. * Update a matrix to values which are computed by:
  6011. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6012. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6013. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6014. * @param startValue defines the first matrix
  6015. * @param endValue defines the second matrix
  6016. * @param gradient defines the gradient between the two matrices
  6017. * @param result defines the target matrix
  6018. */
  6019. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6020. var startScale = MathTmp.Vector3[0];
  6021. var startRotation = MathTmp.Quaternion[0];
  6022. var startTranslation = MathTmp.Vector3[1];
  6023. startValue.decompose(startScale, startRotation, startTranslation);
  6024. var endScale = MathTmp.Vector3[2];
  6025. var endRotation = MathTmp.Quaternion[1];
  6026. var endTranslation = MathTmp.Vector3[3];
  6027. endValue.decompose(endScale, endRotation, endTranslation);
  6028. var resultScale = MathTmp.Vector3[4];
  6029. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6030. var resultRotation = MathTmp.Quaternion[2];
  6031. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6032. var resultTranslation = MathTmp.Vector3[5];
  6033. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6034. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6035. };
  6036. /**
  6037. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6038. * This function works in left handed mode
  6039. * @param eye defines the final position of the entity
  6040. * @param target defines where the entity should look at
  6041. * @param up defines the up vector for the entity
  6042. * @returns the new matrix
  6043. */
  6044. Matrix.LookAtLH = function (eye, target, up) {
  6045. var result = Matrix.Zero();
  6046. Matrix.LookAtLHToRef(eye, target, up, result);
  6047. return result;
  6048. };
  6049. /**
  6050. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6051. * This function works in left handed mode
  6052. * @param eye defines the final position of the entity
  6053. * @param target defines where the entity should look at
  6054. * @param up defines the up vector for the entity
  6055. * @param result defines the target matrix
  6056. */
  6057. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6058. // Z axis
  6059. target.subtractToRef(eye, this._zAxis);
  6060. this._zAxis.normalize();
  6061. // X axis
  6062. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6063. if (this._xAxis.lengthSquared() === 0) {
  6064. this._xAxis.x = 1.0;
  6065. }
  6066. else {
  6067. this._xAxis.normalize();
  6068. }
  6069. // Y axis
  6070. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6071. this._yAxis.normalize();
  6072. // Eye angles
  6073. var ex = -Vector3.Dot(this._xAxis, eye);
  6074. var ey = -Vector3.Dot(this._yAxis, eye);
  6075. var ez = -Vector3.Dot(this._zAxis, eye);
  6076. 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);
  6077. };
  6078. /**
  6079. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6080. * This function works in right handed mode
  6081. * @param eye defines the final position of the entity
  6082. * @param target defines where the entity should look at
  6083. * @param up defines the up vector for the entity
  6084. * @returns the new matrix
  6085. */
  6086. Matrix.LookAtRH = function (eye, target, up) {
  6087. var result = Matrix.Zero();
  6088. Matrix.LookAtRHToRef(eye, target, up, result);
  6089. return result;
  6090. };
  6091. /**
  6092. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6093. * This function works in right handed mode
  6094. * @param eye defines the final position of the entity
  6095. * @param target defines where the entity should look at
  6096. * @param up defines the up vector for the entity
  6097. * @param result defines the target matrix
  6098. */
  6099. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6100. // Z axis
  6101. eye.subtractToRef(target, this._zAxis);
  6102. this._zAxis.normalize();
  6103. // X axis
  6104. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6105. if (this._xAxis.lengthSquared() === 0) {
  6106. this._xAxis.x = 1.0;
  6107. }
  6108. else {
  6109. this._xAxis.normalize();
  6110. }
  6111. // Y axis
  6112. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6113. this._yAxis.normalize();
  6114. // Eye angles
  6115. var ex = -Vector3.Dot(this._xAxis, eye);
  6116. var ey = -Vector3.Dot(this._yAxis, eye);
  6117. var ez = -Vector3.Dot(this._zAxis, eye);
  6118. 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);
  6119. };
  6120. /**
  6121. * Create a left-handed orthographic projection matrix
  6122. * @param width defines the viewport width
  6123. * @param height defines the viewport height
  6124. * @param znear defines the near clip plane
  6125. * @param zfar defines the far clip plane
  6126. * @returns a new matrix as a left-handed orthographic projection matrix
  6127. */
  6128. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6129. var matrix = Matrix.Zero();
  6130. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6131. return matrix;
  6132. };
  6133. /**
  6134. * Store a left-handed orthographic projection to a given matrix
  6135. * @param width defines the viewport width
  6136. * @param height defines the viewport height
  6137. * @param znear defines the near clip plane
  6138. * @param zfar defines the far clip plane
  6139. * @param result defines the target matrix
  6140. */
  6141. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6142. var n = znear;
  6143. var f = zfar;
  6144. var a = 2.0 / width;
  6145. var b = 2.0 / height;
  6146. var c = 2.0 / (f - n);
  6147. var d = -(f + n) / (f - n);
  6148. 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);
  6149. };
  6150. /**
  6151. * Create a left-handed orthographic projection matrix
  6152. * @param left defines the viewport left coordinate
  6153. * @param right defines the viewport right coordinate
  6154. * @param bottom defines the viewport bottom coordinate
  6155. * @param top defines the viewport top coordinate
  6156. * @param znear defines the near clip plane
  6157. * @param zfar defines the far clip plane
  6158. * @returns a new matrix as a left-handed orthographic projection matrix
  6159. */
  6160. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6161. var matrix = Matrix.Zero();
  6162. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6163. return matrix;
  6164. };
  6165. /**
  6166. * Stores a left-handed orthographic projection into a given matrix
  6167. * @param left defines the viewport left coordinate
  6168. * @param right defines the viewport right coordinate
  6169. * @param bottom defines the viewport bottom coordinate
  6170. * @param top defines the viewport top coordinate
  6171. * @param znear defines the near clip plane
  6172. * @param zfar defines the far clip plane
  6173. * @param result defines the target matrix
  6174. */
  6175. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6176. var n = znear;
  6177. var f = zfar;
  6178. var a = 2.0 / (right - left);
  6179. var b = 2.0 / (top - bottom);
  6180. var c = 2.0 / (f - n);
  6181. var d = -(f + n) / (f - n);
  6182. var i0 = (left + right) / (left - right);
  6183. var i1 = (top + bottom) / (bottom - top);
  6184. 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);
  6185. };
  6186. /**
  6187. * Creates a right-handed orthographic projection matrix
  6188. * @param left defines the viewport left coordinate
  6189. * @param right defines the viewport right coordinate
  6190. * @param bottom defines the viewport bottom coordinate
  6191. * @param top defines the viewport top coordinate
  6192. * @param znear defines the near clip plane
  6193. * @param zfar defines the far clip plane
  6194. * @returns a new matrix as a right-handed orthographic projection matrix
  6195. */
  6196. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6197. var matrix = Matrix.Zero();
  6198. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6199. return matrix;
  6200. };
  6201. /**
  6202. * Stores a right-handed orthographic projection into a given matrix
  6203. * @param left defines the viewport left coordinate
  6204. * @param right defines the viewport right coordinate
  6205. * @param bottom defines the viewport bottom coordinate
  6206. * @param top defines the viewport top coordinate
  6207. * @param znear defines the near clip plane
  6208. * @param zfar defines the far clip plane
  6209. * @param result defines the target matrix
  6210. */
  6211. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6212. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6213. result.m[10] *= -1.0;
  6214. };
  6215. /**
  6216. * Creates a left-handed perspective projection matrix
  6217. * @param width defines the viewport width
  6218. * @param height defines the viewport height
  6219. * @param znear defines the near clip plane
  6220. * @param zfar defines the far clip plane
  6221. * @returns a new matrix as a left-handed perspective projection matrix
  6222. */
  6223. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6224. var matrix = Matrix.Zero();
  6225. var n = znear;
  6226. var f = zfar;
  6227. var a = 2.0 * n / width;
  6228. var b = 2.0 * n / height;
  6229. var c = (f + n) / (f - n);
  6230. var d = -2.0 * f * n / (f - n);
  6231. 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);
  6232. return matrix;
  6233. };
  6234. /**
  6235. * Creates a left-handed perspective projection matrix
  6236. * @param fov defines the horizontal field of view
  6237. * @param aspect defines the aspect ratio
  6238. * @param znear defines the near clip plane
  6239. * @param zfar defines the far clip plane
  6240. * @returns a new matrix as a left-handed perspective projection matrix
  6241. */
  6242. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6243. var matrix = Matrix.Zero();
  6244. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6245. return matrix;
  6246. };
  6247. /**
  6248. * Stores a left-handed perspective projection into a given matrix
  6249. * @param fov defines the horizontal field of view
  6250. * @param aspect defines the aspect ratio
  6251. * @param znear defines the near clip plane
  6252. * @param zfar defines the far clip plane
  6253. * @param result defines the target matrix
  6254. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6255. */
  6256. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6257. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6258. var n = znear;
  6259. var f = zfar;
  6260. var t = 1.0 / (Math.tan(fov * 0.5));
  6261. var a = isVerticalFovFixed ? (t / aspect) : t;
  6262. var b = isVerticalFovFixed ? t : (t * aspect);
  6263. var c = (f + n) / (f - n);
  6264. var d = -2.0 * f * n / (f - n);
  6265. 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);
  6266. };
  6267. /**
  6268. * Creates a right-handed perspective projection matrix
  6269. * @param fov defines the horizontal field of view
  6270. * @param aspect defines the aspect ratio
  6271. * @param znear defines the near clip plane
  6272. * @param zfar defines the far clip plane
  6273. * @returns a new matrix as a right-handed perspective projection matrix
  6274. */
  6275. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6276. var matrix = Matrix.Zero();
  6277. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6278. return matrix;
  6279. };
  6280. /**
  6281. * Stores a right-handed perspective projection into a given matrix
  6282. * @param fov defines the horizontal field of view
  6283. * @param aspect defines the aspect ratio
  6284. * @param znear defines the near clip plane
  6285. * @param zfar defines the far clip plane
  6286. * @param result defines the target matrix
  6287. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6288. */
  6289. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6290. //alternatively this could be expressed as:
  6291. // m = PerspectiveFovLHToRef
  6292. // m[10] *= -1.0;
  6293. // m[11] *= -1.0;
  6294. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6295. var n = znear;
  6296. var f = zfar;
  6297. var t = 1.0 / (Math.tan(fov * 0.5));
  6298. var a = isVerticalFovFixed ? (t / aspect) : t;
  6299. var b = isVerticalFovFixed ? t : (t * aspect);
  6300. var c = -(f + n) / (f - n);
  6301. var d = -2 * f * n / (f - n);
  6302. 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);
  6303. };
  6304. /**
  6305. * Stores a perspective projection for WebVR info a given matrix
  6306. * @param fov defines the field of view
  6307. * @param znear defines the near clip plane
  6308. * @param zfar defines the far clip plane
  6309. * @param result defines the target matrix
  6310. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6311. */
  6312. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6313. if (rightHanded === void 0) { rightHanded = false; }
  6314. var rightHandedFactor = rightHanded ? -1 : 1;
  6315. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6316. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6317. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6318. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6319. var xScale = 2.0 / (leftTan + rightTan);
  6320. var yScale = 2.0 / (upTan + downTan);
  6321. result.m[0] = xScale;
  6322. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6323. result.m[5] = yScale;
  6324. result.m[6] = result.m[7] = 0.0;
  6325. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6326. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6327. result.m[10] = -zfar / (znear - zfar);
  6328. result.m[11] = 1.0 * rightHandedFactor;
  6329. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6330. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6331. result._markAsUpdated();
  6332. };
  6333. /**
  6334. * Computes a complete transformation matrix
  6335. * @param viewport defines the viewport to use
  6336. * @param world defines the world matrix
  6337. * @param view defines the view matrix
  6338. * @param projection defines the projection matrix
  6339. * @param zmin defines the near clip plane
  6340. * @param zmax defines the far clip plane
  6341. * @returns the transformation matrix
  6342. */
  6343. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6344. var cw = viewport.width;
  6345. var ch = viewport.height;
  6346. var cx = viewport.x;
  6347. var cy = viewport.y;
  6348. 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);
  6349. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6350. };
  6351. /**
  6352. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6353. * @param matrix defines the matrix to use
  6354. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6355. */
  6356. Matrix.GetAsMatrix2x2 = function (matrix) {
  6357. return new Float32Array([
  6358. matrix.m[0], matrix.m[1],
  6359. matrix.m[4], matrix.m[5]
  6360. ]);
  6361. };
  6362. /**
  6363. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6364. * @param matrix defines the matrix to use
  6365. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6366. */
  6367. Matrix.GetAsMatrix3x3 = function (matrix) {
  6368. return new Float32Array([
  6369. matrix.m[0], matrix.m[1], matrix.m[2],
  6370. matrix.m[4], matrix.m[5], matrix.m[6],
  6371. matrix.m[8], matrix.m[9], matrix.m[10]
  6372. ]);
  6373. };
  6374. /**
  6375. * Compute the transpose of a given matrix
  6376. * @param matrix defines the matrix to transpose
  6377. * @returns the new matrix
  6378. */
  6379. Matrix.Transpose = function (matrix) {
  6380. var result = new Matrix();
  6381. Matrix.TransposeToRef(matrix, result);
  6382. return result;
  6383. };
  6384. /**
  6385. * Compute the transpose of a matrix and store it in a target matrix
  6386. * @param matrix defines the matrix to transpose
  6387. * @param result defines the target matrix
  6388. */
  6389. Matrix.TransposeToRef = function (matrix, result) {
  6390. result.m[0] = matrix.m[0];
  6391. result.m[1] = matrix.m[4];
  6392. result.m[2] = matrix.m[8];
  6393. result.m[3] = matrix.m[12];
  6394. result.m[4] = matrix.m[1];
  6395. result.m[5] = matrix.m[5];
  6396. result.m[6] = matrix.m[9];
  6397. result.m[7] = matrix.m[13];
  6398. result.m[8] = matrix.m[2];
  6399. result.m[9] = matrix.m[6];
  6400. result.m[10] = matrix.m[10];
  6401. result.m[11] = matrix.m[14];
  6402. result.m[12] = matrix.m[3];
  6403. result.m[13] = matrix.m[7];
  6404. result.m[14] = matrix.m[11];
  6405. result.m[15] = matrix.m[15];
  6406. };
  6407. /**
  6408. * Computes a reflection matrix from a plane
  6409. * @param plane defines the reflection plane
  6410. * @returns a new matrix
  6411. */
  6412. Matrix.Reflection = function (plane) {
  6413. var matrix = new Matrix();
  6414. Matrix.ReflectionToRef(plane, matrix);
  6415. return matrix;
  6416. };
  6417. /**
  6418. * Computes a reflection matrix from a plane
  6419. * @param plane defines the reflection plane
  6420. * @param result defines the target matrix
  6421. */
  6422. Matrix.ReflectionToRef = function (plane, result) {
  6423. plane.normalize();
  6424. var x = plane.normal.x;
  6425. var y = plane.normal.y;
  6426. var z = plane.normal.z;
  6427. var temp = -2 * x;
  6428. var temp2 = -2 * y;
  6429. var temp3 = -2 * z;
  6430. result.m[0] = (temp * x) + 1;
  6431. result.m[1] = temp2 * x;
  6432. result.m[2] = temp3 * x;
  6433. result.m[3] = 0.0;
  6434. result.m[4] = temp * y;
  6435. result.m[5] = (temp2 * y) + 1;
  6436. result.m[6] = temp3 * y;
  6437. result.m[7] = 0.0;
  6438. result.m[8] = temp * z;
  6439. result.m[9] = temp2 * z;
  6440. result.m[10] = (temp3 * z) + 1;
  6441. result.m[11] = 0.0;
  6442. result.m[12] = temp * plane.d;
  6443. result.m[13] = temp2 * plane.d;
  6444. result.m[14] = temp3 * plane.d;
  6445. result.m[15] = 1.0;
  6446. result._markAsUpdated();
  6447. };
  6448. /**
  6449. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6450. * @param xaxis defines the value of the 1st axis
  6451. * @param yaxis defines the value of the 2nd axis
  6452. * @param zaxis defines the value of the 3rd axis
  6453. * @param result defines the target matrix
  6454. */
  6455. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6456. result.m[0] = xaxis.x;
  6457. result.m[1] = xaxis.y;
  6458. result.m[2] = xaxis.z;
  6459. result.m[3] = 0.0;
  6460. result.m[4] = yaxis.x;
  6461. result.m[5] = yaxis.y;
  6462. result.m[6] = yaxis.z;
  6463. result.m[7] = 0.0;
  6464. result.m[8] = zaxis.x;
  6465. result.m[9] = zaxis.y;
  6466. result.m[10] = zaxis.z;
  6467. result.m[11] = 0.0;
  6468. result.m[12] = 0.0;
  6469. result.m[13] = 0.0;
  6470. result.m[14] = 0.0;
  6471. result.m[15] = 1.0;
  6472. result._markAsUpdated();
  6473. };
  6474. /**
  6475. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6476. * @param quat defines the quaternion to use
  6477. * @param result defines the target matrix
  6478. */
  6479. Matrix.FromQuaternionToRef = function (quat, result) {
  6480. var xx = quat.x * quat.x;
  6481. var yy = quat.y * quat.y;
  6482. var zz = quat.z * quat.z;
  6483. var xy = quat.x * quat.y;
  6484. var zw = quat.z * quat.w;
  6485. var zx = quat.z * quat.x;
  6486. var yw = quat.y * quat.w;
  6487. var yz = quat.y * quat.z;
  6488. var xw = quat.x * quat.w;
  6489. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6490. result.m[1] = 2.0 * (xy + zw);
  6491. result.m[2] = 2.0 * (zx - yw);
  6492. result.m[3] = 0.0;
  6493. result.m[4] = 2.0 * (xy - zw);
  6494. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6495. result.m[6] = 2.0 * (yz + xw);
  6496. result.m[7] = 0.0;
  6497. result.m[8] = 2.0 * (zx + yw);
  6498. result.m[9] = 2.0 * (yz - xw);
  6499. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6500. result.m[11] = 0.0;
  6501. result.m[12] = 0.0;
  6502. result.m[13] = 0.0;
  6503. result.m[14] = 0.0;
  6504. result.m[15] = 1.0;
  6505. result._markAsUpdated();
  6506. };
  6507. Matrix._tempQuaternion = new Quaternion();
  6508. Matrix._xAxis = Vector3.Zero();
  6509. Matrix._yAxis = Vector3.Zero();
  6510. Matrix._zAxis = Vector3.Zero();
  6511. Matrix._updateFlagSeed = 0;
  6512. Matrix._identityReadOnly = Matrix.Identity();
  6513. return Matrix;
  6514. }());
  6515. BABYLON.Matrix = Matrix;
  6516. var Plane = /** @class */ (function () {
  6517. /**
  6518. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6519. */
  6520. function Plane(a, b, c, d) {
  6521. this.normal = new Vector3(a, b, c);
  6522. this.d = d;
  6523. }
  6524. /**
  6525. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6526. */
  6527. Plane.prototype.asArray = function () {
  6528. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6529. };
  6530. // Methods
  6531. /**
  6532. * Returns a new plane copied from the current Plane.
  6533. */
  6534. Plane.prototype.clone = function () {
  6535. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6536. };
  6537. /**
  6538. * Returns the string "Plane".
  6539. */
  6540. Plane.prototype.getClassName = function () {
  6541. return "Plane";
  6542. };
  6543. /**
  6544. * Returns the Plane hash code.
  6545. */
  6546. Plane.prototype.getHashCode = function () {
  6547. var hash = this.normal.getHashCode();
  6548. hash = (hash * 397) ^ (this.d || 0);
  6549. return hash;
  6550. };
  6551. /**
  6552. * Normalize the current Plane in place.
  6553. * Returns the updated Plane.
  6554. */
  6555. Plane.prototype.normalize = function () {
  6556. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6557. var magnitude = 0.0;
  6558. if (norm !== 0) {
  6559. magnitude = 1.0 / norm;
  6560. }
  6561. this.normal.x *= magnitude;
  6562. this.normal.y *= magnitude;
  6563. this.normal.z *= magnitude;
  6564. this.d *= magnitude;
  6565. return this;
  6566. };
  6567. /**
  6568. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6569. */
  6570. Plane.prototype.transform = function (transformation) {
  6571. var transposedMatrix = Matrix.Transpose(transformation);
  6572. var x = this.normal.x;
  6573. var y = this.normal.y;
  6574. var z = this.normal.z;
  6575. var d = this.d;
  6576. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6577. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6578. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6579. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6580. return new Plane(normalX, normalY, normalZ, finalD);
  6581. };
  6582. /**
  6583. * Returns the dot product (float) of the point coordinates and the plane normal.
  6584. */
  6585. Plane.prototype.dotCoordinate = function (point) {
  6586. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6587. };
  6588. /**
  6589. * Updates the current Plane from the plane defined by the three given points.
  6590. * Returns the updated Plane.
  6591. */
  6592. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6593. var x1 = point2.x - point1.x;
  6594. var y1 = point2.y - point1.y;
  6595. var z1 = point2.z - point1.z;
  6596. var x2 = point3.x - point1.x;
  6597. var y2 = point3.y - point1.y;
  6598. var z2 = point3.z - point1.z;
  6599. var yz = (y1 * z2) - (z1 * y2);
  6600. var xz = (z1 * x2) - (x1 * z2);
  6601. var xy = (x1 * y2) - (y1 * x2);
  6602. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6603. var invPyth;
  6604. if (pyth !== 0) {
  6605. invPyth = 1.0 / pyth;
  6606. }
  6607. else {
  6608. invPyth = 0.0;
  6609. }
  6610. this.normal.x = yz * invPyth;
  6611. this.normal.y = xz * invPyth;
  6612. this.normal.z = xy * invPyth;
  6613. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6614. return this;
  6615. };
  6616. /**
  6617. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6618. */
  6619. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6620. var dot = Vector3.Dot(this.normal, direction);
  6621. return (dot <= epsilon);
  6622. };
  6623. /**
  6624. * Returns the signed distance (float) from the given point to the Plane.
  6625. */
  6626. Plane.prototype.signedDistanceTo = function (point) {
  6627. return Vector3.Dot(point, this.normal) + this.d;
  6628. };
  6629. // Statics
  6630. /**
  6631. * Returns a new Plane from the given array.
  6632. */
  6633. Plane.FromArray = function (array) {
  6634. return new Plane(array[0], array[1], array[2], array[3]);
  6635. };
  6636. /**
  6637. * Returns a new Plane defined by the three given points.
  6638. */
  6639. Plane.FromPoints = function (point1, point2, point3) {
  6640. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6641. result.copyFromPoints(point1, point2, point3);
  6642. return result;
  6643. };
  6644. /**
  6645. * Returns a new Plane the normal vector to this plane at the given origin point.
  6646. * Note : the vector "normal" is updated because normalized.
  6647. */
  6648. Plane.FromPositionAndNormal = function (origin, normal) {
  6649. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6650. normal.normalize();
  6651. result.normal = normal;
  6652. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6653. return result;
  6654. };
  6655. /**
  6656. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6657. */
  6658. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6659. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6660. return Vector3.Dot(point, normal) + d;
  6661. };
  6662. return Plane;
  6663. }());
  6664. BABYLON.Plane = Plane;
  6665. var Viewport = /** @class */ (function () {
  6666. /**
  6667. * Creates a Viewport object located at (x, y) and sized (width, height).
  6668. */
  6669. function Viewport(x, y, width, height) {
  6670. this.x = x;
  6671. this.y = y;
  6672. this.width = width;
  6673. this.height = height;
  6674. }
  6675. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6676. if (renderWidthOrEngine.getRenderWidth) {
  6677. var engine = renderWidthOrEngine;
  6678. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6679. }
  6680. var renderWidth = renderWidthOrEngine;
  6681. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6682. };
  6683. /**
  6684. * Returns a new Viewport copied from the current one.
  6685. */
  6686. Viewport.prototype.clone = function () {
  6687. return new Viewport(this.x, this.y, this.width, this.height);
  6688. };
  6689. return Viewport;
  6690. }());
  6691. BABYLON.Viewport = Viewport;
  6692. var Frustum = /** @class */ (function () {
  6693. function Frustum() {
  6694. }
  6695. /**
  6696. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6697. */
  6698. Frustum.GetPlanes = function (transform) {
  6699. var frustumPlanes = [];
  6700. for (var index = 0; index < 6; index++) {
  6701. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6702. }
  6703. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6704. return frustumPlanes;
  6705. };
  6706. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6707. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6708. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6709. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6710. frustumPlane.d = transform.m[15] + transform.m[14];
  6711. frustumPlane.normalize();
  6712. };
  6713. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6714. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6715. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6716. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6717. frustumPlane.d = transform.m[15] - transform.m[14];
  6718. frustumPlane.normalize();
  6719. };
  6720. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6721. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6722. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6723. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6724. frustumPlane.d = transform.m[15] + transform.m[12];
  6725. frustumPlane.normalize();
  6726. };
  6727. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6728. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6729. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6730. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6731. frustumPlane.d = transform.m[15] - transform.m[12];
  6732. frustumPlane.normalize();
  6733. };
  6734. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6735. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6736. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6737. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6738. frustumPlane.d = transform.m[15] - transform.m[13];
  6739. frustumPlane.normalize();
  6740. };
  6741. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6742. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6743. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6744. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6745. frustumPlane.d = transform.m[15] + transform.m[13];
  6746. frustumPlane.normalize();
  6747. };
  6748. /**
  6749. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6750. */
  6751. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6752. // Near
  6753. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6754. // Far
  6755. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6756. // Left
  6757. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6758. // Right
  6759. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6760. // Top
  6761. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6762. // Bottom
  6763. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6764. };
  6765. return Frustum;
  6766. }());
  6767. BABYLON.Frustum = Frustum;
  6768. /** Defines supported spaces */
  6769. var Space;
  6770. (function (Space) {
  6771. /** Local (object) space */
  6772. Space[Space["LOCAL"] = 0] = "LOCAL";
  6773. /** World space */
  6774. Space[Space["WORLD"] = 1] = "WORLD";
  6775. /** Bone space */
  6776. Space[Space["BONE"] = 2] = "BONE";
  6777. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6778. /** Defines the 3 main axes */
  6779. var Axis = /** @class */ (function () {
  6780. function Axis() {
  6781. }
  6782. /** X axis */
  6783. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6784. /** Y axis */
  6785. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6786. /** Z axis */
  6787. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6788. return Axis;
  6789. }());
  6790. BABYLON.Axis = Axis;
  6791. ;
  6792. var BezierCurve = /** @class */ (function () {
  6793. function BezierCurve() {
  6794. }
  6795. /**
  6796. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6797. */
  6798. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6799. // Extract X (which is equal to time here)
  6800. var f0 = 1 - 3 * x2 + 3 * x1;
  6801. var f1 = 3 * x2 - 6 * x1;
  6802. var f2 = 3 * x1;
  6803. var refinedT = t;
  6804. for (var i = 0; i < 5; i++) {
  6805. var refinedT2 = refinedT * refinedT;
  6806. var refinedT3 = refinedT2 * refinedT;
  6807. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6808. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6809. refinedT -= (x - t) * slope;
  6810. refinedT = Math.min(1, Math.max(0, refinedT));
  6811. }
  6812. // Resolve cubic bezier for the given x
  6813. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6814. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6815. Math.pow(refinedT, 3);
  6816. };
  6817. return BezierCurve;
  6818. }());
  6819. BABYLON.BezierCurve = BezierCurve;
  6820. /**
  6821. * Defines potential orientation for back face culling
  6822. */
  6823. var Orientation;
  6824. (function (Orientation) {
  6825. /**
  6826. * Clockwise
  6827. */
  6828. Orientation[Orientation["CW"] = 0] = "CW";
  6829. /** Counter clockwise */
  6830. Orientation[Orientation["CCW"] = 1] = "CCW";
  6831. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6832. /**
  6833. * Defines angle representation
  6834. */
  6835. var Angle = /** @class */ (function () {
  6836. /**
  6837. * Creates an Angle object of "radians" radians (float).
  6838. */
  6839. function Angle(radians) {
  6840. this._radians = radians;
  6841. if (this._radians < 0.0)
  6842. this._radians += (2.0 * Math.PI);
  6843. }
  6844. /**
  6845. * Get value in degrees
  6846. * @returns the Angle value in degrees (float)
  6847. */
  6848. Angle.prototype.degrees = function () {
  6849. return this._radians * 180.0 / Math.PI;
  6850. };
  6851. /**
  6852. * Get value in radians
  6853. * @returns the Angle value in radians (float)
  6854. */
  6855. Angle.prototype.radians = function () {
  6856. return this._radians;
  6857. };
  6858. /**
  6859. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6860. * @param a defines first vector
  6861. * @param b defines second vector
  6862. * @returns a new Angle
  6863. */
  6864. Angle.BetweenTwoPoints = function (a, b) {
  6865. var delta = b.subtract(a);
  6866. var theta = Math.atan2(delta.y, delta.x);
  6867. return new Angle(theta);
  6868. };
  6869. /**
  6870. * Gets a new Angle object from the given float in radians
  6871. * @param radians defines the angle value in radians
  6872. * @returns a new Angle
  6873. */
  6874. Angle.FromRadians = function (radians) {
  6875. return new Angle(radians);
  6876. };
  6877. /**
  6878. * Gets a new Angle object from the given float in degrees
  6879. * @param degrees defines the angle value in degrees
  6880. * @returns a new Angle
  6881. */
  6882. Angle.FromDegrees = function (degrees) {
  6883. return new Angle(degrees * Math.PI / 180.0);
  6884. };
  6885. return Angle;
  6886. }());
  6887. BABYLON.Angle = Angle;
  6888. var Arc2 = /** @class */ (function () {
  6889. /**
  6890. * Creates an Arc object from the three given points : start, middle and end.
  6891. */
  6892. function Arc2(startPoint, midPoint, endPoint) {
  6893. this.startPoint = startPoint;
  6894. this.midPoint = midPoint;
  6895. this.endPoint = endPoint;
  6896. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6897. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6898. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6899. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6900. 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);
  6901. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6902. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6903. var a1 = this.startAngle.degrees();
  6904. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6905. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6906. // angles correction
  6907. if (a2 - a1 > +180.0)
  6908. a2 -= 360.0;
  6909. if (a2 - a1 < -180.0)
  6910. a2 += 360.0;
  6911. if (a3 - a2 > +180.0)
  6912. a3 -= 360.0;
  6913. if (a3 - a2 < -180.0)
  6914. a3 += 360.0;
  6915. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6916. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6917. }
  6918. return Arc2;
  6919. }());
  6920. BABYLON.Arc2 = Arc2;
  6921. var Path2 = /** @class */ (function () {
  6922. /**
  6923. * Creates a Path2 object from the starting 2D coordinates x and y.
  6924. */
  6925. function Path2(x, y) {
  6926. this._points = new Array();
  6927. this._length = 0.0;
  6928. this.closed = false;
  6929. this._points.push(new Vector2(x, y));
  6930. }
  6931. /**
  6932. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6933. * Returns the updated Path2.
  6934. */
  6935. Path2.prototype.addLineTo = function (x, y) {
  6936. if (this.closed) {
  6937. return this;
  6938. }
  6939. var newPoint = new Vector2(x, y);
  6940. var previousPoint = this._points[this._points.length - 1];
  6941. this._points.push(newPoint);
  6942. this._length += newPoint.subtract(previousPoint).length();
  6943. return this;
  6944. };
  6945. /**
  6946. * 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.
  6947. * Returns the updated Path2.
  6948. */
  6949. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6950. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6951. if (this.closed) {
  6952. return this;
  6953. }
  6954. var startPoint = this._points[this._points.length - 1];
  6955. var midPoint = new Vector2(midX, midY);
  6956. var endPoint = new Vector2(endX, endY);
  6957. var arc = new Arc2(startPoint, midPoint, endPoint);
  6958. var increment = arc.angle.radians() / numberOfSegments;
  6959. if (arc.orientation === Orientation.CW)
  6960. increment *= -1;
  6961. var currentAngle = arc.startAngle.radians() + increment;
  6962. for (var i = 0; i < numberOfSegments; i++) {
  6963. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6964. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6965. this.addLineTo(x, y);
  6966. currentAngle += increment;
  6967. }
  6968. return this;
  6969. };
  6970. /**
  6971. * Closes the Path2.
  6972. * Returns the Path2.
  6973. */
  6974. Path2.prototype.close = function () {
  6975. this.closed = true;
  6976. return this;
  6977. };
  6978. /**
  6979. * Returns the Path2 total length (float).
  6980. */
  6981. Path2.prototype.length = function () {
  6982. var result = this._length;
  6983. if (!this.closed) {
  6984. var lastPoint = this._points[this._points.length - 1];
  6985. var firstPoint = this._points[0];
  6986. result += (firstPoint.subtract(lastPoint).length());
  6987. }
  6988. return result;
  6989. };
  6990. /**
  6991. * Returns the Path2 internal array of points.
  6992. */
  6993. Path2.prototype.getPoints = function () {
  6994. return this._points;
  6995. };
  6996. /**
  6997. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6998. */
  6999. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7000. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7001. return Vector2.Zero();
  7002. }
  7003. var lengthPosition = normalizedLengthPosition * this.length();
  7004. var previousOffset = 0;
  7005. for (var i = 0; i < this._points.length; i++) {
  7006. var j = (i + 1) % this._points.length;
  7007. var a = this._points[i];
  7008. var b = this._points[j];
  7009. var bToA = b.subtract(a);
  7010. var nextOffset = (bToA.length() + previousOffset);
  7011. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7012. var dir = bToA.normalize();
  7013. var localOffset = lengthPosition - previousOffset;
  7014. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7015. }
  7016. previousOffset = nextOffset;
  7017. }
  7018. return Vector2.Zero();
  7019. };
  7020. /**
  7021. * Returns a new Path2 starting at the coordinates (x, y).
  7022. */
  7023. Path2.StartingAt = function (x, y) {
  7024. return new Path2(x, y);
  7025. };
  7026. return Path2;
  7027. }());
  7028. BABYLON.Path2 = Path2;
  7029. var Path3D = /** @class */ (function () {
  7030. /**
  7031. * new Path3D(path, normal, raw)
  7032. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7033. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7034. * path : an array of Vector3, the curve axis of the Path3D
  7035. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7036. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7037. */
  7038. function Path3D(path, firstNormal, raw) {
  7039. if (firstNormal === void 0) { firstNormal = null; }
  7040. this.path = path;
  7041. this._curve = new Array();
  7042. this._distances = new Array();
  7043. this._tangents = new Array();
  7044. this._normals = new Array();
  7045. this._binormals = new Array();
  7046. for (var p = 0; p < path.length; p++) {
  7047. this._curve[p] = path[p].clone(); // hard copy
  7048. }
  7049. this._raw = raw || false;
  7050. this._compute(firstNormal);
  7051. }
  7052. /**
  7053. * Returns the Path3D array of successive Vector3 designing its curve.
  7054. */
  7055. Path3D.prototype.getCurve = function () {
  7056. return this._curve;
  7057. };
  7058. /**
  7059. * Returns an array populated with tangent vectors on each Path3D curve point.
  7060. */
  7061. Path3D.prototype.getTangents = function () {
  7062. return this._tangents;
  7063. };
  7064. /**
  7065. * Returns an array populated with normal vectors on each Path3D curve point.
  7066. */
  7067. Path3D.prototype.getNormals = function () {
  7068. return this._normals;
  7069. };
  7070. /**
  7071. * Returns an array populated with binormal vectors on each Path3D curve point.
  7072. */
  7073. Path3D.prototype.getBinormals = function () {
  7074. return this._binormals;
  7075. };
  7076. /**
  7077. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7078. */
  7079. Path3D.prototype.getDistances = function () {
  7080. return this._distances;
  7081. };
  7082. /**
  7083. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7084. * Returns the same object updated.
  7085. */
  7086. Path3D.prototype.update = function (path, firstNormal) {
  7087. if (firstNormal === void 0) { firstNormal = null; }
  7088. for (var p = 0; p < path.length; p++) {
  7089. this._curve[p].x = path[p].x;
  7090. this._curve[p].y = path[p].y;
  7091. this._curve[p].z = path[p].z;
  7092. }
  7093. this._compute(firstNormal);
  7094. return this;
  7095. };
  7096. // private function compute() : computes tangents, normals and binormals
  7097. Path3D.prototype._compute = function (firstNormal) {
  7098. var l = this._curve.length;
  7099. // first and last tangents
  7100. this._tangents[0] = this._getFirstNonNullVector(0);
  7101. if (!this._raw) {
  7102. this._tangents[0].normalize();
  7103. }
  7104. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7105. if (!this._raw) {
  7106. this._tangents[l - 1].normalize();
  7107. }
  7108. // normals and binormals at first point : arbitrary vector with _normalVector()
  7109. var tg0 = this._tangents[0];
  7110. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7111. this._normals[0] = pp0;
  7112. if (!this._raw) {
  7113. this._normals[0].normalize();
  7114. }
  7115. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7116. if (!this._raw) {
  7117. this._binormals[0].normalize();
  7118. }
  7119. this._distances[0] = 0.0;
  7120. // normals and binormals : next points
  7121. var prev; // previous vector (segment)
  7122. var cur; // current vector (segment)
  7123. var curTang; // current tangent
  7124. // previous normal
  7125. var prevBinor; // previous binormal
  7126. for (var i = 1; i < l; i++) {
  7127. // tangents
  7128. prev = this._getLastNonNullVector(i);
  7129. if (i < l - 1) {
  7130. cur = this._getFirstNonNullVector(i);
  7131. this._tangents[i] = prev.add(cur);
  7132. this._tangents[i].normalize();
  7133. }
  7134. this._distances[i] = this._distances[i - 1] + prev.length();
  7135. // normals and binormals
  7136. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7137. curTang = this._tangents[i];
  7138. prevBinor = this._binormals[i - 1];
  7139. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7140. if (!this._raw) {
  7141. this._normals[i].normalize();
  7142. }
  7143. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7144. if (!this._raw) {
  7145. this._binormals[i].normalize();
  7146. }
  7147. }
  7148. };
  7149. // private function getFirstNonNullVector(index)
  7150. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7151. Path3D.prototype._getFirstNonNullVector = function (index) {
  7152. var i = 1;
  7153. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7154. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7155. i++;
  7156. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7157. }
  7158. return nNVector;
  7159. };
  7160. // private function getLastNonNullVector(index)
  7161. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7162. Path3D.prototype._getLastNonNullVector = function (index) {
  7163. var i = 1;
  7164. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7165. while (nLVector.length() === 0 && index > i + 1) {
  7166. i++;
  7167. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7168. }
  7169. return nLVector;
  7170. };
  7171. // private function normalVector(v0, vt, va) :
  7172. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7173. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7174. Path3D.prototype._normalVector = function (v0, vt, va) {
  7175. var normal0;
  7176. var tgl = vt.length();
  7177. if (tgl === 0.0) {
  7178. tgl = 1.0;
  7179. }
  7180. if (va === undefined || va === null) {
  7181. var point;
  7182. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7183. point = new Vector3(0.0, -1.0, 0.0);
  7184. }
  7185. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7186. point = new Vector3(1.0, 0.0, 0.0);
  7187. }
  7188. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7189. point = new Vector3(0.0, 0.0, 1.0);
  7190. }
  7191. else {
  7192. point = Vector3.Zero();
  7193. }
  7194. normal0 = Vector3.Cross(vt, point);
  7195. }
  7196. else {
  7197. normal0 = Vector3.Cross(vt, va);
  7198. Vector3.CrossToRef(normal0, vt, normal0);
  7199. }
  7200. normal0.normalize();
  7201. return normal0;
  7202. };
  7203. return Path3D;
  7204. }());
  7205. BABYLON.Path3D = Path3D;
  7206. var Curve3 = /** @class */ (function () {
  7207. /**
  7208. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7209. * A Curve3 is designed from a series of successive Vector3.
  7210. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7211. */
  7212. function Curve3(points) {
  7213. this._length = 0.0;
  7214. this._points = points;
  7215. this._length = this._computeLength(points);
  7216. }
  7217. /**
  7218. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7219. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7220. * @param v1 (Vector3) the control point
  7221. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7222. * @param nbPoints (integer) the wanted number of points in the curve
  7223. */
  7224. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7225. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7226. var bez = new Array();
  7227. var equation = function (t, val0, val1, val2) {
  7228. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7229. return res;
  7230. };
  7231. for (var i = 0; i <= nbPoints; i++) {
  7232. 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)));
  7233. }
  7234. return new Curve3(bez);
  7235. };
  7236. /**
  7237. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7238. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7239. * @param v1 (Vector3) the first control point
  7240. * @param v2 (Vector3) the second control point
  7241. * @param v3 (Vector3) the end point of the Cubic Bezier
  7242. * @param nbPoints (integer) the wanted number of points in the curve
  7243. */
  7244. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7245. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7246. var bez = new Array();
  7247. var equation = function (t, val0, val1, val2, val3) {
  7248. 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;
  7249. return res;
  7250. };
  7251. for (var i = 0; i <= nbPoints; i++) {
  7252. 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)));
  7253. }
  7254. return new Curve3(bez);
  7255. };
  7256. /**
  7257. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7258. * @param p1 (Vector3) the origin point of the Hermite Spline
  7259. * @param t1 (Vector3) the tangent vector at the origin point
  7260. * @param p2 (Vector3) the end point of the Hermite Spline
  7261. * @param t2 (Vector3) the tangent vector at the end point
  7262. * @param nbPoints (integer) the wanted number of points in the curve
  7263. */
  7264. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7265. var hermite = new Array();
  7266. var step = 1.0 / nbPoints;
  7267. for (var i = 0; i <= nbPoints; i++) {
  7268. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7269. }
  7270. return new Curve3(hermite);
  7271. };
  7272. /**
  7273. * Returns a Curve3 object along a CatmullRom Spline curve :
  7274. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7275. * @param nbPoints (integer) the wanted number of points between each curve control points
  7276. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7277. */
  7278. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7279. var catmullRom = new Array();
  7280. var step = 1.0 / nbPoints;
  7281. var amount = 0.0;
  7282. if (closed) {
  7283. var pointsCount = points.length;
  7284. for (var i = 0; i < pointsCount; i++) {
  7285. amount = 0;
  7286. for (var c = 0; c < nbPoints; c++) {
  7287. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7288. amount += step;
  7289. }
  7290. }
  7291. catmullRom.push(catmullRom[0]);
  7292. }
  7293. else {
  7294. var totalPoints = new Array();
  7295. totalPoints.push(points[0].clone());
  7296. Array.prototype.push.apply(totalPoints, points);
  7297. totalPoints.push(points[points.length - 1].clone());
  7298. for (var i = 0; i < totalPoints.length - 3; i++) {
  7299. amount = 0;
  7300. for (var c = 0; c < nbPoints; c++) {
  7301. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7302. amount += step;
  7303. }
  7304. }
  7305. i--;
  7306. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7307. }
  7308. return new Curve3(catmullRom);
  7309. };
  7310. /**
  7311. * Returns the Curve3 stored array of successive Vector3
  7312. */
  7313. Curve3.prototype.getPoints = function () {
  7314. return this._points;
  7315. };
  7316. /**
  7317. * Returns the computed length (float) of the curve.
  7318. */
  7319. Curve3.prototype.length = function () {
  7320. return this._length;
  7321. };
  7322. /**
  7323. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7324. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7325. * curveA and curveB keep unchanged.
  7326. */
  7327. Curve3.prototype.continue = function (curve) {
  7328. var lastPoint = this._points[this._points.length - 1];
  7329. var continuedPoints = this._points.slice();
  7330. var curvePoints = curve.getPoints();
  7331. for (var i = 1; i < curvePoints.length; i++) {
  7332. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7333. }
  7334. var continuedCurve = new Curve3(continuedPoints);
  7335. return continuedCurve;
  7336. };
  7337. Curve3.prototype._computeLength = function (path) {
  7338. var l = 0;
  7339. for (var i = 1; i < path.length; i++) {
  7340. l += (path[i].subtract(path[i - 1])).length();
  7341. }
  7342. return l;
  7343. };
  7344. return Curve3;
  7345. }());
  7346. BABYLON.Curve3 = Curve3;
  7347. // Vertex formats
  7348. var PositionNormalVertex = /** @class */ (function () {
  7349. function PositionNormalVertex(position, normal) {
  7350. if (position === void 0) { position = Vector3.Zero(); }
  7351. if (normal === void 0) { normal = Vector3.Up(); }
  7352. this.position = position;
  7353. this.normal = normal;
  7354. }
  7355. PositionNormalVertex.prototype.clone = function () {
  7356. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7357. };
  7358. return PositionNormalVertex;
  7359. }());
  7360. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7361. var PositionNormalTextureVertex = /** @class */ (function () {
  7362. function PositionNormalTextureVertex(position, normal, uv) {
  7363. if (position === void 0) { position = Vector3.Zero(); }
  7364. if (normal === void 0) { normal = Vector3.Up(); }
  7365. if (uv === void 0) { uv = Vector2.Zero(); }
  7366. this.position = position;
  7367. this.normal = normal;
  7368. this.uv = uv;
  7369. }
  7370. PositionNormalTextureVertex.prototype.clone = function () {
  7371. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7372. };
  7373. return PositionNormalTextureVertex;
  7374. }());
  7375. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7376. // Temporary pre-allocated objects for engine internal use
  7377. // usage in any internal function :
  7378. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7379. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7380. var Tmp = /** @class */ (function () {
  7381. function Tmp() {
  7382. }
  7383. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7384. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7385. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7386. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7387. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7388. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7389. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7390. Matrix.Zero(), Matrix.Zero(),
  7391. Matrix.Zero(), Matrix.Zero(),
  7392. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7393. return Tmp;
  7394. }());
  7395. BABYLON.Tmp = Tmp;
  7396. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7397. var MathTmp = /** @class */ (function () {
  7398. function MathTmp() {
  7399. }
  7400. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7401. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7402. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7403. return MathTmp;
  7404. }());
  7405. })(BABYLON || (BABYLON = {}));
  7406. //# sourceMappingURL=babylon.math.js.map
  7407. var BABYLON;
  7408. (function (BABYLON) {
  7409. var Scalar = /** @class */ (function () {
  7410. function Scalar() {
  7411. }
  7412. /**
  7413. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7414. */
  7415. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7416. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7417. var num = a - b;
  7418. return -epsilon <= num && num <= epsilon;
  7419. };
  7420. /**
  7421. * Returns a string : the upper case translation of the number i to hexadecimal.
  7422. */
  7423. Scalar.ToHex = function (i) {
  7424. var str = i.toString(16);
  7425. if (i <= 15) {
  7426. return ("0" + str).toUpperCase();
  7427. }
  7428. return str.toUpperCase();
  7429. };
  7430. /**
  7431. * Returns -1 if value is negative and +1 is value is positive.
  7432. * Returns the value itself if it's equal to zero.
  7433. */
  7434. Scalar.Sign = function (value) {
  7435. value = +value; // convert to a number
  7436. if (value === 0 || isNaN(value))
  7437. return value;
  7438. return value > 0 ? 1 : -1;
  7439. };
  7440. /**
  7441. * Returns the value itself if it's between min and max.
  7442. * Returns min if the value is lower than min.
  7443. * Returns max if the value is greater than max.
  7444. */
  7445. Scalar.Clamp = function (value, min, max) {
  7446. if (min === void 0) { min = 0; }
  7447. if (max === void 0) { max = 1; }
  7448. return Math.min(max, Math.max(min, value));
  7449. };
  7450. /**
  7451. * Returns the log2 of value.
  7452. */
  7453. Scalar.Log2 = function (value) {
  7454. return Math.log(value) * Math.LOG2E;
  7455. };
  7456. /**
  7457. * Loops the value, so that it is never larger than length and never smaller than 0.
  7458. *
  7459. * This is similar to the modulo operator but it works with floating point numbers.
  7460. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7461. * With t = 5 and length = 2.5, the result would be 0.0.
  7462. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7463. */
  7464. Scalar.Repeat = function (value, length) {
  7465. return value - Math.floor(value / length) * length;
  7466. };
  7467. /**
  7468. * Normalize the value between 0.0 and 1.0 using min and max values
  7469. */
  7470. Scalar.Normalize = function (value, min, max) {
  7471. return (value - min) / (max - min);
  7472. };
  7473. /**
  7474. * Denormalize the value from 0.0 and 1.0 using min and max values
  7475. */
  7476. Scalar.Denormalize = function (normalized, min, max) {
  7477. return (normalized * (max - min) + min);
  7478. };
  7479. /**
  7480. * Calculates the shortest difference between two given angles given in degrees.
  7481. */
  7482. Scalar.DeltaAngle = function (current, target) {
  7483. var num = Scalar.Repeat(target - current, 360.0);
  7484. if (num > 180.0) {
  7485. num -= 360.0;
  7486. }
  7487. return num;
  7488. };
  7489. /**
  7490. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7491. *
  7492. * The returned value will move back and forth between 0 and length
  7493. */
  7494. Scalar.PingPong = function (tx, length) {
  7495. var t = Scalar.Repeat(tx, length * 2.0);
  7496. return length - Math.abs(t - length);
  7497. };
  7498. /**
  7499. * Interpolates between min and max with smoothing at the limits.
  7500. *
  7501. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7502. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7503. */
  7504. Scalar.SmoothStep = function (from, to, tx) {
  7505. var t = Scalar.Clamp(tx);
  7506. t = -2.0 * t * t * t + 3.0 * t * t;
  7507. return to * t + from * (1.0 - t);
  7508. };
  7509. /**
  7510. * Moves a value current towards target.
  7511. *
  7512. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7513. * Negative values of maxDelta pushes the value away from target.
  7514. */
  7515. Scalar.MoveTowards = function (current, target, maxDelta) {
  7516. var result = 0;
  7517. if (Math.abs(target - current) <= maxDelta) {
  7518. result = target;
  7519. }
  7520. else {
  7521. result = current + Scalar.Sign(target - current) * maxDelta;
  7522. }
  7523. return result;
  7524. };
  7525. /**
  7526. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7527. *
  7528. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7529. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7530. */
  7531. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7532. var num = Scalar.DeltaAngle(current, target);
  7533. var result = 0;
  7534. if (-maxDelta < num && num < maxDelta) {
  7535. result = target;
  7536. }
  7537. else {
  7538. target = current + num;
  7539. result = Scalar.MoveTowards(current, target, maxDelta);
  7540. }
  7541. return result;
  7542. };
  7543. /**
  7544. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7545. */
  7546. Scalar.Lerp = function (start, end, amount) {
  7547. return start + ((end - start) * amount);
  7548. };
  7549. /**
  7550. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7551. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7552. */
  7553. Scalar.LerpAngle = function (start, end, amount) {
  7554. var num = Scalar.Repeat(end - start, 360.0);
  7555. if (num > 180.0) {
  7556. num -= 360.0;
  7557. }
  7558. return start + num * Scalar.Clamp(amount);
  7559. };
  7560. /**
  7561. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7562. */
  7563. Scalar.InverseLerp = function (a, b, value) {
  7564. var result = 0;
  7565. if (a != b) {
  7566. result = Scalar.Clamp((value - a) / (b - a));
  7567. }
  7568. else {
  7569. result = 0.0;
  7570. }
  7571. return result;
  7572. };
  7573. /**
  7574. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7575. */
  7576. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7577. var squared = amount * amount;
  7578. var cubed = amount * squared;
  7579. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7580. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7581. var part3 = (cubed - (2.0 * squared)) + amount;
  7582. var part4 = cubed - squared;
  7583. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7584. };
  7585. /**
  7586. * Returns a random float number between and min and max values
  7587. */
  7588. Scalar.RandomRange = function (min, max) {
  7589. if (min === max)
  7590. return min;
  7591. return ((Math.random() * (max - min)) + min);
  7592. };
  7593. /**
  7594. * This function returns percentage of a number in a given range.
  7595. *
  7596. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7597. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7598. */
  7599. Scalar.RangeToPercent = function (number, min, max) {
  7600. return ((number - min) / (max - min));
  7601. };
  7602. /**
  7603. * This function returns number that corresponds to the percentage in a given range.
  7604. *
  7605. * PercentToRange(0.34,0,100) will return 34.
  7606. */
  7607. Scalar.PercentToRange = function (percent, min, max) {
  7608. return ((max - min) * percent + min);
  7609. };
  7610. /**
  7611. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7612. * @param angle The angle to normalize in radian.
  7613. * @return The converted angle.
  7614. */
  7615. Scalar.NormalizeRadians = function (angle) {
  7616. // More precise but slower version kept for reference.
  7617. // angle = angle % Tools.TwoPi;
  7618. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7619. //if (angle > Math.PI) {
  7620. // angle -= Tools.TwoPi;
  7621. //}
  7622. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7623. return angle;
  7624. };
  7625. /**
  7626. * Two pi constants convenient for computation.
  7627. */
  7628. Scalar.TwoPi = Math.PI * 2;
  7629. return Scalar;
  7630. }());
  7631. BABYLON.Scalar = Scalar;
  7632. })(BABYLON || (BABYLON = {}));
  7633. //# sourceMappingURL=babylon.math.scalar.js.map
  7634. //# sourceMappingURL=babylon.mixins.js.map
  7635. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7636. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7637. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7638. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7639. //# sourceMappingURL=babylon.webgl2.js.map
  7640. var BABYLON;
  7641. (function (BABYLON) {
  7642. var __decoratorInitialStore = {};
  7643. var __mergedStore = {};
  7644. var _copySource = function (creationFunction, source, instanciate) {
  7645. var destination = creationFunction();
  7646. // Tags
  7647. if (BABYLON.Tags) {
  7648. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7649. }
  7650. var classStore = getMergedStore(destination);
  7651. // Properties
  7652. for (var property in classStore) {
  7653. var propertyDescriptor = classStore[property];
  7654. var sourceProperty = source[property];
  7655. var propertyType = propertyDescriptor.type;
  7656. if (sourceProperty !== undefined && sourceProperty !== null) {
  7657. switch (propertyType) {
  7658. case 0: // Value
  7659. case 6: // Mesh reference
  7660. case 11: // Camera reference
  7661. destination[property] = sourceProperty;
  7662. break;
  7663. case 1: // Texture
  7664. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7665. break;
  7666. case 2: // Color3
  7667. case 3: // FresnelParameters
  7668. case 4: // Vector2
  7669. case 5: // Vector3
  7670. case 7: // Color Curves
  7671. case 10: // Quaternion
  7672. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7673. break;
  7674. }
  7675. }
  7676. }
  7677. return destination;
  7678. };
  7679. function getDirectStore(target) {
  7680. var classKey = target.getClassName();
  7681. if (!__decoratorInitialStore[classKey]) {
  7682. __decoratorInitialStore[classKey] = {};
  7683. }
  7684. return __decoratorInitialStore[classKey];
  7685. }
  7686. /**
  7687. * Return the list of properties flagged as serializable
  7688. * @param target: host object
  7689. */
  7690. function getMergedStore(target) {
  7691. var classKey = target.getClassName();
  7692. if (__mergedStore[classKey]) {
  7693. return __mergedStore[classKey];
  7694. }
  7695. __mergedStore[classKey] = {};
  7696. var store = __mergedStore[classKey];
  7697. var currentTarget = target;
  7698. var currentKey = classKey;
  7699. while (currentKey) {
  7700. var initialStore = __decoratorInitialStore[currentKey];
  7701. for (var property in initialStore) {
  7702. store[property] = initialStore[property];
  7703. }
  7704. var parent_1 = void 0;
  7705. var done = false;
  7706. do {
  7707. parent_1 = Object.getPrototypeOf(currentTarget);
  7708. if (!parent_1.getClassName) {
  7709. done = true;
  7710. break;
  7711. }
  7712. if (parent_1.getClassName() !== currentKey) {
  7713. break;
  7714. }
  7715. currentTarget = parent_1;
  7716. } while (parent_1);
  7717. if (done) {
  7718. break;
  7719. }
  7720. currentKey = parent_1.getClassName();
  7721. currentTarget = parent_1;
  7722. }
  7723. return store;
  7724. }
  7725. function generateSerializableMember(type, sourceName) {
  7726. return function (target, propertyKey) {
  7727. var classStore = getDirectStore(target);
  7728. if (!classStore[propertyKey]) {
  7729. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7730. }
  7731. };
  7732. }
  7733. function generateExpandMember(setCallback, targetKey) {
  7734. if (targetKey === void 0) { targetKey = null; }
  7735. return function (target, propertyKey) {
  7736. var key = targetKey || ("_" + propertyKey);
  7737. Object.defineProperty(target, propertyKey, {
  7738. get: function () {
  7739. return this[key];
  7740. },
  7741. set: function (value) {
  7742. if (this[key] === value) {
  7743. return;
  7744. }
  7745. this[key] = value;
  7746. target[setCallback].apply(this);
  7747. },
  7748. enumerable: true,
  7749. configurable: true
  7750. });
  7751. };
  7752. }
  7753. function expandToProperty(callback, targetKey) {
  7754. if (targetKey === void 0) { targetKey = null; }
  7755. return generateExpandMember(callback, targetKey);
  7756. }
  7757. BABYLON.expandToProperty = expandToProperty;
  7758. function serialize(sourceName) {
  7759. return generateSerializableMember(0, sourceName); // value member
  7760. }
  7761. BABYLON.serialize = serialize;
  7762. function serializeAsTexture(sourceName) {
  7763. return generateSerializableMember(1, sourceName); // texture member
  7764. }
  7765. BABYLON.serializeAsTexture = serializeAsTexture;
  7766. function serializeAsColor3(sourceName) {
  7767. return generateSerializableMember(2, sourceName); // color3 member
  7768. }
  7769. BABYLON.serializeAsColor3 = serializeAsColor3;
  7770. function serializeAsFresnelParameters(sourceName) {
  7771. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7772. }
  7773. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7774. function serializeAsVector2(sourceName) {
  7775. return generateSerializableMember(4, sourceName); // vector2 member
  7776. }
  7777. BABYLON.serializeAsVector2 = serializeAsVector2;
  7778. function serializeAsVector3(sourceName) {
  7779. return generateSerializableMember(5, sourceName); // vector3 member
  7780. }
  7781. BABYLON.serializeAsVector3 = serializeAsVector3;
  7782. function serializeAsMeshReference(sourceName) {
  7783. return generateSerializableMember(6, sourceName); // mesh reference member
  7784. }
  7785. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7786. function serializeAsColorCurves(sourceName) {
  7787. return generateSerializableMember(7, sourceName); // color curves
  7788. }
  7789. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7790. function serializeAsColor4(sourceName) {
  7791. return generateSerializableMember(8, sourceName); // color 4
  7792. }
  7793. BABYLON.serializeAsColor4 = serializeAsColor4;
  7794. function serializeAsImageProcessingConfiguration(sourceName) {
  7795. return generateSerializableMember(9, sourceName); // image processing
  7796. }
  7797. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7798. function serializeAsQuaternion(sourceName) {
  7799. return generateSerializableMember(10, sourceName); // quaternion member
  7800. }
  7801. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7802. /**
  7803. * Decorator used to define property that can be serialized as reference to a camera
  7804. * @param sourceName defines the name of the property to decorate
  7805. */
  7806. function serializeAsCameraReference(sourceName) {
  7807. return generateSerializableMember(11, sourceName); // camera reference member
  7808. }
  7809. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7810. var SerializationHelper = /** @class */ (function () {
  7811. function SerializationHelper() {
  7812. }
  7813. SerializationHelper.Serialize = function (entity, serializationObject) {
  7814. if (!serializationObject) {
  7815. serializationObject = {};
  7816. }
  7817. // Tags
  7818. if (BABYLON.Tags) {
  7819. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7820. }
  7821. var serializedProperties = getMergedStore(entity);
  7822. // Properties
  7823. for (var property in serializedProperties) {
  7824. var propertyDescriptor = serializedProperties[property];
  7825. var targetPropertyName = propertyDescriptor.sourceName || property;
  7826. var propertyType = propertyDescriptor.type;
  7827. var sourceProperty = entity[property];
  7828. if (sourceProperty !== undefined && sourceProperty !== null) {
  7829. switch (propertyType) {
  7830. case 0: // Value
  7831. serializationObject[targetPropertyName] = sourceProperty;
  7832. break;
  7833. case 1: // Texture
  7834. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7835. break;
  7836. case 2: // Color3
  7837. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7838. break;
  7839. case 3: // FresnelParameters
  7840. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7841. break;
  7842. case 4: // Vector2
  7843. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7844. break;
  7845. case 5: // Vector3
  7846. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7847. break;
  7848. case 6: // Mesh reference
  7849. serializationObject[targetPropertyName] = sourceProperty.id;
  7850. break;
  7851. case 7: // Color Curves
  7852. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7853. break;
  7854. case 8: // Color 4
  7855. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7856. break;
  7857. case 9: // Image Processing
  7858. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7859. break;
  7860. case 10: // Quaternion
  7861. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7862. break;
  7863. case 11: // Camera reference
  7864. serializationObject[targetPropertyName] = sourceProperty.id;
  7865. break;
  7866. }
  7867. }
  7868. }
  7869. return serializationObject;
  7870. };
  7871. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7872. if (rootUrl === void 0) { rootUrl = null; }
  7873. var destination = creationFunction();
  7874. if (!rootUrl) {
  7875. rootUrl = "";
  7876. }
  7877. // Tags
  7878. if (BABYLON.Tags) {
  7879. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7880. }
  7881. var classStore = getMergedStore(destination);
  7882. // Properties
  7883. for (var property in classStore) {
  7884. var propertyDescriptor = classStore[property];
  7885. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7886. var propertyType = propertyDescriptor.type;
  7887. if (sourceProperty !== undefined && sourceProperty !== null) {
  7888. var dest = destination;
  7889. switch (propertyType) {
  7890. case 0: // Value
  7891. dest[property] = sourceProperty;
  7892. break;
  7893. case 1: // Texture
  7894. if (scene) {
  7895. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7896. }
  7897. break;
  7898. case 2: // Color3
  7899. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7900. break;
  7901. case 3: // FresnelParameters
  7902. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7903. break;
  7904. case 4: // Vector2
  7905. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7906. break;
  7907. case 5: // Vector3
  7908. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7909. break;
  7910. case 6: // Mesh reference
  7911. if (scene) {
  7912. dest[property] = scene.getLastMeshByID(sourceProperty);
  7913. }
  7914. break;
  7915. case 7: // Color Curves
  7916. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7917. break;
  7918. case 8: // Color 4
  7919. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7920. break;
  7921. case 9: // Image Processing
  7922. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7923. break;
  7924. case 10: // Quaternion
  7925. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7926. break;
  7927. case 11: // Camera reference
  7928. if (scene) {
  7929. dest[property] = scene.getCameraByID(sourceProperty);
  7930. }
  7931. break;
  7932. }
  7933. }
  7934. }
  7935. return destination;
  7936. };
  7937. SerializationHelper.Clone = function (creationFunction, source) {
  7938. return _copySource(creationFunction, source, false);
  7939. };
  7940. SerializationHelper.Instanciate = function (creationFunction, source) {
  7941. return _copySource(creationFunction, source, true);
  7942. };
  7943. return SerializationHelper;
  7944. }());
  7945. BABYLON.SerializationHelper = SerializationHelper;
  7946. })(BABYLON || (BABYLON = {}));
  7947. //# sourceMappingURL=babylon.decorators.js.map
  7948. var BABYLON;
  7949. (function (BABYLON) {
  7950. /**
  7951. * Wrapper class for promise with external resolve and reject.
  7952. */
  7953. var Deferred = /** @class */ (function () {
  7954. /**
  7955. * Constructor for this deferred object.
  7956. */
  7957. function Deferred() {
  7958. var _this = this;
  7959. this.promise = new Promise(function (resolve, reject) {
  7960. _this._resolve = resolve;
  7961. _this._reject = reject;
  7962. });
  7963. }
  7964. Object.defineProperty(Deferred.prototype, "resolve", {
  7965. /**
  7966. * The resolve method of the promise associated with this deferred object.
  7967. */
  7968. get: function () {
  7969. return this._resolve;
  7970. },
  7971. enumerable: true,
  7972. configurable: true
  7973. });
  7974. Object.defineProperty(Deferred.prototype, "reject", {
  7975. /**
  7976. * The reject method of the promise associated with this deferred object.
  7977. */
  7978. get: function () {
  7979. return this._reject;
  7980. },
  7981. enumerable: true,
  7982. configurable: true
  7983. });
  7984. return Deferred;
  7985. }());
  7986. BABYLON.Deferred = Deferred;
  7987. })(BABYLON || (BABYLON = {}));
  7988. //# sourceMappingURL=babylon.deferred.js.map
  7989. var BABYLON;
  7990. (function (BABYLON) {
  7991. /**
  7992. * A class serves as a medium between the observable and its observers
  7993. */
  7994. var EventState = /** @class */ (function () {
  7995. /**
  7996. * Create a new EventState
  7997. * @param mask defines the mask associated with this state
  7998. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7999. * @param target defines the original target of the state
  8000. * @param currentTarget defines the current target of the state
  8001. */
  8002. function EventState(mask, skipNextObservers, target, currentTarget) {
  8003. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8004. this.initalize(mask, skipNextObservers, target, currentTarget);
  8005. }
  8006. /**
  8007. * Initialize the current event state
  8008. * @param mask defines the mask associated with this state
  8009. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8010. * @param target defines the original target of the state
  8011. * @param currentTarget defines the current target of the state
  8012. * @returns the current event state
  8013. */
  8014. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8015. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8016. this.mask = mask;
  8017. this.skipNextObservers = skipNextObservers;
  8018. this.target = target;
  8019. this.currentTarget = currentTarget;
  8020. return this;
  8021. };
  8022. return EventState;
  8023. }());
  8024. BABYLON.EventState = EventState;
  8025. /**
  8026. * Represent an Observer registered to a given Observable object.
  8027. */
  8028. var Observer = /** @class */ (function () {
  8029. /**
  8030. * Creates a new observer
  8031. * @param callback defines the callback to call when the observer is notified
  8032. * @param mask defines the mask of the observer (used to filter notifications)
  8033. * @param scope defines the current scope used to restore the JS context
  8034. */
  8035. function Observer(
  8036. /**
  8037. * Defines the callback to call when the observer is notified
  8038. */
  8039. callback,
  8040. /**
  8041. * Defines the mask of the observer (used to filter notifications)
  8042. */
  8043. mask,
  8044. /**
  8045. * Defines the current scope used to restore the JS context
  8046. */
  8047. scope) {
  8048. if (scope === void 0) { scope = null; }
  8049. this.callback = callback;
  8050. this.mask = mask;
  8051. this.scope = scope;
  8052. /** @hidden */
  8053. this._willBeUnregistered = false;
  8054. /**
  8055. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8056. */
  8057. this.unregisterOnNextCall = false;
  8058. }
  8059. return Observer;
  8060. }());
  8061. BABYLON.Observer = Observer;
  8062. /**
  8063. * Represent a list of observers registered to multiple Observables object.
  8064. */
  8065. var MultiObserver = /** @class */ (function () {
  8066. function MultiObserver() {
  8067. }
  8068. /**
  8069. * Release associated resources
  8070. */
  8071. MultiObserver.prototype.dispose = function () {
  8072. if (this._observers && this._observables) {
  8073. for (var index = 0; index < this._observers.length; index++) {
  8074. this._observables[index].remove(this._observers[index]);
  8075. }
  8076. }
  8077. this._observers = null;
  8078. this._observables = null;
  8079. };
  8080. /**
  8081. * Raise a callback when one of the observable will notify
  8082. * @param observables defines a list of observables to watch
  8083. * @param callback defines the callback to call on notification
  8084. * @param mask defines the mask used to filter notifications
  8085. * @param scope defines the current scope used to restore the JS context
  8086. * @returns the new MultiObserver
  8087. */
  8088. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8089. if (mask === void 0) { mask = -1; }
  8090. if (scope === void 0) { scope = null; }
  8091. var result = new MultiObserver();
  8092. result._observers = new Array();
  8093. result._observables = observables;
  8094. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8095. var observable = observables_1[_i];
  8096. var observer = observable.add(callback, mask, false, scope);
  8097. if (observer) {
  8098. result._observers.push(observer);
  8099. }
  8100. }
  8101. return result;
  8102. };
  8103. return MultiObserver;
  8104. }());
  8105. BABYLON.MultiObserver = MultiObserver;
  8106. /**
  8107. * The Observable class is a simple implementation of the Observable pattern.
  8108. *
  8109. * 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.
  8110. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8111. * 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).
  8112. * 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.
  8113. */
  8114. var Observable = /** @class */ (function () {
  8115. /**
  8116. * Creates a new observable
  8117. * @param onObserverAdded defines a callback to call when a new observer is added
  8118. */
  8119. function Observable(onObserverAdded) {
  8120. this._observers = new Array();
  8121. this._eventState = new EventState(0);
  8122. if (onObserverAdded) {
  8123. this._onObserverAdded = onObserverAdded;
  8124. }
  8125. }
  8126. /**
  8127. * Create a new Observer with the specified callback
  8128. * @param callback the callback that will be executed for that Observer
  8129. * @param mask the mask used to filter observers
  8130. * @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.
  8131. * @param scope optional scope for the callback to be called from
  8132. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8133. * @returns the new observer created for the callback
  8134. */
  8135. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8136. if (mask === void 0) { mask = -1; }
  8137. if (insertFirst === void 0) { insertFirst = false; }
  8138. if (scope === void 0) { scope = null; }
  8139. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8140. if (!callback) {
  8141. return null;
  8142. }
  8143. var observer = new Observer(callback, mask, scope);
  8144. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8145. if (insertFirst) {
  8146. this._observers.unshift(observer);
  8147. }
  8148. else {
  8149. this._observers.push(observer);
  8150. }
  8151. if (this._onObserverAdded) {
  8152. this._onObserverAdded(observer);
  8153. }
  8154. return observer;
  8155. };
  8156. /**
  8157. * Remove an Observer from the Observable object
  8158. * @param observer the instance of the Observer to remove
  8159. * @returns false if it doesn't belong to this Observable
  8160. */
  8161. Observable.prototype.remove = function (observer) {
  8162. if (!observer) {
  8163. return false;
  8164. }
  8165. var index = this._observers.indexOf(observer);
  8166. if (index !== -1) {
  8167. this._observers.splice(index, 1);
  8168. return true;
  8169. }
  8170. return false;
  8171. };
  8172. /**
  8173. * Remove a callback from the Observable object
  8174. * @param callback the callback to remove
  8175. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8176. * @returns false if it doesn't belong to this Observable
  8177. */
  8178. Observable.prototype.removeCallback = function (callback, scope) {
  8179. for (var index = 0; index < this._observers.length; index++) {
  8180. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8181. this._observers.splice(index, 1);
  8182. return true;
  8183. }
  8184. }
  8185. return false;
  8186. };
  8187. Observable.prototype._deferUnregister = function (observer) {
  8188. var _this = this;
  8189. observer.unregisterOnNextCall = false;
  8190. observer._willBeUnregistered = true;
  8191. BABYLON.Tools.SetImmediate(function () {
  8192. _this.remove(observer);
  8193. });
  8194. };
  8195. /**
  8196. * Notify all Observers by calling their respective callback with the given data
  8197. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8198. * @param eventData defines the data to send to all observers
  8199. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8200. * @param target defines the original target of the state
  8201. * @param currentTarget defines the current target of the state
  8202. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8203. */
  8204. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8205. if (mask === void 0) { mask = -1; }
  8206. if (!this._observers.length) {
  8207. return true;
  8208. }
  8209. var state = this._eventState;
  8210. state.mask = mask;
  8211. state.target = target;
  8212. state.currentTarget = currentTarget;
  8213. state.skipNextObservers = false;
  8214. state.lastReturnValue = eventData;
  8215. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8216. var obs = _a[_i];
  8217. if (obs._willBeUnregistered) {
  8218. continue;
  8219. }
  8220. if (obs.mask & mask) {
  8221. if (obs.scope) {
  8222. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8223. }
  8224. else {
  8225. state.lastReturnValue = obs.callback(eventData, state);
  8226. }
  8227. if (obs.unregisterOnNextCall) {
  8228. this._deferUnregister(obs);
  8229. }
  8230. }
  8231. if (state.skipNextObservers) {
  8232. return false;
  8233. }
  8234. }
  8235. return true;
  8236. };
  8237. /**
  8238. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8239. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8240. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8241. * and it is crucial that all callbacks will be executed.
  8242. * The order of the callbacks is kept, callbacks are not executed parallel.
  8243. *
  8244. * @param eventData The data to be sent to each callback
  8245. * @param mask is used to filter observers defaults to -1
  8246. * @param target defines the callback target (see EventState)
  8247. * @param currentTarget defines he current object in the bubbling phase
  8248. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8249. */
  8250. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8251. var _this = this;
  8252. if (mask === void 0) { mask = -1; }
  8253. // create an empty promise
  8254. var p = Promise.resolve(eventData);
  8255. // no observers? return this promise.
  8256. if (!this._observers.length) {
  8257. return p;
  8258. }
  8259. var state = this._eventState;
  8260. state.mask = mask;
  8261. state.target = target;
  8262. state.currentTarget = currentTarget;
  8263. state.skipNextObservers = false;
  8264. // execute one callback after another (not using Promise.all, the order is important)
  8265. this._observers.forEach(function (obs) {
  8266. if (state.skipNextObservers) {
  8267. return;
  8268. }
  8269. if (obs._willBeUnregistered) {
  8270. return;
  8271. }
  8272. if (obs.mask & mask) {
  8273. if (obs.scope) {
  8274. p = p.then(function (lastReturnedValue) {
  8275. state.lastReturnValue = lastReturnedValue;
  8276. return obs.callback.apply(obs.scope, [eventData, state]);
  8277. });
  8278. }
  8279. else {
  8280. p = p.then(function (lastReturnedValue) {
  8281. state.lastReturnValue = lastReturnedValue;
  8282. return obs.callback(eventData, state);
  8283. });
  8284. }
  8285. if (obs.unregisterOnNextCall) {
  8286. _this._deferUnregister(obs);
  8287. }
  8288. }
  8289. });
  8290. // return the eventData
  8291. return p.then(function () { return eventData; });
  8292. };
  8293. /**
  8294. * Notify a specific observer
  8295. * @param observer defines the observer to notify
  8296. * @param eventData defines the data to be sent to each callback
  8297. * @param mask is used to filter observers defaults to -1
  8298. */
  8299. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8300. if (mask === void 0) { mask = -1; }
  8301. var state = this._eventState;
  8302. state.mask = mask;
  8303. state.skipNextObservers = false;
  8304. observer.callback(eventData, state);
  8305. };
  8306. /**
  8307. * Gets a boolean indicating if the observable has at least one observer
  8308. * @returns true is the Observable has at least one Observer registered
  8309. */
  8310. Observable.prototype.hasObservers = function () {
  8311. return this._observers.length > 0;
  8312. };
  8313. /**
  8314. * Clear the list of observers
  8315. */
  8316. Observable.prototype.clear = function () {
  8317. this._observers = new Array();
  8318. this._onObserverAdded = null;
  8319. };
  8320. /**
  8321. * Clone the current observable
  8322. * @returns a new observable
  8323. */
  8324. Observable.prototype.clone = function () {
  8325. var result = new Observable();
  8326. result._observers = this._observers.slice(0);
  8327. return result;
  8328. };
  8329. /**
  8330. * Does this observable handles observer registered with a given mask
  8331. * @param mask defines the mask to be tested
  8332. * @return whether or not one observer registered with the given mask is handeled
  8333. **/
  8334. Observable.prototype.hasSpecificMask = function (mask) {
  8335. if (mask === void 0) { mask = -1; }
  8336. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8337. var obs = _a[_i];
  8338. if (obs.mask & mask || obs.mask === mask) {
  8339. return true;
  8340. }
  8341. }
  8342. return false;
  8343. };
  8344. return Observable;
  8345. }());
  8346. BABYLON.Observable = Observable;
  8347. })(BABYLON || (BABYLON = {}));
  8348. //# sourceMappingURL=babylon.observable.js.map
  8349. var BABYLON;
  8350. (function (BABYLON) {
  8351. var SmartArray = /** @class */ (function () {
  8352. function SmartArray(capacity) {
  8353. this.length = 0;
  8354. this.data = new Array(capacity);
  8355. this._id = SmartArray._GlobalId++;
  8356. }
  8357. SmartArray.prototype.push = function (value) {
  8358. this.data[this.length++] = value;
  8359. if (this.length > this.data.length) {
  8360. this.data.length *= 2;
  8361. }
  8362. };
  8363. SmartArray.prototype.forEach = function (func) {
  8364. for (var index = 0; index < this.length; index++) {
  8365. func(this.data[index]);
  8366. }
  8367. };
  8368. SmartArray.prototype.sort = function (compareFn) {
  8369. this.data.sort(compareFn);
  8370. };
  8371. SmartArray.prototype.reset = function () {
  8372. this.length = 0;
  8373. };
  8374. SmartArray.prototype.dispose = function () {
  8375. this.reset();
  8376. if (this.data) {
  8377. this.data.length = 0;
  8378. this.data = [];
  8379. }
  8380. };
  8381. SmartArray.prototype.concat = function (array) {
  8382. if (array.length === 0) {
  8383. return;
  8384. }
  8385. if (this.length + array.length > this.data.length) {
  8386. this.data.length = (this.length + array.length) * 2;
  8387. }
  8388. for (var index = 0; index < array.length; index++) {
  8389. this.data[this.length++] = (array.data || array)[index];
  8390. }
  8391. };
  8392. SmartArray.prototype.indexOf = function (value) {
  8393. var position = this.data.indexOf(value);
  8394. if (position >= this.length) {
  8395. return -1;
  8396. }
  8397. return position;
  8398. };
  8399. SmartArray.prototype.contains = function (value) {
  8400. return this.data.indexOf(value) !== -1;
  8401. };
  8402. // Statics
  8403. SmartArray._GlobalId = 0;
  8404. return SmartArray;
  8405. }());
  8406. BABYLON.SmartArray = SmartArray;
  8407. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8408. __extends(SmartArrayNoDuplicate, _super);
  8409. function SmartArrayNoDuplicate() {
  8410. var _this = _super !== null && _super.apply(this, arguments) || this;
  8411. _this._duplicateId = 0;
  8412. return _this;
  8413. }
  8414. SmartArrayNoDuplicate.prototype.push = function (value) {
  8415. _super.prototype.push.call(this, value);
  8416. if (!value.__smartArrayFlags) {
  8417. value.__smartArrayFlags = {};
  8418. }
  8419. value.__smartArrayFlags[this._id] = this._duplicateId;
  8420. };
  8421. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8422. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8423. return false;
  8424. }
  8425. this.push(value);
  8426. return true;
  8427. };
  8428. SmartArrayNoDuplicate.prototype.reset = function () {
  8429. _super.prototype.reset.call(this);
  8430. this._duplicateId++;
  8431. };
  8432. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8433. if (array.length === 0) {
  8434. return;
  8435. }
  8436. if (this.length + array.length > this.data.length) {
  8437. this.data.length = (this.length + array.length) * 2;
  8438. }
  8439. for (var index = 0; index < array.length; index++) {
  8440. var item = (array.data || array)[index];
  8441. this.pushNoDuplicate(item);
  8442. }
  8443. };
  8444. return SmartArrayNoDuplicate;
  8445. }(SmartArray));
  8446. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8447. })(BABYLON || (BABYLON = {}));
  8448. //# sourceMappingURL=babylon.smartArray.js.map
  8449. var BABYLON;
  8450. (function (BABYLON) {
  8451. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8452. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8453. var LoadFileError = /** @class */ (function (_super) {
  8454. __extends(LoadFileError, _super);
  8455. function LoadFileError(message, request) {
  8456. var _this = _super.call(this, message) || this;
  8457. _this.request = request;
  8458. _this.name = "LoadFileError";
  8459. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8460. return _this;
  8461. }
  8462. // Polyfill for Object.setPrototypeOf if necessary.
  8463. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8464. return LoadFileError;
  8465. }(Error));
  8466. BABYLON.LoadFileError = LoadFileError;
  8467. var RetryStrategy = /** @class */ (function () {
  8468. function RetryStrategy() {
  8469. }
  8470. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8471. if (maxRetries === void 0) { maxRetries = 3; }
  8472. if (baseInterval === void 0) { baseInterval = 500; }
  8473. return function (url, request, retryIndex) {
  8474. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8475. return -1;
  8476. }
  8477. return Math.pow(2, retryIndex) * baseInterval;
  8478. };
  8479. };
  8480. return RetryStrategy;
  8481. }());
  8482. BABYLON.RetryStrategy = RetryStrategy;
  8483. // Screenshots
  8484. var screenshotCanvas;
  8485. var cloneValue = function (source, destinationObject) {
  8486. if (!source)
  8487. return null;
  8488. if (source instanceof BABYLON.Mesh) {
  8489. return null;
  8490. }
  8491. if (source instanceof BABYLON.SubMesh) {
  8492. return source.clone(destinationObject);
  8493. }
  8494. else if (source.clone) {
  8495. return source.clone();
  8496. }
  8497. return null;
  8498. };
  8499. var Tools = /** @class */ (function () {
  8500. function Tools() {
  8501. }
  8502. /**
  8503. * Interpolates between a and b via alpha
  8504. * @param a The lower value (returned when alpha = 0)
  8505. * @param b The upper value (returned when alpha = 1)
  8506. * @param alpha The interpolation-factor
  8507. * @return The mixed value
  8508. */
  8509. Tools.Mix = function (a, b, alpha) {
  8510. return a * (1 - alpha) + b * alpha;
  8511. };
  8512. Tools.Instantiate = function (className) {
  8513. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8514. return Tools.RegisteredExternalClasses[className];
  8515. }
  8516. var arr = className.split(".");
  8517. var fn = (window || this);
  8518. for (var i = 0, len = arr.length; i < len; i++) {
  8519. fn = fn[arr[i]];
  8520. }
  8521. if (typeof fn !== "function") {
  8522. return null;
  8523. }
  8524. return fn;
  8525. };
  8526. /**
  8527. * Provides a slice function that will work even on IE
  8528. * @param data defines the array to slice
  8529. * @param start defines the start of the data (optional)
  8530. * @param end defines the end of the data (optional)
  8531. * @returns the new sliced array
  8532. */
  8533. Tools.Slice = function (data, start, end) {
  8534. if (data.slice) {
  8535. return data.slice(start, end);
  8536. }
  8537. return Array.prototype.slice.call(data, start, end);
  8538. };
  8539. Tools.SetImmediate = function (action) {
  8540. if (window.setImmediate) {
  8541. window.setImmediate(action);
  8542. }
  8543. else {
  8544. setTimeout(action, 1);
  8545. }
  8546. };
  8547. Tools.IsExponentOfTwo = function (value) {
  8548. var count = 1;
  8549. do {
  8550. count *= 2;
  8551. } while (count < value);
  8552. return count === value;
  8553. };
  8554. /**
  8555. * Returns the nearest 32-bit single precision float representation of a Number
  8556. * @param value A Number. If the parameter is of a different type, it will get converted
  8557. * to a number or to NaN if it cannot be converted
  8558. * @returns number
  8559. */
  8560. Tools.FloatRound = function (value) {
  8561. if (Math.fround) {
  8562. return Math.fround(value);
  8563. }
  8564. return (Tools._tmpFloatArray[0] = value);
  8565. };
  8566. /**
  8567. * Find the next highest power of two.
  8568. * @param x Number to start search from.
  8569. * @return Next highest power of two.
  8570. */
  8571. Tools.CeilingPOT = function (x) {
  8572. x--;
  8573. x |= x >> 1;
  8574. x |= x >> 2;
  8575. x |= x >> 4;
  8576. x |= x >> 8;
  8577. x |= x >> 16;
  8578. x++;
  8579. return x;
  8580. };
  8581. /**
  8582. * Find the next lowest power of two.
  8583. * @param x Number to start search from.
  8584. * @return Next lowest power of two.
  8585. */
  8586. Tools.FloorPOT = function (x) {
  8587. x = x | (x >> 1);
  8588. x = x | (x >> 2);
  8589. x = x | (x >> 4);
  8590. x = x | (x >> 8);
  8591. x = x | (x >> 16);
  8592. return x - (x >> 1);
  8593. };
  8594. /**
  8595. * Find the nearest power of two.
  8596. * @param x Number to start search from.
  8597. * @return Next nearest power of two.
  8598. */
  8599. Tools.NearestPOT = function (x) {
  8600. var c = Tools.CeilingPOT(x);
  8601. var f = Tools.FloorPOT(x);
  8602. return (c - x) > (x - f) ? f : c;
  8603. };
  8604. Tools.GetExponentOfTwo = function (value, max, mode) {
  8605. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8606. var pot;
  8607. switch (mode) {
  8608. case BABYLON.Engine.SCALEMODE_FLOOR:
  8609. pot = Tools.FloorPOT(value);
  8610. break;
  8611. case BABYLON.Engine.SCALEMODE_NEAREST:
  8612. pot = Tools.NearestPOT(value);
  8613. break;
  8614. case BABYLON.Engine.SCALEMODE_CEILING:
  8615. default:
  8616. pot = Tools.CeilingPOT(value);
  8617. break;
  8618. }
  8619. return Math.min(pot, max);
  8620. };
  8621. Tools.GetFilename = function (path) {
  8622. var index = path.lastIndexOf("/");
  8623. if (index < 0)
  8624. return path;
  8625. return path.substring(index + 1);
  8626. };
  8627. /**
  8628. * Extracts the "folder" part of a path (everything before the filename).
  8629. * @param uri The URI to extract the info from
  8630. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8631. * @returns The "folder" part of the path
  8632. */
  8633. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8634. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8635. var index = uri.lastIndexOf("/");
  8636. if (index < 0) {
  8637. if (returnUnchangedIfNoSlash) {
  8638. return uri;
  8639. }
  8640. return "";
  8641. }
  8642. return uri.substring(0, index + 1);
  8643. };
  8644. Tools.GetDOMTextContent = function (element) {
  8645. var result = "";
  8646. var child = element.firstChild;
  8647. while (child) {
  8648. if (child.nodeType === 3) {
  8649. result += child.textContent;
  8650. }
  8651. child = child.nextSibling;
  8652. }
  8653. return result;
  8654. };
  8655. Tools.ToDegrees = function (angle) {
  8656. return angle * 180 / Math.PI;
  8657. };
  8658. Tools.ToRadians = function (angle) {
  8659. return angle * Math.PI / 180;
  8660. };
  8661. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8662. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8663. var output = "";
  8664. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8665. var i = 0;
  8666. var bytes = new Uint8Array(buffer);
  8667. while (i < bytes.length) {
  8668. chr1 = bytes[i++];
  8669. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8670. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8671. enc1 = chr1 >> 2;
  8672. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8673. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8674. enc4 = chr3 & 63;
  8675. if (isNaN(chr2)) {
  8676. enc3 = enc4 = 64;
  8677. }
  8678. else if (isNaN(chr3)) {
  8679. enc4 = 64;
  8680. }
  8681. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8682. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8683. }
  8684. return "data:image/png;base64," + output;
  8685. };
  8686. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8687. if (bias === void 0) { bias = null; }
  8688. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8689. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8690. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8691. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8692. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8693. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8694. }
  8695. if (bias) {
  8696. minimum.x -= minimum.x * bias.x + bias.y;
  8697. minimum.y -= minimum.y * bias.x + bias.y;
  8698. minimum.z -= minimum.z * bias.x + bias.y;
  8699. maximum.x += maximum.x * bias.x + bias.y;
  8700. maximum.y += maximum.y * bias.x + bias.y;
  8701. maximum.z += maximum.z * bias.x + bias.y;
  8702. }
  8703. return {
  8704. minimum: minimum,
  8705. maximum: maximum
  8706. };
  8707. };
  8708. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8709. if (bias === void 0) { bias = null; }
  8710. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8711. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8712. if (!stride) {
  8713. stride = 3;
  8714. }
  8715. for (var index = start; index < start + count; index++) {
  8716. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8717. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8718. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8719. }
  8720. if (bias) {
  8721. minimum.x -= minimum.x * bias.x + bias.y;
  8722. minimum.y -= minimum.y * bias.x + bias.y;
  8723. minimum.z -= minimum.z * bias.x + bias.y;
  8724. maximum.x += maximum.x * bias.x + bias.y;
  8725. maximum.y += maximum.y * bias.x + bias.y;
  8726. maximum.z += maximum.z * bias.x + bias.y;
  8727. }
  8728. return {
  8729. minimum: minimum,
  8730. maximum: maximum
  8731. };
  8732. };
  8733. Tools.Vector2ArrayFeeder = function (array) {
  8734. return function (index) {
  8735. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8736. var length = isFloatArray ? array.length / 2 : array.length;
  8737. if (index >= length) {
  8738. return null;
  8739. }
  8740. if (isFloatArray) {
  8741. var fa = array;
  8742. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8743. }
  8744. var a = array;
  8745. return a[index];
  8746. };
  8747. };
  8748. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8749. if (bias === void 0) { bias = null; }
  8750. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8751. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8752. var i = 0;
  8753. var cur = feeder(i++);
  8754. while (cur) {
  8755. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8756. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8757. cur = feeder(i++);
  8758. }
  8759. if (bias) {
  8760. minimum.x -= minimum.x * bias.x + bias.y;
  8761. minimum.y -= minimum.y * bias.x + bias.y;
  8762. maximum.x += maximum.x * bias.x + bias.y;
  8763. maximum.y += maximum.y * bias.x + bias.y;
  8764. }
  8765. return {
  8766. minimum: minimum,
  8767. maximum: maximum
  8768. };
  8769. };
  8770. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8771. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8772. return null;
  8773. return Array.isArray(obj) ? obj : [obj];
  8774. };
  8775. // Misc.
  8776. Tools.GetPointerPrefix = function () {
  8777. var eventPrefix = "pointer";
  8778. // Check if pointer events are supported
  8779. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8780. eventPrefix = "mouse";
  8781. }
  8782. return eventPrefix;
  8783. };
  8784. /**
  8785. * @param func - the function to be called
  8786. * @param requester - the object that will request the next frame. Falls back to window.
  8787. */
  8788. Tools.QueueNewFrame = function (func, requester) {
  8789. if (!Tools.IsWindowObjectExist()) {
  8790. return setTimeout(func, 16);
  8791. }
  8792. if (!requester) {
  8793. requester = window;
  8794. }
  8795. if (requester.requestAnimationFrame) {
  8796. return requester.requestAnimationFrame(func);
  8797. }
  8798. else if (requester.msRequestAnimationFrame) {
  8799. return requester.msRequestAnimationFrame(func);
  8800. }
  8801. else if (requester.webkitRequestAnimationFrame) {
  8802. return requester.webkitRequestAnimationFrame(func);
  8803. }
  8804. else if (requester.mozRequestAnimationFrame) {
  8805. return requester.mozRequestAnimationFrame(func);
  8806. }
  8807. else if (requester.oRequestAnimationFrame) {
  8808. return requester.oRequestAnimationFrame(func);
  8809. }
  8810. else {
  8811. return window.setTimeout(func, 16);
  8812. }
  8813. };
  8814. Tools.RequestFullscreen = function (element) {
  8815. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8816. if (!requestFunction)
  8817. return;
  8818. requestFunction.call(element);
  8819. };
  8820. Tools.ExitFullscreen = function () {
  8821. if (document.exitFullscreen) {
  8822. document.exitFullscreen();
  8823. }
  8824. else if (document.mozCancelFullScreen) {
  8825. document.mozCancelFullScreen();
  8826. }
  8827. else if (document.webkitCancelFullScreen) {
  8828. document.webkitCancelFullScreen();
  8829. }
  8830. else if (document.msCancelFullScreen) {
  8831. document.msCancelFullScreen();
  8832. }
  8833. };
  8834. Tools.SetCorsBehavior = function (url, element) {
  8835. if (url && url.indexOf("data:") === 0) {
  8836. return;
  8837. }
  8838. if (Tools.CorsBehavior) {
  8839. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8840. element.crossOrigin = Tools.CorsBehavior;
  8841. }
  8842. else {
  8843. var result = Tools.CorsBehavior(url);
  8844. if (result) {
  8845. element.crossOrigin = result;
  8846. }
  8847. }
  8848. }
  8849. };
  8850. // External files
  8851. Tools.CleanUrl = function (url) {
  8852. url = url.replace(/#/mg, "%23");
  8853. return url;
  8854. };
  8855. /**
  8856. * Loads an image as an HTMLImageElement.
  8857. * @param input url string, ArrayBuffer, or Blob to load
  8858. * @param onLoad callback called when the image successfully loads
  8859. * @param onError callback called when the image fails to load
  8860. * @param database database for caching
  8861. * @returns the HTMLImageElement of the loaded image
  8862. */
  8863. Tools.LoadImage = function (input, onLoad, onError, database) {
  8864. var url;
  8865. var usingObjectURL = false;
  8866. if (input instanceof ArrayBuffer) {
  8867. url = URL.createObjectURL(new Blob([input]));
  8868. usingObjectURL = true;
  8869. }
  8870. else if (input instanceof Blob) {
  8871. url = URL.createObjectURL(input);
  8872. usingObjectURL = true;
  8873. }
  8874. else {
  8875. url = Tools.CleanUrl(input);
  8876. url = Tools.PreprocessUrl(input);
  8877. }
  8878. var img = new Image();
  8879. Tools.SetCorsBehavior(url, img);
  8880. var loadHandler = function () {
  8881. if (usingObjectURL && img.src) {
  8882. URL.revokeObjectURL(img.src);
  8883. }
  8884. img.removeEventListener("load", loadHandler);
  8885. img.removeEventListener("error", errorHandler);
  8886. onLoad(img);
  8887. };
  8888. var errorHandler = function (err) {
  8889. if (usingObjectURL && img.src) {
  8890. URL.revokeObjectURL(img.src);
  8891. }
  8892. img.removeEventListener("load", loadHandler);
  8893. img.removeEventListener("error", errorHandler);
  8894. Tools.Error("Error while trying to load image: " + input);
  8895. if (onError) {
  8896. onError("Error while trying to load image: " + input, err);
  8897. }
  8898. };
  8899. img.addEventListener("load", loadHandler);
  8900. img.addEventListener("error", errorHandler);
  8901. var noIndexedDB = function () {
  8902. img.src = url;
  8903. };
  8904. var loadFromIndexedDB = function () {
  8905. if (database) {
  8906. database.loadImageFromDB(url, img);
  8907. }
  8908. };
  8909. //ANY database to do!
  8910. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8911. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8912. }
  8913. else {
  8914. if (url.indexOf("file:") !== -1) {
  8915. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8916. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8917. try {
  8918. var blobURL;
  8919. try {
  8920. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8921. }
  8922. catch (ex) {
  8923. // Chrome doesn't support oneTimeOnly parameter
  8924. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8925. }
  8926. img.src = blobURL;
  8927. usingObjectURL = true;
  8928. }
  8929. catch (e) {
  8930. img.src = "";
  8931. }
  8932. return img;
  8933. }
  8934. }
  8935. noIndexedDB();
  8936. }
  8937. return img;
  8938. };
  8939. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8940. url = Tools.CleanUrl(url);
  8941. url = Tools.PreprocessUrl(url);
  8942. // If file and file input are set
  8943. if (url.indexOf("file:") !== -1) {
  8944. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8945. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8946. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8947. }
  8948. }
  8949. var loadUrl = Tools.BaseUrl + url;
  8950. var aborted = false;
  8951. var fileRequest = {
  8952. onCompleteObservable: new BABYLON.Observable(),
  8953. abort: function () { return aborted = true; },
  8954. };
  8955. var requestFile = function () {
  8956. var request = new XMLHttpRequest();
  8957. var retryHandle = null;
  8958. fileRequest.abort = function () {
  8959. aborted = true;
  8960. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8961. request.abort();
  8962. }
  8963. if (retryHandle !== null) {
  8964. clearTimeout(retryHandle);
  8965. retryHandle = null;
  8966. }
  8967. };
  8968. var retryLoop = function (retryIndex) {
  8969. request.open('GET', loadUrl, true);
  8970. if (useArrayBuffer) {
  8971. request.responseType = "arraybuffer";
  8972. }
  8973. if (onProgress) {
  8974. request.addEventListener("progress", onProgress);
  8975. }
  8976. var onLoadEnd = function () {
  8977. request.removeEventListener("loadend", onLoadEnd);
  8978. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8979. fileRequest.onCompleteObservable.clear();
  8980. };
  8981. request.addEventListener("loadend", onLoadEnd);
  8982. var onReadyStateChange = function () {
  8983. if (aborted) {
  8984. return;
  8985. }
  8986. // In case of undefined state in some browsers.
  8987. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8988. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8989. request.removeEventListener("readystatechange", onReadyStateChange);
  8990. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8991. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8992. return;
  8993. }
  8994. var retryStrategy = Tools.DefaultRetryStrategy;
  8995. if (retryStrategy) {
  8996. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8997. if (waitTime !== -1) {
  8998. // Prevent the request from completing for retry.
  8999. request.removeEventListener("loadend", onLoadEnd);
  9000. request = new XMLHttpRequest();
  9001. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9002. return;
  9003. }
  9004. }
  9005. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9006. if (onError) {
  9007. onError(request, e);
  9008. }
  9009. else {
  9010. throw e;
  9011. }
  9012. }
  9013. };
  9014. request.addEventListener("readystatechange", onReadyStateChange);
  9015. request.send();
  9016. };
  9017. retryLoop(0);
  9018. };
  9019. // Caching all files
  9020. if (database && database.enableSceneOffline) {
  9021. var noIndexedDB_1 = function () {
  9022. if (!aborted) {
  9023. requestFile();
  9024. }
  9025. };
  9026. var loadFromIndexedDB = function () {
  9027. // TODO: database needs to support aborting and should return a IFileRequest
  9028. if (aborted) {
  9029. return;
  9030. }
  9031. if (database) {
  9032. database.loadFileFromDB(url, function (data) {
  9033. if (!aborted) {
  9034. onSuccess(data);
  9035. }
  9036. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9037. }, onProgress ? function (event) {
  9038. if (!aborted) {
  9039. onProgress(event);
  9040. }
  9041. } : undefined, noIndexedDB_1, useArrayBuffer);
  9042. }
  9043. };
  9044. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9045. }
  9046. else {
  9047. requestFile();
  9048. }
  9049. return fileRequest;
  9050. };
  9051. /**
  9052. * Load a script (identified by an url). When the url returns, the
  9053. * content of this file is added into a new script element, attached to the DOM (body element)
  9054. */
  9055. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9056. var head = document.getElementsByTagName('head')[0];
  9057. var script = document.createElement('script');
  9058. script.type = 'text/javascript';
  9059. script.src = scriptUrl;
  9060. script.onload = function () {
  9061. if (onSuccess) {
  9062. onSuccess();
  9063. }
  9064. };
  9065. script.onerror = function (e) {
  9066. if (onError) {
  9067. onError("Unable to load script '" + scriptUrl + "'", e);
  9068. }
  9069. };
  9070. head.appendChild(script);
  9071. };
  9072. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9073. var reader = new FileReader();
  9074. var request = {
  9075. onCompleteObservable: new BABYLON.Observable(),
  9076. abort: function () { return reader.abort(); },
  9077. };
  9078. reader.onloadend = function (e) {
  9079. request.onCompleteObservable.notifyObservers(request);
  9080. };
  9081. reader.onload = function (e) {
  9082. //target doesn't have result from ts 1.3
  9083. callback(e.target['result']);
  9084. };
  9085. reader.onprogress = progressCallback;
  9086. reader.readAsDataURL(fileToLoad);
  9087. return request;
  9088. };
  9089. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9090. var reader = new FileReader();
  9091. var request = {
  9092. onCompleteObservable: new BABYLON.Observable(),
  9093. abort: function () { return reader.abort(); },
  9094. };
  9095. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9096. reader.onerror = function (e) {
  9097. Tools.Log("Error while reading file: " + fileToLoad.name);
  9098. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9099. };
  9100. reader.onload = function (e) {
  9101. //target doesn't have result from ts 1.3
  9102. callback(e.target['result']);
  9103. };
  9104. if (progressCallBack) {
  9105. reader.onprogress = progressCallBack;
  9106. }
  9107. if (!useArrayBuffer) {
  9108. // Asynchronous read
  9109. reader.readAsText(fileToLoad);
  9110. }
  9111. else {
  9112. reader.readAsArrayBuffer(fileToLoad);
  9113. }
  9114. return request;
  9115. };
  9116. //returns a downloadable url to a file content.
  9117. Tools.FileAsURL = function (content) {
  9118. var fileBlob = new Blob([content]);
  9119. var url = window.URL || window.webkitURL;
  9120. var link = url.createObjectURL(fileBlob);
  9121. return link;
  9122. };
  9123. // Misc.
  9124. Tools.Format = function (value, decimals) {
  9125. if (decimals === void 0) { decimals = 2; }
  9126. return value.toFixed(decimals);
  9127. };
  9128. Tools.CheckExtends = function (v, min, max) {
  9129. if (v.x < min.x)
  9130. min.x = v.x;
  9131. if (v.y < min.y)
  9132. min.y = v.y;
  9133. if (v.z < min.z)
  9134. min.z = v.z;
  9135. if (v.x > max.x)
  9136. max.x = v.x;
  9137. if (v.y > max.y)
  9138. max.y = v.y;
  9139. if (v.z > max.z)
  9140. max.z = v.z;
  9141. };
  9142. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9143. for (var prop in source) {
  9144. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9145. continue;
  9146. }
  9147. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9148. continue;
  9149. }
  9150. var sourceValue = source[prop];
  9151. var typeOfSourceValue = typeof sourceValue;
  9152. if (typeOfSourceValue === "function") {
  9153. continue;
  9154. }
  9155. try {
  9156. if (typeOfSourceValue === "object") {
  9157. if (sourceValue instanceof Array) {
  9158. destination[prop] = [];
  9159. if (sourceValue.length > 0) {
  9160. if (typeof sourceValue[0] == "object") {
  9161. for (var index = 0; index < sourceValue.length; index++) {
  9162. var clonedValue = cloneValue(sourceValue[index], destination);
  9163. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9164. destination[prop].push(clonedValue);
  9165. }
  9166. }
  9167. }
  9168. else {
  9169. destination[prop] = sourceValue.slice(0);
  9170. }
  9171. }
  9172. }
  9173. else {
  9174. destination[prop] = cloneValue(sourceValue, destination);
  9175. }
  9176. }
  9177. else {
  9178. destination[prop] = sourceValue;
  9179. }
  9180. }
  9181. catch (e) {
  9182. // Just ignore error (it could be because of a read-only property)
  9183. }
  9184. }
  9185. };
  9186. Tools.IsEmpty = function (obj) {
  9187. for (var i in obj) {
  9188. if (obj.hasOwnProperty(i)) {
  9189. return false;
  9190. }
  9191. }
  9192. return true;
  9193. };
  9194. Tools.RegisterTopRootEvents = function (events) {
  9195. for (var index = 0; index < events.length; index++) {
  9196. var event = events[index];
  9197. window.addEventListener(event.name, event.handler, false);
  9198. try {
  9199. if (window.parent) {
  9200. window.parent.addEventListener(event.name, event.handler, false);
  9201. }
  9202. }
  9203. catch (e) {
  9204. // Silently fails...
  9205. }
  9206. }
  9207. };
  9208. Tools.UnregisterTopRootEvents = function (events) {
  9209. for (var index = 0; index < events.length; index++) {
  9210. var event = events[index];
  9211. window.removeEventListener(event.name, event.handler);
  9212. try {
  9213. if (window.parent) {
  9214. window.parent.removeEventListener(event.name, event.handler);
  9215. }
  9216. }
  9217. catch (e) {
  9218. // Silently fails...
  9219. }
  9220. }
  9221. };
  9222. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9223. if (mimeType === void 0) { mimeType = "image/png"; }
  9224. // Read the contents of the framebuffer
  9225. var numberOfChannelsByLine = width * 4;
  9226. var halfHeight = height / 2;
  9227. //Reading datas from WebGL
  9228. var data = engine.readPixels(0, 0, width, height);
  9229. //To flip image on Y axis.
  9230. for (var i = 0; i < halfHeight; i++) {
  9231. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9232. var currentCell = j + i * numberOfChannelsByLine;
  9233. var targetLine = height - i - 1;
  9234. var targetCell = j + targetLine * numberOfChannelsByLine;
  9235. var temp = data[currentCell];
  9236. data[currentCell] = data[targetCell];
  9237. data[targetCell] = temp;
  9238. }
  9239. }
  9240. // Create a 2D canvas to store the result
  9241. if (!screenshotCanvas) {
  9242. screenshotCanvas = document.createElement('canvas');
  9243. }
  9244. screenshotCanvas.width = width;
  9245. screenshotCanvas.height = height;
  9246. var context = screenshotCanvas.getContext('2d');
  9247. if (context) {
  9248. // Copy the pixels to a 2D canvas
  9249. var imageData = context.createImageData(width, height);
  9250. var castData = (imageData.data);
  9251. castData.set(data);
  9252. context.putImageData(imageData, 0, 0);
  9253. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9254. }
  9255. };
  9256. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9257. if (mimeType === void 0) { mimeType = "image/png"; }
  9258. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9259. if (successCallback) {
  9260. successCallback(base64Image);
  9261. }
  9262. else {
  9263. // We need HTMLCanvasElement.toBlob for HD screenshots
  9264. if (!screenshotCanvas.toBlob) {
  9265. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9266. screenshotCanvas.toBlob = function (callback, type, quality) {
  9267. var _this = this;
  9268. setTimeout(function () {
  9269. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9270. for (var i = 0; i < len; i++) {
  9271. arr[i] = binStr.charCodeAt(i);
  9272. }
  9273. callback(new Blob([arr], { type: type || 'image/png' }));
  9274. });
  9275. };
  9276. }
  9277. screenshotCanvas.toBlob(function (blob) {
  9278. var url = URL.createObjectURL(blob);
  9279. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9280. if (("download" in document.createElement("a"))) {
  9281. var a = window.document.createElement("a");
  9282. a.href = url;
  9283. if (fileName) {
  9284. a.setAttribute("download", fileName);
  9285. }
  9286. else {
  9287. var date = new Date();
  9288. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9289. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9290. }
  9291. window.document.body.appendChild(a);
  9292. a.addEventListener("click", function () {
  9293. if (a.parentElement) {
  9294. a.parentElement.removeChild(a);
  9295. }
  9296. });
  9297. a.click();
  9298. }
  9299. else {
  9300. var newWindow = window.open("");
  9301. if (!newWindow)
  9302. return;
  9303. var img = newWindow.document.createElement("img");
  9304. img.onload = function () {
  9305. // no longer need to read the blob so it's revoked
  9306. URL.revokeObjectURL(url);
  9307. };
  9308. img.src = url;
  9309. newWindow.document.body.appendChild(img);
  9310. }
  9311. });
  9312. }
  9313. };
  9314. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9315. if (mimeType === void 0) { mimeType = "image/png"; }
  9316. var width;
  9317. var height;
  9318. // If a precision value is specified
  9319. if (size.precision) {
  9320. width = Math.round(engine.getRenderWidth() * size.precision);
  9321. height = Math.round(width / engine.getAspectRatio(camera));
  9322. }
  9323. else if (size.width && size.height) {
  9324. width = size.width;
  9325. height = size.height;
  9326. }
  9327. //If passing only width, computing height to keep display canvas ratio.
  9328. else if (size.width && !size.height) {
  9329. width = size.width;
  9330. height = Math.round(width / engine.getAspectRatio(camera));
  9331. }
  9332. //If passing only height, computing width to keep display canvas ratio.
  9333. else if (size.height && !size.width) {
  9334. height = size.height;
  9335. width = Math.round(height * engine.getAspectRatio(camera));
  9336. }
  9337. //Assuming here that "size" parameter is a number
  9338. else if (!isNaN(size)) {
  9339. height = size;
  9340. width = size;
  9341. }
  9342. else {
  9343. Tools.Error("Invalid 'size' parameter !");
  9344. return;
  9345. }
  9346. if (!screenshotCanvas) {
  9347. screenshotCanvas = document.createElement('canvas');
  9348. }
  9349. screenshotCanvas.width = width;
  9350. screenshotCanvas.height = height;
  9351. var renderContext = screenshotCanvas.getContext("2d");
  9352. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9353. var newWidth = width;
  9354. var newHeight = newWidth / ratio;
  9355. if (newHeight > height) {
  9356. newHeight = height;
  9357. newWidth = newHeight * ratio;
  9358. }
  9359. var offsetX = Math.max(0, width - newWidth) / 2;
  9360. var offsetY = Math.max(0, height - newHeight) / 2;
  9361. var renderingCanvas = engine.getRenderingCanvas();
  9362. if (renderContext && renderingCanvas) {
  9363. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9364. }
  9365. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9366. };
  9367. /**
  9368. * Generates an image screenshot from the specified camera.
  9369. *
  9370. * @param engine The engine to use for rendering
  9371. * @param camera The camera to use for rendering
  9372. * @param size This parameter can be set to a single number or to an object with the
  9373. * following (optional) properties: precision, width, height. If a single number is passed,
  9374. * it will be used for both width and height. If an object is passed, the screenshot size
  9375. * will be derived from the parameters. The precision property is a multiplier allowing
  9376. * rendering at a higher or lower resolution.
  9377. * @param successCallback The callback receives a single parameter which contains the
  9378. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9379. * src parameter of an <img> to display it.
  9380. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9381. * Check your browser for supported MIME types.
  9382. * @param samples Texture samples (default: 1)
  9383. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9384. * @param fileName A name for for the downloaded file.
  9385. * @constructor
  9386. */
  9387. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9388. if (mimeType === void 0) { mimeType = "image/png"; }
  9389. if (samples === void 0) { samples = 1; }
  9390. if (antialiasing === void 0) { antialiasing = false; }
  9391. var width;
  9392. var height;
  9393. //If a precision value is specified
  9394. if (size.precision) {
  9395. width = Math.round(engine.getRenderWidth() * size.precision);
  9396. height = Math.round(width / engine.getAspectRatio(camera));
  9397. size = { width: width, height: height };
  9398. }
  9399. else if (size.width && size.height) {
  9400. width = size.width;
  9401. height = size.height;
  9402. }
  9403. //If passing only width, computing height to keep display canvas ratio.
  9404. else if (size.width && !size.height) {
  9405. width = size.width;
  9406. height = Math.round(width / engine.getAspectRatio(camera));
  9407. size = { width: width, height: height };
  9408. }
  9409. //If passing only height, computing width to keep display canvas ratio.
  9410. else if (size.height && !size.width) {
  9411. height = size.height;
  9412. width = Math.round(height * engine.getAspectRatio(camera));
  9413. size = { width: width, height: height };
  9414. }
  9415. //Assuming here that "size" parameter is a number
  9416. else if (!isNaN(size)) {
  9417. height = size;
  9418. width = size;
  9419. }
  9420. else {
  9421. Tools.Error("Invalid 'size' parameter !");
  9422. return;
  9423. }
  9424. var scene = camera.getScene();
  9425. var previousCamera = null;
  9426. if (scene.activeCamera !== camera) {
  9427. previousCamera = scene.activeCamera;
  9428. scene.activeCamera = camera;
  9429. }
  9430. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9431. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9432. texture.renderList = null;
  9433. texture.samples = samples;
  9434. if (antialiasing) {
  9435. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9436. }
  9437. texture.onAfterRenderObservable.add(function () {
  9438. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9439. });
  9440. scene.incrementRenderId();
  9441. scene.resetCachedMaterial();
  9442. texture.render(true);
  9443. texture.dispose();
  9444. if (previousCamera) {
  9445. scene.activeCamera = previousCamera;
  9446. }
  9447. camera.getProjectionMatrix(true); // Force cache refresh;
  9448. };
  9449. // XHR response validator for local file scenario
  9450. Tools.ValidateXHRData = function (xhr, dataType) {
  9451. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9452. if (dataType === void 0) { dataType = 7; }
  9453. try {
  9454. if (dataType & 1) {
  9455. if (xhr.responseText && xhr.responseText.length > 0) {
  9456. return true;
  9457. }
  9458. else if (dataType === 1) {
  9459. return false;
  9460. }
  9461. }
  9462. if (dataType & 2) {
  9463. // Check header width and height since there is no "TGA" magic number
  9464. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9465. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9466. return true;
  9467. }
  9468. else if (dataType === 2) {
  9469. return false;
  9470. }
  9471. }
  9472. if (dataType & 4) {
  9473. // Check for the "DDS" magic number
  9474. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9475. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9476. return true;
  9477. }
  9478. else {
  9479. return false;
  9480. }
  9481. }
  9482. }
  9483. catch (e) {
  9484. // Global protection
  9485. }
  9486. return false;
  9487. };
  9488. /**
  9489. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9490. * Be aware Math.random() could cause collisions, but:
  9491. * "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"
  9492. */
  9493. Tools.RandomId = function () {
  9494. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9495. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9496. return v.toString(16);
  9497. });
  9498. };
  9499. /**
  9500. * Test if the given uri is a base64 string.
  9501. * @param uri The uri to test
  9502. * @return True if the uri is a base64 string or false otherwise.
  9503. */
  9504. Tools.IsBase64 = function (uri) {
  9505. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9506. };
  9507. /**
  9508. * Decode the given base64 uri.
  9509. * @param uri The uri to decode
  9510. * @return The decoded base64 data.
  9511. */
  9512. Tools.DecodeBase64 = function (uri) {
  9513. var decodedString = atob(uri.split(",")[1]);
  9514. var bufferLength = decodedString.length;
  9515. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9516. for (var i = 0; i < bufferLength; i++) {
  9517. bufferView[i] = decodedString.charCodeAt(i);
  9518. }
  9519. return bufferView.buffer;
  9520. };
  9521. Object.defineProperty(Tools, "NoneLogLevel", {
  9522. get: function () {
  9523. return Tools._NoneLogLevel;
  9524. },
  9525. enumerable: true,
  9526. configurable: true
  9527. });
  9528. Object.defineProperty(Tools, "MessageLogLevel", {
  9529. get: function () {
  9530. return Tools._MessageLogLevel;
  9531. },
  9532. enumerable: true,
  9533. configurable: true
  9534. });
  9535. Object.defineProperty(Tools, "WarningLogLevel", {
  9536. get: function () {
  9537. return Tools._WarningLogLevel;
  9538. },
  9539. enumerable: true,
  9540. configurable: true
  9541. });
  9542. Object.defineProperty(Tools, "ErrorLogLevel", {
  9543. get: function () {
  9544. return Tools._ErrorLogLevel;
  9545. },
  9546. enumerable: true,
  9547. configurable: true
  9548. });
  9549. Object.defineProperty(Tools, "AllLogLevel", {
  9550. get: function () {
  9551. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9552. },
  9553. enumerable: true,
  9554. configurable: true
  9555. });
  9556. Tools._AddLogEntry = function (entry) {
  9557. Tools._LogCache = entry + Tools._LogCache;
  9558. if (Tools.OnNewCacheEntry) {
  9559. Tools.OnNewCacheEntry(entry);
  9560. }
  9561. };
  9562. Tools._FormatMessage = function (message) {
  9563. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9564. var date = new Date();
  9565. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9566. };
  9567. Tools._LogDisabled = function (message) {
  9568. // nothing to do
  9569. };
  9570. Tools._LogEnabled = function (message) {
  9571. var formattedMessage = Tools._FormatMessage(message);
  9572. console.log("BJS - " + formattedMessage);
  9573. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9574. Tools._AddLogEntry(entry);
  9575. };
  9576. Tools._WarnDisabled = function (message) {
  9577. // nothing to do
  9578. };
  9579. Tools._WarnEnabled = function (message) {
  9580. var formattedMessage = Tools._FormatMessage(message);
  9581. console.warn("BJS - " + formattedMessage);
  9582. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9583. Tools._AddLogEntry(entry);
  9584. };
  9585. Tools._ErrorDisabled = function (message) {
  9586. // nothing to do
  9587. };
  9588. Tools._ErrorEnabled = function (message) {
  9589. Tools.errorsCount++;
  9590. var formattedMessage = Tools._FormatMessage(message);
  9591. console.error("BJS - " + formattedMessage);
  9592. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9593. Tools._AddLogEntry(entry);
  9594. };
  9595. Object.defineProperty(Tools, "LogCache", {
  9596. get: function () {
  9597. return Tools._LogCache;
  9598. },
  9599. enumerable: true,
  9600. configurable: true
  9601. });
  9602. Tools.ClearLogCache = function () {
  9603. Tools._LogCache = "";
  9604. Tools.errorsCount = 0;
  9605. };
  9606. Object.defineProperty(Tools, "LogLevels", {
  9607. set: function (level) {
  9608. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9609. Tools.Log = Tools._LogEnabled;
  9610. }
  9611. else {
  9612. Tools.Log = Tools._LogDisabled;
  9613. }
  9614. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9615. Tools.Warn = Tools._WarnEnabled;
  9616. }
  9617. else {
  9618. Tools.Warn = Tools._WarnDisabled;
  9619. }
  9620. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9621. Tools.Error = Tools._ErrorEnabled;
  9622. }
  9623. else {
  9624. Tools.Error = Tools._ErrorDisabled;
  9625. }
  9626. },
  9627. enumerable: true,
  9628. configurable: true
  9629. });
  9630. Tools.IsWindowObjectExist = function () {
  9631. return (typeof window) !== "undefined";
  9632. };
  9633. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9634. get: function () {
  9635. return Tools._PerformanceNoneLogLevel;
  9636. },
  9637. enumerable: true,
  9638. configurable: true
  9639. });
  9640. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9641. get: function () {
  9642. return Tools._PerformanceUserMarkLogLevel;
  9643. },
  9644. enumerable: true,
  9645. configurable: true
  9646. });
  9647. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9648. get: function () {
  9649. return Tools._PerformanceConsoleLogLevel;
  9650. },
  9651. enumerable: true,
  9652. configurable: true
  9653. });
  9654. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9655. set: function (level) {
  9656. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9657. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9658. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9659. return;
  9660. }
  9661. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9662. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9663. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9664. return;
  9665. }
  9666. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9667. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9668. },
  9669. enumerable: true,
  9670. configurable: true
  9671. });
  9672. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9673. };
  9674. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9675. };
  9676. Tools._StartUserMark = function (counterName, condition) {
  9677. if (condition === void 0) { condition = true; }
  9678. if (!Tools._performance) {
  9679. if (!Tools.IsWindowObjectExist()) {
  9680. return;
  9681. }
  9682. Tools._performance = window.performance;
  9683. }
  9684. if (!condition || !Tools._performance.mark) {
  9685. return;
  9686. }
  9687. Tools._performance.mark(counterName + "-Begin");
  9688. };
  9689. Tools._EndUserMark = function (counterName, condition) {
  9690. if (condition === void 0) { condition = true; }
  9691. if (!condition || !Tools._performance.mark) {
  9692. return;
  9693. }
  9694. Tools._performance.mark(counterName + "-End");
  9695. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9696. };
  9697. Tools._StartPerformanceConsole = function (counterName, condition) {
  9698. if (condition === void 0) { condition = true; }
  9699. if (!condition) {
  9700. return;
  9701. }
  9702. Tools._StartUserMark(counterName, condition);
  9703. if (console.time) {
  9704. console.time(counterName);
  9705. }
  9706. };
  9707. Tools._EndPerformanceConsole = function (counterName, condition) {
  9708. if (condition === void 0) { condition = true; }
  9709. if (!condition) {
  9710. return;
  9711. }
  9712. Tools._EndUserMark(counterName, condition);
  9713. if (console.time) {
  9714. console.timeEnd(counterName);
  9715. }
  9716. };
  9717. Object.defineProperty(Tools, "Now", {
  9718. get: function () {
  9719. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9720. return window.performance.now();
  9721. }
  9722. return Date.now();
  9723. },
  9724. enumerable: true,
  9725. configurable: true
  9726. });
  9727. /**
  9728. * This method will return the name of the class used to create the instance of the given object.
  9729. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9730. * @param object the object to get the class name from
  9731. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9732. */
  9733. Tools.GetClassName = function (object, isType) {
  9734. if (isType === void 0) { isType = false; }
  9735. var name = null;
  9736. if (!isType && object.getClassName) {
  9737. name = object.getClassName();
  9738. }
  9739. else {
  9740. if (object instanceof Object) {
  9741. var classObj = isType ? object : Object.getPrototypeOf(object);
  9742. name = classObj.constructor["__bjsclassName__"];
  9743. }
  9744. if (!name) {
  9745. name = typeof object;
  9746. }
  9747. }
  9748. return name;
  9749. };
  9750. Tools.First = function (array, predicate) {
  9751. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9752. var el = array_1[_i];
  9753. if (predicate(el)) {
  9754. return el;
  9755. }
  9756. }
  9757. return null;
  9758. };
  9759. /**
  9760. * This method will return the name of the full name of the class, including its owning module (if any).
  9761. * 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).
  9762. * @param object the object to get the class name from
  9763. * @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.
  9764. */
  9765. Tools.getFullClassName = function (object, isType) {
  9766. if (isType === void 0) { isType = false; }
  9767. var className = null;
  9768. var moduleName = null;
  9769. if (!isType && object.getClassName) {
  9770. className = object.getClassName();
  9771. }
  9772. else {
  9773. if (object instanceof Object) {
  9774. var classObj = isType ? object : Object.getPrototypeOf(object);
  9775. className = classObj.constructor["__bjsclassName__"];
  9776. moduleName = classObj.constructor["__bjsmoduleName__"];
  9777. }
  9778. if (!className) {
  9779. className = typeof object;
  9780. }
  9781. }
  9782. if (!className) {
  9783. return null;
  9784. }
  9785. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9786. };
  9787. /**
  9788. * 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.
  9789. * @param array
  9790. */
  9791. Tools.arrayOrStringFeeder = function (array) {
  9792. return function (index) {
  9793. if (index >= array.length) {
  9794. return null;
  9795. }
  9796. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9797. if (val && val.getHashCode) {
  9798. val = val.getHashCode();
  9799. }
  9800. if (typeof val === "string") {
  9801. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9802. }
  9803. return val;
  9804. };
  9805. };
  9806. /**
  9807. * Compute the hashCode of a stream of number
  9808. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9809. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9810. * @return the hash code computed
  9811. */
  9812. Tools.hashCodeFromStream = function (feeder) {
  9813. // Based from here: http://stackoverflow.com/a/7616484/802124
  9814. var hash = 0;
  9815. var index = 0;
  9816. var chr = feeder(index++);
  9817. while (chr != null) {
  9818. hash = ((hash << 5) - hash) + chr;
  9819. hash |= 0; // Convert to 32bit integer
  9820. chr = feeder(index++);
  9821. }
  9822. return hash;
  9823. };
  9824. /**
  9825. * Returns a promise that resolves after the given amount of time.
  9826. * @param delay Number of milliseconds to delay
  9827. * @returns Promise that resolves after the given amount of time
  9828. */
  9829. Tools.DelayAsync = function (delay) {
  9830. return new Promise(function (resolve) {
  9831. setTimeout(function () {
  9832. resolve();
  9833. }, delay);
  9834. });
  9835. };
  9836. Tools.BaseUrl = "";
  9837. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9838. /**
  9839. * Default behaviour for cors in the application.
  9840. * It can be a string if the expected behavior is identical in the entire app.
  9841. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9842. */
  9843. Tools.CorsBehavior = "anonymous";
  9844. Tools.UseFallbackTexture = true;
  9845. /**
  9846. * Use this object to register external classes like custom textures or material
  9847. * to allow the laoders to instantiate them
  9848. */
  9849. Tools.RegisteredExternalClasses = {};
  9850. // Used in case of a texture loading problem
  9851. 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";
  9852. Tools._tmpFloatArray = new Float32Array(1);
  9853. Tools.PreprocessUrl = function (url) {
  9854. return url;
  9855. };
  9856. // Logs
  9857. Tools._NoneLogLevel = 0;
  9858. Tools._MessageLogLevel = 1;
  9859. Tools._WarningLogLevel = 2;
  9860. Tools._ErrorLogLevel = 4;
  9861. Tools._LogCache = "";
  9862. Tools.errorsCount = 0;
  9863. Tools.Log = Tools._LogEnabled;
  9864. Tools.Warn = Tools._WarnEnabled;
  9865. Tools.Error = Tools._ErrorEnabled;
  9866. // Performances
  9867. Tools._PerformanceNoneLogLevel = 0;
  9868. Tools._PerformanceUserMarkLogLevel = 1;
  9869. Tools._PerformanceConsoleLogLevel = 2;
  9870. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9871. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9872. return Tools;
  9873. }());
  9874. BABYLON.Tools = Tools;
  9875. /**
  9876. * This class is used to track a performance counter which is number based.
  9877. * The user has access to many properties which give statistics of different nature
  9878. *
  9879. * The implementer can track two kinds of Performance Counter: time and count
  9880. * 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.
  9881. * 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.
  9882. */
  9883. var PerfCounter = /** @class */ (function () {
  9884. function PerfCounter() {
  9885. this._startMonitoringTime = 0;
  9886. this._min = 0;
  9887. this._max = 0;
  9888. this._average = 0;
  9889. this._lastSecAverage = 0;
  9890. this._current = 0;
  9891. this._totalValueCount = 0;
  9892. this._totalAccumulated = 0;
  9893. this._lastSecAccumulated = 0;
  9894. this._lastSecTime = 0;
  9895. this._lastSecValueCount = 0;
  9896. }
  9897. Object.defineProperty(PerfCounter.prototype, "min", {
  9898. /**
  9899. * Returns the smallest value ever
  9900. */
  9901. get: function () {
  9902. return this._min;
  9903. },
  9904. enumerable: true,
  9905. configurable: true
  9906. });
  9907. Object.defineProperty(PerfCounter.prototype, "max", {
  9908. /**
  9909. * Returns the biggest value ever
  9910. */
  9911. get: function () {
  9912. return this._max;
  9913. },
  9914. enumerable: true,
  9915. configurable: true
  9916. });
  9917. Object.defineProperty(PerfCounter.prototype, "average", {
  9918. /**
  9919. * Returns the average value since the performance counter is running
  9920. */
  9921. get: function () {
  9922. return this._average;
  9923. },
  9924. enumerable: true,
  9925. configurable: true
  9926. });
  9927. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9928. /**
  9929. * Returns the average value of the last second the counter was monitored
  9930. */
  9931. get: function () {
  9932. return this._lastSecAverage;
  9933. },
  9934. enumerable: true,
  9935. configurable: true
  9936. });
  9937. Object.defineProperty(PerfCounter.prototype, "current", {
  9938. /**
  9939. * Returns the current value
  9940. */
  9941. get: function () {
  9942. return this._current;
  9943. },
  9944. enumerable: true,
  9945. configurable: true
  9946. });
  9947. Object.defineProperty(PerfCounter.prototype, "total", {
  9948. get: function () {
  9949. return this._totalAccumulated;
  9950. },
  9951. enumerable: true,
  9952. configurable: true
  9953. });
  9954. Object.defineProperty(PerfCounter.prototype, "count", {
  9955. get: function () {
  9956. return this._totalValueCount;
  9957. },
  9958. enumerable: true,
  9959. configurable: true
  9960. });
  9961. /**
  9962. * Call this method to start monitoring a new frame.
  9963. * 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.
  9964. */
  9965. PerfCounter.prototype.fetchNewFrame = function () {
  9966. this._totalValueCount++;
  9967. this._current = 0;
  9968. this._lastSecValueCount++;
  9969. };
  9970. /**
  9971. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9972. * @param newCount the count value to add to the monitored count
  9973. * @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.
  9974. */
  9975. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9976. if (!PerfCounter.Enabled) {
  9977. return;
  9978. }
  9979. this._current += newCount;
  9980. if (fetchResult) {
  9981. this._fetchResult();
  9982. }
  9983. };
  9984. /**
  9985. * Start monitoring this performance counter
  9986. */
  9987. PerfCounter.prototype.beginMonitoring = function () {
  9988. if (!PerfCounter.Enabled) {
  9989. return;
  9990. }
  9991. this._startMonitoringTime = Tools.Now;
  9992. };
  9993. /**
  9994. * Compute the time lapsed since the previous beginMonitoring() call.
  9995. * @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
  9996. */
  9997. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9998. if (newFrame === void 0) { newFrame = true; }
  9999. if (!PerfCounter.Enabled) {
  10000. return;
  10001. }
  10002. if (newFrame) {
  10003. this.fetchNewFrame();
  10004. }
  10005. var currentTime = Tools.Now;
  10006. this._current = currentTime - this._startMonitoringTime;
  10007. if (newFrame) {
  10008. this._fetchResult();
  10009. }
  10010. };
  10011. PerfCounter.prototype._fetchResult = function () {
  10012. this._totalAccumulated += this._current;
  10013. this._lastSecAccumulated += this._current;
  10014. // Min/Max update
  10015. this._min = Math.min(this._min, this._current);
  10016. this._max = Math.max(this._max, this._current);
  10017. this._average = this._totalAccumulated / this._totalValueCount;
  10018. // Reset last sec?
  10019. var now = Tools.Now;
  10020. if ((now - this._lastSecTime) > 1000) {
  10021. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10022. this._lastSecTime = now;
  10023. this._lastSecAccumulated = 0;
  10024. this._lastSecValueCount = 0;
  10025. }
  10026. };
  10027. PerfCounter.Enabled = true;
  10028. return PerfCounter;
  10029. }());
  10030. BABYLON.PerfCounter = PerfCounter;
  10031. /**
  10032. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10033. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10034. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10035. * @param name The name of the class, case should be preserved
  10036. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10037. */
  10038. function className(name, module) {
  10039. return function (target) {
  10040. target["__bjsclassName__"] = name;
  10041. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10042. };
  10043. }
  10044. BABYLON.className = className;
  10045. /**
  10046. * An implementation of a loop for asynchronous functions.
  10047. */
  10048. var AsyncLoop = /** @class */ (function () {
  10049. /**
  10050. * Constroctor.
  10051. * @param iterations the number of iterations.
  10052. * @param _fn the function to run each iteration
  10053. * @param _successCallback the callback that will be called upon succesful execution
  10054. * @param offset starting offset.
  10055. */
  10056. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10057. if (offset === void 0) { offset = 0; }
  10058. this.iterations = iterations;
  10059. this._fn = _fn;
  10060. this._successCallback = _successCallback;
  10061. this.index = offset - 1;
  10062. this._done = false;
  10063. }
  10064. /**
  10065. * Execute the next iteration. Must be called after the last iteration was finished.
  10066. */
  10067. AsyncLoop.prototype.executeNext = function () {
  10068. if (!this._done) {
  10069. if (this.index + 1 < this.iterations) {
  10070. ++this.index;
  10071. this._fn(this);
  10072. }
  10073. else {
  10074. this.breakLoop();
  10075. }
  10076. }
  10077. };
  10078. /**
  10079. * Break the loop and run the success callback.
  10080. */
  10081. AsyncLoop.prototype.breakLoop = function () {
  10082. this._done = true;
  10083. this._successCallback();
  10084. };
  10085. /**
  10086. * Helper function
  10087. */
  10088. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10089. if (offset === void 0) { offset = 0; }
  10090. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10091. loop.executeNext();
  10092. return loop;
  10093. };
  10094. /**
  10095. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10096. * @param iterations total number of iterations
  10097. * @param syncedIterations number of synchronous iterations in each async iteration.
  10098. * @param fn the function to call each iteration.
  10099. * @param callback a success call back that will be called when iterating stops.
  10100. * @param breakFunction a break condition (optional)
  10101. * @param timeout timeout settings for the setTimeout function. default - 0.
  10102. * @constructor
  10103. */
  10104. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10105. if (timeout === void 0) { timeout = 0; }
  10106. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10107. if (breakFunction && breakFunction())
  10108. loop.breakLoop();
  10109. else {
  10110. setTimeout(function () {
  10111. for (var i = 0; i < syncedIterations; ++i) {
  10112. var iteration = (loop.index * syncedIterations) + i;
  10113. if (iteration >= iterations)
  10114. break;
  10115. fn(iteration);
  10116. if (breakFunction && breakFunction()) {
  10117. loop.breakLoop();
  10118. break;
  10119. }
  10120. }
  10121. loop.executeNext();
  10122. }, timeout);
  10123. }
  10124. }, callback);
  10125. };
  10126. return AsyncLoop;
  10127. }());
  10128. BABYLON.AsyncLoop = AsyncLoop;
  10129. })(BABYLON || (BABYLON = {}));
  10130. //# sourceMappingURL=babylon.tools.js.map
  10131. var BABYLON;
  10132. (function (BABYLON) {
  10133. var PromiseStates;
  10134. (function (PromiseStates) {
  10135. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10136. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10137. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10138. })(PromiseStates || (PromiseStates = {}));
  10139. var FulFillmentAgregator = /** @class */ (function () {
  10140. function FulFillmentAgregator() {
  10141. this.count = 0;
  10142. this.target = 0;
  10143. this.results = [];
  10144. }
  10145. return FulFillmentAgregator;
  10146. }());
  10147. var InternalPromise = /** @class */ (function () {
  10148. function InternalPromise(resolver) {
  10149. var _this = this;
  10150. this._state = PromiseStates.Pending;
  10151. this._children = new Array();
  10152. this._rejectWasConsumed = false;
  10153. if (!resolver) {
  10154. return;
  10155. }
  10156. try {
  10157. resolver(function (value) {
  10158. _this._resolve(value);
  10159. }, function (reason) {
  10160. _this._reject(reason);
  10161. });
  10162. }
  10163. catch (e) {
  10164. this._reject(e);
  10165. }
  10166. }
  10167. Object.defineProperty(InternalPromise.prototype, "_result", {
  10168. get: function () {
  10169. return this._resultValue;
  10170. },
  10171. set: function (value) {
  10172. this._resultValue = value;
  10173. if (this._parent && this._parent._result === undefined) {
  10174. this._parent._result = value;
  10175. }
  10176. },
  10177. enumerable: true,
  10178. configurable: true
  10179. });
  10180. InternalPromise.prototype.catch = function (onRejected) {
  10181. return this.then(undefined, onRejected);
  10182. };
  10183. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10184. var _this = this;
  10185. var newPromise = new InternalPromise();
  10186. newPromise._onFulfilled = onFulfilled;
  10187. newPromise._onRejected = onRejected;
  10188. // Composition
  10189. this._children.push(newPromise);
  10190. newPromise._parent = this;
  10191. if (this._state !== PromiseStates.Pending) {
  10192. BABYLON.Tools.SetImmediate(function () {
  10193. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10194. var returnedValue = newPromise._resolve(_this._result);
  10195. if (returnedValue !== undefined && returnedValue !== null) {
  10196. if (returnedValue._state !== undefined) {
  10197. var returnedPromise = returnedValue;
  10198. newPromise._children.push(returnedPromise);
  10199. returnedPromise._parent = newPromise;
  10200. newPromise = returnedPromise;
  10201. }
  10202. else {
  10203. newPromise._result = returnedValue;
  10204. }
  10205. }
  10206. }
  10207. else {
  10208. newPromise._reject(_this._reason);
  10209. }
  10210. });
  10211. }
  10212. return newPromise;
  10213. };
  10214. InternalPromise.prototype._moveChildren = function (children) {
  10215. var _this = this;
  10216. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10217. this._children.forEach(function (child) {
  10218. child._parent = _this;
  10219. });
  10220. if (this._state === PromiseStates.Fulfilled) {
  10221. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10222. var child = _b[_i];
  10223. child._resolve(this._result);
  10224. }
  10225. }
  10226. else if (this._state === PromiseStates.Rejected) {
  10227. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10228. var child = _d[_c];
  10229. child._reject(this._reason);
  10230. }
  10231. }
  10232. var _a;
  10233. };
  10234. InternalPromise.prototype._resolve = function (value) {
  10235. try {
  10236. this._state = PromiseStates.Fulfilled;
  10237. var returnedValue = null;
  10238. if (this._onFulfilled) {
  10239. returnedValue = this._onFulfilled(value);
  10240. }
  10241. if (returnedValue !== undefined && returnedValue !== null) {
  10242. if (returnedValue._state !== undefined) {
  10243. // Transmit children
  10244. var returnedPromise = returnedValue;
  10245. returnedPromise._parent = this;
  10246. returnedPromise._moveChildren(this._children);
  10247. value = returnedPromise._result;
  10248. }
  10249. else {
  10250. value = returnedValue;
  10251. }
  10252. }
  10253. this._result = value;
  10254. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10255. var child = _a[_i];
  10256. child._resolve(value);
  10257. }
  10258. this._children.length = 0;
  10259. delete this._onFulfilled;
  10260. delete this._onRejected;
  10261. }
  10262. catch (e) {
  10263. this._reject(e, true);
  10264. }
  10265. };
  10266. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10267. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10268. this._state = PromiseStates.Rejected;
  10269. this._reason = reason;
  10270. if (this._onRejected && !onLocalThrow) {
  10271. try {
  10272. this._onRejected(reason);
  10273. this._rejectWasConsumed = true;
  10274. }
  10275. catch (e) {
  10276. reason = e;
  10277. }
  10278. }
  10279. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10280. var child = _a[_i];
  10281. if (this._rejectWasConsumed) {
  10282. child._resolve(null);
  10283. }
  10284. else {
  10285. child._reject(reason);
  10286. }
  10287. }
  10288. this._children.length = 0;
  10289. delete this._onFulfilled;
  10290. delete this._onRejected;
  10291. };
  10292. InternalPromise.resolve = function (value) {
  10293. var newPromise = new InternalPromise();
  10294. newPromise._resolve(value);
  10295. return newPromise;
  10296. };
  10297. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10298. promise.then(function (value) {
  10299. agregator.results[index] = value;
  10300. agregator.count++;
  10301. if (agregator.count === agregator.target) {
  10302. agregator.rootPromise._resolve(agregator.results);
  10303. }
  10304. return null;
  10305. }, function (reason) {
  10306. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10307. agregator.rootPromise._reject(reason);
  10308. }
  10309. });
  10310. };
  10311. InternalPromise.all = function (promises) {
  10312. var newPromise = new InternalPromise();
  10313. var agregator = new FulFillmentAgregator();
  10314. agregator.target = promises.length;
  10315. agregator.rootPromise = newPromise;
  10316. if (promises.length) {
  10317. for (var index = 0; index < promises.length; index++) {
  10318. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10319. }
  10320. }
  10321. else {
  10322. newPromise._resolve([]);
  10323. }
  10324. return newPromise;
  10325. };
  10326. InternalPromise.race = function (promises) {
  10327. var newPromise = new InternalPromise();
  10328. if (promises.length) {
  10329. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10330. var promise = promises_1[_i];
  10331. promise.then(function (value) {
  10332. if (newPromise) {
  10333. newPromise._resolve(value);
  10334. newPromise = null;
  10335. }
  10336. return null;
  10337. }, function (reason) {
  10338. if (newPromise) {
  10339. newPromise._reject(reason);
  10340. newPromise = null;
  10341. }
  10342. });
  10343. }
  10344. }
  10345. return newPromise;
  10346. };
  10347. return InternalPromise;
  10348. }());
  10349. /**
  10350. * Helper class that provides a small promise polyfill
  10351. */
  10352. var PromisePolyfill = /** @class */ (function () {
  10353. function PromisePolyfill() {
  10354. }
  10355. /**
  10356. * Static function used to check if the polyfill is required
  10357. * If this is the case then the function will inject the polyfill to window.Promise
  10358. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10359. */
  10360. PromisePolyfill.Apply = function (force) {
  10361. if (force === void 0) { force = false; }
  10362. if (force || typeof Promise === 'undefined') {
  10363. var root = window;
  10364. root.Promise = InternalPromise;
  10365. }
  10366. };
  10367. return PromisePolyfill;
  10368. }());
  10369. BABYLON.PromisePolyfill = PromisePolyfill;
  10370. })(BABYLON || (BABYLON = {}));
  10371. //# sourceMappingURL=babylon.promise.js.map
  10372. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10373. var BABYLON;
  10374. (function (BABYLON) {
  10375. /**
  10376. * Helper class to push actions to a pool of workers.
  10377. */
  10378. var WorkerPool = /** @class */ (function () {
  10379. /**
  10380. * Constructor
  10381. * @param workers Array of workers to use for actions
  10382. */
  10383. function WorkerPool(workers) {
  10384. this._pendingActions = new Array();
  10385. this._workerInfos = workers.map(function (worker) { return ({
  10386. worker: worker,
  10387. active: false
  10388. }); });
  10389. }
  10390. /**
  10391. * Terminates all workers and clears any pending actions.
  10392. */
  10393. WorkerPool.prototype.dispose = function () {
  10394. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10395. var workerInfo = _a[_i];
  10396. workerInfo.worker.terminate();
  10397. }
  10398. delete this._workerInfos;
  10399. delete this._pendingActions;
  10400. };
  10401. /**
  10402. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10403. * pended until a worker has completed its action.
  10404. * @param action The action to perform. Call onComplete when the action is complete.
  10405. */
  10406. WorkerPool.prototype.push = function (action) {
  10407. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10408. var workerInfo = _a[_i];
  10409. if (!workerInfo.active) {
  10410. this._execute(workerInfo, action);
  10411. return;
  10412. }
  10413. }
  10414. this._pendingActions.push(action);
  10415. };
  10416. WorkerPool.prototype._execute = function (workerInfo, action) {
  10417. var _this = this;
  10418. workerInfo.active = true;
  10419. action(workerInfo.worker, function () {
  10420. workerInfo.active = false;
  10421. var nextAction = _this._pendingActions.shift();
  10422. if (nextAction) {
  10423. _this._execute(workerInfo, nextAction);
  10424. }
  10425. });
  10426. };
  10427. return WorkerPool;
  10428. }());
  10429. BABYLON.WorkerPool = WorkerPool;
  10430. })(BABYLON || (BABYLON = {}));
  10431. //# sourceMappingURL=babylon.workerPool.js.map
  10432. var BABYLON;
  10433. (function (BABYLON) {
  10434. /**
  10435. * @hidden
  10436. **/
  10437. var _AlphaState = /** @class */ (function () {
  10438. /**
  10439. * Initializes the state.
  10440. */
  10441. function _AlphaState() {
  10442. this._isAlphaBlendDirty = false;
  10443. this._isBlendFunctionParametersDirty = false;
  10444. this._isBlendEquationParametersDirty = false;
  10445. this._isBlendConstantsDirty = false;
  10446. this._alphaBlend = false;
  10447. this._blendFunctionParameters = new Array(4);
  10448. this._blendEquationParameters = new Array(2);
  10449. this._blendConstants = new Array(4);
  10450. this.reset();
  10451. }
  10452. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10453. get: function () {
  10454. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10455. },
  10456. enumerable: true,
  10457. configurable: true
  10458. });
  10459. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10460. get: function () {
  10461. return this._alphaBlend;
  10462. },
  10463. set: function (value) {
  10464. if (this._alphaBlend === value) {
  10465. return;
  10466. }
  10467. this._alphaBlend = value;
  10468. this._isAlphaBlendDirty = true;
  10469. },
  10470. enumerable: true,
  10471. configurable: true
  10472. });
  10473. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10474. if (this._blendConstants[0] === r &&
  10475. this._blendConstants[1] === g &&
  10476. this._blendConstants[2] === b &&
  10477. this._blendConstants[3] === a) {
  10478. return;
  10479. }
  10480. this._blendConstants[0] = r;
  10481. this._blendConstants[1] = g;
  10482. this._blendConstants[2] = b;
  10483. this._blendConstants[3] = a;
  10484. this._isBlendConstantsDirty = true;
  10485. };
  10486. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10487. if (this._blendFunctionParameters[0] === value0 &&
  10488. this._blendFunctionParameters[1] === value1 &&
  10489. this._blendFunctionParameters[2] === value2 &&
  10490. this._blendFunctionParameters[3] === value3) {
  10491. return;
  10492. }
  10493. this._blendFunctionParameters[0] = value0;
  10494. this._blendFunctionParameters[1] = value1;
  10495. this._blendFunctionParameters[2] = value2;
  10496. this._blendFunctionParameters[3] = value3;
  10497. this._isBlendFunctionParametersDirty = true;
  10498. };
  10499. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10500. if (this._blendEquationParameters[0] === rgb &&
  10501. this._blendEquationParameters[1] === alpha) {
  10502. return;
  10503. }
  10504. this._blendEquationParameters[0] = rgb;
  10505. this._blendEquationParameters[1] = alpha;
  10506. this._isBlendEquationParametersDirty = true;
  10507. };
  10508. _AlphaState.prototype.reset = function () {
  10509. this._alphaBlend = false;
  10510. this._blendFunctionParameters[0] = null;
  10511. this._blendFunctionParameters[1] = null;
  10512. this._blendFunctionParameters[2] = null;
  10513. this._blendFunctionParameters[3] = null;
  10514. this._blendEquationParameters[0] = null;
  10515. this._blendEquationParameters[1] = null;
  10516. this._blendConstants[0] = null;
  10517. this._blendConstants[1] = null;
  10518. this._blendConstants[2] = null;
  10519. this._blendConstants[3] = null;
  10520. this._isAlphaBlendDirty = true;
  10521. this._isBlendFunctionParametersDirty = false;
  10522. this._isBlendEquationParametersDirty = false;
  10523. this._isBlendConstantsDirty = false;
  10524. };
  10525. _AlphaState.prototype.apply = function (gl) {
  10526. if (!this.isDirty) {
  10527. return;
  10528. }
  10529. // Alpha blend
  10530. if (this._isAlphaBlendDirty) {
  10531. if (this._alphaBlend) {
  10532. gl.enable(gl.BLEND);
  10533. }
  10534. else {
  10535. gl.disable(gl.BLEND);
  10536. }
  10537. this._isAlphaBlendDirty = false;
  10538. }
  10539. // Alpha function
  10540. if (this._isBlendFunctionParametersDirty) {
  10541. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10542. this._isBlendFunctionParametersDirty = false;
  10543. }
  10544. // Alpha equation
  10545. if (this._isBlendEquationParametersDirty) {
  10546. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10547. this._isBlendEquationParametersDirty = false;
  10548. }
  10549. // Constants
  10550. if (this._isBlendConstantsDirty) {
  10551. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10552. this._isBlendConstantsDirty = false;
  10553. }
  10554. };
  10555. return _AlphaState;
  10556. }());
  10557. BABYLON._AlphaState = _AlphaState;
  10558. })(BABYLON || (BABYLON = {}));
  10559. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10560. var BABYLON;
  10561. (function (BABYLON) {
  10562. /**
  10563. * @hidden
  10564. **/
  10565. var _DepthCullingState = /** @class */ (function () {
  10566. /**
  10567. * Initializes the state.
  10568. */
  10569. function _DepthCullingState() {
  10570. this._isDepthTestDirty = false;
  10571. this._isDepthMaskDirty = false;
  10572. this._isDepthFuncDirty = false;
  10573. this._isCullFaceDirty = false;
  10574. this._isCullDirty = false;
  10575. this._isZOffsetDirty = false;
  10576. this._isFrontFaceDirty = false;
  10577. this.reset();
  10578. }
  10579. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10580. get: function () {
  10581. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10582. },
  10583. enumerable: true,
  10584. configurable: true
  10585. });
  10586. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10587. get: function () {
  10588. return this._zOffset;
  10589. },
  10590. set: function (value) {
  10591. if (this._zOffset === value) {
  10592. return;
  10593. }
  10594. this._zOffset = value;
  10595. this._isZOffsetDirty = true;
  10596. },
  10597. enumerable: true,
  10598. configurable: true
  10599. });
  10600. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10601. get: function () {
  10602. return this._cullFace;
  10603. },
  10604. set: function (value) {
  10605. if (this._cullFace === value) {
  10606. return;
  10607. }
  10608. this._cullFace = value;
  10609. this._isCullFaceDirty = true;
  10610. },
  10611. enumerable: true,
  10612. configurable: true
  10613. });
  10614. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10615. get: function () {
  10616. return this._cull;
  10617. },
  10618. set: function (value) {
  10619. if (this._cull === value) {
  10620. return;
  10621. }
  10622. this._cull = value;
  10623. this._isCullDirty = true;
  10624. },
  10625. enumerable: true,
  10626. configurable: true
  10627. });
  10628. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10629. get: function () {
  10630. return this._depthFunc;
  10631. },
  10632. set: function (value) {
  10633. if (this._depthFunc === value) {
  10634. return;
  10635. }
  10636. this._depthFunc = value;
  10637. this._isDepthFuncDirty = true;
  10638. },
  10639. enumerable: true,
  10640. configurable: true
  10641. });
  10642. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10643. get: function () {
  10644. return this._depthMask;
  10645. },
  10646. set: function (value) {
  10647. if (this._depthMask === value) {
  10648. return;
  10649. }
  10650. this._depthMask = value;
  10651. this._isDepthMaskDirty = true;
  10652. },
  10653. enumerable: true,
  10654. configurable: true
  10655. });
  10656. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10657. get: function () {
  10658. return this._depthTest;
  10659. },
  10660. set: function (value) {
  10661. if (this._depthTest === value) {
  10662. return;
  10663. }
  10664. this._depthTest = value;
  10665. this._isDepthTestDirty = true;
  10666. },
  10667. enumerable: true,
  10668. configurable: true
  10669. });
  10670. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10671. get: function () {
  10672. return this._frontFace;
  10673. },
  10674. set: function (value) {
  10675. if (this._frontFace === value) {
  10676. return;
  10677. }
  10678. this._frontFace = value;
  10679. this._isFrontFaceDirty = true;
  10680. },
  10681. enumerable: true,
  10682. configurable: true
  10683. });
  10684. _DepthCullingState.prototype.reset = function () {
  10685. this._depthMask = true;
  10686. this._depthTest = true;
  10687. this._depthFunc = null;
  10688. this._cullFace = null;
  10689. this._cull = null;
  10690. this._zOffset = 0;
  10691. this._frontFace = null;
  10692. this._isDepthTestDirty = true;
  10693. this._isDepthMaskDirty = true;
  10694. this._isDepthFuncDirty = false;
  10695. this._isCullFaceDirty = false;
  10696. this._isCullDirty = false;
  10697. this._isZOffsetDirty = false;
  10698. this._isFrontFaceDirty = false;
  10699. };
  10700. _DepthCullingState.prototype.apply = function (gl) {
  10701. if (!this.isDirty) {
  10702. return;
  10703. }
  10704. // Cull
  10705. if (this._isCullDirty) {
  10706. if (this.cull) {
  10707. gl.enable(gl.CULL_FACE);
  10708. }
  10709. else {
  10710. gl.disable(gl.CULL_FACE);
  10711. }
  10712. this._isCullDirty = false;
  10713. }
  10714. // Cull face
  10715. if (this._isCullFaceDirty) {
  10716. gl.cullFace(this.cullFace);
  10717. this._isCullFaceDirty = false;
  10718. }
  10719. // Depth mask
  10720. if (this._isDepthMaskDirty) {
  10721. gl.depthMask(this.depthMask);
  10722. this._isDepthMaskDirty = false;
  10723. }
  10724. // Depth test
  10725. if (this._isDepthTestDirty) {
  10726. if (this.depthTest) {
  10727. gl.enable(gl.DEPTH_TEST);
  10728. }
  10729. else {
  10730. gl.disable(gl.DEPTH_TEST);
  10731. }
  10732. this._isDepthTestDirty = false;
  10733. }
  10734. // Depth func
  10735. if (this._isDepthFuncDirty) {
  10736. gl.depthFunc(this.depthFunc);
  10737. this._isDepthFuncDirty = false;
  10738. }
  10739. // zOffset
  10740. if (this._isZOffsetDirty) {
  10741. if (this.zOffset) {
  10742. gl.enable(gl.POLYGON_OFFSET_FILL);
  10743. gl.polygonOffset(this.zOffset, 0);
  10744. }
  10745. else {
  10746. gl.disable(gl.POLYGON_OFFSET_FILL);
  10747. }
  10748. this._isZOffsetDirty = false;
  10749. }
  10750. // Front face
  10751. if (this._isFrontFaceDirty) {
  10752. gl.frontFace(this.frontFace);
  10753. this._isFrontFaceDirty = false;
  10754. }
  10755. };
  10756. return _DepthCullingState;
  10757. }());
  10758. BABYLON._DepthCullingState = _DepthCullingState;
  10759. })(BABYLON || (BABYLON = {}));
  10760. //# sourceMappingURL=babylon.depthCullingState.js.map
  10761. var BABYLON;
  10762. (function (BABYLON) {
  10763. /**
  10764. * @hidden
  10765. **/
  10766. var _StencilState = /** @class */ (function () {
  10767. function _StencilState() {
  10768. this._isStencilTestDirty = false;
  10769. this._isStencilMaskDirty = false;
  10770. this._isStencilFuncDirty = false;
  10771. this._isStencilOpDirty = false;
  10772. this.reset();
  10773. }
  10774. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10775. get: function () {
  10776. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10777. },
  10778. enumerable: true,
  10779. configurable: true
  10780. });
  10781. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10782. get: function () {
  10783. return this._stencilFunc;
  10784. },
  10785. set: function (value) {
  10786. if (this._stencilFunc === value) {
  10787. return;
  10788. }
  10789. this._stencilFunc = value;
  10790. this._isStencilFuncDirty = true;
  10791. },
  10792. enumerable: true,
  10793. configurable: true
  10794. });
  10795. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10796. get: function () {
  10797. return this._stencilFuncRef;
  10798. },
  10799. set: function (value) {
  10800. if (this._stencilFuncRef === value) {
  10801. return;
  10802. }
  10803. this._stencilFuncRef = value;
  10804. this._isStencilFuncDirty = true;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10810. get: function () {
  10811. return this._stencilFuncMask;
  10812. },
  10813. set: function (value) {
  10814. if (this._stencilFuncMask === value) {
  10815. return;
  10816. }
  10817. this._stencilFuncMask = value;
  10818. this._isStencilFuncDirty = true;
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10824. get: function () {
  10825. return this._stencilOpStencilFail;
  10826. },
  10827. set: function (value) {
  10828. if (this._stencilOpStencilFail === value) {
  10829. return;
  10830. }
  10831. this._stencilOpStencilFail = value;
  10832. this._isStencilOpDirty = true;
  10833. },
  10834. enumerable: true,
  10835. configurable: true
  10836. });
  10837. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10838. get: function () {
  10839. return this._stencilOpDepthFail;
  10840. },
  10841. set: function (value) {
  10842. if (this._stencilOpDepthFail === value) {
  10843. return;
  10844. }
  10845. this._stencilOpDepthFail = value;
  10846. this._isStencilOpDirty = true;
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10852. get: function () {
  10853. return this._stencilOpStencilDepthPass;
  10854. },
  10855. set: function (value) {
  10856. if (this._stencilOpStencilDepthPass === value) {
  10857. return;
  10858. }
  10859. this._stencilOpStencilDepthPass = value;
  10860. this._isStencilOpDirty = true;
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10866. get: function () {
  10867. return this._stencilMask;
  10868. },
  10869. set: function (value) {
  10870. if (this._stencilMask === value) {
  10871. return;
  10872. }
  10873. this._stencilMask = value;
  10874. this._isStencilMaskDirty = true;
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10880. get: function () {
  10881. return this._stencilTest;
  10882. },
  10883. set: function (value) {
  10884. if (this._stencilTest === value) {
  10885. return;
  10886. }
  10887. this._stencilTest = value;
  10888. this._isStencilTestDirty = true;
  10889. },
  10890. enumerable: true,
  10891. configurable: true
  10892. });
  10893. _StencilState.prototype.reset = function () {
  10894. this._stencilTest = false;
  10895. this._stencilMask = 0xFF;
  10896. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10897. this._stencilFuncRef = 1;
  10898. this._stencilFuncMask = 0xFF;
  10899. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10900. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10901. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10902. this._isStencilTestDirty = true;
  10903. this._isStencilMaskDirty = true;
  10904. this._isStencilFuncDirty = true;
  10905. this._isStencilOpDirty = true;
  10906. };
  10907. _StencilState.prototype.apply = function (gl) {
  10908. if (!this.isDirty) {
  10909. return;
  10910. }
  10911. // Stencil test
  10912. if (this._isStencilTestDirty) {
  10913. if (this.stencilTest) {
  10914. gl.enable(gl.STENCIL_TEST);
  10915. }
  10916. else {
  10917. gl.disable(gl.STENCIL_TEST);
  10918. }
  10919. this._isStencilTestDirty = false;
  10920. }
  10921. // Stencil mask
  10922. if (this._isStencilMaskDirty) {
  10923. gl.stencilMask(this.stencilMask);
  10924. this._isStencilMaskDirty = false;
  10925. }
  10926. // Stencil func
  10927. if (this._isStencilFuncDirty) {
  10928. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10929. this._isStencilFuncDirty = false;
  10930. }
  10931. // Stencil op
  10932. if (this._isStencilOpDirty) {
  10933. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10934. this._isStencilOpDirty = false;
  10935. }
  10936. };
  10937. return _StencilState;
  10938. }());
  10939. BABYLON._StencilState = _StencilState;
  10940. })(BABYLON || (BABYLON = {}));
  10941. //# sourceMappingURL=babylon.stencilState.js.map
  10942. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10943. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10944. s = arguments[i];
  10945. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10946. t[p] = s[p];
  10947. }
  10948. return t;
  10949. };
  10950. var BABYLON;
  10951. (function (BABYLON) {
  10952. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10953. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10954. };
  10955. var compileRawShader = function (gl, source, type) {
  10956. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10957. gl.shaderSource(shader, source);
  10958. gl.compileShader(shader);
  10959. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10960. var log = gl.getShaderInfoLog(shader);
  10961. if (log) {
  10962. throw new Error(log);
  10963. }
  10964. }
  10965. if (!shader) {
  10966. throw new Error("Something went wrong while compile the shader.");
  10967. }
  10968. return shader;
  10969. };
  10970. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10971. var magFilter = gl.NEAREST;
  10972. var minFilter = gl.NEAREST;
  10973. switch (samplingMode) {
  10974. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10975. magFilter = gl.LINEAR;
  10976. if (generateMipMaps) {
  10977. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10978. }
  10979. else {
  10980. minFilter = gl.LINEAR;
  10981. }
  10982. break;
  10983. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10984. magFilter = gl.LINEAR;
  10985. if (generateMipMaps) {
  10986. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10987. }
  10988. else {
  10989. minFilter = gl.LINEAR;
  10990. }
  10991. break;
  10992. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10993. magFilter = gl.NEAREST;
  10994. if (generateMipMaps) {
  10995. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10996. }
  10997. else {
  10998. minFilter = gl.NEAREST;
  10999. }
  11000. break;
  11001. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11002. magFilter = gl.NEAREST;
  11003. if (generateMipMaps) {
  11004. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11005. }
  11006. else {
  11007. minFilter = gl.NEAREST;
  11008. }
  11009. break;
  11010. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11011. magFilter = gl.NEAREST;
  11012. if (generateMipMaps) {
  11013. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11014. }
  11015. else {
  11016. minFilter = gl.LINEAR;
  11017. }
  11018. break;
  11019. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11020. magFilter = gl.NEAREST;
  11021. if (generateMipMaps) {
  11022. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11023. }
  11024. else {
  11025. minFilter = gl.LINEAR;
  11026. }
  11027. break;
  11028. case BABYLON.Texture.NEAREST_LINEAR:
  11029. magFilter = gl.NEAREST;
  11030. minFilter = gl.LINEAR;
  11031. break;
  11032. case BABYLON.Texture.NEAREST_NEAREST:
  11033. magFilter = gl.NEAREST;
  11034. minFilter = gl.NEAREST;
  11035. break;
  11036. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11037. magFilter = gl.LINEAR;
  11038. if (generateMipMaps) {
  11039. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11040. }
  11041. else {
  11042. minFilter = gl.NEAREST;
  11043. }
  11044. break;
  11045. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11046. magFilter = gl.LINEAR;
  11047. if (generateMipMaps) {
  11048. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11049. }
  11050. else {
  11051. minFilter = gl.NEAREST;
  11052. }
  11053. break;
  11054. case BABYLON.Texture.LINEAR_LINEAR:
  11055. magFilter = gl.LINEAR;
  11056. minFilter = gl.LINEAR;
  11057. break;
  11058. case BABYLON.Texture.LINEAR_NEAREST:
  11059. magFilter = gl.LINEAR;
  11060. minFilter = gl.NEAREST;
  11061. break;
  11062. }
  11063. return {
  11064. min: minFilter,
  11065. mag: magFilter
  11066. };
  11067. };
  11068. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11069. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11070. var img;
  11071. var onload = function () {
  11072. loadedImages[index] = img;
  11073. loadedImages._internalCount++;
  11074. if (scene) {
  11075. scene._removePendingData(img);
  11076. }
  11077. if (loadedImages._internalCount === 6) {
  11078. onfinish(loadedImages);
  11079. }
  11080. };
  11081. var onerror = function (message, exception) {
  11082. if (scene) {
  11083. scene._removePendingData(img);
  11084. }
  11085. if (onErrorCallBack) {
  11086. onErrorCallBack(message, exception);
  11087. }
  11088. };
  11089. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11090. if (scene) {
  11091. scene._addPendingData(img);
  11092. }
  11093. };
  11094. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11095. if (onError === void 0) { onError = null; }
  11096. var loadedImages = [];
  11097. loadedImages._internalCount = 0;
  11098. for (var index = 0; index < 6; index++) {
  11099. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11100. }
  11101. };
  11102. var BufferPointer = /** @class */ (function () {
  11103. function BufferPointer() {
  11104. }
  11105. return BufferPointer;
  11106. }());
  11107. /**
  11108. * Interface for attribute information associated with buffer instanciation
  11109. */
  11110. var InstancingAttributeInfo = /** @class */ (function () {
  11111. function InstancingAttributeInfo() {
  11112. }
  11113. return InstancingAttributeInfo;
  11114. }());
  11115. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11116. /**
  11117. * Define options used to create a render target texture
  11118. */
  11119. var RenderTargetCreationOptions = /** @class */ (function () {
  11120. function RenderTargetCreationOptions() {
  11121. }
  11122. return RenderTargetCreationOptions;
  11123. }());
  11124. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11125. /**
  11126. * Define options used to create a depth texture
  11127. */
  11128. var DepthTextureCreationOptions = /** @class */ (function () {
  11129. function DepthTextureCreationOptions() {
  11130. }
  11131. return DepthTextureCreationOptions;
  11132. }());
  11133. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11134. /**
  11135. * Class used to describe the capabilities of the engine relatively to the current browser
  11136. */
  11137. var EngineCapabilities = /** @class */ (function () {
  11138. function EngineCapabilities() {
  11139. }
  11140. return EngineCapabilities;
  11141. }());
  11142. BABYLON.EngineCapabilities = EngineCapabilities;
  11143. /**
  11144. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11145. */
  11146. var Engine = /** @class */ (function () {
  11147. /**
  11148. * Creates a new engine
  11149. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11150. * @param antialias defines enable antialiasing (default: false)
  11151. * @param options defines further options to be sent to the getContext() function
  11152. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11153. */
  11154. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11155. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11156. var _this = this;
  11157. // Public members
  11158. /**
  11159. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11160. */
  11161. this.forcePOTTextures = false;
  11162. /**
  11163. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11164. */
  11165. this.isFullscreen = false;
  11166. /**
  11167. * Gets a boolean indicating if the pointer is currently locked
  11168. */
  11169. this.isPointerLock = false;
  11170. /**
  11171. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11172. */
  11173. this.cullBackFaces = true;
  11174. /**
  11175. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11176. */
  11177. this.renderEvenInBackground = true;
  11178. /**
  11179. * Gets or sets a boolean indicating that cache can be kept between frames
  11180. */
  11181. this.preventCacheWipeBetweenFrames = false;
  11182. /**
  11183. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11184. **/
  11185. this.enableOfflineSupport = false;
  11186. /**
  11187. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11188. **/
  11189. this.disableManifestCheck = false;
  11190. /**
  11191. * Gets the list of created scenes
  11192. */
  11193. this.scenes = new Array();
  11194. /**
  11195. * Gets the list of created postprocesses
  11196. */
  11197. this.postProcesses = new Array();
  11198. // Observables
  11199. /**
  11200. * Observable event triggered each time the rendering canvas is resized
  11201. */
  11202. this.onResizeObservable = new BABYLON.Observable();
  11203. /**
  11204. * Observable event triggered each time the canvas loses focus
  11205. */
  11206. this.onCanvasBlurObservable = new BABYLON.Observable();
  11207. /**
  11208. * Observable event triggered each time the canvas gains focus
  11209. */
  11210. this.onCanvasFocusObservable = new BABYLON.Observable();
  11211. /**
  11212. * Observable event triggered each time the canvas receives pointerout event
  11213. */
  11214. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11215. /**
  11216. * Observable event triggered before each texture is initialized
  11217. */
  11218. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11219. //WebVR
  11220. this._vrDisplay = undefined;
  11221. this._vrSupported = false;
  11222. this._vrExclusivePointerMode = false;
  11223. // Uniform buffers list
  11224. /**
  11225. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11226. */
  11227. this.disableUniformBuffers = false;
  11228. /** @hidden */
  11229. this._uniformBuffers = new Array();
  11230. // Observables
  11231. /**
  11232. * Observable raised when the engine begins a new frame
  11233. */
  11234. this.onBeginFrameObservable = new BABYLON.Observable();
  11235. /**
  11236. * Observable raised when the engine ends the current frame
  11237. */
  11238. this.onEndFrameObservable = new BABYLON.Observable();
  11239. /**
  11240. * Observable raised when the engine is about to compile a shader
  11241. */
  11242. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11243. /**
  11244. * Observable raised when the engine has jsut compiled a shader
  11245. */
  11246. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11247. this._windowIsBackground = false;
  11248. this._webGLVersion = 1.0;
  11249. /** @hidden */
  11250. this._badOS = false;
  11251. /** @hidden */
  11252. this._badDesktopOS = false;
  11253. /**
  11254. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11255. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11256. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11257. */
  11258. this.disableTextureBindingOptimization = false;
  11259. /**
  11260. * Observable signaled when VR display mode changes
  11261. */
  11262. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11263. /**
  11264. * Observable signaled when VR request present is complete
  11265. */
  11266. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11267. /**
  11268. * Observable signaled when VR request present starts
  11269. */
  11270. this.onVRRequestPresentStart = new BABYLON.Observable();
  11271. this._colorWrite = true;
  11272. /** @hidden */
  11273. this._drawCalls = new BABYLON.PerfCounter();
  11274. /** @hidden */
  11275. this._textureCollisions = new BABYLON.PerfCounter();
  11276. this._renderingQueueLaunched = false;
  11277. this._activeRenderLoops = new Array();
  11278. // Deterministic lockstepMaxSteps
  11279. this._deterministicLockstep = false;
  11280. this._lockstepMaxSteps = 4;
  11281. // Lost context
  11282. /**
  11283. * Observable signaled when a context lost event is raised
  11284. */
  11285. this.onContextLostObservable = new BABYLON.Observable();
  11286. /**
  11287. * Observable signaled when a context restored event is raised
  11288. */
  11289. this.onContextRestoredObservable = new BABYLON.Observable();
  11290. this._contextWasLost = false;
  11291. this._doNotHandleContextLost = false;
  11292. // FPS
  11293. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11294. this._fps = 60;
  11295. this._deltaTime = 0;
  11296. /**
  11297. * Turn this value on if you want to pause FPS computation when in background
  11298. */
  11299. this.disablePerformanceMonitorInBackground = false;
  11300. // States
  11301. /** @hidden */
  11302. this._depthCullingState = new BABYLON._DepthCullingState();
  11303. /** @hidden */
  11304. this._stencilState = new BABYLON._StencilState();
  11305. /** @hidden */
  11306. this._alphaState = new BABYLON._AlphaState();
  11307. /** @hidden */
  11308. this._alphaMode = Engine.ALPHA_DISABLE;
  11309. // Cache
  11310. this._internalTexturesCache = new Array();
  11311. /** @hidden */
  11312. this._activeChannel = 0;
  11313. this._currentTextureChannel = -1;
  11314. /** @hidden */
  11315. this._boundTexturesCache = {};
  11316. this._compiledEffects = {};
  11317. this._vertexAttribArraysEnabled = [];
  11318. this._uintIndicesCurrentlySet = false;
  11319. this._currentBoundBuffer = new Array();
  11320. this._currentBufferPointers = new Array();
  11321. this._currentInstanceLocations = new Array();
  11322. this._currentInstanceBuffers = new Array();
  11323. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11324. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11325. this._vaoRecordInProgress = false;
  11326. this._mustWipeVertexAttributes = false;
  11327. this._nextFreeTextureSlots = new Array();
  11328. this._maxSimultaneousTextures = 0;
  11329. this._activeRequests = new Array();
  11330. // Hardware supported Compressed Textures
  11331. this._texturesSupported = new Array();
  11332. this._onVRFullScreenTriggered = function () {
  11333. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11334. //get the old size before we change
  11335. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11336. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11337. //get the width and height, change the render size
  11338. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11339. _this.setHardwareScalingLevel(1);
  11340. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11341. }
  11342. else {
  11343. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11344. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11345. }
  11346. };
  11347. this._boundUniforms = {};
  11348. // Register promises
  11349. BABYLON.PromisePolyfill.Apply();
  11350. var canvas = null;
  11351. Engine.Instances.push(this);
  11352. if (!canvasOrContext) {
  11353. return;
  11354. }
  11355. options = options || {};
  11356. if (canvasOrContext.getContext) {
  11357. canvas = canvasOrContext;
  11358. this._renderingCanvas = canvas;
  11359. if (antialias != null) {
  11360. options.antialias = antialias;
  11361. }
  11362. if (options.deterministicLockstep === undefined) {
  11363. options.deterministicLockstep = false;
  11364. }
  11365. if (options.lockstepMaxSteps === undefined) {
  11366. options.lockstepMaxSteps = 4;
  11367. }
  11368. if (options.preserveDrawingBuffer === undefined) {
  11369. options.preserveDrawingBuffer = false;
  11370. }
  11371. if (options.audioEngine === undefined) {
  11372. options.audioEngine = true;
  11373. }
  11374. if (options.stencil === undefined) {
  11375. options.stencil = true;
  11376. }
  11377. this._deterministicLockstep = options.deterministicLockstep;
  11378. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11379. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11380. // Exceptions
  11381. if (navigator && navigator.userAgent) {
  11382. var ua = navigator.userAgent;
  11383. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11384. var exception = _a[_i];
  11385. var key = exception.key;
  11386. var targets = exception.targets;
  11387. if (ua.indexOf(key) > -1) {
  11388. if (exception.capture && exception.captureConstraint) {
  11389. var capture = exception.capture;
  11390. var constraint = exception.captureConstraint;
  11391. var regex = new RegExp(capture);
  11392. var matches = regex.exec(ua);
  11393. if (matches && matches.length > 0) {
  11394. var capturedValue = parseInt(matches[matches.length - 1]);
  11395. if (capturedValue >= constraint) {
  11396. continue;
  11397. }
  11398. }
  11399. }
  11400. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11401. var target = targets_1[_b];
  11402. switch (target) {
  11403. case "uniformBuffer":
  11404. this.disableUniformBuffers = true;
  11405. break;
  11406. case "textureBindingOptimization":
  11407. this.disableTextureBindingOptimization = true;
  11408. break;
  11409. }
  11410. }
  11411. }
  11412. }
  11413. }
  11414. // GL
  11415. if (!options.disableWebGL2Support) {
  11416. try {
  11417. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11418. if (this._gl) {
  11419. this._webGLVersion = 2.0;
  11420. }
  11421. }
  11422. catch (e) {
  11423. // Do nothing
  11424. }
  11425. }
  11426. if (!this._gl) {
  11427. if (!canvas) {
  11428. throw new Error("The provided canvas is null or undefined.");
  11429. }
  11430. try {
  11431. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11432. }
  11433. catch (e) {
  11434. throw new Error("WebGL not supported");
  11435. }
  11436. }
  11437. if (!this._gl) {
  11438. throw new Error("WebGL not supported");
  11439. }
  11440. this._onCanvasFocus = function () {
  11441. _this.onCanvasFocusObservable.notifyObservers(_this);
  11442. };
  11443. this._onCanvasBlur = function () {
  11444. _this.onCanvasBlurObservable.notifyObservers(_this);
  11445. };
  11446. canvas.addEventListener("focus", this._onCanvasFocus);
  11447. canvas.addEventListener("blur", this._onCanvasBlur);
  11448. this._onBlur = function () {
  11449. if (_this.disablePerformanceMonitorInBackground) {
  11450. _this._performanceMonitor.disable();
  11451. }
  11452. _this._windowIsBackground = true;
  11453. };
  11454. this._onFocus = function () {
  11455. if (_this.disablePerformanceMonitorInBackground) {
  11456. _this._performanceMonitor.enable();
  11457. }
  11458. _this._windowIsBackground = false;
  11459. };
  11460. this._onCanvasPointerOut = function (ev) {
  11461. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11462. };
  11463. window.addEventListener("blur", this._onBlur);
  11464. window.addEventListener("focus", this._onFocus);
  11465. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11466. // Context lost
  11467. if (!this._doNotHandleContextLost) {
  11468. this._onContextLost = function (evt) {
  11469. evt.preventDefault();
  11470. _this._contextWasLost = true;
  11471. BABYLON.Tools.Warn("WebGL context lost.");
  11472. _this.onContextLostObservable.notifyObservers(_this);
  11473. };
  11474. this._onContextRestored = function (evt) {
  11475. // Adding a timeout to avoid race condition at browser level
  11476. setTimeout(function () {
  11477. // Rebuild gl context
  11478. _this._initGLContext();
  11479. // Rebuild effects
  11480. _this._rebuildEffects();
  11481. // Rebuild textures
  11482. _this._rebuildInternalTextures();
  11483. // Rebuild buffers
  11484. _this._rebuildBuffers();
  11485. // Cache
  11486. _this.wipeCaches(true);
  11487. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11488. _this.onContextRestoredObservable.notifyObservers(_this);
  11489. _this._contextWasLost = false;
  11490. }, 0);
  11491. };
  11492. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11493. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11494. }
  11495. }
  11496. else {
  11497. this._gl = canvasOrContext;
  11498. this._renderingCanvas = this._gl.canvas;
  11499. if (this._gl.renderbufferStorageMultisample) {
  11500. this._webGLVersion = 2.0;
  11501. }
  11502. options.stencil = this._gl.getContextAttributes().stencil;
  11503. }
  11504. // Viewport
  11505. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11506. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11507. this.resize();
  11508. this._isStencilEnable = options.stencil ? true : false;
  11509. this._initGLContext();
  11510. if (canvas) {
  11511. // Fullscreen
  11512. this._onFullscreenChange = function () {
  11513. if (document.fullscreen !== undefined) {
  11514. _this.isFullscreen = document.fullscreen;
  11515. }
  11516. else if (document.mozFullScreen !== undefined) {
  11517. _this.isFullscreen = document.mozFullScreen;
  11518. }
  11519. else if (document.webkitIsFullScreen !== undefined) {
  11520. _this.isFullscreen = document.webkitIsFullScreen;
  11521. }
  11522. else if (document.msIsFullScreen !== undefined) {
  11523. _this.isFullscreen = document.msIsFullScreen;
  11524. }
  11525. // Pointer lock
  11526. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11527. canvas.requestPointerLock = canvas.requestPointerLock ||
  11528. canvas.msRequestPointerLock ||
  11529. canvas.mozRequestPointerLock ||
  11530. canvas.webkitRequestPointerLock;
  11531. if (canvas.requestPointerLock) {
  11532. canvas.requestPointerLock();
  11533. }
  11534. }
  11535. };
  11536. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11537. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11538. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11539. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11540. // Pointer lock
  11541. this._onPointerLockChange = function () {
  11542. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11543. document.webkitPointerLockElement === canvas ||
  11544. document.msPointerLockElement === canvas ||
  11545. document.pointerLockElement === canvas);
  11546. };
  11547. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11548. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11549. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11550. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11551. this._onVRDisplayPointerRestricted = function () {
  11552. if (canvas) {
  11553. canvas.requestPointerLock();
  11554. }
  11555. };
  11556. this._onVRDisplayPointerUnrestricted = function () {
  11557. document.exitPointerLock();
  11558. };
  11559. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11560. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11561. }
  11562. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11563. Engine.audioEngine = new BABYLON.AudioEngine();
  11564. }
  11565. // Prepare buffer pointers
  11566. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11567. this._currentBufferPointers[i] = new BufferPointer();
  11568. }
  11569. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11570. // Load WebVR Devices
  11571. if (options.autoEnableWebVR) {
  11572. this.initWebVR();
  11573. }
  11574. // Detect if we are running on a faulty buggy OS.
  11575. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11576. // Detect if we are running on a faulty buggy desktop OS.
  11577. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11578. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11579. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11580. }
  11581. Object.defineProperty(Engine, "LastCreatedEngine", {
  11582. /**
  11583. * Gets the latest created engine
  11584. */
  11585. get: function () {
  11586. if (Engine.Instances.length === 0) {
  11587. return null;
  11588. }
  11589. return Engine.Instances[Engine.Instances.length - 1];
  11590. },
  11591. enumerable: true,
  11592. configurable: true
  11593. });
  11594. Object.defineProperty(Engine, "LastCreatedScene", {
  11595. /**
  11596. * Gets the latest created scene
  11597. */
  11598. get: function () {
  11599. var lastCreatedEngine = Engine.LastCreatedEngine;
  11600. if (!lastCreatedEngine) {
  11601. return null;
  11602. }
  11603. if (lastCreatedEngine.scenes.length === 0) {
  11604. return null;
  11605. }
  11606. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11607. },
  11608. enumerable: true,
  11609. configurable: true
  11610. });
  11611. /**
  11612. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11613. * @param flag defines which part of the materials must be marked as dirty
  11614. * @param predicate defines a predicate used to filter which materials should be affected
  11615. */
  11616. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11617. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11618. var engine = Engine.Instances[engineIndex];
  11619. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11620. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11621. }
  11622. }
  11623. };
  11624. Object.defineProperty(Engine, "NEVER", {
  11625. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11626. get: function () {
  11627. return Engine._NEVER;
  11628. },
  11629. enumerable: true,
  11630. configurable: true
  11631. });
  11632. Object.defineProperty(Engine, "ALWAYS", {
  11633. /** 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 */
  11634. get: function () {
  11635. return Engine._ALWAYS;
  11636. },
  11637. enumerable: true,
  11638. configurable: true
  11639. });
  11640. Object.defineProperty(Engine, "LESS", {
  11641. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11642. get: function () {
  11643. return Engine._LESS;
  11644. },
  11645. enumerable: true,
  11646. configurable: true
  11647. });
  11648. Object.defineProperty(Engine, "EQUAL", {
  11649. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11650. get: function () {
  11651. return Engine._EQUAL;
  11652. },
  11653. enumerable: true,
  11654. configurable: true
  11655. });
  11656. Object.defineProperty(Engine, "LEQUAL", {
  11657. /** 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 */
  11658. get: function () {
  11659. return Engine._LEQUAL;
  11660. },
  11661. enumerable: true,
  11662. configurable: true
  11663. });
  11664. Object.defineProperty(Engine, "GREATER", {
  11665. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11666. get: function () {
  11667. return Engine._GREATER;
  11668. },
  11669. enumerable: true,
  11670. configurable: true
  11671. });
  11672. Object.defineProperty(Engine, "GEQUAL", {
  11673. /** 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 */
  11674. get: function () {
  11675. return Engine._GEQUAL;
  11676. },
  11677. enumerable: true,
  11678. configurable: true
  11679. });
  11680. Object.defineProperty(Engine, "NOTEQUAL", {
  11681. /** 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 */
  11682. get: function () {
  11683. return Engine._NOTEQUAL;
  11684. },
  11685. enumerable: true,
  11686. configurable: true
  11687. });
  11688. Object.defineProperty(Engine, "KEEP", {
  11689. /** Passed to stencilOperation to specify that stencil value must be kept */
  11690. get: function () {
  11691. return Engine._KEEP;
  11692. },
  11693. enumerable: true,
  11694. configurable: true
  11695. });
  11696. Object.defineProperty(Engine, "REPLACE", {
  11697. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11698. get: function () {
  11699. return Engine._REPLACE;
  11700. },
  11701. enumerable: true,
  11702. configurable: true
  11703. });
  11704. Object.defineProperty(Engine, "INCR", {
  11705. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11706. get: function () {
  11707. return Engine._INCR;
  11708. },
  11709. enumerable: true,
  11710. configurable: true
  11711. });
  11712. Object.defineProperty(Engine, "DECR", {
  11713. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11714. get: function () {
  11715. return Engine._DECR;
  11716. },
  11717. enumerable: true,
  11718. configurable: true
  11719. });
  11720. Object.defineProperty(Engine, "INVERT", {
  11721. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11722. get: function () {
  11723. return Engine._INVERT;
  11724. },
  11725. enumerable: true,
  11726. configurable: true
  11727. });
  11728. Object.defineProperty(Engine, "INCR_WRAP", {
  11729. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11730. get: function () {
  11731. return Engine._INCR_WRAP;
  11732. },
  11733. enumerable: true,
  11734. configurable: true
  11735. });
  11736. Object.defineProperty(Engine, "DECR_WRAP", {
  11737. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11738. get: function () {
  11739. return Engine._DECR_WRAP;
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11745. // Alpha
  11746. /** Defines that alpha blending is disabled */
  11747. get: function () {
  11748. return Engine._ALPHA_DISABLE;
  11749. },
  11750. enumerable: true,
  11751. configurable: true
  11752. });
  11753. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11754. /** Defines that alpha blending to SRC + DEST */
  11755. get: function () {
  11756. return Engine._ALPHA_ONEONE;
  11757. },
  11758. enumerable: true,
  11759. configurable: true
  11760. });
  11761. Object.defineProperty(Engine, "ALPHA_ADD", {
  11762. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11763. get: function () {
  11764. return Engine._ALPHA_ADD;
  11765. },
  11766. enumerable: true,
  11767. configurable: true
  11768. });
  11769. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11770. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11771. get: function () {
  11772. return Engine._ALPHA_COMBINE;
  11773. },
  11774. enumerable: true,
  11775. configurable: true
  11776. });
  11777. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11778. /** Defines that alpha blending to DEST - SRC * DEST */
  11779. get: function () {
  11780. return Engine._ALPHA_SUBTRACT;
  11781. },
  11782. enumerable: true,
  11783. configurable: true
  11784. });
  11785. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11786. /** Defines that alpha blending to SRC * DEST */
  11787. get: function () {
  11788. return Engine._ALPHA_MULTIPLY;
  11789. },
  11790. enumerable: true,
  11791. configurable: true
  11792. });
  11793. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11794. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11795. get: function () {
  11796. return Engine._ALPHA_MAXIMIZED;
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11802. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11803. get: function () {
  11804. return Engine._ALPHA_PREMULTIPLIED;
  11805. },
  11806. enumerable: true,
  11807. configurable: true
  11808. });
  11809. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11810. /**
  11811. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11812. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11813. */
  11814. get: function () {
  11815. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11816. },
  11817. enumerable: true,
  11818. configurable: true
  11819. });
  11820. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11821. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11822. get: function () {
  11823. return Engine._ALPHA_INTERPOLATE;
  11824. },
  11825. enumerable: true,
  11826. configurable: true
  11827. });
  11828. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11829. /**
  11830. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11831. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11832. */
  11833. get: function () {
  11834. return Engine._ALPHA_SCREENMODE;
  11835. },
  11836. enumerable: true,
  11837. configurable: true
  11838. });
  11839. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11840. // Delays
  11841. /** Defines that the ressource is not delayed*/
  11842. get: function () {
  11843. return Engine._DELAYLOADSTATE_NONE;
  11844. },
  11845. enumerable: true,
  11846. configurable: true
  11847. });
  11848. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11849. /** Defines that the ressource was successfully delay loaded */
  11850. get: function () {
  11851. return Engine._DELAYLOADSTATE_LOADED;
  11852. },
  11853. enumerable: true,
  11854. configurable: true
  11855. });
  11856. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11857. /** Defines that the ressource is currently delay loading */
  11858. get: function () {
  11859. return Engine._DELAYLOADSTATE_LOADING;
  11860. },
  11861. enumerable: true,
  11862. configurable: true
  11863. });
  11864. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11865. /** Defines that the ressource is delayed and has not started loading */
  11866. get: function () {
  11867. return Engine._DELAYLOADSTATE_NOTLOADED;
  11868. },
  11869. enumerable: true,
  11870. configurable: true
  11871. });
  11872. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11873. /** ALPHA */
  11874. get: function () {
  11875. return Engine._TEXTUREFORMAT_ALPHA;
  11876. },
  11877. enumerable: true,
  11878. configurable: true
  11879. });
  11880. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11881. /** LUMINANCE */
  11882. get: function () {
  11883. return Engine._TEXTUREFORMAT_LUMINANCE;
  11884. },
  11885. enumerable: true,
  11886. configurable: true
  11887. });
  11888. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11889. /**
  11890. * R32F
  11891. */
  11892. get: function () {
  11893. return Engine._TEXTUREFORMAT_R32F;
  11894. },
  11895. enumerable: true,
  11896. configurable: true
  11897. });
  11898. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11899. /**
  11900. * RG32F
  11901. */
  11902. get: function () {
  11903. return Engine._TEXTUREFORMAT_RG32F;
  11904. },
  11905. enumerable: true,
  11906. configurable: true
  11907. });
  11908. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11909. /**
  11910. * RGB32F
  11911. */
  11912. get: function () {
  11913. return Engine._TEXTUREFORMAT_RGB32F;
  11914. },
  11915. enumerable: true,
  11916. configurable: true
  11917. });
  11918. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11919. /**
  11920. * RGBA32F
  11921. */
  11922. get: function () {
  11923. return Engine._TEXTUREFORMAT_RGBA32F;
  11924. },
  11925. enumerable: true,
  11926. configurable: true
  11927. });
  11928. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11929. /** LUMINANCE_ALPHA */
  11930. get: function () {
  11931. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11932. },
  11933. enumerable: true,
  11934. configurable: true
  11935. });
  11936. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11937. /** RGB */
  11938. get: function () {
  11939. return Engine._TEXTUREFORMAT_RGB;
  11940. },
  11941. enumerable: true,
  11942. configurable: true
  11943. });
  11944. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11945. /** RGBA */
  11946. get: function () {
  11947. return Engine._TEXTUREFORMAT_RGBA;
  11948. },
  11949. enumerable: true,
  11950. configurable: true
  11951. });
  11952. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11953. /** UNSIGNED_INT */
  11954. get: function () {
  11955. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11961. /** FLOAT */
  11962. get: function () {
  11963. return Engine._TEXTURETYPE_FLOAT;
  11964. },
  11965. enumerable: true,
  11966. configurable: true
  11967. });
  11968. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11969. /** HALF_FLOAT */
  11970. get: function () {
  11971. return Engine._TEXTURETYPE_HALF_FLOAT;
  11972. },
  11973. enumerable: true,
  11974. configurable: true
  11975. });
  11976. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11977. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11978. get: function () {
  11979. return Engine._SCALEMODE_FLOOR;
  11980. },
  11981. enumerable: true,
  11982. configurable: true
  11983. });
  11984. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11985. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11986. get: function () {
  11987. return Engine._SCALEMODE_NEAREST;
  11988. },
  11989. enumerable: true,
  11990. configurable: true
  11991. });
  11992. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11993. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11994. get: function () {
  11995. return Engine._SCALEMODE_CEILING;
  11996. },
  11997. enumerable: true,
  11998. configurable: true
  11999. });
  12000. Object.defineProperty(Engine, "Version", {
  12001. /**
  12002. * Returns the current version of the framework
  12003. */
  12004. get: function () {
  12005. return "3.3.0-alpha.0";
  12006. },
  12007. enumerable: true,
  12008. configurable: true
  12009. });
  12010. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12011. /**
  12012. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12013. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12014. */
  12015. get: function () {
  12016. return this._vrExclusivePointerMode;
  12017. },
  12018. enumerable: true,
  12019. configurable: true
  12020. });
  12021. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12022. /**
  12023. * Gets a boolean indicating that the engine supports uniform buffers
  12024. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12025. */
  12026. get: function () {
  12027. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12028. },
  12029. enumerable: true,
  12030. configurable: true
  12031. });
  12032. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12033. /**
  12034. * Gets a boolean indicating that only power of 2 textures are supported
  12035. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12036. */
  12037. get: function () {
  12038. return this._webGLVersion < 2 || this.forcePOTTextures;
  12039. },
  12040. enumerable: true,
  12041. configurable: true
  12042. });
  12043. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12044. /**
  12045. * Gets the performance monitor attached to this engine
  12046. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12047. */
  12048. get: function () {
  12049. return this._performanceMonitor;
  12050. },
  12051. enumerable: true,
  12052. configurable: true
  12053. });
  12054. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12055. /**
  12056. * Gets the list of texture formats supported
  12057. */
  12058. get: function () {
  12059. return this._texturesSupported;
  12060. },
  12061. enumerable: true,
  12062. configurable: true
  12063. });
  12064. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12065. /**
  12066. * Gets the list of texture formats in use
  12067. */
  12068. get: function () {
  12069. return this._textureFormatInUse;
  12070. },
  12071. enumerable: true,
  12072. configurable: true
  12073. });
  12074. Object.defineProperty(Engine.prototype, "currentViewport", {
  12075. /**
  12076. * Gets the current viewport
  12077. */
  12078. get: function () {
  12079. return this._cachedViewport;
  12080. },
  12081. enumerable: true,
  12082. configurable: true
  12083. });
  12084. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12085. /**
  12086. * Gets the default empty texture
  12087. */
  12088. get: function () {
  12089. if (!this._emptyTexture) {
  12090. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12091. }
  12092. return this._emptyTexture;
  12093. },
  12094. enumerable: true,
  12095. configurable: true
  12096. });
  12097. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12098. /**
  12099. * Gets the default empty 3D texture
  12100. */
  12101. get: function () {
  12102. if (!this._emptyTexture3D) {
  12103. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12104. }
  12105. return this._emptyTexture3D;
  12106. },
  12107. enumerable: true,
  12108. configurable: true
  12109. });
  12110. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12111. /**
  12112. * Gets the default empty cube texture
  12113. */
  12114. get: function () {
  12115. if (!this._emptyCubeTexture) {
  12116. var faceData = new Uint8Array(4);
  12117. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12118. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12119. }
  12120. return this._emptyCubeTexture;
  12121. },
  12122. enumerable: true,
  12123. configurable: true
  12124. });
  12125. Engine.prototype._rebuildInternalTextures = function () {
  12126. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12127. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12128. var internalTexture = currentState_1[_i];
  12129. internalTexture._rebuild();
  12130. }
  12131. };
  12132. Engine.prototype._rebuildEffects = function () {
  12133. for (var key in this._compiledEffects) {
  12134. var effect = this._compiledEffects[key];
  12135. effect._prepareEffect();
  12136. }
  12137. BABYLON.Effect.ResetCache();
  12138. };
  12139. Engine.prototype._rebuildBuffers = function () {
  12140. // Index / Vertex
  12141. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12142. var scene = _a[_i];
  12143. scene.resetCachedMaterial();
  12144. scene._rebuildGeometries();
  12145. scene._rebuildTextures();
  12146. }
  12147. // Uniforms
  12148. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12149. var uniformBuffer = _c[_b];
  12150. uniformBuffer._rebuild();
  12151. }
  12152. };
  12153. Engine.prototype._initGLContext = function () {
  12154. // Caps
  12155. this._caps = new EngineCapabilities();
  12156. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12157. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12158. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12159. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12160. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12161. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12162. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12163. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12164. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12165. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12166. // Infos
  12167. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12168. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12169. if (rendererInfo != null) {
  12170. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12171. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12172. }
  12173. if (!this._glVendor) {
  12174. this._glVendor = "Unknown vendor";
  12175. }
  12176. if (!this._glRenderer) {
  12177. this._glRenderer = "Unknown renderer";
  12178. }
  12179. // Constants
  12180. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12181. if (this._gl.RGBA16F !== 0x881A) {
  12182. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12183. }
  12184. if (this._gl.RGBA32F !== 0x8814) {
  12185. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12186. }
  12187. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12188. this._gl.DEPTH24_STENCIL8 = 35056;
  12189. }
  12190. // Extensions
  12191. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12192. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12193. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12194. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12195. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12196. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12197. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12198. 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');
  12199. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12200. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12201. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12202. this._caps.highPrecisionShaderSupported = true;
  12203. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12204. if (this._caps.timerQuery) {
  12205. if (this._webGLVersion === 1) {
  12206. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12207. }
  12208. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12209. }
  12210. // Checks if some of the format renders first to allow the use of webgl inspector.
  12211. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12212. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12213. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12214. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12215. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12216. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12217. if (this._webGLVersion > 1) {
  12218. this._gl.HALF_FLOAT_OES = 0x140B;
  12219. }
  12220. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12221. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12222. // Draw buffers
  12223. if (this._webGLVersion > 1) {
  12224. this._caps.drawBuffersExtension = true;
  12225. }
  12226. else {
  12227. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12228. if (drawBuffersExtension !== null) {
  12229. this._caps.drawBuffersExtension = true;
  12230. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12231. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12232. for (var i = 0; i < 16; i++) {
  12233. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12234. }
  12235. }
  12236. else {
  12237. this._caps.drawBuffersExtension = false;
  12238. }
  12239. }
  12240. // Depth Texture
  12241. if (this._webGLVersion > 1) {
  12242. this._caps.depthTextureExtension = true;
  12243. }
  12244. else {
  12245. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12246. if (depthTextureExtension != null) {
  12247. this._caps.depthTextureExtension = true;
  12248. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12249. }
  12250. }
  12251. // Vertex array object
  12252. if (this._webGLVersion > 1) {
  12253. this._caps.vertexArrayObject = true;
  12254. }
  12255. else {
  12256. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12257. if (vertexArrayObjectExtension != null) {
  12258. this._caps.vertexArrayObject = true;
  12259. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12260. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12261. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12262. }
  12263. else {
  12264. this._caps.vertexArrayObject = false;
  12265. }
  12266. }
  12267. // Instances count
  12268. if (this._webGLVersion > 1) {
  12269. this._caps.instancedArrays = true;
  12270. }
  12271. else {
  12272. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12273. if (instanceExtension != null) {
  12274. this._caps.instancedArrays = true;
  12275. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12276. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12277. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12278. }
  12279. else {
  12280. this._caps.instancedArrays = false;
  12281. }
  12282. }
  12283. // Intelligently add supported compressed formats in order to check for.
  12284. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12285. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12286. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12287. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12288. if (this._caps.astc)
  12289. this.texturesSupported.push('-astc.ktx');
  12290. if (this._caps.s3tc)
  12291. this.texturesSupported.push('-dxt.ktx');
  12292. if (this._caps.pvrtc)
  12293. this.texturesSupported.push('-pvrtc.ktx');
  12294. if (this._caps.etc2)
  12295. this.texturesSupported.push('-etc2.ktx');
  12296. if (this._caps.etc1)
  12297. this.texturesSupported.push('-etc1.ktx');
  12298. if (this._gl.getShaderPrecisionFormat) {
  12299. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12300. if (highp) {
  12301. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12302. }
  12303. }
  12304. // Depth buffer
  12305. this.setDepthBuffer(true);
  12306. this.setDepthFunctionToLessOrEqual();
  12307. this.setDepthWrite(true);
  12308. // Texture maps
  12309. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12310. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12311. this._nextFreeTextureSlots.push(slot);
  12312. }
  12313. };
  12314. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12315. /**
  12316. * Gets version of the current webGL context
  12317. */
  12318. get: function () {
  12319. return this._webGLVersion;
  12320. },
  12321. enumerable: true,
  12322. configurable: true
  12323. });
  12324. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12325. /**
  12326. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12327. */
  12328. get: function () {
  12329. return this._isStencilEnable;
  12330. },
  12331. enumerable: true,
  12332. configurable: true
  12333. });
  12334. Engine.prototype._prepareWorkingCanvas = function () {
  12335. if (this._workingCanvas) {
  12336. return;
  12337. }
  12338. this._workingCanvas = document.createElement("canvas");
  12339. var context = this._workingCanvas.getContext("2d");
  12340. if (context) {
  12341. this._workingContext = context;
  12342. }
  12343. };
  12344. /**
  12345. * Reset the texture cache to empty state
  12346. */
  12347. Engine.prototype.resetTextureCache = function () {
  12348. for (var key in this._boundTexturesCache) {
  12349. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12350. continue;
  12351. }
  12352. var boundTexture = this._boundTexturesCache[key];
  12353. if (boundTexture) {
  12354. this._removeDesignatedSlot(boundTexture);
  12355. }
  12356. this._boundTexturesCache[key] = null;
  12357. }
  12358. if (!this.disableTextureBindingOptimization) {
  12359. this._nextFreeTextureSlots = [];
  12360. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12361. this._nextFreeTextureSlots.push(slot);
  12362. }
  12363. }
  12364. this._currentTextureChannel = -1;
  12365. };
  12366. /**
  12367. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12368. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12369. * @returns true if engine is in deterministic lock step mode
  12370. */
  12371. Engine.prototype.isDeterministicLockStep = function () {
  12372. return this._deterministicLockstep;
  12373. };
  12374. /**
  12375. * Gets the max steps when engine is running in deterministic lock step
  12376. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12377. * @returns the max steps
  12378. */
  12379. Engine.prototype.getLockstepMaxSteps = function () {
  12380. return this._lockstepMaxSteps;
  12381. };
  12382. /**
  12383. * Gets an object containing information about the current webGL context
  12384. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12385. */
  12386. Engine.prototype.getGlInfo = function () {
  12387. return {
  12388. vendor: this._glVendor,
  12389. renderer: this._glRenderer,
  12390. version: this._glVersion
  12391. };
  12392. };
  12393. /**
  12394. * Gets current aspect ratio
  12395. * @param camera defines the camera to use to get the aspect ratio
  12396. * @param useScreen defines if screen size must be used (or the current render target if any)
  12397. * @returns a number defining the aspect ratio
  12398. */
  12399. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12400. if (useScreen === void 0) { useScreen = false; }
  12401. var viewport = camera.viewport;
  12402. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12403. };
  12404. /**
  12405. * Gets current screen aspect ratio
  12406. * @returns a number defining the aspect ratio
  12407. */
  12408. Engine.prototype.getScreenAspectRatio = function () {
  12409. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12410. };
  12411. /**
  12412. * Gets the current render width
  12413. * @param useScreen defines if screen size must be used (or the current render target if any)
  12414. * @returns a number defining the current render width
  12415. */
  12416. Engine.prototype.getRenderWidth = function (useScreen) {
  12417. if (useScreen === void 0) { useScreen = false; }
  12418. if (!useScreen && this._currentRenderTarget) {
  12419. return this._currentRenderTarget.width;
  12420. }
  12421. return this._gl.drawingBufferWidth;
  12422. };
  12423. /**
  12424. * Gets the current render height
  12425. * @param useScreen defines if screen size must be used (or the current render target if any)
  12426. * @returns a number defining the current render height
  12427. */
  12428. Engine.prototype.getRenderHeight = function (useScreen) {
  12429. if (useScreen === void 0) { useScreen = false; }
  12430. if (!useScreen && this._currentRenderTarget) {
  12431. return this._currentRenderTarget.height;
  12432. }
  12433. return this._gl.drawingBufferHeight;
  12434. };
  12435. /**
  12436. * Gets the HTML canvas attached with the current webGL context
  12437. * @returns a HTML canvas
  12438. */
  12439. Engine.prototype.getRenderingCanvas = function () {
  12440. return this._renderingCanvas;
  12441. };
  12442. /**
  12443. * Gets the client rect of the HTML canvas attached with the current webGL context
  12444. * @returns a client rectanglee
  12445. */
  12446. Engine.prototype.getRenderingCanvasClientRect = function () {
  12447. if (!this._renderingCanvas) {
  12448. return null;
  12449. }
  12450. return this._renderingCanvas.getBoundingClientRect();
  12451. };
  12452. /**
  12453. * Defines the hardware scaling level.
  12454. * By default the hardware scaling level is computed from the window device ratio.
  12455. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12456. * @param level defines the level to use
  12457. */
  12458. Engine.prototype.setHardwareScalingLevel = function (level) {
  12459. this._hardwareScalingLevel = level;
  12460. this.resize();
  12461. };
  12462. /**
  12463. * Gets the current hardware scaling level.
  12464. * By default the hardware scaling level is computed from the window device ratio.
  12465. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12466. * @returns a number indicating the current hardware scaling level
  12467. */
  12468. Engine.prototype.getHardwareScalingLevel = function () {
  12469. return this._hardwareScalingLevel;
  12470. };
  12471. /**
  12472. * Gets the list of loaded textures
  12473. * @returns an array containing all loaded textures
  12474. */
  12475. Engine.prototype.getLoadedTexturesCache = function () {
  12476. return this._internalTexturesCache;
  12477. };
  12478. /**
  12479. * Gets the object containing all engine capabilities
  12480. * @returns the EngineCapabilities object
  12481. */
  12482. Engine.prototype.getCaps = function () {
  12483. return this._caps;
  12484. };
  12485. Object.defineProperty(Engine.prototype, "drawCalls", {
  12486. /** @hidden */
  12487. get: function () {
  12488. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12489. return 0;
  12490. },
  12491. enumerable: true,
  12492. configurable: true
  12493. });
  12494. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12495. /** @hidden */
  12496. get: function () {
  12497. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12498. return null;
  12499. },
  12500. enumerable: true,
  12501. configurable: true
  12502. });
  12503. /**
  12504. * Gets the current depth function
  12505. * @returns a number defining the depth function
  12506. */
  12507. Engine.prototype.getDepthFunction = function () {
  12508. return this._depthCullingState.depthFunc;
  12509. };
  12510. /**
  12511. * Sets the current depth function
  12512. * @param depthFunc defines the function to use
  12513. */
  12514. Engine.prototype.setDepthFunction = function (depthFunc) {
  12515. this._depthCullingState.depthFunc = depthFunc;
  12516. };
  12517. /**
  12518. * Sets the current depth function to GREATER
  12519. */
  12520. Engine.prototype.setDepthFunctionToGreater = function () {
  12521. this._depthCullingState.depthFunc = this._gl.GREATER;
  12522. };
  12523. /**
  12524. * Sets the current depth function to GEQUAL
  12525. */
  12526. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12527. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12528. };
  12529. /**
  12530. * Sets the current depth function to LESS
  12531. */
  12532. Engine.prototype.setDepthFunctionToLess = function () {
  12533. this._depthCullingState.depthFunc = this._gl.LESS;
  12534. };
  12535. /**
  12536. * Sets the current depth function to LEQUAL
  12537. */
  12538. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12539. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12540. };
  12541. /**
  12542. * Gets a boolean indicating if stencil buffer is enabled
  12543. * @returns the current stencil buffer state
  12544. */
  12545. Engine.prototype.getStencilBuffer = function () {
  12546. return this._stencilState.stencilTest;
  12547. };
  12548. /**
  12549. * Enable or disable the stencil buffer
  12550. * @param enable defines if the stencil buffer must be enabled or disabled
  12551. */
  12552. Engine.prototype.setStencilBuffer = function (enable) {
  12553. this._stencilState.stencilTest = enable;
  12554. };
  12555. /**
  12556. * Gets the current stencil mask
  12557. * @returns a number defining the new stencil mask to use
  12558. */
  12559. Engine.prototype.getStencilMask = function () {
  12560. return this._stencilState.stencilMask;
  12561. };
  12562. /**
  12563. * Sets the current stencil mask
  12564. * @param mask defines the new stencil mask to use
  12565. */
  12566. Engine.prototype.setStencilMask = function (mask) {
  12567. this._stencilState.stencilMask = mask;
  12568. };
  12569. /**
  12570. * Gets the current stencil function
  12571. * @returns a number defining the stencil function to use
  12572. */
  12573. Engine.prototype.getStencilFunction = function () {
  12574. return this._stencilState.stencilFunc;
  12575. };
  12576. /**
  12577. * Gets the current stencil reference value
  12578. * @returns a number defining the stencil reference value to use
  12579. */
  12580. Engine.prototype.getStencilFunctionReference = function () {
  12581. return this._stencilState.stencilFuncRef;
  12582. };
  12583. /**
  12584. * Gets the current stencil mask
  12585. * @returns a number defining the stencil mask to use
  12586. */
  12587. Engine.prototype.getStencilFunctionMask = function () {
  12588. return this._stencilState.stencilFuncMask;
  12589. };
  12590. /**
  12591. * Sets the current stencil function
  12592. * @param stencilFunc defines the new stencil function to use
  12593. */
  12594. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12595. this._stencilState.stencilFunc = stencilFunc;
  12596. };
  12597. /**
  12598. * Sets the current stencil reference
  12599. * @param reference defines the new stencil reference to use
  12600. */
  12601. Engine.prototype.setStencilFunctionReference = function (reference) {
  12602. this._stencilState.stencilFuncRef = reference;
  12603. };
  12604. /**
  12605. * Sets the current stencil mask
  12606. * @param mask defines the new stencil mask to use
  12607. */
  12608. Engine.prototype.setStencilFunctionMask = function (mask) {
  12609. this._stencilState.stencilFuncMask = mask;
  12610. };
  12611. /**
  12612. * Gets the current stencil operation when stencil fails
  12613. * @returns a number defining stencil operation to use when stencil fails
  12614. */
  12615. Engine.prototype.getStencilOperationFail = function () {
  12616. return this._stencilState.stencilOpStencilFail;
  12617. };
  12618. /**
  12619. * Gets the current stencil operation when depth fails
  12620. * @returns a number defining stencil operation to use when depth fails
  12621. */
  12622. Engine.prototype.getStencilOperationDepthFail = function () {
  12623. return this._stencilState.stencilOpDepthFail;
  12624. };
  12625. /**
  12626. * Gets the current stencil operation when stencil passes
  12627. * @returns a number defining stencil operation to use when stencil passes
  12628. */
  12629. Engine.prototype.getStencilOperationPass = function () {
  12630. return this._stencilState.stencilOpStencilDepthPass;
  12631. };
  12632. /**
  12633. * Sets the stencil operation to use when stencil fails
  12634. * @param operation defines the stencil operation to use when stencil fails
  12635. */
  12636. Engine.prototype.setStencilOperationFail = function (operation) {
  12637. this._stencilState.stencilOpStencilFail = operation;
  12638. };
  12639. /**
  12640. * Sets the stencil operation to use when depth fails
  12641. * @param operation defines the stencil operation to use when depth fails
  12642. */
  12643. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12644. this._stencilState.stencilOpDepthFail = operation;
  12645. };
  12646. /**
  12647. * Sets the stencil operation to use when stencil passes
  12648. * @param operation defines the stencil operation to use when stencil passes
  12649. */
  12650. Engine.prototype.setStencilOperationPass = function (operation) {
  12651. this._stencilState.stencilOpStencilDepthPass = operation;
  12652. };
  12653. /**
  12654. * Sets a boolean indicating if the dithering state is enabled or disabled
  12655. * @param value defines the dithering state
  12656. */
  12657. Engine.prototype.setDitheringState = function (value) {
  12658. if (value) {
  12659. this._gl.enable(this._gl.DITHER);
  12660. }
  12661. else {
  12662. this._gl.disable(this._gl.DITHER);
  12663. }
  12664. };
  12665. /**
  12666. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12667. * @param value defines the rasterizer state
  12668. */
  12669. Engine.prototype.setRasterizerState = function (value) {
  12670. if (value) {
  12671. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12672. }
  12673. else {
  12674. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12675. }
  12676. };
  12677. /**
  12678. * stop executing a render loop function and remove it from the execution array
  12679. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12680. */
  12681. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12682. if (!renderFunction) {
  12683. this._activeRenderLoops = [];
  12684. return;
  12685. }
  12686. var index = this._activeRenderLoops.indexOf(renderFunction);
  12687. if (index >= 0) {
  12688. this._activeRenderLoops.splice(index, 1);
  12689. }
  12690. };
  12691. /** @hidden */
  12692. Engine.prototype._renderLoop = function () {
  12693. if (!this._contextWasLost) {
  12694. var shouldRender = true;
  12695. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12696. shouldRender = false;
  12697. }
  12698. if (shouldRender) {
  12699. // Start new frame
  12700. this.beginFrame();
  12701. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12702. var renderFunction = this._activeRenderLoops[index];
  12703. renderFunction();
  12704. }
  12705. // Present
  12706. this.endFrame();
  12707. }
  12708. }
  12709. if (this._activeRenderLoops.length > 0) {
  12710. // Register new frame
  12711. var requester = null;
  12712. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12713. requester = this._vrDisplay;
  12714. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12715. }
  12716. else {
  12717. this._renderingQueueLaunched = false;
  12718. }
  12719. };
  12720. /**
  12721. * Register and execute a render loop. The engine can have more than one render function
  12722. * @param renderFunction defines the function to continuously execute
  12723. */
  12724. Engine.prototype.runRenderLoop = function (renderFunction) {
  12725. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12726. return;
  12727. }
  12728. this._activeRenderLoops.push(renderFunction);
  12729. if (!this._renderingQueueLaunched) {
  12730. this._renderingQueueLaunched = true;
  12731. this._bindedRenderFunction = this._renderLoop.bind(this);
  12732. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12733. }
  12734. };
  12735. /**
  12736. * Toggle full screen mode
  12737. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12738. * @param options defines an option object to be sent to the requestFullscreen function
  12739. */
  12740. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12741. if (this.isFullscreen) {
  12742. BABYLON.Tools.ExitFullscreen();
  12743. }
  12744. else {
  12745. this._pointerLockRequested = requestPointerLock;
  12746. if (this._renderingCanvas) {
  12747. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12748. }
  12749. }
  12750. };
  12751. /**
  12752. * Clear the current render buffer or the current render target (if any is set up)
  12753. * @param color defines the color to use
  12754. * @param backBuffer defines if the back buffer must be cleared
  12755. * @param depth defines if the depth buffer must be cleared
  12756. * @param stencil defines if the stencil buffer must be cleared
  12757. */
  12758. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12759. if (stencil === void 0) { stencil = false; }
  12760. this.applyStates();
  12761. var mode = 0;
  12762. if (backBuffer && color) {
  12763. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12764. mode |= this._gl.COLOR_BUFFER_BIT;
  12765. }
  12766. if (depth) {
  12767. this._gl.clearDepth(1.0);
  12768. mode |= this._gl.DEPTH_BUFFER_BIT;
  12769. }
  12770. if (stencil) {
  12771. this._gl.clearStencil(0);
  12772. mode |= this._gl.STENCIL_BUFFER_BIT;
  12773. }
  12774. this._gl.clear(mode);
  12775. };
  12776. /**
  12777. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12778. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12779. * @param y defines the y-coordinate of the corner of the clear rectangle
  12780. * @param width defines the width of the clear rectangle
  12781. * @param height defines the height of the clear rectangle
  12782. * @param clearColor defines the clear color
  12783. */
  12784. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12785. var gl = this._gl;
  12786. // Save state
  12787. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12788. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12789. // Change state
  12790. gl.enable(gl.SCISSOR_TEST);
  12791. gl.scissor(x, y, width, height);
  12792. // Clear
  12793. this.clear(clearColor, true, true, true);
  12794. // Restore state
  12795. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12796. if (curScissor === true) {
  12797. gl.enable(gl.SCISSOR_TEST);
  12798. }
  12799. else {
  12800. gl.disable(gl.SCISSOR_TEST);
  12801. }
  12802. };
  12803. /**
  12804. * Set the WebGL's viewport
  12805. * @param viewport defines the viewport element to be used
  12806. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12807. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12808. */
  12809. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12810. var width = requiredWidth || this.getRenderWidth();
  12811. var height = requiredHeight || this.getRenderHeight();
  12812. var x = viewport.x || 0;
  12813. var y = viewport.y || 0;
  12814. this._cachedViewport = viewport;
  12815. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12816. };
  12817. /**
  12818. * Directly set the WebGL Viewport
  12819. * @param x defines the x coordinate of the viewport (in screen space)
  12820. * @param y defines the y coordinate of the viewport (in screen space)
  12821. * @param width defines the width of the viewport (in screen space)
  12822. * @param height defines the height of the viewport (in screen space)
  12823. * @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
  12824. */
  12825. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12826. var currentViewport = this._cachedViewport;
  12827. this._cachedViewport = null;
  12828. this._gl.viewport(x, y, width, height);
  12829. return currentViewport;
  12830. };
  12831. /**
  12832. * Begin a new frame
  12833. */
  12834. Engine.prototype.beginFrame = function () {
  12835. this.onBeginFrameObservable.notifyObservers(this);
  12836. this._measureFps();
  12837. };
  12838. /**
  12839. * Enf the current frame
  12840. */
  12841. Engine.prototype.endFrame = function () {
  12842. // Force a flush in case we are using a bad OS.
  12843. if (this._badOS) {
  12844. this.flushFramebuffer();
  12845. }
  12846. // Submit frame to the vr device, if enabled
  12847. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12848. // TODO: We should only submit the frame if we read frameData successfully.
  12849. this._vrDisplay.submitFrame();
  12850. }
  12851. this.onEndFrameObservable.notifyObservers(this);
  12852. };
  12853. /**
  12854. * Resize the view according to the canvas' size
  12855. */
  12856. Engine.prototype.resize = function () {
  12857. // We're not resizing the size of the canvas while in VR mode & presenting
  12858. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12859. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12860. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12861. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12862. }
  12863. };
  12864. /**
  12865. * Force a specific size of the canvas
  12866. * @param width defines the new canvas' width
  12867. * @param height defines the new canvas' height
  12868. */
  12869. Engine.prototype.setSize = function (width, height) {
  12870. if (!this._renderingCanvas) {
  12871. return;
  12872. }
  12873. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12874. return;
  12875. }
  12876. this._renderingCanvas.width = width;
  12877. this._renderingCanvas.height = height;
  12878. for (var index = 0; index < this.scenes.length; index++) {
  12879. var scene = this.scenes[index];
  12880. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12881. var cam = scene.cameras[camIndex];
  12882. cam._currentRenderId = 0;
  12883. }
  12884. }
  12885. if (this.onResizeObservable.hasObservers) {
  12886. this.onResizeObservable.notifyObservers(this);
  12887. }
  12888. };
  12889. // WebVR functions
  12890. /**
  12891. * Gets a boolean indicating if a webVR device was detected
  12892. * @returns true if a webVR device was detected
  12893. */
  12894. Engine.prototype.isVRDevicePresent = function () {
  12895. return !!this._vrDisplay;
  12896. };
  12897. /**
  12898. * Gets the current webVR device
  12899. * @returns the current webVR device (or null)
  12900. */
  12901. Engine.prototype.getVRDevice = function () {
  12902. return this._vrDisplay;
  12903. };
  12904. /**
  12905. * Initializes a webVR display and starts listening to display change events
  12906. * The onVRDisplayChangedObservable will be notified upon these changes
  12907. * @returns The onVRDisplayChangedObservable
  12908. */
  12909. Engine.prototype.initWebVR = function () {
  12910. this.initWebVRAsync();
  12911. return this.onVRDisplayChangedObservable;
  12912. };
  12913. /**
  12914. * Initializes a webVR display and starts listening to display change events
  12915. * The onVRDisplayChangedObservable will be notified upon these changes
  12916. * @returns A promise containing a VRDisplay and if vr is supported
  12917. */
  12918. Engine.prototype.initWebVRAsync = function () {
  12919. var _this = this;
  12920. var notifyObservers = function () {
  12921. var eventArgs = {
  12922. vrDisplay: _this._vrDisplay,
  12923. vrSupported: _this._vrSupported
  12924. };
  12925. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12926. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12927. };
  12928. if (!this._onVrDisplayConnect) {
  12929. this._onVrDisplayConnect = function (event) {
  12930. _this._vrDisplay = event.display;
  12931. notifyObservers();
  12932. };
  12933. this._onVrDisplayDisconnect = function () {
  12934. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12935. _this._vrDisplay = undefined;
  12936. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12937. notifyObservers();
  12938. };
  12939. this._onVrDisplayPresentChange = function () {
  12940. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12941. };
  12942. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12943. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12944. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12945. }
  12946. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12947. this._webVRInitPromise.then(notifyObservers);
  12948. return this._webVRInitPromise;
  12949. };
  12950. /**
  12951. * Call this function to switch to webVR mode
  12952. * Will do nothing if webVR is not supported or if there is no webVR device
  12953. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12954. */
  12955. Engine.prototype.enableVR = function () {
  12956. var _this = this;
  12957. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12958. var onResolved = function () {
  12959. _this.onVRRequestPresentComplete.notifyObservers(true);
  12960. _this._onVRFullScreenTriggered();
  12961. };
  12962. var onRejected = function () {
  12963. _this.onVRRequestPresentComplete.notifyObservers(false);
  12964. };
  12965. this.onVRRequestPresentStart.notifyObservers(this);
  12966. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12967. }
  12968. };
  12969. /**
  12970. * Call this function to leave webVR mode
  12971. * Will do nothing if webVR is not supported or if there is no webVR device
  12972. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12973. */
  12974. Engine.prototype.disableVR = function () {
  12975. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12976. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12977. }
  12978. };
  12979. Engine.prototype._getVRDisplaysAsync = function () {
  12980. var _this = this;
  12981. return new Promise(function (res, rej) {
  12982. if (navigator.getVRDisplays) {
  12983. navigator.getVRDisplays().then(function (devices) {
  12984. _this._vrSupported = true;
  12985. // note that devices may actually be an empty array. This is fine;
  12986. // we expect this._vrDisplay to be undefined in this case.
  12987. _this._vrDisplay = devices[0];
  12988. res({
  12989. vrDisplay: _this._vrDisplay,
  12990. vrSupported: _this._vrSupported
  12991. });
  12992. });
  12993. }
  12994. else {
  12995. _this._vrDisplay = undefined;
  12996. _this._vrSupported = false;
  12997. res({
  12998. vrDisplay: _this._vrDisplay,
  12999. vrSupported: _this._vrSupported
  13000. });
  13001. }
  13002. });
  13003. };
  13004. /**
  13005. * Binds the frame buffer to the specified texture.
  13006. * @param texture The texture to render to or null for the default canvas
  13007. * @param faceIndex The face of the texture to render to in case of cube texture
  13008. * @param requiredWidth The width of the target to render to
  13009. * @param requiredHeight The height of the target to render to
  13010. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13011. * @param depthStencilTexture The depth stencil texture to use to render
  13012. */
  13013. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  13014. if (this._currentRenderTarget) {
  13015. this.unBindFramebuffer(this._currentRenderTarget);
  13016. }
  13017. this._currentRenderTarget = texture;
  13018. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13019. var gl = this._gl;
  13020. if (texture.isCube) {
  13021. if (faceIndex === undefined) {
  13022. faceIndex = 0;
  13023. }
  13024. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13025. if (depthStencilTexture) {
  13026. if (depthStencilTexture._generateStencilBuffer) {
  13027. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13028. }
  13029. else {
  13030. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13031. }
  13032. }
  13033. }
  13034. if (this._cachedViewport && !forceFullscreenViewport) {
  13035. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13036. }
  13037. else {
  13038. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13039. }
  13040. this.wipeCaches();
  13041. };
  13042. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13043. if (this._currentFramebuffer !== framebuffer) {
  13044. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13045. this._currentFramebuffer = framebuffer;
  13046. }
  13047. };
  13048. /**
  13049. * Unbind the current render target texture from the webGL context
  13050. * @param texture defines the render target texture to unbind
  13051. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13052. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13053. */
  13054. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13055. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13056. this._currentRenderTarget = null;
  13057. // If MSAA, we need to bitblt back to main texture
  13058. var gl = this._gl;
  13059. if (texture._MSAAFramebuffer) {
  13060. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13061. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13062. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13063. }
  13064. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13065. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13066. gl.generateMipmap(gl.TEXTURE_2D);
  13067. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13068. }
  13069. if (onBeforeUnbind) {
  13070. if (texture._MSAAFramebuffer) {
  13071. // Bind the correct framebuffer
  13072. this.bindUnboundFramebuffer(texture._framebuffer);
  13073. }
  13074. onBeforeUnbind();
  13075. }
  13076. this.bindUnboundFramebuffer(null);
  13077. };
  13078. /**
  13079. * Unbind a list of render target textures from the webGL context
  13080. * This is used only when drawBuffer extension or webGL2 are active
  13081. * @param textures defines the render target textures to unbind
  13082. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13083. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13084. */
  13085. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13086. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13087. this._currentRenderTarget = null;
  13088. // If MSAA, we need to bitblt back to main texture
  13089. var gl = this._gl;
  13090. if (textures[0]._MSAAFramebuffer) {
  13091. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13092. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13093. var attachments = textures[0]._attachments;
  13094. if (!attachments) {
  13095. attachments = new Array(textures.length);
  13096. textures[0]._attachments = attachments;
  13097. }
  13098. for (var i = 0; i < textures.length; i++) {
  13099. var texture = textures[i];
  13100. for (var j = 0; j < attachments.length; j++) {
  13101. attachments[j] = gl.NONE;
  13102. }
  13103. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13104. gl.readBuffer(attachments[i]);
  13105. gl.drawBuffers(attachments);
  13106. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13107. }
  13108. for (var i = 0; i < attachments.length; i++) {
  13109. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13110. }
  13111. gl.drawBuffers(attachments);
  13112. }
  13113. for (var i = 0; i < textures.length; i++) {
  13114. var texture = textures[i];
  13115. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13116. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13117. gl.generateMipmap(gl.TEXTURE_2D);
  13118. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13119. }
  13120. }
  13121. if (onBeforeUnbind) {
  13122. if (textures[0]._MSAAFramebuffer) {
  13123. // Bind the correct framebuffer
  13124. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13125. }
  13126. onBeforeUnbind();
  13127. }
  13128. this.bindUnboundFramebuffer(null);
  13129. };
  13130. /**
  13131. * Force the mipmap generation for the given render target texture
  13132. * @param texture defines the render target texture to use
  13133. */
  13134. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13135. if (texture.generateMipMaps) {
  13136. var gl = this._gl;
  13137. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13138. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13139. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13140. }
  13141. };
  13142. /**
  13143. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13144. */
  13145. Engine.prototype.flushFramebuffer = function () {
  13146. this._gl.flush();
  13147. };
  13148. /**
  13149. * Unbind the current render target and bind the default framebuffer
  13150. */
  13151. Engine.prototype.restoreDefaultFramebuffer = function () {
  13152. if (this._currentRenderTarget) {
  13153. this.unBindFramebuffer(this._currentRenderTarget);
  13154. }
  13155. else {
  13156. this.bindUnboundFramebuffer(null);
  13157. }
  13158. if (this._cachedViewport) {
  13159. this.setViewport(this._cachedViewport);
  13160. }
  13161. this.wipeCaches();
  13162. };
  13163. // UBOs
  13164. /**
  13165. * Create an uniform buffer
  13166. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13167. * @param elements defines the content of the uniform buffer
  13168. * @returns the webGL uniform buffer
  13169. */
  13170. Engine.prototype.createUniformBuffer = function (elements) {
  13171. var ubo = this._gl.createBuffer();
  13172. if (!ubo) {
  13173. throw new Error("Unable to create uniform buffer");
  13174. }
  13175. this.bindUniformBuffer(ubo);
  13176. if (elements instanceof Float32Array) {
  13177. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13178. }
  13179. else {
  13180. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13181. }
  13182. this.bindUniformBuffer(null);
  13183. ubo.references = 1;
  13184. return ubo;
  13185. };
  13186. /**
  13187. * Create a dynamic uniform buffer
  13188. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13189. * @param elements defines the content of the uniform buffer
  13190. * @returns the webGL uniform buffer
  13191. */
  13192. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13193. var ubo = this._gl.createBuffer();
  13194. if (!ubo) {
  13195. throw new Error("Unable to create dynamic uniform buffer");
  13196. }
  13197. this.bindUniformBuffer(ubo);
  13198. if (elements instanceof Float32Array) {
  13199. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13200. }
  13201. else {
  13202. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13203. }
  13204. this.bindUniformBuffer(null);
  13205. ubo.references = 1;
  13206. return ubo;
  13207. };
  13208. /**
  13209. * Update an existing uniform buffer
  13210. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13211. * @param uniformBuffer defines the target uniform buffer
  13212. * @param elements defines the content to update
  13213. * @param offset defines the offset in the uniform buffer where update should start
  13214. * @param count defines the size of the data to update
  13215. */
  13216. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13217. this.bindUniformBuffer(uniformBuffer);
  13218. if (offset === undefined) {
  13219. offset = 0;
  13220. }
  13221. if (count === undefined) {
  13222. if (elements instanceof Float32Array) {
  13223. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13224. }
  13225. else {
  13226. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13227. }
  13228. }
  13229. else {
  13230. if (elements instanceof Float32Array) {
  13231. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13232. }
  13233. else {
  13234. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13235. }
  13236. }
  13237. this.bindUniformBuffer(null);
  13238. };
  13239. // VBOs
  13240. Engine.prototype._resetVertexBufferBinding = function () {
  13241. this.bindArrayBuffer(null);
  13242. this._cachedVertexBuffers = null;
  13243. };
  13244. /**
  13245. * Creates a vertex buffer
  13246. * @param data the data for the vertex buffer
  13247. * @returns the new WebGL static buffer
  13248. */
  13249. Engine.prototype.createVertexBuffer = function (data) {
  13250. var vbo = this._gl.createBuffer();
  13251. if (!vbo) {
  13252. throw new Error("Unable to create vertex buffer");
  13253. }
  13254. this.bindArrayBuffer(vbo);
  13255. if (data instanceof Array) {
  13256. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13257. }
  13258. else {
  13259. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13260. }
  13261. this._resetVertexBufferBinding();
  13262. vbo.references = 1;
  13263. return vbo;
  13264. };
  13265. /**
  13266. * Creates a dynamic vertex buffer
  13267. * @param data the data for the dynamic vertex buffer
  13268. * @returns the new WebGL dynamic buffer
  13269. */
  13270. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13271. var vbo = this._gl.createBuffer();
  13272. if (!vbo) {
  13273. throw new Error("Unable to create dynamic vertex buffer");
  13274. }
  13275. this.bindArrayBuffer(vbo);
  13276. if (data instanceof Array) {
  13277. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13278. }
  13279. else {
  13280. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13281. }
  13282. this._resetVertexBufferBinding();
  13283. vbo.references = 1;
  13284. return vbo;
  13285. };
  13286. /**
  13287. * Update a dynamic index buffer
  13288. * @param indexBuffer defines the target index buffer
  13289. * @param indices defines the data to update
  13290. * @param offset defines the offset in the target index buffer where update should start
  13291. */
  13292. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13293. if (offset === void 0) { offset = 0; }
  13294. // Force cache update
  13295. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13296. this.bindIndexBuffer(indexBuffer);
  13297. var arrayBuffer;
  13298. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13299. arrayBuffer = indices;
  13300. }
  13301. else {
  13302. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13303. }
  13304. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13305. this._resetIndexBufferBinding();
  13306. };
  13307. /**
  13308. * Updates a dynamic vertex buffer.
  13309. * @param vertexBuffer the vertex buffer to update
  13310. * @param data the data used to update the vertex buffer
  13311. * @param byteOffset the byte offset of the data
  13312. * @param byteLength the byte length of the data
  13313. */
  13314. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13315. this.bindArrayBuffer(vertexBuffer);
  13316. if (byteOffset === undefined) {
  13317. byteOffset = 0;
  13318. }
  13319. if (byteLength === undefined) {
  13320. if (data instanceof Array) {
  13321. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13322. }
  13323. else {
  13324. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13325. }
  13326. }
  13327. else {
  13328. if (data instanceof Array) {
  13329. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13330. }
  13331. else {
  13332. if (data instanceof ArrayBuffer) {
  13333. data = new Uint8Array(data, byteOffset, byteLength);
  13334. }
  13335. else {
  13336. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13337. }
  13338. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13339. }
  13340. }
  13341. this._resetVertexBufferBinding();
  13342. };
  13343. Engine.prototype._resetIndexBufferBinding = function () {
  13344. this.bindIndexBuffer(null);
  13345. this._cachedIndexBuffer = null;
  13346. };
  13347. /**
  13348. * Creates a new index buffer
  13349. * @param indices defines the content of the index buffer
  13350. * @param updatable defines if the index buffer must be updatable
  13351. * @returns a new webGL buffer
  13352. */
  13353. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13354. var vbo = this._gl.createBuffer();
  13355. if (!vbo) {
  13356. throw new Error("Unable to create index buffer");
  13357. }
  13358. this.bindIndexBuffer(vbo);
  13359. // Check for 32 bits indices
  13360. var arrayBuffer;
  13361. var need32Bits = false;
  13362. if (indices instanceof Uint16Array) {
  13363. arrayBuffer = indices;
  13364. }
  13365. else {
  13366. //check 32 bit support
  13367. if (this._caps.uintIndices) {
  13368. if (indices instanceof Uint32Array) {
  13369. arrayBuffer = indices;
  13370. need32Bits = true;
  13371. }
  13372. else {
  13373. //number[] or Int32Array, check if 32 bit is necessary
  13374. for (var index = 0; index < indices.length; index++) {
  13375. if (indices[index] > 65535) {
  13376. need32Bits = true;
  13377. break;
  13378. }
  13379. }
  13380. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13381. }
  13382. }
  13383. else {
  13384. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13385. arrayBuffer = new Uint16Array(indices);
  13386. }
  13387. }
  13388. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13389. this._resetIndexBufferBinding();
  13390. vbo.references = 1;
  13391. vbo.is32Bits = need32Bits;
  13392. return vbo;
  13393. };
  13394. /**
  13395. * Bind a webGL buffer to the webGL context
  13396. * @param buffer defines the buffer to bind
  13397. */
  13398. Engine.prototype.bindArrayBuffer = function (buffer) {
  13399. if (!this._vaoRecordInProgress) {
  13400. this._unbindVertexArrayObject();
  13401. }
  13402. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13403. };
  13404. /**
  13405. * Bind an uniform buffer to the current webGL context
  13406. * @param buffer defines the buffer to bind
  13407. */
  13408. Engine.prototype.bindUniformBuffer = function (buffer) {
  13409. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13410. };
  13411. /**
  13412. * Bind a buffer to the current webGL context at a given location
  13413. * @param buffer defines the buffer to bind
  13414. * @param location defines the index where to bind the buffer
  13415. */
  13416. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13417. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13418. };
  13419. /**
  13420. * Bind a specific block at a given index in a specific shader program
  13421. * @param shaderProgram defines the shader program
  13422. * @param blockName defines the block name
  13423. * @param index defines the index where to bind the block
  13424. */
  13425. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13426. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13427. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13428. };
  13429. ;
  13430. Engine.prototype.bindIndexBuffer = function (buffer) {
  13431. if (!this._vaoRecordInProgress) {
  13432. this._unbindVertexArrayObject();
  13433. }
  13434. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13435. };
  13436. Engine.prototype.bindBuffer = function (buffer, target) {
  13437. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13438. this._gl.bindBuffer(target, buffer);
  13439. this._currentBoundBuffer[target] = buffer;
  13440. }
  13441. };
  13442. /**
  13443. * update the bound buffer with the given data
  13444. * @param data defines the data to update
  13445. */
  13446. Engine.prototype.updateArrayBuffer = function (data) {
  13447. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13448. };
  13449. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13450. var pointer = this._currentBufferPointers[indx];
  13451. var changed = false;
  13452. if (!pointer.active) {
  13453. changed = true;
  13454. pointer.active = true;
  13455. pointer.index = indx;
  13456. pointer.size = size;
  13457. pointer.type = type;
  13458. pointer.normalized = normalized;
  13459. pointer.stride = stride;
  13460. pointer.offset = offset;
  13461. pointer.buffer = buffer;
  13462. }
  13463. else {
  13464. if (pointer.buffer !== buffer) {
  13465. pointer.buffer = buffer;
  13466. changed = true;
  13467. }
  13468. if (pointer.size !== size) {
  13469. pointer.size = size;
  13470. changed = true;
  13471. }
  13472. if (pointer.type !== type) {
  13473. pointer.type = type;
  13474. changed = true;
  13475. }
  13476. if (pointer.normalized !== normalized) {
  13477. pointer.normalized = normalized;
  13478. changed = true;
  13479. }
  13480. if (pointer.stride !== stride) {
  13481. pointer.stride = stride;
  13482. changed = true;
  13483. }
  13484. if (pointer.offset !== offset) {
  13485. pointer.offset = offset;
  13486. changed = true;
  13487. }
  13488. }
  13489. if (changed || this._vaoRecordInProgress) {
  13490. this.bindArrayBuffer(buffer);
  13491. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13492. }
  13493. };
  13494. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13495. if (indexBuffer == null) {
  13496. return;
  13497. }
  13498. if (this._cachedIndexBuffer !== indexBuffer) {
  13499. this._cachedIndexBuffer = indexBuffer;
  13500. this.bindIndexBuffer(indexBuffer);
  13501. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13502. }
  13503. };
  13504. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13505. var attributes = effect.getAttributesNames();
  13506. if (!this._vaoRecordInProgress) {
  13507. this._unbindVertexArrayObject();
  13508. }
  13509. this.unbindAllAttributes();
  13510. for (var index = 0; index < attributes.length; index++) {
  13511. var order = effect.getAttributeLocation(index);
  13512. if (order >= 0) {
  13513. var vertexBuffer = vertexBuffers[attributes[index]];
  13514. if (!vertexBuffer) {
  13515. continue;
  13516. }
  13517. this._gl.enableVertexAttribArray(order);
  13518. if (!this._vaoRecordInProgress) {
  13519. this._vertexAttribArraysEnabled[order] = true;
  13520. }
  13521. var buffer = vertexBuffer.getBuffer();
  13522. if (buffer) {
  13523. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13524. if (vertexBuffer.getIsInstanced()) {
  13525. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13526. if (!this._vaoRecordInProgress) {
  13527. this._currentInstanceLocations.push(order);
  13528. this._currentInstanceBuffers.push(buffer);
  13529. }
  13530. }
  13531. }
  13532. }
  13533. }
  13534. };
  13535. /**
  13536. * Records a vertex array object
  13537. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13538. * @param vertexBuffers defines the list of vertex buffers to store
  13539. * @param indexBuffer defines the index buffer to store
  13540. * @param effect defines the effect to store
  13541. * @returns the new vertex array object
  13542. */
  13543. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13544. var vao = this._gl.createVertexArray();
  13545. this._vaoRecordInProgress = true;
  13546. this._gl.bindVertexArray(vao);
  13547. this._mustWipeVertexAttributes = true;
  13548. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13549. this.bindIndexBuffer(indexBuffer);
  13550. this._vaoRecordInProgress = false;
  13551. this._gl.bindVertexArray(null);
  13552. return vao;
  13553. };
  13554. /**
  13555. * Bind a specific vertex array object
  13556. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13557. * @param vertexArrayObject defines the vertex array object to bind
  13558. * @param indexBuffer defines the index buffer to bind
  13559. */
  13560. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13561. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13562. this._cachedVertexArrayObject = vertexArrayObject;
  13563. this._gl.bindVertexArray(vertexArrayObject);
  13564. this._cachedVertexBuffers = null;
  13565. this._cachedIndexBuffer = null;
  13566. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13567. this._mustWipeVertexAttributes = true;
  13568. }
  13569. };
  13570. /**
  13571. * Bind webGl buffers directly to the webGL context
  13572. * @param vertexBuffer defines the vertex buffer to bind
  13573. * @param indexBuffer defines the index buffer to bind
  13574. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13575. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13576. * @param effect defines the effect associated with the vertex buffer
  13577. */
  13578. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13579. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13580. this._cachedVertexBuffers = vertexBuffer;
  13581. this._cachedEffectForVertexBuffers = effect;
  13582. var attributesCount = effect.getAttributesCount();
  13583. this._unbindVertexArrayObject();
  13584. this.unbindAllAttributes();
  13585. var offset = 0;
  13586. for (var index = 0; index < attributesCount; index++) {
  13587. if (index < vertexDeclaration.length) {
  13588. var order = effect.getAttributeLocation(index);
  13589. if (order >= 0) {
  13590. this._gl.enableVertexAttribArray(order);
  13591. this._vertexAttribArraysEnabled[order] = true;
  13592. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13593. }
  13594. offset += vertexDeclaration[index] * 4;
  13595. }
  13596. }
  13597. }
  13598. this._bindIndexBufferWithCache(indexBuffer);
  13599. };
  13600. Engine.prototype._unbindVertexArrayObject = function () {
  13601. if (!this._cachedVertexArrayObject) {
  13602. return;
  13603. }
  13604. this._cachedVertexArrayObject = null;
  13605. this._gl.bindVertexArray(null);
  13606. };
  13607. /**
  13608. * Bind a list of vertex buffers to the webGL context
  13609. * @param vertexBuffers defines the list of vertex buffers to bind
  13610. * @param indexBuffer defines the index buffer to bind
  13611. * @param effect defines the effect associated with the vertex buffers
  13612. */
  13613. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13614. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13615. this._cachedVertexBuffers = vertexBuffers;
  13616. this._cachedEffectForVertexBuffers = effect;
  13617. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13618. }
  13619. this._bindIndexBufferWithCache(indexBuffer);
  13620. };
  13621. /**
  13622. * Unbind all instance attributes
  13623. */
  13624. Engine.prototype.unbindInstanceAttributes = function () {
  13625. var boundBuffer;
  13626. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13627. var instancesBuffer = this._currentInstanceBuffers[i];
  13628. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13629. boundBuffer = instancesBuffer;
  13630. this.bindArrayBuffer(instancesBuffer);
  13631. }
  13632. var offsetLocation = this._currentInstanceLocations[i];
  13633. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13634. }
  13635. this._currentInstanceBuffers.length = 0;
  13636. this._currentInstanceLocations.length = 0;
  13637. };
  13638. /**
  13639. * Release and free the memory of a vertex array object
  13640. * @param vao defines the vertex array object to delete
  13641. */
  13642. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13643. this._gl.deleteVertexArray(vao);
  13644. };
  13645. /** @hidden */
  13646. Engine.prototype._releaseBuffer = function (buffer) {
  13647. buffer.references--;
  13648. if (buffer.references === 0) {
  13649. this._gl.deleteBuffer(buffer);
  13650. return true;
  13651. }
  13652. return false;
  13653. };
  13654. /**
  13655. * Creates a webGL buffer to use with instanciation
  13656. * @param capacity defines the size of the buffer
  13657. * @returns the webGL buffer
  13658. */
  13659. Engine.prototype.createInstancesBuffer = function (capacity) {
  13660. var buffer = this._gl.createBuffer();
  13661. if (!buffer) {
  13662. throw new Error("Unable to create instance buffer");
  13663. }
  13664. buffer.capacity = capacity;
  13665. this.bindArrayBuffer(buffer);
  13666. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13667. return buffer;
  13668. };
  13669. /**
  13670. * Delete a webGL buffer used with instanciation
  13671. * @param buffer defines the webGL buffer to delete
  13672. */
  13673. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13674. this._gl.deleteBuffer(buffer);
  13675. };
  13676. /**
  13677. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13678. * @param instancesBuffer defines the webGL buffer to update and bind
  13679. * @param data defines the data to store in the buffer
  13680. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13681. */
  13682. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13683. this.bindArrayBuffer(instancesBuffer);
  13684. if (data) {
  13685. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13686. }
  13687. if (offsetLocations[0].index !== undefined) {
  13688. var stride = 0;
  13689. for (var i = 0; i < offsetLocations.length; i++) {
  13690. var ai = offsetLocations[i];
  13691. stride += ai.attributeSize * 4;
  13692. }
  13693. for (var i = 0; i < offsetLocations.length; i++) {
  13694. var ai = offsetLocations[i];
  13695. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13696. this._gl.enableVertexAttribArray(ai.index);
  13697. this._vertexAttribArraysEnabled[ai.index] = true;
  13698. }
  13699. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13700. this._gl.vertexAttribDivisor(ai.index, 1);
  13701. this._currentInstanceLocations.push(ai.index);
  13702. this._currentInstanceBuffers.push(instancesBuffer);
  13703. }
  13704. }
  13705. else {
  13706. for (var index = 0; index < 4; index++) {
  13707. var offsetLocation = offsetLocations[index];
  13708. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13709. this._gl.enableVertexAttribArray(offsetLocation);
  13710. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13711. }
  13712. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13713. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13714. this._currentInstanceLocations.push(offsetLocation);
  13715. this._currentInstanceBuffers.push(instancesBuffer);
  13716. }
  13717. }
  13718. };
  13719. /**
  13720. * Apply all cached states (depth, culling, stencil and alpha)
  13721. */
  13722. Engine.prototype.applyStates = function () {
  13723. this._depthCullingState.apply(this._gl);
  13724. this._stencilState.apply(this._gl);
  13725. this._alphaState.apply(this._gl);
  13726. };
  13727. /**
  13728. * Send a draw order
  13729. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13730. * @param indexStart defines the starting index
  13731. * @param indexCount defines the number of index to draw
  13732. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13733. */
  13734. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13735. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13736. };
  13737. /**
  13738. * Draw a list of points
  13739. * @param verticesStart defines the index of first vertex to draw
  13740. * @param verticesCount defines the count of vertices to draw
  13741. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13742. */
  13743. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13744. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13745. };
  13746. /**
  13747. * Draw a list of unindexed primitives
  13748. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13749. * @param verticesStart defines the index of first vertex to draw
  13750. * @param verticesCount defines the count of vertices to draw
  13751. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13752. */
  13753. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13754. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13755. };
  13756. /**
  13757. * Draw a list of indexed primitives
  13758. * @param fillMode defines the primitive to use
  13759. * @param indexStart defines the starting index
  13760. * @param indexCount defines the number of index to draw
  13761. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13762. */
  13763. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13764. // Apply states
  13765. this.applyStates();
  13766. this._drawCalls.addCount(1, false);
  13767. // Render
  13768. var drawMode = this._drawMode(fillMode);
  13769. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13770. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13771. if (instancesCount) {
  13772. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13773. }
  13774. else {
  13775. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13776. }
  13777. };
  13778. /**
  13779. * Draw a list of unindexed primitives
  13780. * @param fillMode defines the primitive to use
  13781. * @param verticesStart defines the index of first vertex to draw
  13782. * @param verticesCount defines the count of vertices to draw
  13783. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13784. */
  13785. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13786. // Apply states
  13787. this.applyStates();
  13788. this._drawCalls.addCount(1, false);
  13789. var drawMode = this._drawMode(fillMode);
  13790. if (instancesCount) {
  13791. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13792. }
  13793. else {
  13794. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13795. }
  13796. };
  13797. Engine.prototype._drawMode = function (fillMode) {
  13798. switch (fillMode) {
  13799. // Triangle views
  13800. case BABYLON.Material.TriangleFillMode:
  13801. return this._gl.TRIANGLES;
  13802. case BABYLON.Material.PointFillMode:
  13803. return this._gl.POINTS;
  13804. case BABYLON.Material.WireFrameFillMode:
  13805. return this._gl.LINES;
  13806. // Draw modes
  13807. case BABYLON.Material.PointListDrawMode:
  13808. return this._gl.POINTS;
  13809. case BABYLON.Material.LineListDrawMode:
  13810. return this._gl.LINES;
  13811. case BABYLON.Material.LineLoopDrawMode:
  13812. return this._gl.LINE_LOOP;
  13813. case BABYLON.Material.LineStripDrawMode:
  13814. return this._gl.LINE_STRIP;
  13815. case BABYLON.Material.TriangleStripDrawMode:
  13816. return this._gl.TRIANGLE_STRIP;
  13817. case BABYLON.Material.TriangleFanDrawMode:
  13818. return this._gl.TRIANGLE_FAN;
  13819. default:
  13820. return this._gl.TRIANGLES;
  13821. }
  13822. };
  13823. // Shaders
  13824. /** @hidden */
  13825. Engine.prototype._releaseEffect = function (effect) {
  13826. if (this._compiledEffects[effect._key]) {
  13827. delete this._compiledEffects[effect._key];
  13828. this._deleteProgram(effect.getProgram());
  13829. }
  13830. };
  13831. /** @hidden */
  13832. Engine.prototype._deleteProgram = function (program) {
  13833. if (program) {
  13834. program.__SPECTOR_rebuildProgram = null;
  13835. if (program.transformFeedback) {
  13836. this.deleteTransformFeedback(program.transformFeedback);
  13837. program.transformFeedback = null;
  13838. }
  13839. this._gl.deleteProgram(program);
  13840. }
  13841. };
  13842. /**
  13843. * Create a new effect (used to store vertex/fragment shaders)
  13844. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13845. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13846. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13847. * @param samplers defines an array of string used to represent textures
  13848. * @param defines defines the string containing the defines to use to compile the shaders
  13849. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13850. * @param onCompiled defines a function to call when the effect creation is successful
  13851. * @param onError defines a function to call when the effect creation has failed
  13852. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13853. * @returns the new Effect
  13854. */
  13855. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13856. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13857. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13858. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13859. if (this._compiledEffects[name]) {
  13860. var compiledEffect = this._compiledEffects[name];
  13861. if (onCompiled && compiledEffect.isReady()) {
  13862. onCompiled(compiledEffect);
  13863. }
  13864. return compiledEffect;
  13865. }
  13866. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13867. effect._key = name;
  13868. this._compiledEffects[name] = effect;
  13869. return effect;
  13870. };
  13871. /**
  13872. * Create an effect to use with particle systems
  13873. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13874. * @param uniformsNames defines a list of attribute names
  13875. * @param samplers defines an array of string used to represent textures
  13876. * @param defines defines the string containing the defines to use to compile the shaders
  13877. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13878. * @param onCompiled defines a function to call when the effect creation is successful
  13879. * @param onError defines a function to call when the effect creation has failed
  13880. * @returns the new Effect
  13881. */
  13882. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13883. if (uniformsNames === void 0) { uniformsNames = []; }
  13884. if (samplers === void 0) { samplers = []; }
  13885. if (defines === void 0) { defines = ""; }
  13886. return this.createEffect({
  13887. vertex: "particles",
  13888. fragmentElement: fragmentName
  13889. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13890. };
  13891. /**
  13892. * Directly creates a webGL program
  13893. * @param vertexCode defines the vertex shader code to use
  13894. * @param fragmentCode defines the fragment shader code to use
  13895. * @param context defines the webGL context to use (if not set, the current one will be used)
  13896. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13897. * @returns the new webGL program
  13898. */
  13899. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13900. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13901. context = context || this._gl;
  13902. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13903. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13904. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13905. };
  13906. /**
  13907. * Creates a webGL program
  13908. * @param vertexCode defines the vertex shader code to use
  13909. * @param fragmentCode defines the fragment shader code to use
  13910. * @param defines defines the string containing the defines to use to compile the shaders
  13911. * @param context defines the webGL context to use (if not set, the current one will be used)
  13912. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13913. * @returns the new webGL program
  13914. */
  13915. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13916. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13917. context = context || this._gl;
  13918. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13919. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13920. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13921. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13922. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13923. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13924. return program;
  13925. };
  13926. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13927. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13928. var shaderProgram = context.createProgram();
  13929. if (!shaderProgram) {
  13930. throw new Error("Unable to create program");
  13931. }
  13932. context.attachShader(shaderProgram, vertexShader);
  13933. context.attachShader(shaderProgram, fragmentShader);
  13934. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13935. var transformFeedback = this.createTransformFeedback();
  13936. this.bindTransformFeedback(transformFeedback);
  13937. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13938. shaderProgram.transformFeedback = transformFeedback;
  13939. }
  13940. context.linkProgram(shaderProgram);
  13941. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13942. this.bindTransformFeedback(null);
  13943. }
  13944. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13945. if (!linked) {
  13946. context.validateProgram(shaderProgram);
  13947. var error = context.getProgramInfoLog(shaderProgram);
  13948. if (error) {
  13949. throw new Error(error);
  13950. }
  13951. }
  13952. context.deleteShader(vertexShader);
  13953. context.deleteShader(fragmentShader);
  13954. return shaderProgram;
  13955. };
  13956. /**
  13957. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13958. * @param shaderProgram defines the webGL program to use
  13959. * @param uniformsNames defines the list of uniform names
  13960. * @returns an array of webGL uniform locations
  13961. */
  13962. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13963. var results = new Array();
  13964. for (var index = 0; index < uniformsNames.length; index++) {
  13965. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13966. }
  13967. return results;
  13968. };
  13969. /**
  13970. * Gets the lsit of active attributes for a given webGL program
  13971. * @param shaderProgram defines the webGL program to use
  13972. * @param attributesNames defines the list of attribute names to get
  13973. * @returns an array of indices indicating the offset of each attribute
  13974. */
  13975. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13976. var results = [];
  13977. for (var index = 0; index < attributesNames.length; index++) {
  13978. try {
  13979. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13980. }
  13981. catch (e) {
  13982. results.push(-1);
  13983. }
  13984. }
  13985. return results;
  13986. };
  13987. /**
  13988. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13989. * @param effect defines the effect to activate
  13990. */
  13991. Engine.prototype.enableEffect = function (effect) {
  13992. if (!effect) {
  13993. return;
  13994. }
  13995. // Use program
  13996. this.bindSamplers(effect);
  13997. this._currentEffect = effect;
  13998. if (effect.onBind) {
  13999. effect.onBind(effect);
  14000. }
  14001. effect.onBindObservable.notifyObservers(effect);
  14002. };
  14003. /**
  14004. * Set the value of an uniform to an array of int32
  14005. * @param uniform defines the webGL uniform location where to store the value
  14006. * @param array defines the array of int32 to store
  14007. */
  14008. Engine.prototype.setIntArray = function (uniform, array) {
  14009. if (!uniform)
  14010. return;
  14011. this._gl.uniform1iv(uniform, array);
  14012. };
  14013. /**
  14014. * Set the value of an uniform to an array of int32 (stored as vec2)
  14015. * @param uniform defines the webGL uniform location where to store the value
  14016. * @param array defines the array of int32 to store
  14017. */
  14018. Engine.prototype.setIntArray2 = function (uniform, array) {
  14019. if (!uniform || array.length % 2 !== 0)
  14020. return;
  14021. this._gl.uniform2iv(uniform, array);
  14022. };
  14023. /**
  14024. * Set the value of an uniform to an array of int32 (stored as vec3)
  14025. * @param uniform defines the webGL uniform location where to store the value
  14026. * @param array defines the array of int32 to store
  14027. */
  14028. Engine.prototype.setIntArray3 = function (uniform, array) {
  14029. if (!uniform || array.length % 3 !== 0)
  14030. return;
  14031. this._gl.uniform3iv(uniform, array);
  14032. };
  14033. /**
  14034. * Set the value of an uniform to an array of int32 (stored as vec4)
  14035. * @param uniform defines the webGL uniform location where to store the value
  14036. * @param array defines the array of int32 to store
  14037. */
  14038. Engine.prototype.setIntArray4 = function (uniform, array) {
  14039. if (!uniform || array.length % 4 !== 0)
  14040. return;
  14041. this._gl.uniform4iv(uniform, array);
  14042. };
  14043. /**
  14044. * Set the value of an uniform to an array of float32
  14045. * @param uniform defines the webGL uniform location where to store the value
  14046. * @param array defines the array of float32 to store
  14047. */
  14048. Engine.prototype.setFloatArray = function (uniform, array) {
  14049. if (!uniform)
  14050. return;
  14051. this._gl.uniform1fv(uniform, array);
  14052. };
  14053. /**
  14054. * Set the value of an uniform to an array of float32 (stored as vec2)
  14055. * @param uniform defines the webGL uniform location where to store the value
  14056. * @param array defines the array of float32 to store
  14057. */
  14058. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14059. if (!uniform || array.length % 2 !== 0)
  14060. return;
  14061. this._gl.uniform2fv(uniform, array);
  14062. };
  14063. /**
  14064. * Set the value of an uniform to an array of float32 (stored as vec3)
  14065. * @param uniform defines the webGL uniform location where to store the value
  14066. * @param array defines the array of float32 to store
  14067. */
  14068. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14069. if (!uniform || array.length % 3 !== 0)
  14070. return;
  14071. this._gl.uniform3fv(uniform, array);
  14072. };
  14073. /**
  14074. * Set the value of an uniform to an array of float32 (stored as vec4)
  14075. * @param uniform defines the webGL uniform location where to store the value
  14076. * @param array defines the array of float32 to store
  14077. */
  14078. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14079. if (!uniform || array.length % 4 !== 0)
  14080. return;
  14081. this._gl.uniform4fv(uniform, array);
  14082. };
  14083. /**
  14084. * Set the value of an uniform to an array of number
  14085. * @param uniform defines the webGL uniform location where to store the value
  14086. * @param array defines the array of number to store
  14087. */
  14088. Engine.prototype.setArray = function (uniform, array) {
  14089. if (!uniform)
  14090. return;
  14091. this._gl.uniform1fv(uniform, array);
  14092. };
  14093. /**
  14094. * Set the value of an uniform to an array of number (stored as vec2)
  14095. * @param uniform defines the webGL uniform location where to store the value
  14096. * @param array defines the array of number to store
  14097. */
  14098. Engine.prototype.setArray2 = function (uniform, array) {
  14099. if (!uniform || array.length % 2 !== 0)
  14100. return;
  14101. this._gl.uniform2fv(uniform, array);
  14102. };
  14103. /**
  14104. * Set the value of an uniform to an array of number (stored as vec3)
  14105. * @param uniform defines the webGL uniform location where to store the value
  14106. * @param array defines the array of number to store
  14107. */
  14108. Engine.prototype.setArray3 = function (uniform, array) {
  14109. if (!uniform || array.length % 3 !== 0)
  14110. return;
  14111. this._gl.uniform3fv(uniform, array);
  14112. };
  14113. /**
  14114. * Set the value of an uniform to an array of number (stored as vec4)
  14115. * @param uniform defines the webGL uniform location where to store the value
  14116. * @param array defines the array of number to store
  14117. */
  14118. Engine.prototype.setArray4 = function (uniform, array) {
  14119. if (!uniform || array.length % 4 !== 0)
  14120. return;
  14121. this._gl.uniform4fv(uniform, array);
  14122. };
  14123. /**
  14124. * Set the value of an uniform to an array of float32 (stored as matrices)
  14125. * @param uniform defines the webGL uniform location where to store the value
  14126. * @param matrices defines the array of float32 to store
  14127. */
  14128. Engine.prototype.setMatrices = function (uniform, matrices) {
  14129. if (!uniform)
  14130. return;
  14131. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14132. };
  14133. /**
  14134. * Set the value of an uniform to a matrix
  14135. * @param uniform defines the webGL uniform location where to store the value
  14136. * @param matrix defines the matrix to store
  14137. */
  14138. Engine.prototype.setMatrix = function (uniform, matrix) {
  14139. if (!uniform)
  14140. return;
  14141. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14142. };
  14143. /**
  14144. * Set the value of an uniform to a matrix (3x3)
  14145. * @param uniform defines the webGL uniform location where to store the value
  14146. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14147. */
  14148. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14149. if (!uniform)
  14150. return;
  14151. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14152. };
  14153. /**
  14154. * Set the value of an uniform to a matrix (2x2)
  14155. * @param uniform defines the webGL uniform location where to store the value
  14156. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14157. */
  14158. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14159. if (!uniform)
  14160. return;
  14161. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14162. };
  14163. /**
  14164. * Set the value of an uniform to a number (int)
  14165. * @param uniform defines the webGL uniform location where to store the value
  14166. * @param value defines the int number to store
  14167. */
  14168. Engine.prototype.setInt = function (uniform, value) {
  14169. if (!uniform)
  14170. return;
  14171. this._gl.uniform1i(uniform, value);
  14172. };
  14173. /**
  14174. * Set the value of an uniform to a number (float)
  14175. * @param uniform defines the webGL uniform location where to store the value
  14176. * @param value defines the float number to store
  14177. */
  14178. Engine.prototype.setFloat = function (uniform, value) {
  14179. if (!uniform)
  14180. return;
  14181. this._gl.uniform1f(uniform, value);
  14182. };
  14183. /**
  14184. * Set the value of an uniform to a vec2
  14185. * @param uniform defines the webGL uniform location where to store the value
  14186. * @param x defines the 1st component of the value
  14187. * @param y defines the 2nd component of the value
  14188. */
  14189. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14190. if (!uniform)
  14191. return;
  14192. this._gl.uniform2f(uniform, x, y);
  14193. };
  14194. /**
  14195. * Set the value of an uniform to a vec3
  14196. * @param uniform defines the webGL uniform location where to store the value
  14197. * @param x defines the 1st component of the value
  14198. * @param y defines the 2nd component of the value
  14199. * @param z defines the 3rd component of the value
  14200. */
  14201. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14202. if (!uniform)
  14203. return;
  14204. this._gl.uniform3f(uniform, x, y, z);
  14205. };
  14206. /**
  14207. * Set the value of an uniform to a boolean
  14208. * @param uniform defines the webGL uniform location where to store the value
  14209. * @param bool defines the boolean to store
  14210. */
  14211. Engine.prototype.setBool = function (uniform, bool) {
  14212. if (!uniform)
  14213. return;
  14214. this._gl.uniform1i(uniform, bool);
  14215. };
  14216. /**
  14217. * Set the value of an uniform to a vec4
  14218. * @param uniform defines the webGL uniform location where to store the value
  14219. * @param x defines the 1st component of the value
  14220. * @param y defines the 2nd component of the value
  14221. * @param z defines the 3rd component of the value
  14222. * @param w defines the 4th component of the value
  14223. */
  14224. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14225. if (!uniform)
  14226. return;
  14227. this._gl.uniform4f(uniform, x, y, z, w);
  14228. };
  14229. /**
  14230. * Set the value of an uniform to a Color3
  14231. * @param uniform defines the webGL uniform location where to store the value
  14232. * @param color3 defines the color to store
  14233. */
  14234. Engine.prototype.setColor3 = function (uniform, color3) {
  14235. if (!uniform)
  14236. return;
  14237. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14238. };
  14239. /**
  14240. * Set the value of an uniform to a Color3 and an alpha value
  14241. * @param uniform defines the webGL uniform location where to store the value
  14242. * @param color3 defines the color to store
  14243. * @param alpha defines the alpha component to store
  14244. */
  14245. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14246. if (!uniform)
  14247. return;
  14248. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14249. };
  14250. /**
  14251. * Sets a Color4 on a uniform variable
  14252. * @param uniform defines the uniform location
  14253. * @param color4 defines the value to be set
  14254. */
  14255. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14256. if (!uniform)
  14257. return;
  14258. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14259. };
  14260. // States
  14261. /**
  14262. * Set various states to the webGL context
  14263. * @param culling defines backface culling state
  14264. * @param zOffset defines the value to apply to zOffset (0 by default)
  14265. * @param force defines if states must be applied even if cache is up to date
  14266. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14267. */
  14268. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14269. if (zOffset === void 0) { zOffset = 0; }
  14270. if (reverseSide === void 0) { reverseSide = false; }
  14271. // Culling
  14272. if (this._depthCullingState.cull !== culling || force) {
  14273. this._depthCullingState.cull = culling;
  14274. }
  14275. // Cull face
  14276. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14277. if (this._depthCullingState.cullFace !== cullFace || force) {
  14278. this._depthCullingState.cullFace = cullFace;
  14279. }
  14280. // Z offset
  14281. this.setZOffset(zOffset);
  14282. // Front face
  14283. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14284. if (this._depthCullingState.frontFace !== frontFace || force) {
  14285. this._depthCullingState.frontFace = frontFace;
  14286. }
  14287. };
  14288. /**
  14289. * Set the z offset to apply to current rendering
  14290. * @param value defines the offset to apply
  14291. */
  14292. Engine.prototype.setZOffset = function (value) {
  14293. this._depthCullingState.zOffset = value;
  14294. };
  14295. /**
  14296. * Gets the current value of the zOffset
  14297. * @returns the current zOffset state
  14298. */
  14299. Engine.prototype.getZOffset = function () {
  14300. return this._depthCullingState.zOffset;
  14301. };
  14302. /**
  14303. * Enable or disable depth buffering
  14304. * @param enable defines the state to set
  14305. */
  14306. Engine.prototype.setDepthBuffer = function (enable) {
  14307. this._depthCullingState.depthTest = enable;
  14308. };
  14309. /**
  14310. * Gets a boolean indicating if depth writing is enabled
  14311. * @returns the current depth writing state
  14312. */
  14313. Engine.prototype.getDepthWrite = function () {
  14314. return this._depthCullingState.depthMask;
  14315. };
  14316. /**
  14317. * Enable or disable depth writing
  14318. * @param enable defines the state to set
  14319. */
  14320. Engine.prototype.setDepthWrite = function (enable) {
  14321. this._depthCullingState.depthMask = enable;
  14322. };
  14323. /**
  14324. * Enable or disable color writing
  14325. * @param enable defines the state to set
  14326. */
  14327. Engine.prototype.setColorWrite = function (enable) {
  14328. this._gl.colorMask(enable, enable, enable, enable);
  14329. this._colorWrite = enable;
  14330. };
  14331. /**
  14332. * Gets a boolean indicating if color writing is enabled
  14333. * @returns the current color writing state
  14334. */
  14335. Engine.prototype.getColorWrite = function () {
  14336. return this._colorWrite;
  14337. };
  14338. /**
  14339. * Sets alpha constants used by some alpha blending modes
  14340. * @param r defines the red component
  14341. * @param g defines the green component
  14342. * @param b defines the blue component
  14343. * @param a defines the alpha component
  14344. */
  14345. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14346. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14347. };
  14348. /**
  14349. * Sets the current alpha mode
  14350. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14351. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14352. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14353. */
  14354. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14355. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14356. if (this._alphaMode === mode) {
  14357. return;
  14358. }
  14359. switch (mode) {
  14360. case Engine.ALPHA_DISABLE:
  14361. this._alphaState.alphaBlend = false;
  14362. break;
  14363. case Engine.ALPHA_PREMULTIPLIED:
  14364. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14365. this._alphaState.alphaBlend = true;
  14366. break;
  14367. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14368. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14369. this._alphaState.alphaBlend = true;
  14370. break;
  14371. case Engine.ALPHA_COMBINE:
  14372. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14373. this._alphaState.alphaBlend = true;
  14374. break;
  14375. case Engine.ALPHA_ONEONE:
  14376. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14377. this._alphaState.alphaBlend = true;
  14378. break;
  14379. case Engine.ALPHA_ADD:
  14380. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14381. this._alphaState.alphaBlend = true;
  14382. break;
  14383. case Engine.ALPHA_SUBTRACT:
  14384. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14385. this._alphaState.alphaBlend = true;
  14386. break;
  14387. case Engine.ALPHA_MULTIPLY:
  14388. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14389. this._alphaState.alphaBlend = true;
  14390. break;
  14391. case Engine.ALPHA_MAXIMIZED:
  14392. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14393. this._alphaState.alphaBlend = true;
  14394. break;
  14395. case Engine.ALPHA_INTERPOLATE:
  14396. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14397. this._alphaState.alphaBlend = true;
  14398. break;
  14399. case Engine.ALPHA_SCREENMODE:
  14400. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14401. this._alphaState.alphaBlend = true;
  14402. break;
  14403. }
  14404. if (!noDepthWriteChange) {
  14405. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14406. }
  14407. this._alphaMode = mode;
  14408. };
  14409. /**
  14410. * Gets the current alpha mode
  14411. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14412. * @returns the current alpha mode
  14413. */
  14414. Engine.prototype.getAlphaMode = function () {
  14415. return this._alphaMode;
  14416. };
  14417. // Textures
  14418. /**
  14419. * Force the entire cache to be cleared
  14420. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14421. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14422. */
  14423. Engine.prototype.wipeCaches = function (bruteForce) {
  14424. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14425. return;
  14426. }
  14427. this._currentEffect = null;
  14428. if (bruteForce) {
  14429. this.resetTextureCache();
  14430. this._currentProgram = null;
  14431. this._stencilState.reset();
  14432. this._depthCullingState.reset();
  14433. this.setDepthFunctionToLessOrEqual();
  14434. this._alphaState.reset();
  14435. }
  14436. this._resetVertexBufferBinding();
  14437. this._cachedIndexBuffer = null;
  14438. this._cachedEffectForVertexBuffers = null;
  14439. this._unbindVertexArrayObject();
  14440. this.bindIndexBuffer(null);
  14441. };
  14442. /**
  14443. * Set the compressed texture format to use, based on the formats you have, and the formats
  14444. * supported by the hardware / browser.
  14445. *
  14446. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14447. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14448. * to API arguments needed to compressed textures. This puts the burden on the container
  14449. * generator to house the arcane code for determining these for current & future formats.
  14450. *
  14451. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14452. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14453. *
  14454. * Note: The result of this call is not taken into account when a texture is base64.
  14455. *
  14456. * @param formatsAvailable defines the list of those format families you have created
  14457. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14458. *
  14459. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14460. * @returns The extension selected.
  14461. */
  14462. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14463. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14464. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14465. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14466. return this._textureFormatInUse = this._texturesSupported[i];
  14467. }
  14468. }
  14469. }
  14470. // actively set format to nothing, to allow this to be called more than once
  14471. // and possibly fail the 2nd time
  14472. this._textureFormatInUse = null;
  14473. return null;
  14474. };
  14475. /** @hidden */
  14476. Engine.prototype._createTexture = function () {
  14477. var texture = this._gl.createTexture();
  14478. if (!texture) {
  14479. throw new Error("Unable to create texture");
  14480. }
  14481. return texture;
  14482. };
  14483. /**
  14484. * Usually called from BABYLON.Texture.ts.
  14485. * Passed information to create a WebGLTexture
  14486. * @param urlArg defines a value which contains one of the following:
  14487. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14488. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14489. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14490. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14491. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14492. * @param scene needed for loading to the correct scene
  14493. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14494. * @param onLoad optional callback to be called upon successful completion
  14495. * @param onError optional callback to be called upon failure
  14496. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14497. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14498. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14499. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14500. */
  14501. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14502. var _this = this;
  14503. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14504. if (onLoad === void 0) { onLoad = null; }
  14505. if (onError === void 0) { onError = null; }
  14506. if (buffer === void 0) { buffer = null; }
  14507. if (fallback === void 0) { fallback = null; }
  14508. if (format === void 0) { format = null; }
  14509. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14510. var fromData = url.substr(0, 5) === "data:";
  14511. var fromBlob = url.substr(0, 5) === "blob:";
  14512. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14513. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14514. // establish the file extension, if possible
  14515. var lastDot = url.lastIndexOf('.');
  14516. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14517. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14518. var isTGA = (extension.indexOf(".tga") === 0);
  14519. // determine if a ktx file should be substituted
  14520. var isKTX = false;
  14521. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14522. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14523. isKTX = true;
  14524. }
  14525. if (scene) {
  14526. scene._addPendingData(texture);
  14527. }
  14528. texture.url = url;
  14529. texture.generateMipMaps = !noMipmap;
  14530. texture.samplingMode = samplingMode;
  14531. texture.invertY = invertY;
  14532. if (!this._doNotHandleContextLost) {
  14533. // Keep a link to the buffer only if we plan to handle context lost
  14534. texture._buffer = buffer;
  14535. }
  14536. var onLoadObserver = null;
  14537. if (onLoad && !fallback) {
  14538. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14539. }
  14540. if (!fallback)
  14541. this._internalTexturesCache.push(texture);
  14542. var onerror = function (message, exception) {
  14543. if (scene) {
  14544. scene._removePendingData(texture);
  14545. }
  14546. if (onLoadObserver) {
  14547. texture.onLoadedObservable.remove(onLoadObserver);
  14548. }
  14549. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14550. if (isKTX) {
  14551. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14552. }
  14553. else if (BABYLON.Tools.UseFallbackTexture) {
  14554. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14555. }
  14556. if (onError) {
  14557. onError(message || "Unknown error", exception);
  14558. }
  14559. };
  14560. var callback = null;
  14561. // processing for non-image formats
  14562. if (isKTX || isTGA || isDDS) {
  14563. if (isKTX) {
  14564. callback = function (data) {
  14565. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14566. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14567. ktx.uploadLevels(_this._gl, !noMipmap);
  14568. return false;
  14569. }, samplingMode);
  14570. };
  14571. }
  14572. else if (isTGA) {
  14573. callback = function (arrayBuffer) {
  14574. var data = new Uint8Array(arrayBuffer);
  14575. var header = BABYLON.TGATools.GetTGAHeader(data);
  14576. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14577. BABYLON.TGATools.UploadContent(_this._gl, data);
  14578. return false;
  14579. }, samplingMode);
  14580. };
  14581. }
  14582. else if (isDDS) {
  14583. callback = function (data) {
  14584. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14585. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14586. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14587. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14588. return false;
  14589. }, samplingMode);
  14590. };
  14591. }
  14592. if (!buffer) {
  14593. this._loadFile(url, function (data) {
  14594. if (callback) {
  14595. callback(data);
  14596. }
  14597. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14598. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14599. });
  14600. }
  14601. else {
  14602. if (callback) {
  14603. callback(buffer);
  14604. }
  14605. }
  14606. // image format processing
  14607. }
  14608. else {
  14609. var onload = function (img) {
  14610. if (fromBlob && !_this._doNotHandleContextLost) {
  14611. // We need to store the image if we need to rebuild the texture
  14612. // in case of a webgl context lost
  14613. texture._buffer = img;
  14614. }
  14615. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14616. var gl = _this._gl;
  14617. var isPot = (img.width === potWidth && img.height === potHeight);
  14618. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14619. if (isPot) {
  14620. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14621. return false;
  14622. }
  14623. // Using shaders to rescale because canvas.drawImage is lossy
  14624. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14625. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14626. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14627. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14628. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14629. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14630. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14631. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14632. _this._releaseTexture(source);
  14633. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14634. continuationCallback();
  14635. });
  14636. return true;
  14637. }, samplingMode);
  14638. };
  14639. if (!fromData || isBase64) {
  14640. if (buffer instanceof HTMLImageElement) {
  14641. onload(buffer);
  14642. }
  14643. else {
  14644. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14645. }
  14646. }
  14647. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14648. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14649. }
  14650. else {
  14651. onload(buffer);
  14652. }
  14653. }
  14654. return texture;
  14655. };
  14656. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14657. var _this = this;
  14658. var rtt = this.createRenderTargetTexture({
  14659. width: destination.width,
  14660. height: destination.height,
  14661. }, {
  14662. generateMipMaps: false,
  14663. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14664. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14665. generateDepthBuffer: false,
  14666. generateStencilBuffer: false
  14667. });
  14668. if (!this._rescalePostProcess) {
  14669. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14670. }
  14671. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14672. _this._rescalePostProcess.onApply = function (effect) {
  14673. effect._bindTexture("textureSampler", source);
  14674. };
  14675. var hostingScene = scene;
  14676. if (!hostingScene) {
  14677. hostingScene = _this.scenes[_this.scenes.length - 1];
  14678. }
  14679. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14680. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14681. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14682. _this.unBindFramebuffer(rtt);
  14683. _this._releaseTexture(rtt);
  14684. if (onComplete) {
  14685. onComplete();
  14686. }
  14687. });
  14688. };
  14689. /**
  14690. * Update a raw texture
  14691. * @param texture defines the texture to update
  14692. * @param data defines the data to store in the texture
  14693. * @param format defines the format of the data
  14694. * @param invertY defines if data must be stored with Y axis inverted
  14695. * @param compression defines the compression used (null by default)
  14696. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14697. */
  14698. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14699. if (compression === void 0) { compression = null; }
  14700. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14701. if (!texture) {
  14702. return;
  14703. }
  14704. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14705. var internalFormat = this._getInternalFormat(format);
  14706. var textureType = this._getWebGLTextureType(type);
  14707. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14708. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14709. if (!this._doNotHandleContextLost) {
  14710. texture._bufferView = data;
  14711. texture.format = format;
  14712. texture.type = type;
  14713. texture.invertY = invertY;
  14714. texture._compression = compression;
  14715. }
  14716. if (texture.width % 4 !== 0) {
  14717. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14718. }
  14719. if (compression && data) {
  14720. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14721. }
  14722. else {
  14723. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14724. }
  14725. if (texture.generateMipMaps) {
  14726. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14727. }
  14728. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14729. // this.resetTextureCache();
  14730. texture.isReady = true;
  14731. };
  14732. /**
  14733. * Creates a raw texture
  14734. * @param data defines the data to store in the texture
  14735. * @param width defines the width of the texture
  14736. * @param height defines the height of the texture
  14737. * @param format defines the format of the data
  14738. * @param generateMipMaps defines if the engine should generate the mip levels
  14739. * @param invertY defines if data must be stored with Y axis inverted
  14740. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14741. * @param compression defines the compression used (null by default)
  14742. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14743. * @returns the raw texture inside an InternalTexture
  14744. */
  14745. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14746. if (compression === void 0) { compression = null; }
  14747. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14748. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14749. texture.baseWidth = width;
  14750. texture.baseHeight = height;
  14751. texture.width = width;
  14752. texture.height = height;
  14753. texture.format = format;
  14754. texture.generateMipMaps = generateMipMaps;
  14755. texture.samplingMode = samplingMode;
  14756. texture.invertY = invertY;
  14757. texture._compression = compression;
  14758. texture.type = type;
  14759. if (!this._doNotHandleContextLost) {
  14760. texture._bufferView = data;
  14761. }
  14762. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14763. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14764. // Filters
  14765. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14766. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14767. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14768. if (generateMipMaps) {
  14769. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14770. }
  14771. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14772. this._internalTexturesCache.push(texture);
  14773. return texture;
  14774. };
  14775. /**
  14776. * Creates a dynamic texture
  14777. * @param width defines the width of the texture
  14778. * @param height defines the height of the texture
  14779. * @param generateMipMaps defines if the engine should generate the mip levels
  14780. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14781. * @returns the dynamic texture inside an InternalTexture
  14782. */
  14783. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14784. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14785. texture.baseWidth = width;
  14786. texture.baseHeight = height;
  14787. if (generateMipMaps) {
  14788. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14789. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14790. }
  14791. // this.resetTextureCache();
  14792. texture.width = width;
  14793. texture.height = height;
  14794. texture.isReady = false;
  14795. texture.generateMipMaps = generateMipMaps;
  14796. texture.samplingMode = samplingMode;
  14797. this.updateTextureSamplingMode(samplingMode, texture);
  14798. this._internalTexturesCache.push(texture);
  14799. return texture;
  14800. };
  14801. /**
  14802. * Update the sampling mode of a given texture
  14803. * @param samplingMode defines the required sampling mode
  14804. * @param texture defines the texture to update
  14805. */
  14806. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14807. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14808. if (texture.isCube) {
  14809. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14810. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14811. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14812. }
  14813. else if (texture.is3D) {
  14814. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14815. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14816. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14817. }
  14818. else {
  14819. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14820. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14821. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14822. }
  14823. texture.samplingMode = samplingMode;
  14824. };
  14825. /**
  14826. * Update the content of a dynamic texture
  14827. * @param texture defines the texture to update
  14828. * @param canvas defines the canvas containing the source
  14829. * @param invertY defines if data must be stored with Y axis inverted
  14830. * @param premulAlpha defines if alpha is stored as premultiplied
  14831. * @param format defines the format of the data
  14832. */
  14833. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14834. if (premulAlpha === void 0) { premulAlpha = false; }
  14835. if (!texture) {
  14836. return;
  14837. }
  14838. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14839. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14840. if (premulAlpha) {
  14841. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14842. }
  14843. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14844. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14845. if (texture.generateMipMaps) {
  14846. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14847. }
  14848. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14849. if (premulAlpha) {
  14850. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14851. }
  14852. texture.isReady = true;
  14853. };
  14854. /**
  14855. * Update a video texture
  14856. * @param texture defines the texture to update
  14857. * @param video defines the video element to use
  14858. * @param invertY defines if data must be stored with Y axis inverted
  14859. */
  14860. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14861. if (!texture || texture._isDisabled) {
  14862. return;
  14863. }
  14864. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14865. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14866. try {
  14867. // Testing video texture support
  14868. if (this._videoTextureSupported === undefined) {
  14869. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14870. if (this._gl.getError() !== 0) {
  14871. this._videoTextureSupported = false;
  14872. }
  14873. else {
  14874. this._videoTextureSupported = true;
  14875. }
  14876. }
  14877. // Copy video through the current working canvas if video texture is not supported
  14878. if (!this._videoTextureSupported) {
  14879. if (!texture._workingCanvas) {
  14880. texture._workingCanvas = document.createElement("canvas");
  14881. var context = texture._workingCanvas.getContext("2d");
  14882. if (!context) {
  14883. throw new Error("Unable to get 2d context");
  14884. }
  14885. texture._workingContext = context;
  14886. texture._workingCanvas.width = texture.width;
  14887. texture._workingCanvas.height = texture.height;
  14888. }
  14889. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14890. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14891. }
  14892. else {
  14893. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14894. }
  14895. if (texture.generateMipMaps) {
  14896. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14897. }
  14898. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14899. // this.resetTextureCache();
  14900. texture.isReady = true;
  14901. }
  14902. catch (ex) {
  14903. // Something unexpected
  14904. // Let's disable the texture
  14905. texture._isDisabled = true;
  14906. }
  14907. };
  14908. /**
  14909. * Updates a depth texture Comparison Mode and Function.
  14910. * If the comparison Function is equal to 0, the mode will be set to none.
  14911. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14912. * @param texture The texture to set the comparison function for
  14913. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14914. */
  14915. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14916. if (this.webGLVersion === 1) {
  14917. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14918. return;
  14919. }
  14920. var gl = this._gl;
  14921. if (texture.isCube) {
  14922. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14923. if (comparisonFunction === 0) {
  14924. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14925. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14926. }
  14927. else {
  14928. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14929. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14930. }
  14931. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14932. }
  14933. else {
  14934. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14935. if (comparisonFunction === 0) {
  14936. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14937. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14938. }
  14939. else {
  14940. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14941. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14942. }
  14943. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14944. }
  14945. texture._comparisonFunction = comparisonFunction;
  14946. };
  14947. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14948. var width = size.width || size;
  14949. var height = size.height || size;
  14950. internalTexture.baseWidth = width;
  14951. internalTexture.baseHeight = height;
  14952. internalTexture.width = width;
  14953. internalTexture.height = height;
  14954. internalTexture.isReady = true;
  14955. internalTexture.samples = 1;
  14956. internalTexture.generateMipMaps = false;
  14957. internalTexture._generateDepthBuffer = true;
  14958. internalTexture._generateStencilBuffer = generateStencil;
  14959. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14960. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14961. internalTexture._comparisonFunction = comparisonFunction;
  14962. var gl = this._gl;
  14963. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14964. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14965. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14966. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14967. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14968. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14969. if (comparisonFunction === 0) {
  14970. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14971. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14972. }
  14973. else {
  14974. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14975. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14976. }
  14977. };
  14978. /**
  14979. * Creates a depth stencil texture.
  14980. * This is only available in WebGL 2 or with the depth texture extension available.
  14981. * @param size The size of face edge in the texture.
  14982. * @param options The options defining the texture.
  14983. * @returns The texture
  14984. */
  14985. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14986. if (options.isCube) {
  14987. var width = size.width || size;
  14988. return this._createDepthStencilCubeTexture(width, options);
  14989. }
  14990. else {
  14991. return this._createDepthStencilTexture(size, options);
  14992. }
  14993. };
  14994. /**
  14995. * Creates a depth stencil texture.
  14996. * This is only available in WebGL 2 or with the depth texture extension available.
  14997. * @param size The size of face edge in the texture.
  14998. * @param options The options defining the texture.
  14999. * @returns The texture
  15000. */
  15001. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15002. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15003. if (!this._caps.depthTextureExtension) {
  15004. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15005. return internalTexture;
  15006. }
  15007. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15008. var gl = this._gl;
  15009. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15010. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15011. if (this.webGLVersion > 1) {
  15012. if (internalOptions.generateStencil) {
  15013. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15014. }
  15015. else {
  15016. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15017. }
  15018. }
  15019. else {
  15020. if (internalOptions.generateStencil) {
  15021. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15022. }
  15023. else {
  15024. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15025. }
  15026. }
  15027. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15028. return internalTexture;
  15029. };
  15030. /**
  15031. * Creates a depth stencil cube texture.
  15032. * This is only available in WebGL 2.
  15033. * @param size The size of face edge in the cube texture.
  15034. * @param options The options defining the cube texture.
  15035. * @returns The cube texture
  15036. */
  15037. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15038. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15039. internalTexture.isCube = true;
  15040. if (this.webGLVersion === 1) {
  15041. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15042. return internalTexture;
  15043. }
  15044. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15045. var gl = this._gl;
  15046. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15047. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15048. // Create the depth/stencil buffer
  15049. for (var face = 0; face < 6; face++) {
  15050. if (internalOptions.generateStencil) {
  15051. 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);
  15052. }
  15053. else {
  15054. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15055. }
  15056. }
  15057. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15058. return internalTexture;
  15059. };
  15060. /**
  15061. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15062. * @param renderTarget The render target to set the frame buffer for
  15063. */
  15064. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15065. // Create the framebuffer
  15066. var internalTexture = renderTarget.getInternalTexture();
  15067. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15068. return;
  15069. }
  15070. var gl = this._gl;
  15071. var depthStencilTexture = renderTarget.depthStencilTexture;
  15072. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15073. if (depthStencilTexture.isCube) {
  15074. if (depthStencilTexture._generateStencilBuffer) {
  15075. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15076. }
  15077. else {
  15078. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15079. }
  15080. }
  15081. else {
  15082. if (depthStencilTexture._generateStencilBuffer) {
  15083. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15084. }
  15085. else {
  15086. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15087. }
  15088. }
  15089. this.bindUnboundFramebuffer(null);
  15090. };
  15091. /**
  15092. * Creates a new render target texture
  15093. * @param size defines the size of the texture
  15094. * @param options defines the options used to create the texture
  15095. * @returns a new render target texture stored in an InternalTexture
  15096. */
  15097. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15098. var fullOptions = new RenderTargetCreationOptions();
  15099. if (options !== undefined && typeof options === "object") {
  15100. fullOptions.generateMipMaps = options.generateMipMaps;
  15101. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15102. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15103. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15104. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15105. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15106. }
  15107. else {
  15108. fullOptions.generateMipMaps = options;
  15109. fullOptions.generateDepthBuffer = true;
  15110. fullOptions.generateStencilBuffer = false;
  15111. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15112. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15113. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15114. }
  15115. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15116. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15117. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15118. }
  15119. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15120. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15121. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15122. }
  15123. var gl = this._gl;
  15124. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15125. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15126. var width = size.width || size;
  15127. var height = size.height || size;
  15128. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15129. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15130. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15131. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15132. }
  15133. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15134. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15135. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15136. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15137. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15138. // Create the framebuffer
  15139. var framebuffer = gl.createFramebuffer();
  15140. this.bindUnboundFramebuffer(framebuffer);
  15141. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15142. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15143. if (fullOptions.generateMipMaps) {
  15144. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15145. }
  15146. // Unbind
  15147. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15148. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15149. this.bindUnboundFramebuffer(null);
  15150. texture._framebuffer = framebuffer;
  15151. texture.baseWidth = width;
  15152. texture.baseHeight = height;
  15153. texture.width = width;
  15154. texture.height = height;
  15155. texture.isReady = true;
  15156. texture.samples = 1;
  15157. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15158. texture.samplingMode = fullOptions.samplingMode;
  15159. texture.type = fullOptions.type;
  15160. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15161. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15162. // this.resetTextureCache();
  15163. this._internalTexturesCache.push(texture);
  15164. return texture;
  15165. };
  15166. /**
  15167. * Create a multi render target texture
  15168. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15169. * @param size defines the size of the texture
  15170. * @param options defines the creation options
  15171. * @returns the cube texture as an InternalTexture
  15172. */
  15173. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15174. var generateMipMaps = false;
  15175. var generateDepthBuffer = true;
  15176. var generateStencilBuffer = false;
  15177. var generateDepthTexture = false;
  15178. var textureCount = 1;
  15179. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15180. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15181. var types = new Array();
  15182. var samplingModes = new Array();
  15183. if (options !== undefined) {
  15184. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15185. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15186. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15187. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15188. textureCount = options.textureCount || 1;
  15189. if (options.types) {
  15190. types = options.types;
  15191. }
  15192. if (options.samplingModes) {
  15193. samplingModes = options.samplingModes;
  15194. }
  15195. }
  15196. var gl = this._gl;
  15197. // Create the framebuffer
  15198. var framebuffer = gl.createFramebuffer();
  15199. this.bindUnboundFramebuffer(framebuffer);
  15200. var width = size.width || size;
  15201. var height = size.height || size;
  15202. var textures = [];
  15203. var attachments = [];
  15204. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15205. for (var i = 0; i < textureCount; i++) {
  15206. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15207. var type = types[i] || defaultType;
  15208. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15209. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15210. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15211. }
  15212. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15213. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15214. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15215. }
  15216. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15217. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15218. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15219. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15220. }
  15221. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15222. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15223. textures.push(texture);
  15224. attachments.push(attachment);
  15225. gl.activeTexture(gl["TEXTURE" + i]);
  15226. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15227. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15228. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15229. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15230. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15231. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15232. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15233. if (generateMipMaps) {
  15234. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15235. }
  15236. // Unbind
  15237. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15238. texture._framebuffer = framebuffer;
  15239. texture._depthStencilBuffer = depthStencilBuffer;
  15240. texture.baseWidth = width;
  15241. texture.baseHeight = height;
  15242. texture.width = width;
  15243. texture.height = height;
  15244. texture.isReady = true;
  15245. texture.samples = 1;
  15246. texture.generateMipMaps = generateMipMaps;
  15247. texture.samplingMode = samplingMode;
  15248. texture.type = type;
  15249. texture._generateDepthBuffer = generateDepthBuffer;
  15250. texture._generateStencilBuffer = generateStencilBuffer;
  15251. texture._attachments = attachments;
  15252. this._internalTexturesCache.push(texture);
  15253. }
  15254. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15255. // Depth texture
  15256. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15257. gl.activeTexture(gl.TEXTURE0);
  15258. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15259. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15260. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15261. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15262. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15263. 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);
  15264. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15265. depthTexture._framebuffer = framebuffer;
  15266. depthTexture.baseWidth = width;
  15267. depthTexture.baseHeight = height;
  15268. depthTexture.width = width;
  15269. depthTexture.height = height;
  15270. depthTexture.isReady = true;
  15271. depthTexture.samples = 1;
  15272. depthTexture.generateMipMaps = generateMipMaps;
  15273. depthTexture.samplingMode = gl.NEAREST;
  15274. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15275. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15276. textures.push(depthTexture);
  15277. this._internalTexturesCache.push(depthTexture);
  15278. }
  15279. gl.drawBuffers(attachments);
  15280. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15281. this.bindUnboundFramebuffer(null);
  15282. this.resetTextureCache();
  15283. return textures;
  15284. };
  15285. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15286. if (samples === void 0) { samples = 1; }
  15287. var depthStencilBuffer = null;
  15288. var gl = this._gl;
  15289. // Create the depth/stencil buffer
  15290. if (generateStencilBuffer) {
  15291. depthStencilBuffer = gl.createRenderbuffer();
  15292. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15293. if (samples > 1) {
  15294. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15295. }
  15296. else {
  15297. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15298. }
  15299. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15300. }
  15301. else if (generateDepthBuffer) {
  15302. depthStencilBuffer = gl.createRenderbuffer();
  15303. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15304. if (samples > 1) {
  15305. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15306. }
  15307. else {
  15308. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15309. }
  15310. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15311. }
  15312. return depthStencilBuffer;
  15313. };
  15314. /**
  15315. * Updates the sample count of a render target texture
  15316. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15317. * @param texture defines the texture to update
  15318. * @param samples defines the sample count to set
  15319. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15320. */
  15321. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15322. if (this.webGLVersion < 2 || !texture) {
  15323. return 1;
  15324. }
  15325. if (texture.samples === samples) {
  15326. return samples;
  15327. }
  15328. var gl = this._gl;
  15329. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15330. // Dispose previous render buffers
  15331. if (texture._depthStencilBuffer) {
  15332. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15333. texture._depthStencilBuffer = null;
  15334. }
  15335. if (texture._MSAAFramebuffer) {
  15336. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15337. texture._MSAAFramebuffer = null;
  15338. }
  15339. if (texture._MSAARenderBuffer) {
  15340. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15341. texture._MSAARenderBuffer = null;
  15342. }
  15343. if (samples > 1) {
  15344. var framebuffer = gl.createFramebuffer();
  15345. if (!framebuffer) {
  15346. throw new Error("Unable to create multi sampled framebuffer");
  15347. }
  15348. texture._MSAAFramebuffer = framebuffer;
  15349. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15350. var colorRenderbuffer = gl.createRenderbuffer();
  15351. if (!colorRenderbuffer) {
  15352. throw new Error("Unable to create multi sampled framebuffer");
  15353. }
  15354. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15355. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15356. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15357. texture._MSAARenderBuffer = colorRenderbuffer;
  15358. }
  15359. else {
  15360. this.bindUnboundFramebuffer(texture._framebuffer);
  15361. }
  15362. texture.samples = samples;
  15363. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15364. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15365. this.bindUnboundFramebuffer(null);
  15366. return samples;
  15367. };
  15368. /**
  15369. * Update the sample count for a given multiple render target texture
  15370. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15371. * @param textures defines the textures to update
  15372. * @param samples defines the sample count to set
  15373. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15374. */
  15375. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15376. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15377. return 1;
  15378. }
  15379. if (textures[0].samples === samples) {
  15380. return samples;
  15381. }
  15382. var gl = this._gl;
  15383. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15384. // Dispose previous render buffers
  15385. if (textures[0]._depthStencilBuffer) {
  15386. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15387. textures[0]._depthStencilBuffer = null;
  15388. }
  15389. if (textures[0]._MSAAFramebuffer) {
  15390. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15391. textures[0]._MSAAFramebuffer = null;
  15392. }
  15393. for (var i = 0; i < textures.length; i++) {
  15394. if (textures[i]._MSAARenderBuffer) {
  15395. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15396. textures[i]._MSAARenderBuffer = null;
  15397. }
  15398. }
  15399. if (samples > 1) {
  15400. var framebuffer = gl.createFramebuffer();
  15401. if (!framebuffer) {
  15402. throw new Error("Unable to create multi sampled framebuffer");
  15403. }
  15404. this.bindUnboundFramebuffer(framebuffer);
  15405. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15406. var attachments = [];
  15407. for (var i = 0; i < textures.length; i++) {
  15408. var texture = textures[i];
  15409. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15410. var colorRenderbuffer = gl.createRenderbuffer();
  15411. if (!colorRenderbuffer) {
  15412. throw new Error("Unable to create multi sampled framebuffer");
  15413. }
  15414. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15415. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15416. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15417. texture._MSAAFramebuffer = framebuffer;
  15418. texture._MSAARenderBuffer = colorRenderbuffer;
  15419. texture.samples = samples;
  15420. texture._depthStencilBuffer = depthStencilBuffer;
  15421. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15422. attachments.push(attachment);
  15423. }
  15424. gl.drawBuffers(attachments);
  15425. }
  15426. else {
  15427. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15428. }
  15429. this.bindUnboundFramebuffer(null);
  15430. return samples;
  15431. };
  15432. /** @hidden */
  15433. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15434. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15435. };
  15436. /** @hidden */
  15437. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15438. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15439. };
  15440. /**
  15441. * Creates a new render target cube texture
  15442. * @param size defines the size of the texture
  15443. * @param options defines the options used to create the texture
  15444. * @returns a new render target cube texture stored in an InternalTexture
  15445. */
  15446. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15447. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15448. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15449. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15450. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15451. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15452. }
  15453. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15454. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15455. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15456. }
  15457. var gl = this._gl;
  15458. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15459. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15460. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15461. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15462. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15463. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15464. }
  15465. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15466. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15467. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15468. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15469. for (var face = 0; face < 6; face++) {
  15470. 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);
  15471. }
  15472. // Create the framebuffer
  15473. var framebuffer = gl.createFramebuffer();
  15474. this.bindUnboundFramebuffer(framebuffer);
  15475. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15476. // MipMaps
  15477. if (fullOptions.generateMipMaps) {
  15478. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15479. }
  15480. // Unbind
  15481. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15482. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15483. this.bindUnboundFramebuffer(null);
  15484. texture._framebuffer = framebuffer;
  15485. texture.width = size;
  15486. texture.height = size;
  15487. texture.isReady = true;
  15488. texture.isCube = true;
  15489. texture.samples = 1;
  15490. texture.generateMipMaps = fullOptions.generateMipMaps;
  15491. texture.samplingMode = fullOptions.samplingMode;
  15492. texture.type = fullOptions.type;
  15493. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15494. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15495. this._internalTexturesCache.push(texture);
  15496. return texture;
  15497. };
  15498. /**
  15499. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15500. * @param rootUrl defines the url where the file to load is located
  15501. * @param scene defines the current scene
  15502. * @param scale defines scale to apply to the mip map selection
  15503. * @param offset defines offset to apply to the mip map selection
  15504. * @param onLoad defines an optional callback raised when the texture is loaded
  15505. * @param onError defines an optional callback raised if there is an issue to load the texture
  15506. * @param format defines the format of the data
  15507. * @param forcedExtension defines the extension to use to pick the right loader
  15508. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15509. * @returns the cube texture as an InternalTexture
  15510. */
  15511. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15512. var _this = this;
  15513. if (onLoad === void 0) { onLoad = null; }
  15514. if (onError === void 0) { onError = null; }
  15515. if (forcedExtension === void 0) { forcedExtension = null; }
  15516. if (createPolynomials === void 0) { createPolynomials = true; }
  15517. var callback = function (loadData) {
  15518. if (!loadData) {
  15519. if (onLoad) {
  15520. onLoad(null);
  15521. }
  15522. return;
  15523. }
  15524. var texture = loadData.texture;
  15525. if (!createPolynomials) {
  15526. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15527. }
  15528. else if (loadData.info.sphericalPolynomial) {
  15529. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15530. }
  15531. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15532. texture._lodGenerationScale = scale;
  15533. texture._lodGenerationOffset = offset;
  15534. if (_this._caps.textureLOD) {
  15535. // Do not add extra process if texture lod is supported.
  15536. if (onLoad) {
  15537. onLoad(texture);
  15538. }
  15539. return;
  15540. }
  15541. var mipSlices = 3;
  15542. var gl = _this._gl;
  15543. var width = loadData.width;
  15544. if (!width) {
  15545. return;
  15546. }
  15547. var textures = [];
  15548. for (var i = 0; i < mipSlices; i++) {
  15549. //compute LOD from even spacing in smoothness (matching shader calculation)
  15550. var smoothness = i / (mipSlices - 1);
  15551. var roughness = 1 - smoothness;
  15552. var minLODIndex = offset; // roughness = 0
  15553. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15554. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15555. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15556. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15557. glTextureFromLod.isCube = true;
  15558. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15559. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15560. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15561. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15562. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15563. if (loadData.isDDS) {
  15564. var info = loadData.info;
  15565. var data = loadData.data;
  15566. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15567. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15568. }
  15569. else {
  15570. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15571. }
  15572. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15573. // Wrap in a base texture for easy binding.
  15574. var lodTexture = new BABYLON.BaseTexture(scene);
  15575. lodTexture.isCube = true;
  15576. lodTexture._texture = glTextureFromLod;
  15577. glTextureFromLod.isReady = true;
  15578. textures.push(lodTexture);
  15579. }
  15580. texture._lodTextureHigh = textures[2];
  15581. texture._lodTextureMid = textures[1];
  15582. texture._lodTextureLow = textures[0];
  15583. if (onLoad) {
  15584. onLoad(texture);
  15585. }
  15586. };
  15587. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials);
  15588. };
  15589. /**
  15590. * Creates a cube texture
  15591. * @param rootUrl defines the url where the files to load is located
  15592. * @param scene defines the current scene
  15593. * @param files defines the list of files to load (1 per face)
  15594. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15595. * @param onLoad defines an optional callback raised when the texture is loaded
  15596. * @param onError defines an optional callback raised if there is an issue to load the texture
  15597. * @param format defines the format of the data
  15598. * @param forcedExtension defines the extension to use to pick the right loader
  15599. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15600. * @returns the cube texture as an InternalTexture
  15601. */
  15602. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15603. var _this = this;
  15604. if (onLoad === void 0) { onLoad = null; }
  15605. if (onError === void 0) { onError = null; }
  15606. if (forcedExtension === void 0) { forcedExtension = null; }
  15607. if (createPolynomials === void 0) { createPolynomials = false; }
  15608. var gl = this._gl;
  15609. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15610. texture.isCube = true;
  15611. texture.url = rootUrl;
  15612. texture.generateMipMaps = !noMipmap;
  15613. if (!this._doNotHandleContextLost) {
  15614. texture._extension = forcedExtension;
  15615. texture._files = files;
  15616. }
  15617. var isKTX = false;
  15618. var isDDS = false;
  15619. var lastDot = rootUrl.lastIndexOf('.');
  15620. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15621. if (this._textureFormatInUse) {
  15622. extension = this._textureFormatInUse;
  15623. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15624. isKTX = true;
  15625. }
  15626. else {
  15627. isDDS = (extension === ".dds");
  15628. }
  15629. var onerror = function (request, exception) {
  15630. if (onError && request) {
  15631. onError(request.status + " " + request.statusText, exception);
  15632. }
  15633. };
  15634. if (isKTX) {
  15635. this._loadFile(rootUrl, function (data) {
  15636. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15637. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15638. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15639. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15640. ktx.uploadLevels(_this._gl, !noMipmap);
  15641. _this.setCubeMapTextureParams(gl, loadMipmap);
  15642. texture.width = ktx.pixelWidth;
  15643. texture.height = ktx.pixelHeight;
  15644. texture.isReady = true;
  15645. }, undefined, undefined, true, onerror);
  15646. }
  15647. else if (isDDS) {
  15648. if (files && files.length === 6) {
  15649. this._cascadeLoadFiles(scene, function (imgs) {
  15650. var info;
  15651. var loadMipmap = false;
  15652. var width = 0;
  15653. for (var index = 0; index < imgs.length; index++) {
  15654. var data = imgs[index];
  15655. info = BABYLON.DDSTools.GetDDSInfo(data);
  15656. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15657. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15658. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15659. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15660. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15661. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15662. }
  15663. texture.width = info.width;
  15664. texture.height = info.height;
  15665. texture.type = info.textureType;
  15666. width = info.width;
  15667. }
  15668. _this.setCubeMapTextureParams(gl, loadMipmap);
  15669. texture.isReady = true;
  15670. if (onLoad) {
  15671. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15672. }
  15673. }, files, onError);
  15674. }
  15675. else {
  15676. this._loadFile(rootUrl, function (data) {
  15677. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15678. if (createPolynomials) {
  15679. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15680. }
  15681. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15682. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15683. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15684. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15685. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15686. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15687. }
  15688. _this.setCubeMapTextureParams(gl, loadMipmap);
  15689. texture.width = info.width;
  15690. texture.height = info.height;
  15691. texture.isReady = true;
  15692. texture.type = info.textureType;
  15693. if (onLoad) {
  15694. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15695. }
  15696. }, undefined, undefined, true, onerror);
  15697. }
  15698. }
  15699. else {
  15700. if (!files) {
  15701. throw new Error("Cannot load cubemap because files were not defined");
  15702. }
  15703. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15704. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15705. var height = width;
  15706. _this._prepareWorkingCanvas();
  15707. if (!_this._workingCanvas || !_this._workingContext) {
  15708. return;
  15709. }
  15710. _this._workingCanvas.width = width;
  15711. _this._workingCanvas.height = height;
  15712. var faces = [
  15713. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15714. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15715. ];
  15716. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15717. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15718. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15719. for (var index = 0; index < faces.length; index++) {
  15720. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15721. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15722. }
  15723. if (!noMipmap) {
  15724. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15725. }
  15726. _this.setCubeMapTextureParams(gl, !noMipmap);
  15727. texture.width = width;
  15728. texture.height = height;
  15729. texture.isReady = true;
  15730. if (format) {
  15731. texture.format = format;
  15732. }
  15733. texture.onLoadedObservable.notifyObservers(texture);
  15734. texture.onLoadedObservable.clear();
  15735. if (onLoad) {
  15736. onLoad();
  15737. }
  15738. }, files, onError);
  15739. }
  15740. this._internalTexturesCache.push(texture);
  15741. return texture;
  15742. };
  15743. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15744. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15745. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15746. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15747. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15748. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15749. // this.resetTextureCache();
  15750. };
  15751. /**
  15752. * Update a raw cube texture
  15753. * @param texture defines the texture to udpdate
  15754. * @param data defines the data to store
  15755. * @param format defines the data format
  15756. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15757. * @param invertY defines if data must be stored with Y axis inverted
  15758. * @param compression defines the compression used (null by default)
  15759. * @param level defines which level of the texture to update
  15760. */
  15761. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15762. if (compression === void 0) { compression = null; }
  15763. if (level === void 0) { level = 0; }
  15764. texture._bufferViewArray = data;
  15765. texture.format = format;
  15766. texture.type = type;
  15767. texture.invertY = invertY;
  15768. texture._compression = compression;
  15769. var gl = this._gl;
  15770. var textureType = this._getWebGLTextureType(type);
  15771. var internalFormat = this._getInternalFormat(format);
  15772. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15773. var needConversion = false;
  15774. if (internalFormat === gl.RGB) {
  15775. internalFormat = gl.RGBA;
  15776. needConversion = true;
  15777. }
  15778. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15779. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15780. if (texture.width % 4 !== 0) {
  15781. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15782. }
  15783. // Data are known to be in +X +Y +Z -X -Y -Z
  15784. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15785. var faceData = data[faceIndex];
  15786. if (compression) {
  15787. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15788. }
  15789. else {
  15790. if (needConversion) {
  15791. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15792. }
  15793. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15794. }
  15795. }
  15796. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15797. if (isPot && texture.generateMipMaps && level === 0) {
  15798. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15799. }
  15800. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15801. // this.resetTextureCache();
  15802. texture.isReady = true;
  15803. };
  15804. /**
  15805. * Creates a new raw cube texture
  15806. * @param data defines the array of data to use to create each face
  15807. * @param size defines the size of the textures
  15808. * @param format defines the format of the data
  15809. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15810. * @param generateMipMaps defines if the engine should generate the mip levels
  15811. * @param invertY defines if data must be stored with Y axis inverted
  15812. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15813. * @param compression defines the compression used (null by default)
  15814. * @returns the cube texture as an InternalTexture
  15815. */
  15816. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15817. if (compression === void 0) { compression = null; }
  15818. var gl = this._gl;
  15819. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15820. texture.isCube = true;
  15821. texture.generateMipMaps = generateMipMaps;
  15822. texture.format = format;
  15823. texture.type = type;
  15824. if (!this._doNotHandleContextLost) {
  15825. texture._bufferViewArray = data;
  15826. }
  15827. var textureType = this._getWebGLTextureType(type);
  15828. var internalFormat = this._getInternalFormat(format);
  15829. if (internalFormat === gl.RGB) {
  15830. internalFormat = gl.RGBA;
  15831. }
  15832. var width = size;
  15833. var height = width;
  15834. texture.width = width;
  15835. texture.height = height;
  15836. // Double check on POT to generate Mips.
  15837. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15838. if (!isPot) {
  15839. generateMipMaps = false;
  15840. }
  15841. // Upload data if needed. The texture won't be ready until then.
  15842. if (data) {
  15843. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15844. }
  15845. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15846. // Filters
  15847. if (data && generateMipMaps) {
  15848. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15849. }
  15850. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15851. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15852. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15853. }
  15854. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15855. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15856. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15857. }
  15858. else {
  15859. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15860. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15861. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15862. }
  15863. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15865. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15866. return texture;
  15867. };
  15868. /**
  15869. * Creates a new raw cube texture from a specified url
  15870. * @param url defines the url where the data is located
  15871. * @param scene defines the current scene
  15872. * @param size defines the size of the textures
  15873. * @param format defines the format of the data
  15874. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15875. * @param noMipmap defines if the engine should avoid generating the mip levels
  15876. * @param callback defines a callback used to extract texture data from loaded data
  15877. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15878. * @param onLoad defines a callback called when texture is loaded
  15879. * @param onError defines a callback called if there is an error
  15880. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15881. * @param invertY defines if data must be stored with Y axis inverted
  15882. * @returns the cube texture as an InternalTexture
  15883. */
  15884. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15885. var _this = this;
  15886. if (onLoad === void 0) { onLoad = null; }
  15887. if (onError === void 0) { onError = null; }
  15888. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15889. if (invertY === void 0) { invertY = false; }
  15890. var gl = this._gl;
  15891. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15892. scene._addPendingData(texture);
  15893. texture.url = url;
  15894. this._internalTexturesCache.push(texture);
  15895. var onerror = function (request, exception) {
  15896. scene._removePendingData(texture);
  15897. if (onError && request) {
  15898. onError(request.status + " " + request.statusText, exception);
  15899. }
  15900. };
  15901. var internalCallback = function (data) {
  15902. var width = texture.width;
  15903. var faceDataArrays = callback(data);
  15904. if (!faceDataArrays) {
  15905. return;
  15906. }
  15907. if (mipmapGenerator) {
  15908. var textureType = _this._getWebGLTextureType(type);
  15909. var internalFormat = _this._getInternalFormat(format);
  15910. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15911. var needConversion = false;
  15912. if (internalFormat === gl.RGB) {
  15913. internalFormat = gl.RGBA;
  15914. needConversion = true;
  15915. }
  15916. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15917. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15918. var mipData = mipmapGenerator(faceDataArrays);
  15919. for (var level = 0; level < mipData.length; level++) {
  15920. var mipSize = width >> level;
  15921. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15922. var mipFaceData = mipData[level][faceIndex];
  15923. if (needConversion) {
  15924. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15925. }
  15926. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15927. }
  15928. }
  15929. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15930. }
  15931. else {
  15932. texture.generateMipMaps = !noMipmap;
  15933. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15934. }
  15935. texture.isReady = true;
  15936. // this.resetTextureCache();
  15937. scene._removePendingData(texture);
  15938. if (onLoad) {
  15939. onLoad();
  15940. }
  15941. };
  15942. this._loadFile(url, function (data) {
  15943. internalCallback(data);
  15944. }, undefined, scene.database, true, onerror);
  15945. return texture;
  15946. };
  15947. ;
  15948. /**
  15949. * Update a raw 3D texture
  15950. * @param texture defines the texture to update
  15951. * @param data defines the data to store
  15952. * @param format defines the data format
  15953. * @param invertY defines if data must be stored with Y axis inverted
  15954. * @param compression defines the used compression (can be null)
  15955. */
  15956. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15957. if (compression === void 0) { compression = null; }
  15958. var internalFormat = this._getInternalFormat(format);
  15959. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15960. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15961. if (!this._doNotHandleContextLost) {
  15962. texture._bufferView = data;
  15963. texture.format = format;
  15964. texture.invertY = invertY;
  15965. texture._compression = compression;
  15966. }
  15967. if (texture.width % 4 !== 0) {
  15968. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15969. }
  15970. if (compression && data) {
  15971. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15972. }
  15973. else {
  15974. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15975. }
  15976. if (texture.generateMipMaps) {
  15977. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15978. }
  15979. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15980. // this.resetTextureCache();
  15981. texture.isReady = true;
  15982. };
  15983. /**
  15984. * Creates a new raw 3D texture
  15985. * @param data defines the data used to create the texture
  15986. * @param width defines the width of the texture
  15987. * @param height defines the height of the texture
  15988. * @param depth defines the depth of the texture
  15989. * @param format defines the format of the texture
  15990. * @param generateMipMaps defines if the engine must generate mip levels
  15991. * @param invertY defines if data must be stored with Y axis inverted
  15992. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15993. * @param compression defines the compressed used (can be null)
  15994. * @returns a new raw 3D texture (stored in an InternalTexture)
  15995. */
  15996. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15997. if (compression === void 0) { compression = null; }
  15998. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15999. texture.baseWidth = width;
  16000. texture.baseHeight = height;
  16001. texture.baseDepth = depth;
  16002. texture.width = width;
  16003. texture.height = height;
  16004. texture.depth = depth;
  16005. texture.format = format;
  16006. texture.generateMipMaps = generateMipMaps;
  16007. texture.samplingMode = samplingMode;
  16008. texture.is3D = true;
  16009. if (!this._doNotHandleContextLost) {
  16010. texture._bufferView = data;
  16011. }
  16012. this.updateRawTexture3D(texture, data, format, invertY, compression);
  16013. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16014. // Filters
  16015. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16016. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16017. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16018. if (generateMipMaps) {
  16019. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16020. }
  16021. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16022. this._internalTexturesCache.push(texture);
  16023. return texture;
  16024. };
  16025. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16026. var gl = this._gl;
  16027. if (!gl) {
  16028. return;
  16029. }
  16030. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16031. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16032. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16033. if (!noMipmap && !isCompressed) {
  16034. gl.generateMipmap(gl.TEXTURE_2D);
  16035. }
  16036. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16037. // this.resetTextureCache();
  16038. if (scene) {
  16039. scene._removePendingData(texture);
  16040. }
  16041. texture.onLoadedObservable.notifyObservers(texture);
  16042. texture.onLoadedObservable.clear();
  16043. };
  16044. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16045. var _this = this;
  16046. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16047. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16048. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16049. var gl = this._gl;
  16050. if (!gl) {
  16051. return;
  16052. }
  16053. if (!texture._webGLTexture) {
  16054. // this.resetTextureCache();
  16055. if (scene) {
  16056. scene._removePendingData(texture);
  16057. }
  16058. return;
  16059. }
  16060. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16061. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16062. texture.baseWidth = width;
  16063. texture.baseHeight = height;
  16064. texture.width = potWidth;
  16065. texture.height = potHeight;
  16066. texture.isReady = true;
  16067. if (processFunction(potWidth, potHeight, function () {
  16068. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16069. })) {
  16070. // Returning as texture needs extra async steps
  16071. return;
  16072. }
  16073. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16074. };
  16075. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16076. // Create new RGBA data container.
  16077. var rgbaData;
  16078. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16079. rgbaData = new Float32Array(width * height * 4);
  16080. }
  16081. else {
  16082. rgbaData = new Uint32Array(width * height * 4);
  16083. }
  16084. // Convert each pixel.
  16085. for (var x = 0; x < width; x++) {
  16086. for (var y = 0; y < height; y++) {
  16087. var index = (y * width + x) * 3;
  16088. var newIndex = (y * width + x) * 4;
  16089. // Map Old Value to new value.
  16090. rgbaData[newIndex + 0] = rgbData[index + 0];
  16091. rgbaData[newIndex + 1] = rgbData[index + 1];
  16092. rgbaData[newIndex + 2] = rgbData[index + 2];
  16093. // Add fully opaque alpha channel.
  16094. rgbaData[newIndex + 3] = 1;
  16095. }
  16096. }
  16097. return rgbaData;
  16098. };
  16099. /** @hidden */
  16100. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16101. var gl = this._gl;
  16102. if (texture._framebuffer) {
  16103. gl.deleteFramebuffer(texture._framebuffer);
  16104. texture._framebuffer = null;
  16105. }
  16106. if (texture._depthStencilBuffer) {
  16107. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16108. texture._depthStencilBuffer = null;
  16109. }
  16110. if (texture._MSAAFramebuffer) {
  16111. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16112. texture._MSAAFramebuffer = null;
  16113. }
  16114. if (texture._MSAARenderBuffer) {
  16115. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16116. texture._MSAARenderBuffer = null;
  16117. }
  16118. };
  16119. /** @hidden */
  16120. Engine.prototype._releaseTexture = function (texture) {
  16121. var gl = this._gl;
  16122. this._releaseFramebufferObjects(texture);
  16123. gl.deleteTexture(texture._webGLTexture);
  16124. // Unbind channels
  16125. this.unbindAllTextures();
  16126. var index = this._internalTexturesCache.indexOf(texture);
  16127. if (index !== -1) {
  16128. this._internalTexturesCache.splice(index, 1);
  16129. }
  16130. // Integrated fixed lod samplers.
  16131. if (texture._lodTextureHigh) {
  16132. texture._lodTextureHigh.dispose();
  16133. }
  16134. if (texture._lodTextureMid) {
  16135. texture._lodTextureMid.dispose();
  16136. }
  16137. if (texture._lodTextureLow) {
  16138. texture._lodTextureLow.dispose();
  16139. }
  16140. // Set output texture of post process to null if the texture has been released/disposed
  16141. this.scenes.forEach(function (scene) {
  16142. scene.postProcesses.forEach(function (postProcess) {
  16143. if (postProcess._outputTexture == texture) {
  16144. postProcess._outputTexture = null;
  16145. }
  16146. });
  16147. scene.cameras.forEach(function (camera) {
  16148. camera._postProcesses.forEach(function (postProcess) {
  16149. if (postProcess) {
  16150. if (postProcess._outputTexture == texture) {
  16151. postProcess._outputTexture = null;
  16152. }
  16153. }
  16154. });
  16155. });
  16156. });
  16157. };
  16158. Engine.prototype.setProgram = function (program) {
  16159. if (this._currentProgram !== program) {
  16160. this._gl.useProgram(program);
  16161. this._currentProgram = program;
  16162. }
  16163. };
  16164. /**
  16165. * Binds an effect to the webGL context
  16166. * @param effect defines the effect to bind
  16167. */
  16168. Engine.prototype.bindSamplers = function (effect) {
  16169. this.setProgram(effect.getProgram());
  16170. var samplers = effect.getSamplers();
  16171. for (var index = 0; index < samplers.length; index++) {
  16172. var uniform = effect.getUniform(samplers[index]);
  16173. if (uniform) {
  16174. this._boundUniforms[index] = uniform;
  16175. }
  16176. }
  16177. this._currentEffect = null;
  16178. };
  16179. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16180. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16181. return;
  16182. }
  16183. // Remove
  16184. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16185. // Bind last to it
  16186. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16187. // Bind to dummy
  16188. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16189. };
  16190. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16191. if (!internalTexture) {
  16192. return -1;
  16193. }
  16194. internalTexture._initialSlot = channel;
  16195. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16196. if (channel !== internalTexture._designatedSlot) {
  16197. this._textureCollisions.addCount(1, false);
  16198. }
  16199. }
  16200. else {
  16201. if (channel !== internalTexture._designatedSlot) {
  16202. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16203. return internalTexture._designatedSlot;
  16204. }
  16205. else {
  16206. // No slot for this texture, let's pick a new one (if we find a free slot)
  16207. if (this._nextFreeTextureSlots.length) {
  16208. return this._nextFreeTextureSlots[0];
  16209. }
  16210. // We need to recycle the oldest bound texture, sorry.
  16211. this._textureCollisions.addCount(1, false);
  16212. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16213. }
  16214. }
  16215. }
  16216. return channel;
  16217. };
  16218. Engine.prototype._linkTrackers = function (previous, next) {
  16219. previous.next = next;
  16220. next.previous = previous;
  16221. };
  16222. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16223. var currentSlot = internalTexture._designatedSlot;
  16224. if (currentSlot === -1) {
  16225. return -1;
  16226. }
  16227. internalTexture._designatedSlot = -1;
  16228. if (this.disableTextureBindingOptimization) {
  16229. return -1;
  16230. }
  16231. // Remove from bound list
  16232. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16233. // Free the slot
  16234. this._boundTexturesCache[currentSlot] = null;
  16235. this._nextFreeTextureSlots.push(currentSlot);
  16236. return currentSlot;
  16237. };
  16238. Engine.prototype._activateCurrentTexture = function () {
  16239. if (this._currentTextureChannel !== this._activeChannel) {
  16240. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16241. this._currentTextureChannel = this._activeChannel;
  16242. }
  16243. };
  16244. /** @hidden */
  16245. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16246. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16247. if (force === void 0) { force = false; }
  16248. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16249. this._activeChannel = texture._designatedSlot;
  16250. }
  16251. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16252. var isTextureForRendering = texture && texture._initialSlot > -1;
  16253. if (currentTextureBound !== texture || force) {
  16254. if (currentTextureBound) {
  16255. this._removeDesignatedSlot(currentTextureBound);
  16256. }
  16257. this._activateCurrentTexture();
  16258. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16259. this._boundTexturesCache[this._activeChannel] = texture;
  16260. if (texture) {
  16261. if (!this.disableTextureBindingOptimization) {
  16262. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16263. if (slotIndex > -1) {
  16264. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16265. }
  16266. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16267. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16268. }
  16269. texture._designatedSlot = this._activeChannel;
  16270. }
  16271. }
  16272. else if (forTextureDataUpdate) {
  16273. this._activateCurrentTexture();
  16274. }
  16275. if (isTextureForRendering && !forTextureDataUpdate) {
  16276. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16277. }
  16278. };
  16279. /** @hidden */
  16280. Engine.prototype._bindTexture = function (channel, texture) {
  16281. if (channel < 0) {
  16282. return;
  16283. }
  16284. if (texture) {
  16285. channel = this._getCorrectTextureChannel(channel, texture);
  16286. }
  16287. this._activeChannel = channel;
  16288. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16289. };
  16290. /**
  16291. * Sets a texture to the webGL context from a postprocess
  16292. * @param channel defines the channel to use
  16293. * @param postProcess defines the source postprocess
  16294. */
  16295. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16296. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16297. };
  16298. /**
  16299. * Binds the output of the passed in post process to the texture channel specified
  16300. * @param channel The channel the texture should be bound to
  16301. * @param postProcess The post process which's output should be bound
  16302. */
  16303. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16304. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16305. };
  16306. /**
  16307. * Unbind all textures from the webGL context
  16308. */
  16309. Engine.prototype.unbindAllTextures = function () {
  16310. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16311. this._activeChannel = channel;
  16312. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16313. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16314. if (this.webGLVersion > 1) {
  16315. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16316. }
  16317. }
  16318. };
  16319. /**
  16320. * Sets a texture to the according uniform.
  16321. * @param channel The texture channel
  16322. * @param uniform The uniform to set
  16323. * @param texture The texture to apply
  16324. */
  16325. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16326. if (channel < 0) {
  16327. return;
  16328. }
  16329. if (uniform) {
  16330. this._boundUniforms[channel] = uniform;
  16331. }
  16332. this._setTexture(channel, texture);
  16333. };
  16334. /**
  16335. * Sets a depth stencil texture from a render target to the according uniform.
  16336. * @param channel The texture channel
  16337. * @param uniform The uniform to set
  16338. * @param texture The render target texture containing the depth stencil texture to apply
  16339. */
  16340. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16341. if (channel < 0) {
  16342. return;
  16343. }
  16344. if (uniform) {
  16345. this._boundUniforms[channel] = uniform;
  16346. }
  16347. if (!texture || !texture.depthStencilTexture) {
  16348. this._setTexture(channel, null);
  16349. }
  16350. else {
  16351. this._setTexture(channel, texture, false, true);
  16352. }
  16353. };
  16354. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16355. var uniform = this._boundUniforms[sourceSlot];
  16356. if (uniform._currentState === destination) {
  16357. return;
  16358. }
  16359. this._gl.uniform1i(uniform, destination);
  16360. uniform._currentState = destination;
  16361. };
  16362. Engine.prototype._getTextureWrapMode = function (mode) {
  16363. switch (mode) {
  16364. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16365. return this._gl.REPEAT;
  16366. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16367. return this._gl.CLAMP_TO_EDGE;
  16368. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16369. return this._gl.MIRRORED_REPEAT;
  16370. }
  16371. return this._gl.REPEAT;
  16372. };
  16373. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16374. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16375. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16376. // Not ready?
  16377. if (!texture) {
  16378. if (this._boundTexturesCache[channel] != null) {
  16379. this._activeChannel = channel;
  16380. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16381. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16382. if (this.webGLVersion > 1) {
  16383. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16384. }
  16385. }
  16386. return false;
  16387. }
  16388. // Video
  16389. if (texture.video) {
  16390. this._activeChannel = channel;
  16391. texture.update();
  16392. }
  16393. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16394. texture.delayLoad();
  16395. return false;
  16396. }
  16397. var internalTexture;
  16398. if (depthStencilTexture) {
  16399. internalTexture = texture.depthStencilTexture;
  16400. }
  16401. else if (texture.isReady()) {
  16402. internalTexture = texture.getInternalTexture();
  16403. }
  16404. else if (texture.isCube) {
  16405. internalTexture = this.emptyCubeTexture;
  16406. }
  16407. else if (texture.is3D) {
  16408. internalTexture = this.emptyTexture3D;
  16409. }
  16410. else {
  16411. internalTexture = this.emptyTexture;
  16412. }
  16413. if (!isPartOfTextureArray) {
  16414. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16415. }
  16416. var needToBind = true;
  16417. if (this._boundTexturesCache[channel] === internalTexture) {
  16418. this._moveBoundTextureOnTop(internalTexture);
  16419. if (!isPartOfTextureArray) {
  16420. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16421. }
  16422. needToBind = false;
  16423. }
  16424. this._activeChannel = channel;
  16425. if (internalTexture && internalTexture.is3D) {
  16426. if (needToBind) {
  16427. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16428. }
  16429. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16430. internalTexture._cachedWrapU = texture.wrapU;
  16431. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16432. }
  16433. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16434. internalTexture._cachedWrapV = texture.wrapV;
  16435. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16436. }
  16437. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16438. internalTexture._cachedWrapR = texture.wrapR;
  16439. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16440. }
  16441. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16442. }
  16443. else if (internalTexture && internalTexture.isCube) {
  16444. if (needToBind) {
  16445. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16446. }
  16447. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16448. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16449. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16450. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16451. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16452. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16453. }
  16454. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16455. }
  16456. else {
  16457. if (needToBind) {
  16458. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16459. }
  16460. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16461. internalTexture._cachedWrapU = texture.wrapU;
  16462. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16463. }
  16464. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16465. internalTexture._cachedWrapV = texture.wrapV;
  16466. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16467. }
  16468. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16469. }
  16470. return true;
  16471. };
  16472. /**
  16473. * Sets an array of texture to the webGL context
  16474. * @param channel defines the channel where the texture array must be set
  16475. * @param uniform defines the associated uniform location
  16476. * @param textures defines the array of textures to bind
  16477. */
  16478. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16479. if (channel < 0 || !uniform) {
  16480. return;
  16481. }
  16482. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16483. this._textureUnits = new Int32Array(textures.length);
  16484. }
  16485. for (var i = 0; i < textures.length; i++) {
  16486. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16487. }
  16488. this._gl.uniform1iv(uniform, this._textureUnits);
  16489. for (var index = 0; index < textures.length; index++) {
  16490. this._setTexture(this._textureUnits[index], textures[index], true);
  16491. }
  16492. };
  16493. /** @hidden */
  16494. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16495. var internalTexture = texture.getInternalTexture();
  16496. if (!internalTexture) {
  16497. return;
  16498. }
  16499. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16500. var value = texture.anisotropicFilteringLevel;
  16501. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16502. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16503. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16504. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16505. }
  16506. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16507. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16508. internalTexture._cachedAnisotropicFilteringLevel = value;
  16509. }
  16510. };
  16511. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16512. this._bindTextureDirectly(target, texture, true, true);
  16513. this._gl.texParameterf(target, parameter, value);
  16514. };
  16515. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16516. if (texture) {
  16517. this._bindTextureDirectly(target, texture, true, true);
  16518. }
  16519. this._gl.texParameteri(target, parameter, value);
  16520. };
  16521. /**
  16522. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16523. * @param x defines the x coordinate of the rectangle where pixels must be read
  16524. * @param y defines the y coordinate of the rectangle where pixels must be read
  16525. * @param width defines the width of the rectangle where pixels must be read
  16526. * @param height defines the height of the rectangle where pixels must be read
  16527. * @returns a Uint8Array containing RGBA colors
  16528. */
  16529. Engine.prototype.readPixels = function (x, y, width, height) {
  16530. var data = new Uint8Array(height * width * 4);
  16531. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16532. return data;
  16533. };
  16534. /**
  16535. * Add an externaly attached data from its key.
  16536. * This method call will fail and return false, if such key already exists.
  16537. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16538. * @param key the unique key that identifies the data
  16539. * @param data the data object to associate to the key for this Engine instance
  16540. * @return true if no such key were already present and the data was added successfully, false otherwise
  16541. */
  16542. Engine.prototype.addExternalData = function (key, data) {
  16543. if (!this._externalData) {
  16544. this._externalData = new BABYLON.StringDictionary();
  16545. }
  16546. return this._externalData.add(key, data);
  16547. };
  16548. /**
  16549. * Get an externaly attached data from its key
  16550. * @param key the unique key that identifies the data
  16551. * @return the associated data, if present (can be null), or undefined if not present
  16552. */
  16553. Engine.prototype.getExternalData = function (key) {
  16554. if (!this._externalData) {
  16555. this._externalData = new BABYLON.StringDictionary();
  16556. }
  16557. return this._externalData.get(key);
  16558. };
  16559. /**
  16560. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16561. * @param key the unique key that identifies the data
  16562. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16563. * @return the associated data, can be null if the factory returned null.
  16564. */
  16565. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16566. if (!this._externalData) {
  16567. this._externalData = new BABYLON.StringDictionary();
  16568. }
  16569. return this._externalData.getOrAddWithFactory(key, factory);
  16570. };
  16571. /**
  16572. * Remove an externaly attached data from the Engine instance
  16573. * @param key the unique key that identifies the data
  16574. * @return true if the data was successfully removed, false if it doesn't exist
  16575. */
  16576. Engine.prototype.removeExternalData = function (key) {
  16577. if (!this._externalData) {
  16578. this._externalData = new BABYLON.StringDictionary();
  16579. }
  16580. return this._externalData.remove(key);
  16581. };
  16582. /**
  16583. * Unbind all vertex attributes from the webGL context
  16584. */
  16585. Engine.prototype.unbindAllAttributes = function () {
  16586. if (this._mustWipeVertexAttributes) {
  16587. this._mustWipeVertexAttributes = false;
  16588. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16589. this._gl.disableVertexAttribArray(i);
  16590. this._vertexAttribArraysEnabled[i] = false;
  16591. this._currentBufferPointers[i].active = false;
  16592. }
  16593. return;
  16594. }
  16595. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16596. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16597. continue;
  16598. }
  16599. this._gl.disableVertexAttribArray(i);
  16600. this._vertexAttribArraysEnabled[i] = false;
  16601. this._currentBufferPointers[i].active = false;
  16602. }
  16603. };
  16604. /**
  16605. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16606. */
  16607. Engine.prototype.releaseEffects = function () {
  16608. for (var name in this._compiledEffects) {
  16609. this._deleteProgram(this._compiledEffects[name]._program);
  16610. }
  16611. this._compiledEffects = {};
  16612. };
  16613. /**
  16614. * Dispose and release all associated resources
  16615. */
  16616. Engine.prototype.dispose = function () {
  16617. this.hideLoadingUI();
  16618. this.stopRenderLoop();
  16619. // Release postProcesses
  16620. while (this.postProcesses.length) {
  16621. this.postProcesses[0].dispose();
  16622. }
  16623. // Empty texture
  16624. if (this._emptyTexture) {
  16625. this._releaseTexture(this._emptyTexture);
  16626. this._emptyTexture = null;
  16627. }
  16628. if (this._emptyCubeTexture) {
  16629. this._releaseTexture(this._emptyCubeTexture);
  16630. this._emptyCubeTexture = null;
  16631. }
  16632. // Rescale PP
  16633. if (this._rescalePostProcess) {
  16634. this._rescalePostProcess.dispose();
  16635. }
  16636. // Release scenes
  16637. while (this.scenes.length) {
  16638. this.scenes[0].dispose();
  16639. }
  16640. // Release audio engine
  16641. if (Engine.audioEngine) {
  16642. Engine.audioEngine.dispose();
  16643. }
  16644. // Release effects
  16645. this.releaseEffects();
  16646. // Unbind
  16647. this.unbindAllAttributes();
  16648. this._boundUniforms = [];
  16649. if (this._dummyFramebuffer) {
  16650. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16651. }
  16652. //WebVR
  16653. this.disableVR();
  16654. // Events
  16655. if (BABYLON.Tools.IsWindowObjectExist()) {
  16656. window.removeEventListener("blur", this._onBlur);
  16657. window.removeEventListener("focus", this._onFocus);
  16658. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16659. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16660. if (this._renderingCanvas) {
  16661. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16662. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16663. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16664. if (!this._doNotHandleContextLost) {
  16665. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16666. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16667. }
  16668. }
  16669. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16670. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16671. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16672. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16673. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16674. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16675. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16676. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16677. if (this._onVrDisplayConnect) {
  16678. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16679. if (this._onVrDisplayDisconnect) {
  16680. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16681. }
  16682. if (this._onVrDisplayPresentChange) {
  16683. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16684. }
  16685. this._onVrDisplayConnect = null;
  16686. this._onVrDisplayDisconnect = null;
  16687. }
  16688. }
  16689. // Remove from Instances
  16690. var index = Engine.Instances.indexOf(this);
  16691. if (index >= 0) {
  16692. Engine.Instances.splice(index, 1);
  16693. }
  16694. this._workingCanvas = null;
  16695. this._workingContext = null;
  16696. this._currentBufferPointers = [];
  16697. this._renderingCanvas = null;
  16698. this._currentProgram = null;
  16699. this._bindedRenderFunction = null;
  16700. this.onResizeObservable.clear();
  16701. this.onCanvasBlurObservable.clear();
  16702. this.onCanvasFocusObservable.clear();
  16703. this.onCanvasPointerOutObservable.clear();
  16704. this.onBeginFrameObservable.clear();
  16705. this.onEndFrameObservable.clear();
  16706. BABYLON.Effect.ResetCache();
  16707. // Abort active requests
  16708. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16709. var request = _a[_i];
  16710. request.abort();
  16711. }
  16712. };
  16713. // Loading screen
  16714. /**
  16715. * Display the loading screen
  16716. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16717. */
  16718. Engine.prototype.displayLoadingUI = function () {
  16719. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16720. return;
  16721. }
  16722. var loadingScreen = this.loadingScreen;
  16723. if (loadingScreen) {
  16724. loadingScreen.displayLoadingUI();
  16725. }
  16726. };
  16727. /**
  16728. * Hide the loading screen
  16729. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16730. */
  16731. Engine.prototype.hideLoadingUI = function () {
  16732. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16733. return;
  16734. }
  16735. var loadingScreen = this.loadingScreen;
  16736. if (loadingScreen) {
  16737. loadingScreen.hideLoadingUI();
  16738. }
  16739. };
  16740. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16741. /**
  16742. * Gets the current loading screen object
  16743. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16744. */
  16745. get: function () {
  16746. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16747. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16748. return this._loadingScreen;
  16749. },
  16750. /**
  16751. * Sets the current loading screen object
  16752. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16753. */
  16754. set: function (loadingScreen) {
  16755. this._loadingScreen = loadingScreen;
  16756. },
  16757. enumerable: true,
  16758. configurable: true
  16759. });
  16760. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16761. /**
  16762. * Sets the current loading screen text
  16763. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16764. */
  16765. set: function (text) {
  16766. this.loadingScreen.loadingUIText = text;
  16767. },
  16768. enumerable: true,
  16769. configurable: true
  16770. });
  16771. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16772. /**
  16773. * Sets the current loading screen background color
  16774. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16775. */
  16776. set: function (color) {
  16777. this.loadingScreen.loadingUIBackgroundColor = color;
  16778. },
  16779. enumerable: true,
  16780. configurable: true
  16781. });
  16782. /**
  16783. * Attach a new callback raised when context lost event is fired
  16784. * @param callback defines the callback to call
  16785. */
  16786. Engine.prototype.attachContextLostEvent = function (callback) {
  16787. if (this._renderingCanvas) {
  16788. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16789. }
  16790. };
  16791. /**
  16792. * Attach a new callback raised when context restored event is fired
  16793. * @param callback defines the callback to call
  16794. */
  16795. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16796. if (this._renderingCanvas) {
  16797. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16798. }
  16799. };
  16800. /**
  16801. * Gets the source code of the vertex shader associated with a specific webGL program
  16802. * @param program defines the program to use
  16803. * @returns a string containing the source code of the vertex shader associated with the program
  16804. */
  16805. Engine.prototype.getVertexShaderSource = function (program) {
  16806. var shaders = this._gl.getAttachedShaders(program);
  16807. if (!shaders) {
  16808. return null;
  16809. }
  16810. return this._gl.getShaderSource(shaders[0]);
  16811. };
  16812. /**
  16813. * Gets the source code of the fragment shader associated with a specific webGL program
  16814. * @param program defines the program to use
  16815. * @returns a string containing the source code of the fragment shader associated with the program
  16816. */
  16817. Engine.prototype.getFragmentShaderSource = function (program) {
  16818. var shaders = this._gl.getAttachedShaders(program);
  16819. if (!shaders) {
  16820. return null;
  16821. }
  16822. return this._gl.getShaderSource(shaders[1]);
  16823. };
  16824. /**
  16825. * Get the current error code of the webGL context
  16826. * @returns the error code
  16827. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16828. */
  16829. Engine.prototype.getError = function () {
  16830. return this._gl.getError();
  16831. };
  16832. // FPS
  16833. /**
  16834. * Gets the current framerate
  16835. * @returns a number representing the framerate
  16836. */
  16837. Engine.prototype.getFps = function () {
  16838. return this._fps;
  16839. };
  16840. /**
  16841. * Gets the time spent between current and previous frame
  16842. * @returns a number representing the delta time in ms
  16843. */
  16844. Engine.prototype.getDeltaTime = function () {
  16845. return this._deltaTime;
  16846. };
  16847. Engine.prototype._measureFps = function () {
  16848. this._performanceMonitor.sampleFrame();
  16849. this._fps = this._performanceMonitor.averageFPS;
  16850. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16851. };
  16852. /** @hidden */
  16853. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16854. if (faceIndex === void 0) { faceIndex = -1; }
  16855. var gl = this._gl;
  16856. if (!this._dummyFramebuffer) {
  16857. var dummy = gl.createFramebuffer();
  16858. if (!dummy) {
  16859. throw new Error("Unable to create dummy framebuffer");
  16860. }
  16861. this._dummyFramebuffer = dummy;
  16862. }
  16863. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16864. if (faceIndex > -1) {
  16865. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16866. }
  16867. else {
  16868. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16869. }
  16870. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16871. var buffer;
  16872. switch (readType) {
  16873. case gl.UNSIGNED_BYTE:
  16874. buffer = new Uint8Array(4 * width * height);
  16875. readType = gl.UNSIGNED_BYTE;
  16876. break;
  16877. default:
  16878. buffer = new Float32Array(4 * width * height);
  16879. readType = gl.FLOAT;
  16880. break;
  16881. }
  16882. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16883. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16884. return buffer;
  16885. };
  16886. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16887. if (this._webGLVersion > 1) {
  16888. return this._caps.colorBufferFloat;
  16889. }
  16890. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16891. };
  16892. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16893. if (this._webGLVersion > 1) {
  16894. return this._caps.colorBufferFloat;
  16895. }
  16896. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16897. };
  16898. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16899. Engine.prototype._canRenderToFramebuffer = function (type) {
  16900. var gl = this._gl;
  16901. //clear existing errors
  16902. while (gl.getError() !== gl.NO_ERROR) { }
  16903. var successful = true;
  16904. var texture = gl.createTexture();
  16905. gl.bindTexture(gl.TEXTURE_2D, texture);
  16906. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16907. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16908. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16909. var fb = gl.createFramebuffer();
  16910. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16911. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16912. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16913. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16914. successful = successful && (gl.getError() === gl.NO_ERROR);
  16915. //try render by clearing frame buffer's color buffer
  16916. if (successful) {
  16917. gl.clear(gl.COLOR_BUFFER_BIT);
  16918. successful = successful && (gl.getError() === gl.NO_ERROR);
  16919. }
  16920. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16921. if (successful) {
  16922. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16923. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16924. var readFormat = gl.RGBA;
  16925. var readType = gl.UNSIGNED_BYTE;
  16926. var buffer = new Uint8Array(4);
  16927. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16928. successful = successful && (gl.getError() === gl.NO_ERROR);
  16929. }
  16930. //clean up
  16931. gl.deleteTexture(texture);
  16932. gl.deleteFramebuffer(fb);
  16933. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16934. //clear accumulated errors
  16935. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16936. return successful;
  16937. };
  16938. /** @hidden */
  16939. Engine.prototype._getWebGLTextureType = function (type) {
  16940. if (type === Engine.TEXTURETYPE_FLOAT) {
  16941. return this._gl.FLOAT;
  16942. }
  16943. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16944. // Add Half Float Constant.
  16945. return this._gl.HALF_FLOAT_OES;
  16946. }
  16947. return this._gl.UNSIGNED_BYTE;
  16948. };
  16949. ;
  16950. Engine.prototype._getInternalFormat = function (format) {
  16951. var internalFormat = this._gl.RGBA;
  16952. switch (format) {
  16953. case Engine.TEXTUREFORMAT_ALPHA:
  16954. internalFormat = this._gl.ALPHA;
  16955. break;
  16956. case Engine.TEXTUREFORMAT_LUMINANCE:
  16957. internalFormat = this._gl.LUMINANCE;
  16958. break;
  16959. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16960. internalFormat = this._gl.LUMINANCE_ALPHA;
  16961. break;
  16962. case Engine.TEXTUREFORMAT_RGB:
  16963. case Engine.TEXTUREFORMAT_RGB32F:
  16964. internalFormat = this._gl.RGB;
  16965. break;
  16966. case Engine.TEXTUREFORMAT_RGBA:
  16967. case Engine.TEXTUREFORMAT_RGBA32F:
  16968. internalFormat = this._gl.RGBA;
  16969. break;
  16970. case Engine.TEXTUREFORMAT_R32F:
  16971. internalFormat = this._gl.RED;
  16972. break;
  16973. case Engine.TEXTUREFORMAT_RG32F:
  16974. internalFormat = this._gl.RG;
  16975. break;
  16976. }
  16977. return internalFormat;
  16978. };
  16979. /** @hidden */
  16980. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16981. if (this._webGLVersion === 1) {
  16982. if (format) {
  16983. switch (format) {
  16984. case Engine.TEXTUREFORMAT_LUMINANCE:
  16985. return this._gl.LUMINANCE;
  16986. }
  16987. }
  16988. return this._gl.RGBA;
  16989. }
  16990. if (type === Engine.TEXTURETYPE_FLOAT) {
  16991. if (format) {
  16992. switch (format) {
  16993. case Engine.TEXTUREFORMAT_R32F:
  16994. return this._gl.R32F;
  16995. case Engine.TEXTUREFORMAT_RG32F:
  16996. return this._gl.RG32F;
  16997. case Engine.TEXTUREFORMAT_RGB32F:
  16998. return this._gl.RGB32F;
  16999. }
  17000. }
  17001. return this._gl.RGBA32F;
  17002. }
  17003. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17004. return this._gl.RGBA16F;
  17005. }
  17006. if (format) {
  17007. switch (format) {
  17008. case Engine.TEXTUREFORMAT_LUMINANCE:
  17009. return this._gl.LUMINANCE;
  17010. case Engine.TEXTUREFORMAT_RGB:
  17011. return this._gl.RGB;
  17012. }
  17013. }
  17014. return this._gl.RGBA;
  17015. };
  17016. ;
  17017. /** @hidden */
  17018. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17019. if (type === Engine.TEXTURETYPE_FLOAT) {
  17020. return this._gl.RGBA32F;
  17021. }
  17022. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17023. return this._gl.RGBA16F;
  17024. }
  17025. return this._gl.RGBA8;
  17026. };
  17027. ;
  17028. /**
  17029. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17030. * @return the new query
  17031. */
  17032. Engine.prototype.createQuery = function () {
  17033. return this._gl.createQuery();
  17034. };
  17035. /**
  17036. * Delete and release a webGL query
  17037. * @param query defines the query to delete
  17038. * @return the current engine
  17039. */
  17040. Engine.prototype.deleteQuery = function (query) {
  17041. this._gl.deleteQuery(query);
  17042. return this;
  17043. };
  17044. /**
  17045. * Check if a given query has resolved and got its value
  17046. * @param query defines the query to check
  17047. * @returns true if the query got its value
  17048. */
  17049. Engine.prototype.isQueryResultAvailable = function (query) {
  17050. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17051. };
  17052. /**
  17053. * Gets the value of a given query
  17054. * @param query defines the query to check
  17055. * @returns the value of the query
  17056. */
  17057. Engine.prototype.getQueryResult = function (query) {
  17058. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17059. };
  17060. /**
  17061. * Initiates an occlusion query
  17062. * @param algorithmType defines the algorithm to use
  17063. * @param query defines the query to use
  17064. * @returns the current engine
  17065. * @see http://doc.babylonjs.com/features/occlusionquery
  17066. */
  17067. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17068. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17069. this._gl.beginQuery(glAlgorithm, query);
  17070. return this;
  17071. };
  17072. /**
  17073. * Ends an occlusion query
  17074. * @see http://doc.babylonjs.com/features/occlusionquery
  17075. * @param algorithmType defines the algorithm to use
  17076. * @returns the current engine
  17077. */
  17078. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17079. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17080. this._gl.endQuery(glAlgorithm);
  17081. return this;
  17082. };
  17083. /* Time queries */
  17084. Engine.prototype._createTimeQuery = function () {
  17085. var timerQuery = this._caps.timerQuery;
  17086. if (timerQuery.createQueryEXT) {
  17087. return timerQuery.createQueryEXT();
  17088. }
  17089. return this.createQuery();
  17090. };
  17091. Engine.prototype._deleteTimeQuery = function (query) {
  17092. var timerQuery = this._caps.timerQuery;
  17093. if (timerQuery.deleteQueryEXT) {
  17094. timerQuery.deleteQueryEXT(query);
  17095. return;
  17096. }
  17097. this.deleteQuery(query);
  17098. };
  17099. Engine.prototype._getTimeQueryResult = function (query) {
  17100. var timerQuery = this._caps.timerQuery;
  17101. if (timerQuery.getQueryObjectEXT) {
  17102. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17103. }
  17104. return this.getQueryResult(query);
  17105. };
  17106. Engine.prototype._getTimeQueryAvailability = function (query) {
  17107. var timerQuery = this._caps.timerQuery;
  17108. if (timerQuery.getQueryObjectEXT) {
  17109. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17110. }
  17111. return this.isQueryResultAvailable(query);
  17112. };
  17113. /**
  17114. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17115. * Please note that only one query can be issued at a time
  17116. * @returns a time token used to track the time span
  17117. */
  17118. Engine.prototype.startTimeQuery = function () {
  17119. var timerQuery = this._caps.timerQuery;
  17120. if (!timerQuery) {
  17121. return null;
  17122. }
  17123. var token = new BABYLON._TimeToken();
  17124. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17125. if (this._caps.canUseTimestampForTimerQuery) {
  17126. token._startTimeQuery = this._createTimeQuery();
  17127. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17128. }
  17129. else {
  17130. if (this._currentNonTimestampToken) {
  17131. return this._currentNonTimestampToken;
  17132. }
  17133. token._timeElapsedQuery = this._createTimeQuery();
  17134. if (timerQuery.beginQueryEXT) {
  17135. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17136. }
  17137. else {
  17138. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17139. }
  17140. this._currentNonTimestampToken = token;
  17141. }
  17142. return token;
  17143. };
  17144. /**
  17145. * Ends a time query
  17146. * @param token defines the token used to measure the time span
  17147. * @returns the time spent (in ns)
  17148. */
  17149. Engine.prototype.endTimeQuery = function (token) {
  17150. var timerQuery = this._caps.timerQuery;
  17151. if (!timerQuery || !token) {
  17152. return -1;
  17153. }
  17154. if (this._caps.canUseTimestampForTimerQuery) {
  17155. if (!token._startTimeQuery) {
  17156. return -1;
  17157. }
  17158. if (!token._endTimeQuery) {
  17159. token._endTimeQuery = this._createTimeQuery();
  17160. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17161. }
  17162. }
  17163. else if (!token._timeElapsedQueryEnded) {
  17164. if (!token._timeElapsedQuery) {
  17165. return -1;
  17166. }
  17167. if (timerQuery.endQueryEXT) {
  17168. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17169. }
  17170. else {
  17171. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17172. }
  17173. token._timeElapsedQueryEnded = true;
  17174. }
  17175. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17176. var available = false;
  17177. if (token._endTimeQuery) {
  17178. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17179. }
  17180. else if (token._timeElapsedQuery) {
  17181. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17182. }
  17183. if (available && !disjoint) {
  17184. var result = 0;
  17185. if (this._caps.canUseTimestampForTimerQuery) {
  17186. if (!token._startTimeQuery || !token._endTimeQuery) {
  17187. return -1;
  17188. }
  17189. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17190. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17191. result = timeEnd - timeStart;
  17192. this._deleteTimeQuery(token._startTimeQuery);
  17193. this._deleteTimeQuery(token._endTimeQuery);
  17194. token._startTimeQuery = null;
  17195. token._endTimeQuery = null;
  17196. }
  17197. else {
  17198. if (!token._timeElapsedQuery) {
  17199. return -1;
  17200. }
  17201. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17202. this._deleteTimeQuery(token._timeElapsedQuery);
  17203. token._timeElapsedQuery = null;
  17204. token._timeElapsedQueryEnded = false;
  17205. this._currentNonTimestampToken = null;
  17206. }
  17207. return result;
  17208. }
  17209. return -1;
  17210. };
  17211. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17212. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17213. };
  17214. // Transform feedback
  17215. /**
  17216. * Creates a webGL transform feedback object
  17217. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17218. * @returns the webGL transform feedback object
  17219. */
  17220. Engine.prototype.createTransformFeedback = function () {
  17221. return this._gl.createTransformFeedback();
  17222. };
  17223. /**
  17224. * Delete a webGL transform feedback object
  17225. * @param value defines the webGL transform feedback object to delete
  17226. */
  17227. Engine.prototype.deleteTransformFeedback = function (value) {
  17228. this._gl.deleteTransformFeedback(value);
  17229. };
  17230. /**
  17231. * Bind a webGL transform feedback object to the webgl context
  17232. * @param value defines the webGL transform feedback object to bind
  17233. */
  17234. Engine.prototype.bindTransformFeedback = function (value) {
  17235. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17236. };
  17237. /**
  17238. * Begins a transform feedback operation
  17239. * @param usePoints defines if points or triangles must be used
  17240. */
  17241. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17242. if (usePoints === void 0) { usePoints = true; }
  17243. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17244. };
  17245. /**
  17246. * Ends a transform feedback operation
  17247. */
  17248. Engine.prototype.endTransformFeedback = function () {
  17249. this._gl.endTransformFeedback();
  17250. };
  17251. /**
  17252. * Specify the varyings to use with transform feedback
  17253. * @param program defines the associated webGL program
  17254. * @param value defines the list of strings representing the varying names
  17255. */
  17256. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17257. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17258. };
  17259. /**
  17260. * Bind a webGL buffer for a transform feedback operation
  17261. * @param value defines the webGL buffer to bind
  17262. */
  17263. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17264. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17265. };
  17266. /** @hidden */
  17267. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17268. var _this = this;
  17269. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17270. this._activeRequests.push(request);
  17271. request.onCompleteObservable.add(function (request) {
  17272. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17273. });
  17274. return request;
  17275. };
  17276. /** @hidden */
  17277. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17278. var _this = this;
  17279. return new Promise(function (resolve, reject) {
  17280. _this._loadFile(url, function (data) {
  17281. resolve(data);
  17282. }, undefined, database, useArrayBuffer, function (request, exception) {
  17283. reject(exception);
  17284. });
  17285. });
  17286. };
  17287. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17288. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17289. var onload = function (data) {
  17290. loadedFiles[index] = data;
  17291. loadedFiles._internalCount++;
  17292. if (loadedFiles._internalCount === 6) {
  17293. onfinish(loadedFiles);
  17294. }
  17295. };
  17296. var onerror = function (request, exception) {
  17297. if (onErrorCallBack && request) {
  17298. onErrorCallBack(request.status + " " + request.statusText, exception);
  17299. }
  17300. };
  17301. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17302. };
  17303. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17304. if (onError === void 0) { onError = null; }
  17305. var loadedFiles = [];
  17306. loadedFiles._internalCount = 0;
  17307. for (var index = 0; index < 6; index++) {
  17308. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17309. }
  17310. };
  17311. // Statics
  17312. /**
  17313. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17314. * @returns true if the engine can be created
  17315. * @ignorenaming
  17316. */
  17317. Engine.isSupported = function () {
  17318. try {
  17319. var tempcanvas = document.createElement("canvas");
  17320. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17321. return gl != null && !!window.WebGLRenderingContext;
  17322. }
  17323. catch (e) {
  17324. return false;
  17325. }
  17326. };
  17327. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17328. Engine.ExceptionList = [
  17329. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17330. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17331. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17332. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17333. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17334. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17335. ];
  17336. /** Gets the list of created engines */
  17337. Engine.Instances = new Array();
  17338. // Const statics
  17339. Engine._ALPHA_DISABLE = 0;
  17340. Engine._ALPHA_ADD = 1;
  17341. Engine._ALPHA_COMBINE = 2;
  17342. Engine._ALPHA_SUBTRACT = 3;
  17343. Engine._ALPHA_MULTIPLY = 4;
  17344. Engine._ALPHA_MAXIMIZED = 5;
  17345. Engine._ALPHA_ONEONE = 6;
  17346. Engine._ALPHA_PREMULTIPLIED = 7;
  17347. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17348. Engine._ALPHA_INTERPOLATE = 9;
  17349. Engine._ALPHA_SCREENMODE = 10;
  17350. Engine._DELAYLOADSTATE_NONE = 0;
  17351. Engine._DELAYLOADSTATE_LOADED = 1;
  17352. Engine._DELAYLOADSTATE_LOADING = 2;
  17353. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17354. Engine._TEXTUREFORMAT_ALPHA = 0;
  17355. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17356. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17357. Engine._TEXTUREFORMAT_RGB = 4;
  17358. Engine._TEXTUREFORMAT_RGBA = 5;
  17359. Engine._TEXTUREFORMAT_R32F = 6;
  17360. Engine._TEXTUREFORMAT_RG32F = 7;
  17361. Engine._TEXTUREFORMAT_RGB32F = 8;
  17362. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17363. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17364. Engine._TEXTURETYPE_FLOAT = 1;
  17365. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17366. // Depht or Stencil test Constants.
  17367. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17368. 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.
  17369. 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.
  17370. 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.
  17371. 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.
  17372. 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.
  17373. 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.
  17374. 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.
  17375. // Stencil Actions Constants.
  17376. Engine._KEEP = 0x1E00;
  17377. Engine._REPLACE = 0x1E01;
  17378. Engine._INCR = 0x1E02;
  17379. Engine._DECR = 0x1E03;
  17380. Engine._INVERT = 0x150A;
  17381. Engine._INCR_WRAP = 0x8507;
  17382. Engine._DECR_WRAP = 0x8508;
  17383. // Texture rescaling mode
  17384. Engine._SCALEMODE_FLOOR = 1;
  17385. Engine._SCALEMODE_NEAREST = 2;
  17386. Engine._SCALEMODE_CEILING = 3;
  17387. // Updatable statics so stick with vars here
  17388. /**
  17389. * Gets or sets the epsilon value used by collision engine
  17390. */
  17391. Engine.CollisionsEpsilon = 0.001;
  17392. /**
  17393. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17394. */
  17395. Engine.CodeRepository = "src/";
  17396. /**
  17397. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17398. */
  17399. Engine.ShadersRepository = "src/Shaders/";
  17400. return Engine;
  17401. }());
  17402. BABYLON.Engine = Engine;
  17403. })(BABYLON || (BABYLON = {}));
  17404. //# sourceMappingURL=babylon.engine.js.map
  17405. var BABYLON;
  17406. (function (BABYLON) {
  17407. /**
  17408. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17409. */
  17410. var Node = /** @class */ (function () {
  17411. /**
  17412. * Creates a new Node
  17413. * @param {string} name - the name and id to be given to this node
  17414. * @param {BABYLON.Scene} the scene this node will be added to
  17415. */
  17416. function Node(name, scene) {
  17417. if (scene === void 0) { scene = null; }
  17418. /**
  17419. * Gets or sets a string used to store user defined state for the node
  17420. */
  17421. this.state = "";
  17422. /**
  17423. * Gets or sets an object used to store user defined information for the node
  17424. */
  17425. this.metadata = null;
  17426. /**
  17427. * Gets or sets a boolean used to define if the node must be serialized
  17428. */
  17429. this.doNotSerialize = false;
  17430. /** @hidden */
  17431. this._isDisposed = false;
  17432. /**
  17433. * Gets a list of Animations associated with the node
  17434. */
  17435. this.animations = new Array();
  17436. this._ranges = {};
  17437. this._isEnabled = true;
  17438. this._isReady = true;
  17439. /** @hidden */
  17440. this._currentRenderId = -1;
  17441. this._parentRenderId = -1;
  17442. this._childRenderId = -1;
  17443. this._animationPropertiesOverride = null;
  17444. /**
  17445. * An event triggered when the mesh is disposed
  17446. */
  17447. this.onDisposeObservable = new BABYLON.Observable();
  17448. // Behaviors
  17449. this._behaviors = new Array();
  17450. this.name = name;
  17451. this.id = name;
  17452. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17453. this.uniqueId = this._scene.getUniqueId();
  17454. this._initCache();
  17455. }
  17456. /**
  17457. * Gets a boolean indicating if the node has been disposed
  17458. * @returns true if the node was disposed
  17459. */
  17460. Node.prototype.isDisposed = function () {
  17461. return this._isDisposed;
  17462. };
  17463. Object.defineProperty(Node.prototype, "parent", {
  17464. get: function () {
  17465. return this._parentNode;
  17466. },
  17467. /**
  17468. * Gets or sets the parent of the node
  17469. */
  17470. set: function (parent) {
  17471. if (this._parentNode === parent) {
  17472. return;
  17473. }
  17474. // Remove self from list of children of parent
  17475. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17476. var index = this._parentNode._children.indexOf(this);
  17477. if (index !== -1) {
  17478. this._parentNode._children.splice(index, 1);
  17479. }
  17480. }
  17481. // Store new parent
  17482. this._parentNode = parent;
  17483. // Add as child to new parent
  17484. if (this._parentNode) {
  17485. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17486. this._parentNode._children = new Array();
  17487. }
  17488. this._parentNode._children.push(this);
  17489. }
  17490. },
  17491. enumerable: true,
  17492. configurable: true
  17493. });
  17494. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17495. /**
  17496. * Gets or sets the animation properties override
  17497. */
  17498. get: function () {
  17499. if (!this._animationPropertiesOverride) {
  17500. return this._scene.animationPropertiesOverride;
  17501. }
  17502. return this._animationPropertiesOverride;
  17503. },
  17504. set: function (value) {
  17505. this._animationPropertiesOverride = value;
  17506. },
  17507. enumerable: true,
  17508. configurable: true
  17509. });
  17510. /**
  17511. * Gets a string idenfifying the name of the class
  17512. * @returns "Node" string
  17513. */
  17514. Node.prototype.getClassName = function () {
  17515. return "Node";
  17516. };
  17517. Object.defineProperty(Node.prototype, "onDispose", {
  17518. /**
  17519. * Sets a callback that will be raised when the node will be disposed
  17520. */
  17521. set: function (callback) {
  17522. if (this._onDisposeObserver) {
  17523. this.onDisposeObservable.remove(this._onDisposeObserver);
  17524. }
  17525. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17526. },
  17527. enumerable: true,
  17528. configurable: true
  17529. });
  17530. /**
  17531. * Gets the scene of the node
  17532. * @returns a {BABYLON.Scene}
  17533. */
  17534. Node.prototype.getScene = function () {
  17535. return this._scene;
  17536. };
  17537. /**
  17538. * Gets the engine of the node
  17539. * @returns a {BABYLON.Engine}
  17540. */
  17541. Node.prototype.getEngine = function () {
  17542. return this._scene.getEngine();
  17543. };
  17544. /**
  17545. * Attach a behavior to the node
  17546. * @see http://doc.babylonjs.com/features/behaviour
  17547. * @param behavior defines the behavior to attach
  17548. * @returns the current Node
  17549. */
  17550. Node.prototype.addBehavior = function (behavior) {
  17551. var _this = this;
  17552. var index = this._behaviors.indexOf(behavior);
  17553. if (index !== -1) {
  17554. return this;
  17555. }
  17556. behavior.init();
  17557. if (this._scene.isLoading) {
  17558. // We defer the attach when the scene will be loaded
  17559. var observer = this._scene.onDataLoadedObservable.add(function () {
  17560. behavior.attach(_this);
  17561. setTimeout(function () {
  17562. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17563. _this._scene.onDataLoadedObservable.remove(observer);
  17564. }, 0);
  17565. });
  17566. }
  17567. else {
  17568. behavior.attach(this);
  17569. }
  17570. this._behaviors.push(behavior);
  17571. return this;
  17572. };
  17573. /**
  17574. * Remove an attached behavior
  17575. * @see http://doc.babylonjs.com/features/behaviour
  17576. * @param behavior defines the behavior to attach
  17577. * @returns the current Node
  17578. */
  17579. Node.prototype.removeBehavior = function (behavior) {
  17580. var index = this._behaviors.indexOf(behavior);
  17581. if (index === -1) {
  17582. return this;
  17583. }
  17584. this._behaviors[index].detach();
  17585. this._behaviors.splice(index, 1);
  17586. return this;
  17587. };
  17588. Object.defineProperty(Node.prototype, "behaviors", {
  17589. /**
  17590. * Gets the list of attached behaviors
  17591. * @see http://doc.babylonjs.com/features/behaviour
  17592. */
  17593. get: function () {
  17594. return this._behaviors;
  17595. },
  17596. enumerable: true,
  17597. configurable: true
  17598. });
  17599. /**
  17600. * Gets an attached behavior by name
  17601. * @param name defines the name of the behavior to look for
  17602. * @see http://doc.babylonjs.com/features/behaviour
  17603. * @returns null if behavior was not found else the requested behavior
  17604. */
  17605. Node.prototype.getBehaviorByName = function (name) {
  17606. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17607. var behavior = _a[_i];
  17608. if (behavior.name === name) {
  17609. return behavior;
  17610. }
  17611. }
  17612. return null;
  17613. };
  17614. /**
  17615. * Returns the world matrix of the node
  17616. * @returns a matrix containing the node's world matrix
  17617. */
  17618. Node.prototype.getWorldMatrix = function () {
  17619. return BABYLON.Matrix.Identity();
  17620. };
  17621. /** @hidden */
  17622. Node.prototype._getWorldMatrixDeterminant = function () {
  17623. return 1;
  17624. };
  17625. // override it in derived class if you add new variables to the cache
  17626. // and call the parent class method
  17627. /** @hidden */
  17628. Node.prototype._initCache = function () {
  17629. this._cache = {};
  17630. this._cache.parent = undefined;
  17631. };
  17632. /** @hidden */
  17633. Node.prototype.updateCache = function (force) {
  17634. if (!force && this.isSynchronized())
  17635. return;
  17636. this._cache.parent = this.parent;
  17637. this._updateCache();
  17638. };
  17639. // override it in derived class if you add new variables to the cache
  17640. // and call the parent class method if !ignoreParentClass
  17641. /** @hidden */
  17642. Node.prototype._updateCache = function (ignoreParentClass) {
  17643. };
  17644. // override it in derived class if you add new variables to the cache
  17645. /** @hidden */
  17646. Node.prototype._isSynchronized = function () {
  17647. return true;
  17648. };
  17649. /** @hidden */
  17650. Node.prototype._markSyncedWithParent = function () {
  17651. if (this.parent) {
  17652. this._parentRenderId = this.parent._childRenderId;
  17653. }
  17654. };
  17655. /** @hidden */
  17656. Node.prototype.isSynchronizedWithParent = function () {
  17657. if (!this.parent) {
  17658. return true;
  17659. }
  17660. if (this._parentRenderId !== this.parent._childRenderId) {
  17661. return false;
  17662. }
  17663. return this.parent.isSynchronized();
  17664. };
  17665. /** @hidden */
  17666. Node.prototype.isSynchronized = function (updateCache) {
  17667. var check = this.hasNewParent();
  17668. check = check || !this.isSynchronizedWithParent();
  17669. check = check || !this._isSynchronized();
  17670. if (updateCache)
  17671. this.updateCache(true);
  17672. return !check;
  17673. };
  17674. /** @hidden */
  17675. Node.prototype.hasNewParent = function (update) {
  17676. if (this._cache.parent === this.parent)
  17677. return false;
  17678. if (update)
  17679. this._cache.parent = this.parent;
  17680. return true;
  17681. };
  17682. /**
  17683. * Is this node ready to be used/rendered
  17684. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17685. * @return true if the node is ready
  17686. */
  17687. Node.prototype.isReady = function (completeCheck) {
  17688. if (completeCheck === void 0) { completeCheck = false; }
  17689. return this._isReady;
  17690. };
  17691. /**
  17692. * Is this node enabled?
  17693. * 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
  17694. * @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
  17695. * @return whether this node (and its parent) is enabled
  17696. */
  17697. Node.prototype.isEnabled = function (checkAncestors) {
  17698. if (checkAncestors === void 0) { checkAncestors = true; }
  17699. if (checkAncestors === false) {
  17700. return this._isEnabled;
  17701. }
  17702. if (this._isEnabled === false) {
  17703. return false;
  17704. }
  17705. if (this.parent !== undefined && this.parent !== null) {
  17706. return this.parent.isEnabled(checkAncestors);
  17707. }
  17708. return true;
  17709. };
  17710. /**
  17711. * Set the enabled state of this node
  17712. * @param value defines the new enabled state
  17713. */
  17714. Node.prototype.setEnabled = function (value) {
  17715. this._isEnabled = value;
  17716. };
  17717. /**
  17718. * Is this node a descendant of the given node?
  17719. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17720. * @param ancestor defines the parent node to inspect
  17721. * @returns a boolean indicating if this node is a descendant of the given node
  17722. */
  17723. Node.prototype.isDescendantOf = function (ancestor) {
  17724. if (this.parent) {
  17725. if (this.parent === ancestor) {
  17726. return true;
  17727. }
  17728. return this.parent.isDescendantOf(ancestor);
  17729. }
  17730. return false;
  17731. };
  17732. /** @hidden */
  17733. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17734. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17735. if (!this._children) {
  17736. return;
  17737. }
  17738. for (var index = 0; index < this._children.length; index++) {
  17739. var item = this._children[index];
  17740. if (!predicate || predicate(item)) {
  17741. results.push(item);
  17742. }
  17743. if (!directDescendantsOnly) {
  17744. item._getDescendants(results, false, predicate);
  17745. }
  17746. }
  17747. };
  17748. /**
  17749. * Will return all nodes that have this node as ascendant
  17750. * @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
  17751. * @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
  17752. * @return all children nodes of all types
  17753. */
  17754. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17755. var results = new Array();
  17756. this._getDescendants(results, directDescendantsOnly, predicate);
  17757. return results;
  17758. };
  17759. /**
  17760. * Get all child-meshes of this node
  17761. * @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
  17762. * @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
  17763. * @returns an array of {BABYLON.AbstractMesh}
  17764. */
  17765. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17766. var results = [];
  17767. this._getDescendants(results, directDescendantsOnly, function (node) {
  17768. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17769. });
  17770. return results;
  17771. };
  17772. /**
  17773. * Get all child-transformNodes of this node
  17774. * @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
  17775. * @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
  17776. * @returns an array of {BABYLON.TransformNode}
  17777. */
  17778. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17779. var results = [];
  17780. this._getDescendants(results, directDescendantsOnly, function (node) {
  17781. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17782. });
  17783. return results;
  17784. };
  17785. /**
  17786. * Get all direct children of this node
  17787. * @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
  17788. * @returns an array of {BABYLON.Node}
  17789. */
  17790. Node.prototype.getChildren = function (predicate) {
  17791. return this.getDescendants(true, predicate);
  17792. };
  17793. /** @hidden */
  17794. Node.prototype._setReady = function (state) {
  17795. if (state === this._isReady) {
  17796. return;
  17797. }
  17798. if (!state) {
  17799. this._isReady = false;
  17800. return;
  17801. }
  17802. if (this.onReady) {
  17803. this.onReady(this);
  17804. }
  17805. this._isReady = true;
  17806. };
  17807. /**
  17808. * Get an animation by name
  17809. * @param name defines the name of the animation to look for
  17810. * @returns null if not found else the requested animation
  17811. */
  17812. Node.prototype.getAnimationByName = function (name) {
  17813. for (var i = 0; i < this.animations.length; i++) {
  17814. var animation = this.animations[i];
  17815. if (animation.name === name) {
  17816. return animation;
  17817. }
  17818. }
  17819. return null;
  17820. };
  17821. /**
  17822. * Creates an animation range for this node
  17823. * @param name defines the name of the range
  17824. * @param from defines the starting key
  17825. * @param to defines the end key
  17826. */
  17827. Node.prototype.createAnimationRange = function (name, from, to) {
  17828. // check name not already in use
  17829. if (!this._ranges[name]) {
  17830. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17831. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17832. if (this.animations[i]) {
  17833. this.animations[i].createRange(name, from, to);
  17834. }
  17835. }
  17836. }
  17837. };
  17838. /**
  17839. * Delete a specific animation range
  17840. * @param name defines the name of the range to delete
  17841. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17842. */
  17843. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17844. if (deleteFrames === void 0) { deleteFrames = true; }
  17845. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17846. if (this.animations[i]) {
  17847. this.animations[i].deleteRange(name, deleteFrames);
  17848. }
  17849. }
  17850. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17851. };
  17852. /**
  17853. * Get an animation range by name
  17854. * @param name defines the name of the animation range to look for
  17855. * @returns null if not found else the requested animation range
  17856. */
  17857. Node.prototype.getAnimationRange = function (name) {
  17858. return this._ranges[name];
  17859. };
  17860. /**
  17861. * Will start the animation sequence
  17862. * @param name defines the range frames for animation sequence
  17863. * @param loop defines if the animation should loop (false by default)
  17864. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17865. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17866. * @returns the object created for this animation. If range does not exist, it will return null
  17867. */
  17868. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17869. var range = this.getAnimationRange(name);
  17870. if (!range) {
  17871. return null;
  17872. }
  17873. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17874. };
  17875. /**
  17876. * Serialize animation ranges into a JSON compatible object
  17877. * @returns serialization object
  17878. */
  17879. Node.prototype.serializeAnimationRanges = function () {
  17880. var serializationRanges = [];
  17881. for (var name in this._ranges) {
  17882. var localRange = this._ranges[name];
  17883. if (!localRange) {
  17884. continue;
  17885. }
  17886. var range = {};
  17887. range.name = name;
  17888. range.from = localRange.from;
  17889. range.to = localRange.to;
  17890. serializationRanges.push(range);
  17891. }
  17892. return serializationRanges;
  17893. };
  17894. /**
  17895. * Computes the world matrix of the node
  17896. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17897. * @returns the world matrix
  17898. */
  17899. Node.prototype.computeWorldMatrix = function (force) {
  17900. return BABYLON.Matrix.Identity();
  17901. };
  17902. /**
  17903. * Releases resources associated with this node.
  17904. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17905. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17906. */
  17907. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17908. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17909. if (!doNotRecurse) {
  17910. var nodes = this.getDescendants(true);
  17911. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17912. var node = nodes_1[_i];
  17913. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17914. }
  17915. }
  17916. else {
  17917. var transformNodes = this.getChildTransformNodes(true);
  17918. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17919. var transformNode = transformNodes_1[_a];
  17920. transformNode.parent = null;
  17921. transformNode.computeWorldMatrix(true);
  17922. }
  17923. }
  17924. this.parent = null;
  17925. // Callback
  17926. this.onDisposeObservable.notifyObservers(this);
  17927. this.onDisposeObservable.clear();
  17928. // Behaviors
  17929. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17930. var behavior = _c[_b];
  17931. behavior.detach();
  17932. }
  17933. this._behaviors = [];
  17934. this._isDisposed = true;
  17935. };
  17936. /**
  17937. * Parse animation range data from a serialization object and store them into a given node
  17938. * @param node defines where to store the animation ranges
  17939. * @param parsedNode defines the serialization object to read data from
  17940. * @param scene defines the hosting scene
  17941. */
  17942. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17943. if (parsedNode.ranges) {
  17944. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17945. var data = parsedNode.ranges[index];
  17946. node.createAnimationRange(data.name, data.from, data.to);
  17947. }
  17948. }
  17949. };
  17950. __decorate([
  17951. BABYLON.serialize()
  17952. ], Node.prototype, "name", void 0);
  17953. __decorate([
  17954. BABYLON.serialize()
  17955. ], Node.prototype, "id", void 0);
  17956. __decorate([
  17957. BABYLON.serialize()
  17958. ], Node.prototype, "uniqueId", void 0);
  17959. __decorate([
  17960. BABYLON.serialize()
  17961. ], Node.prototype, "state", void 0);
  17962. __decorate([
  17963. BABYLON.serialize()
  17964. ], Node.prototype, "metadata", void 0);
  17965. return Node;
  17966. }());
  17967. BABYLON.Node = Node;
  17968. })(BABYLON || (BABYLON = {}));
  17969. //# sourceMappingURL=babylon.node.js.map
  17970. var BABYLON;
  17971. (function (BABYLON) {
  17972. var BoundingSphere = /** @class */ (function () {
  17973. /**
  17974. * Creates a new bounding sphere
  17975. * @param min defines the minimum vector (in local space)
  17976. * @param max defines the maximum vector (in local space)
  17977. */
  17978. function BoundingSphere(min, max) {
  17979. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17980. this.reConstruct(min, max);
  17981. }
  17982. /**
  17983. * Recreates the entire bounding sphere from scratch
  17984. * @param min defines the new minimum vector (in local space)
  17985. * @param max defines the new maximum vector (in local space)
  17986. */
  17987. BoundingSphere.prototype.reConstruct = function (min, max) {
  17988. this.minimum = min.clone();
  17989. this.maximum = max.clone();
  17990. var distance = BABYLON.Vector3.Distance(min, max);
  17991. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17992. this.radius = distance * 0.5;
  17993. this.centerWorld = BABYLON.Vector3.Zero();
  17994. this._update(BABYLON.Matrix.Identity());
  17995. };
  17996. // Methods
  17997. BoundingSphere.prototype._update = function (world) {
  17998. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17999. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18000. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18001. };
  18002. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18003. for (var i = 0; i < 6; i++) {
  18004. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18005. return false;
  18006. }
  18007. return true;
  18008. };
  18009. BoundingSphere.prototype.intersectsPoint = function (point) {
  18010. var x = this.centerWorld.x - point.x;
  18011. var y = this.centerWorld.y - point.y;
  18012. var z = this.centerWorld.z - point.z;
  18013. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18014. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18015. return false;
  18016. return true;
  18017. };
  18018. // Statics
  18019. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18020. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18021. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18022. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18023. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18024. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18025. return false;
  18026. return true;
  18027. };
  18028. return BoundingSphere;
  18029. }());
  18030. BABYLON.BoundingSphere = BoundingSphere;
  18031. })(BABYLON || (BABYLON = {}));
  18032. //# sourceMappingURL=babylon.boundingSphere.js.map
  18033. var BABYLON;
  18034. (function (BABYLON) {
  18035. var BoundingBox = /** @class */ (function () {
  18036. /**
  18037. * Creates a new bounding box
  18038. * @param min defines the minimum vector (in local space)
  18039. * @param max defines the maximum vector (in local space)
  18040. */
  18041. function BoundingBox(min, max) {
  18042. this.vectorsWorld = new Array();
  18043. this.reConstruct(min, max);
  18044. }
  18045. // Methods
  18046. /**
  18047. * Recreates the entire bounding box from scratch
  18048. * @param min defines the new minimum vector (in local space)
  18049. * @param max defines the new maximum vector (in local space)
  18050. */
  18051. BoundingBox.prototype.reConstruct = function (min, max) {
  18052. this.minimum = min.clone();
  18053. this.maximum = max.clone();
  18054. // Bounding vectors
  18055. this.vectors = new Array();
  18056. this.vectors.push(this.minimum.clone());
  18057. this.vectors.push(this.maximum.clone());
  18058. this.vectors.push(this.minimum.clone());
  18059. this.vectors[2].x = this.maximum.x;
  18060. this.vectors.push(this.minimum.clone());
  18061. this.vectors[3].y = this.maximum.y;
  18062. this.vectors.push(this.minimum.clone());
  18063. this.vectors[4].z = this.maximum.z;
  18064. this.vectors.push(this.maximum.clone());
  18065. this.vectors[5].z = this.minimum.z;
  18066. this.vectors.push(this.maximum.clone());
  18067. this.vectors[6].x = this.minimum.x;
  18068. this.vectors.push(this.maximum.clone());
  18069. this.vectors[7].y = this.minimum.y;
  18070. // OBB
  18071. this.center = this.maximum.add(this.minimum).scale(0.5);
  18072. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18073. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18074. // World
  18075. for (var index = 0; index < this.vectors.length; index++) {
  18076. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18077. }
  18078. this.minimumWorld = BABYLON.Vector3.Zero();
  18079. this.maximumWorld = BABYLON.Vector3.Zero();
  18080. this.centerWorld = BABYLON.Vector3.Zero();
  18081. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18082. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18083. };
  18084. BoundingBox.prototype.getWorldMatrix = function () {
  18085. return this._worldMatrix;
  18086. };
  18087. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18088. this._worldMatrix.copyFrom(matrix);
  18089. return this;
  18090. };
  18091. BoundingBox.prototype._update = function (world) {
  18092. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18093. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18094. for (var index = 0; index < this.vectors.length; index++) {
  18095. var v = this.vectorsWorld[index];
  18096. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18097. if (v.x < this.minimumWorld.x)
  18098. this.minimumWorld.x = v.x;
  18099. if (v.y < this.minimumWorld.y)
  18100. this.minimumWorld.y = v.y;
  18101. if (v.z < this.minimumWorld.z)
  18102. this.minimumWorld.z = v.z;
  18103. if (v.x > this.maximumWorld.x)
  18104. this.maximumWorld.x = v.x;
  18105. if (v.y > this.maximumWorld.y)
  18106. this.maximumWorld.y = v.y;
  18107. if (v.z > this.maximumWorld.z)
  18108. this.maximumWorld.z = v.z;
  18109. }
  18110. // Extend
  18111. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18112. this.extendSizeWorld.scaleInPlace(0.5);
  18113. // OBB
  18114. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18115. this.centerWorld.scaleInPlace(0.5);
  18116. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18117. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18118. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18119. this._worldMatrix = world;
  18120. };
  18121. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18122. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18123. };
  18124. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18125. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18126. };
  18127. BoundingBox.prototype.intersectsPoint = function (point) {
  18128. var delta = -BABYLON.Epsilon;
  18129. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18130. return false;
  18131. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18132. return false;
  18133. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18134. return false;
  18135. return true;
  18136. };
  18137. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18138. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18139. };
  18140. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18141. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18142. return false;
  18143. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18144. return false;
  18145. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18146. return false;
  18147. return true;
  18148. };
  18149. // Statics
  18150. BoundingBox.Intersects = function (box0, box1) {
  18151. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18152. return false;
  18153. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18154. return false;
  18155. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18156. return false;
  18157. return true;
  18158. };
  18159. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18160. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18161. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18162. return (num <= (sphereRadius * sphereRadius));
  18163. };
  18164. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18165. for (var p = 0; p < 6; p++) {
  18166. for (var i = 0; i < 8; i++) {
  18167. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18168. return false;
  18169. }
  18170. }
  18171. }
  18172. return true;
  18173. };
  18174. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18175. for (var p = 0; p < 6; p++) {
  18176. var inCount = 8;
  18177. for (var i = 0; i < 8; i++) {
  18178. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18179. --inCount;
  18180. }
  18181. else {
  18182. break;
  18183. }
  18184. }
  18185. if (inCount === 0)
  18186. return false;
  18187. }
  18188. return true;
  18189. };
  18190. return BoundingBox;
  18191. }());
  18192. BABYLON.BoundingBox = BoundingBox;
  18193. })(BABYLON || (BABYLON = {}));
  18194. //# sourceMappingURL=babylon.boundingBox.js.map
  18195. var BABYLON;
  18196. (function (BABYLON) {
  18197. var computeBoxExtents = function (axis, box) {
  18198. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18199. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18200. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18201. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18202. var r = r0 + r1 + r2;
  18203. return {
  18204. min: p - r,
  18205. max: p + r
  18206. };
  18207. };
  18208. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18209. var axisOverlap = function (axis, box0, box1) {
  18210. var result0 = computeBoxExtents(axis, box0);
  18211. var result1 = computeBoxExtents(axis, box1);
  18212. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18213. };
  18214. var BoundingInfo = /** @class */ (function () {
  18215. function BoundingInfo(minimum, maximum) {
  18216. this.minimum = minimum;
  18217. this.maximum = maximum;
  18218. this._isLocked = false;
  18219. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18220. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18221. }
  18222. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18223. get: function () {
  18224. return this._isLocked;
  18225. },
  18226. set: function (value) {
  18227. this._isLocked = value;
  18228. },
  18229. enumerable: true,
  18230. configurable: true
  18231. });
  18232. // Methods
  18233. BoundingInfo.prototype.update = function (world) {
  18234. if (this._isLocked) {
  18235. return;
  18236. }
  18237. this.boundingBox._update(world);
  18238. this.boundingSphere._update(world);
  18239. };
  18240. /**
  18241. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18242. * @param center New center of the bounding info
  18243. * @param extend New extend of the bounding info
  18244. */
  18245. BoundingInfo.prototype.centerOn = function (center, extend) {
  18246. this.minimum = center.subtract(extend);
  18247. this.maximum = center.add(extend);
  18248. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18249. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18250. return this;
  18251. };
  18252. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18253. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18254. return false;
  18255. return this.boundingBox.isInFrustum(frustumPlanes);
  18256. };
  18257. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18258. /**
  18259. * Gets the world distance between the min and max points of the bounding box
  18260. */
  18261. get: function () {
  18262. var boundingBox = this.boundingBox;
  18263. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18264. return size.length();
  18265. },
  18266. enumerable: true,
  18267. configurable: true
  18268. });
  18269. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18270. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18271. };
  18272. BoundingInfo.prototype._checkCollision = function (collider) {
  18273. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18274. };
  18275. BoundingInfo.prototype.intersectsPoint = function (point) {
  18276. if (!this.boundingSphere.centerWorld) {
  18277. return false;
  18278. }
  18279. if (!this.boundingSphere.intersectsPoint(point)) {
  18280. return false;
  18281. }
  18282. if (!this.boundingBox.intersectsPoint(point)) {
  18283. return false;
  18284. }
  18285. return true;
  18286. };
  18287. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18288. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18289. return false;
  18290. }
  18291. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18292. return false;
  18293. }
  18294. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18295. return false;
  18296. }
  18297. if (!precise) {
  18298. return true;
  18299. }
  18300. var box0 = this.boundingBox;
  18301. var box1 = boundingInfo.boundingBox;
  18302. if (!axisOverlap(box0.directions[0], box0, box1))
  18303. return false;
  18304. if (!axisOverlap(box0.directions[1], box0, box1))
  18305. return false;
  18306. if (!axisOverlap(box0.directions[2], box0, box1))
  18307. return false;
  18308. if (!axisOverlap(box1.directions[0], box0, box1))
  18309. return false;
  18310. if (!axisOverlap(box1.directions[1], box0, box1))
  18311. return false;
  18312. if (!axisOverlap(box1.directions[2], box0, box1))
  18313. return false;
  18314. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18315. return false;
  18316. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18317. return false;
  18318. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18319. return false;
  18320. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18321. return false;
  18322. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18323. return false;
  18324. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18325. return false;
  18326. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18327. return false;
  18328. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18329. return false;
  18330. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18331. return false;
  18332. return true;
  18333. };
  18334. return BoundingInfo;
  18335. }());
  18336. BABYLON.BoundingInfo = BoundingInfo;
  18337. })(BABYLON || (BABYLON = {}));
  18338. //# sourceMappingURL=babylon.boundingInfo.js.map
  18339. var BABYLON;
  18340. (function (BABYLON) {
  18341. var TransformNode = /** @class */ (function (_super) {
  18342. __extends(TransformNode, _super);
  18343. function TransformNode(name, scene, isPure) {
  18344. if (scene === void 0) { scene = null; }
  18345. if (isPure === void 0) { isPure = true; }
  18346. var _this = _super.call(this, name, scene) || this;
  18347. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18348. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18349. _this._up = new BABYLON.Vector3(0, 1, 0);
  18350. _this._right = new BABYLON.Vector3(1, 0, 0);
  18351. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18352. // Properties
  18353. _this._rotation = BABYLON.Vector3.Zero();
  18354. _this._scaling = BABYLON.Vector3.One();
  18355. _this._isDirty = false;
  18356. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18357. _this.scalingDeterminant = 1;
  18358. _this.infiniteDistance = false;
  18359. _this.position = BABYLON.Vector3.Zero();
  18360. _this._localWorld = BABYLON.Matrix.Zero();
  18361. _this._worldMatrix = BABYLON.Matrix.Zero();
  18362. _this._worldMatrixDeterminant = 0;
  18363. _this._absolutePosition = BABYLON.Vector3.Zero();
  18364. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18365. _this._postMultiplyPivotMatrix = false;
  18366. _this._isWorldMatrixFrozen = false;
  18367. /**
  18368. * An event triggered after the world matrix is updated
  18369. */
  18370. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18371. _this._nonUniformScaling = false;
  18372. if (isPure) {
  18373. _this.getScene().addTransformNode(_this);
  18374. }
  18375. return _this;
  18376. }
  18377. /**
  18378. * Gets a string idenfifying the name of the class
  18379. * @returns "TransformNode" string
  18380. */
  18381. TransformNode.prototype.getClassName = function () {
  18382. return "TransformNode";
  18383. };
  18384. Object.defineProperty(TransformNode.prototype, "rotation", {
  18385. /**
  18386. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18387. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18388. * Default : (0.0, 0.0, 0.0)
  18389. */
  18390. get: function () {
  18391. return this._rotation;
  18392. },
  18393. set: function (newRotation) {
  18394. this._rotation = newRotation;
  18395. },
  18396. enumerable: true,
  18397. configurable: true
  18398. });
  18399. Object.defineProperty(TransformNode.prototype, "scaling", {
  18400. /**
  18401. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18402. * Default : (1.0, 1.0, 1.0)
  18403. */
  18404. get: function () {
  18405. return this._scaling;
  18406. },
  18407. /**
  18408. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18409. * Default : (1.0, 1.0, 1.0)
  18410. */
  18411. set: function (newScaling) {
  18412. this._scaling = newScaling;
  18413. },
  18414. enumerable: true,
  18415. configurable: true
  18416. });
  18417. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18418. /**
  18419. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18420. * It's null by default.
  18421. * 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)
  18422. */
  18423. get: function () {
  18424. return this._rotationQuaternion;
  18425. },
  18426. set: function (quaternion) {
  18427. this._rotationQuaternion = quaternion;
  18428. //reset the rotation vector.
  18429. if (quaternion && this.rotation.length()) {
  18430. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18431. }
  18432. },
  18433. enumerable: true,
  18434. configurable: true
  18435. });
  18436. Object.defineProperty(TransformNode.prototype, "forward", {
  18437. /**
  18438. * The forward direction of that transform in world space.
  18439. */
  18440. get: function () {
  18441. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18442. },
  18443. enumerable: true,
  18444. configurable: true
  18445. });
  18446. Object.defineProperty(TransformNode.prototype, "up", {
  18447. /**
  18448. * The up direction of that transform in world space.
  18449. */
  18450. get: function () {
  18451. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18452. },
  18453. enumerable: true,
  18454. configurable: true
  18455. });
  18456. Object.defineProperty(TransformNode.prototype, "right", {
  18457. /**
  18458. * The right direction of that transform in world space.
  18459. */
  18460. get: function () {
  18461. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18462. },
  18463. enumerable: true,
  18464. configurable: true
  18465. });
  18466. /**
  18467. * Returns the latest update of the World matrix
  18468. * Returns a Matrix.
  18469. */
  18470. TransformNode.prototype.getWorldMatrix = function () {
  18471. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18472. this.computeWorldMatrix();
  18473. }
  18474. return this._worldMatrix;
  18475. };
  18476. /** @hidden */
  18477. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18478. return this._worldMatrixDeterminant;
  18479. };
  18480. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18481. /**
  18482. * Returns directly the latest state of the mesh World matrix.
  18483. * A Matrix is returned.
  18484. */
  18485. get: function () {
  18486. return this._worldMatrix;
  18487. },
  18488. enumerable: true,
  18489. configurable: true
  18490. });
  18491. /**
  18492. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18493. * Returns the TransformNode.
  18494. */
  18495. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18496. this._poseMatrix.copyFrom(matrix);
  18497. return this;
  18498. };
  18499. /**
  18500. * Returns the mesh Pose matrix.
  18501. * Returned object : Matrix
  18502. */
  18503. TransformNode.prototype.getPoseMatrix = function () {
  18504. return this._poseMatrix;
  18505. };
  18506. TransformNode.prototype._isSynchronized = function () {
  18507. if (this._isDirty) {
  18508. return false;
  18509. }
  18510. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18511. return false;
  18512. if (this._cache.pivotMatrixUpdated) {
  18513. return false;
  18514. }
  18515. if (this.infiniteDistance) {
  18516. return false;
  18517. }
  18518. if (!this._cache.position.equals(this.position))
  18519. return false;
  18520. if (this.rotationQuaternion) {
  18521. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18522. return false;
  18523. }
  18524. if (!this._cache.rotation.equals(this.rotation))
  18525. return false;
  18526. if (!this._cache.scaling.equals(this.scaling))
  18527. return false;
  18528. return true;
  18529. };
  18530. TransformNode.prototype._initCache = function () {
  18531. _super.prototype._initCache.call(this);
  18532. this._cache.localMatrixUpdated = false;
  18533. this._cache.position = BABYLON.Vector3.Zero();
  18534. this._cache.scaling = BABYLON.Vector3.Zero();
  18535. this._cache.rotation = BABYLON.Vector3.Zero();
  18536. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18537. this._cache.billboardMode = -1;
  18538. };
  18539. TransformNode.prototype.markAsDirty = function (property) {
  18540. if (property === "rotation") {
  18541. this.rotationQuaternion = null;
  18542. }
  18543. this._currentRenderId = Number.MAX_VALUE;
  18544. this._isDirty = true;
  18545. return this;
  18546. };
  18547. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18548. /**
  18549. * Returns the current mesh absolute position.
  18550. * Retuns a Vector3.
  18551. */
  18552. get: function () {
  18553. return this._absolutePosition;
  18554. },
  18555. enumerable: true,
  18556. configurable: true
  18557. });
  18558. /**
  18559. * Sets a new matrix to apply before all other transformation
  18560. * @param matrix defines the transform matrix
  18561. * @returns the current TransformNode
  18562. */
  18563. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18564. return this.setPivotMatrix(matrix, false);
  18565. };
  18566. /**
  18567. * Sets a new pivot matrix to the current node
  18568. * @param matrix defines the new pivot matrix to use
  18569. * @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
  18570. * @returns the current TransformNode
  18571. */
  18572. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18573. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18574. this._pivotMatrix = matrix.clone();
  18575. this._cache.pivotMatrixUpdated = true;
  18576. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18577. if (this._postMultiplyPivotMatrix) {
  18578. if (!this._pivotMatrixInverse) {
  18579. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18580. }
  18581. else {
  18582. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18583. }
  18584. }
  18585. return this;
  18586. };
  18587. /**
  18588. * Returns the mesh pivot matrix.
  18589. * Default : Identity.
  18590. * A Matrix is returned.
  18591. */
  18592. TransformNode.prototype.getPivotMatrix = function () {
  18593. return this._pivotMatrix;
  18594. };
  18595. /**
  18596. * Prevents the World matrix to be computed any longer.
  18597. * Returns the TransformNode.
  18598. */
  18599. TransformNode.prototype.freezeWorldMatrix = function () {
  18600. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18601. this.computeWorldMatrix(true);
  18602. this._isWorldMatrixFrozen = true;
  18603. return this;
  18604. };
  18605. /**
  18606. * Allows back the World matrix computation.
  18607. * Returns the TransformNode.
  18608. */
  18609. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18610. this._isWorldMatrixFrozen = false;
  18611. this.computeWorldMatrix(true);
  18612. return this;
  18613. };
  18614. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18615. /**
  18616. * True if the World matrix has been frozen.
  18617. * Returns a boolean.
  18618. */
  18619. get: function () {
  18620. return this._isWorldMatrixFrozen;
  18621. },
  18622. enumerable: true,
  18623. configurable: true
  18624. });
  18625. /**
  18626. * Retuns the mesh absolute position in the World.
  18627. * Returns a Vector3.
  18628. */
  18629. TransformNode.prototype.getAbsolutePosition = function () {
  18630. this.computeWorldMatrix();
  18631. return this._absolutePosition;
  18632. };
  18633. /**
  18634. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18635. * Returns the TransformNode.
  18636. */
  18637. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18638. if (!absolutePosition) {
  18639. return this;
  18640. }
  18641. var absolutePositionX;
  18642. var absolutePositionY;
  18643. var absolutePositionZ;
  18644. if (absolutePosition.x === undefined) {
  18645. if (arguments.length < 3) {
  18646. return this;
  18647. }
  18648. absolutePositionX = arguments[0];
  18649. absolutePositionY = arguments[1];
  18650. absolutePositionZ = arguments[2];
  18651. }
  18652. else {
  18653. absolutePositionX = absolutePosition.x;
  18654. absolutePositionY = absolutePosition.y;
  18655. absolutePositionZ = absolutePosition.z;
  18656. }
  18657. if (this.parent) {
  18658. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18659. invertParentWorldMatrix.invert();
  18660. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18661. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18662. }
  18663. else {
  18664. this.position.x = absolutePositionX;
  18665. this.position.y = absolutePositionY;
  18666. this.position.z = absolutePositionZ;
  18667. }
  18668. return this;
  18669. };
  18670. /**
  18671. * Sets the mesh position in its local space.
  18672. * Returns the TransformNode.
  18673. */
  18674. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18675. this.computeWorldMatrix();
  18676. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18677. return this;
  18678. };
  18679. /**
  18680. * Returns the mesh position in the local space from the current World matrix values.
  18681. * Returns a new Vector3.
  18682. */
  18683. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18684. this.computeWorldMatrix();
  18685. var invLocalWorldMatrix = this._localWorld.clone();
  18686. invLocalWorldMatrix.invert();
  18687. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18688. };
  18689. /**
  18690. * Translates the mesh along the passed Vector3 in its local space.
  18691. * Returns the TransformNode.
  18692. */
  18693. TransformNode.prototype.locallyTranslate = function (vector3) {
  18694. this.computeWorldMatrix(true);
  18695. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18696. return this;
  18697. };
  18698. /**
  18699. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18700. * @param targetPoint the position (must be in same space as current mesh) to look at
  18701. * @param yawCor optional yaw (y-axis) correction in radians
  18702. * @param pitchCor optional pitch (x-axis) correction in radians
  18703. * @param rollCor optional roll (z-axis) correction in radians
  18704. * @param space the choosen space of the target
  18705. * @returns the TransformNode.
  18706. */
  18707. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18708. if (yawCor === void 0) { yawCor = 0; }
  18709. if (pitchCor === void 0) { pitchCor = 0; }
  18710. if (rollCor === void 0) { rollCor = 0; }
  18711. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18712. var dv = TransformNode._lookAtVectorCache;
  18713. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18714. targetPoint.subtractToRef(pos, dv);
  18715. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18716. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18717. var pitch = Math.atan2(dv.y, len);
  18718. if (this.rotationQuaternion) {
  18719. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18720. }
  18721. else {
  18722. this.rotation.x = pitch + pitchCor;
  18723. this.rotation.y = yaw + yawCor;
  18724. this.rotation.z = rollCor;
  18725. }
  18726. return this;
  18727. };
  18728. /**
  18729. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18730. * This Vector3 is expressed in the World space.
  18731. */
  18732. TransformNode.prototype.getDirection = function (localAxis) {
  18733. var result = BABYLON.Vector3.Zero();
  18734. this.getDirectionToRef(localAxis, result);
  18735. return result;
  18736. };
  18737. /**
  18738. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18739. * localAxis is expressed in the mesh local space.
  18740. * result is computed in the Wordl space from the mesh World matrix.
  18741. * Returns the TransformNode.
  18742. */
  18743. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18744. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18745. return this;
  18746. };
  18747. /**
  18748. * Sets a new pivot point to the current node
  18749. * @param point defines the new pivot point to use
  18750. * @param space defines if the point is in world or local space (local by default)
  18751. * @returns the current TransformNode
  18752. */
  18753. TransformNode.prototype.setPivotPoint = function (point, space) {
  18754. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18755. if (this.getScene().getRenderId() == 0) {
  18756. this.computeWorldMatrix(true);
  18757. }
  18758. var wm = this.getWorldMatrix();
  18759. if (space == BABYLON.Space.WORLD) {
  18760. var tmat = BABYLON.Tmp.Matrix[0];
  18761. wm.invertToRef(tmat);
  18762. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18763. }
  18764. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18765. };
  18766. /**
  18767. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18768. */
  18769. TransformNode.prototype.getPivotPoint = function () {
  18770. var point = BABYLON.Vector3.Zero();
  18771. this.getPivotPointToRef(point);
  18772. return point;
  18773. };
  18774. /**
  18775. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18776. * Returns the TransformNode.
  18777. */
  18778. TransformNode.prototype.getPivotPointToRef = function (result) {
  18779. result.x = -this._pivotMatrix.m[12];
  18780. result.y = -this._pivotMatrix.m[13];
  18781. result.z = -this._pivotMatrix.m[14];
  18782. return this;
  18783. };
  18784. /**
  18785. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18786. */
  18787. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18788. var point = BABYLON.Vector3.Zero();
  18789. this.getAbsolutePivotPointToRef(point);
  18790. return point;
  18791. };
  18792. /**
  18793. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18794. * Returns the TransformNode.
  18795. */
  18796. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18797. result.x = this._pivotMatrix.m[12];
  18798. result.y = this._pivotMatrix.m[13];
  18799. result.z = this._pivotMatrix.m[14];
  18800. this.getPivotPointToRef(result);
  18801. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18802. return this;
  18803. };
  18804. /**
  18805. * Defines the passed node as the parent of the current node.
  18806. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18807. * Returns the TransformNode.
  18808. */
  18809. TransformNode.prototype.setParent = function (node) {
  18810. if (node === null) {
  18811. var rotation = BABYLON.Tmp.Quaternion[0];
  18812. var position = BABYLON.Tmp.Vector3[0];
  18813. var scale = BABYLON.Tmp.Vector3[1];
  18814. if (this.parent && this.parent.computeWorldMatrix) {
  18815. this.parent.computeWorldMatrix(true);
  18816. }
  18817. this.computeWorldMatrix(true);
  18818. this.getWorldMatrix().decompose(scale, rotation, position);
  18819. if (this.rotationQuaternion) {
  18820. this.rotationQuaternion.copyFrom(rotation);
  18821. }
  18822. else {
  18823. rotation.toEulerAnglesToRef(this.rotation);
  18824. }
  18825. this.scaling.x = scale.x;
  18826. this.scaling.y = scale.y;
  18827. this.scaling.z = scale.z;
  18828. this.position.x = position.x;
  18829. this.position.y = position.y;
  18830. this.position.z = position.z;
  18831. }
  18832. else {
  18833. var rotation = BABYLON.Tmp.Quaternion[0];
  18834. var position = BABYLON.Tmp.Vector3[0];
  18835. var scale = BABYLON.Tmp.Vector3[1];
  18836. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18837. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18838. this.computeWorldMatrix(true);
  18839. node.computeWorldMatrix(true);
  18840. node.getWorldMatrix().invertToRef(invParentMatrix);
  18841. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18842. diffMatrix.decompose(scale, rotation, position);
  18843. if (this.rotationQuaternion) {
  18844. this.rotationQuaternion.copyFrom(rotation);
  18845. }
  18846. else {
  18847. rotation.toEulerAnglesToRef(this.rotation);
  18848. }
  18849. this.position.x = position.x;
  18850. this.position.y = position.y;
  18851. this.position.z = position.z;
  18852. this.scaling.x = scale.x;
  18853. this.scaling.y = scale.y;
  18854. this.scaling.z = scale.z;
  18855. }
  18856. this.parent = node;
  18857. return this;
  18858. };
  18859. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18860. get: function () {
  18861. return this._nonUniformScaling;
  18862. },
  18863. enumerable: true,
  18864. configurable: true
  18865. });
  18866. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18867. if (this._nonUniformScaling === value) {
  18868. return false;
  18869. }
  18870. this._nonUniformScaling = true;
  18871. return true;
  18872. };
  18873. /**
  18874. * Attach the current TransformNode to another TransformNode associated with a bone
  18875. * @param bone Bone affecting the TransformNode
  18876. * @param affectedTransformNode TransformNode associated with the bone
  18877. */
  18878. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18879. this._transformToBoneReferal = affectedTransformNode;
  18880. this.parent = bone;
  18881. if (bone.getWorldMatrix().determinant() < 0) {
  18882. this.scalingDeterminant *= -1;
  18883. }
  18884. return this;
  18885. };
  18886. TransformNode.prototype.detachFromBone = function () {
  18887. if (!this.parent) {
  18888. return this;
  18889. }
  18890. if (this.parent.getWorldMatrix().determinant() < 0) {
  18891. this.scalingDeterminant *= -1;
  18892. }
  18893. this._transformToBoneReferal = null;
  18894. this.parent = null;
  18895. return this;
  18896. };
  18897. /**
  18898. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18899. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18900. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18901. * The passed axis is also normalized.
  18902. * Returns the TransformNode.
  18903. */
  18904. TransformNode.prototype.rotate = function (axis, amount, space) {
  18905. axis.normalize();
  18906. if (!this.rotationQuaternion) {
  18907. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18908. this.rotation = BABYLON.Vector3.Zero();
  18909. }
  18910. var rotationQuaternion;
  18911. if (!space || space === BABYLON.Space.LOCAL) {
  18912. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18913. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18914. }
  18915. else {
  18916. if (this.parent) {
  18917. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18918. invertParentWorldMatrix.invert();
  18919. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18920. }
  18921. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18922. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18923. }
  18924. return this;
  18925. };
  18926. /**
  18927. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18928. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18929. * The passed axis is also normalized.
  18930. * Returns the TransformNode.
  18931. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18932. */
  18933. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18934. axis.normalize();
  18935. if (!this.rotationQuaternion) {
  18936. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18937. this.rotation.copyFromFloats(0, 0, 0);
  18938. }
  18939. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18940. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18941. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18942. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18943. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18944. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18945. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18946. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18947. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18948. return this;
  18949. };
  18950. /**
  18951. * Translates the mesh along the axis vector for the passed distance in the given space.
  18952. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18953. * Returns the TransformNode.
  18954. */
  18955. TransformNode.prototype.translate = function (axis, distance, space) {
  18956. var displacementVector = axis.scale(distance);
  18957. if (!space || space === BABYLON.Space.LOCAL) {
  18958. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18959. this.setPositionWithLocalVector(tempV3);
  18960. }
  18961. else {
  18962. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18963. }
  18964. return this;
  18965. };
  18966. /**
  18967. * Adds a rotation step to the mesh current rotation.
  18968. * x, y, z are Euler angles expressed in radians.
  18969. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18970. * This means this rotation is made in the mesh local space only.
  18971. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18972. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18973. * ```javascript
  18974. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18975. * ```
  18976. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18977. * 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.
  18978. * Returns the TransformNode.
  18979. */
  18980. TransformNode.prototype.addRotation = function (x, y, z) {
  18981. var rotationQuaternion;
  18982. if (this.rotationQuaternion) {
  18983. rotationQuaternion = this.rotationQuaternion;
  18984. }
  18985. else {
  18986. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18987. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18988. }
  18989. var accumulation = BABYLON.Tmp.Quaternion[0];
  18990. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18991. rotationQuaternion.multiplyInPlace(accumulation);
  18992. if (!this.rotationQuaternion) {
  18993. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18994. }
  18995. return this;
  18996. };
  18997. /**
  18998. * Computes the mesh World matrix and returns it.
  18999. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19000. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19001. * If the parameter `force`is set to `true`, the actual computation is done.
  19002. * Returns the mesh World Matrix.
  19003. */
  19004. TransformNode.prototype.computeWorldMatrix = function (force) {
  19005. if (this._isWorldMatrixFrozen) {
  19006. return this._worldMatrix;
  19007. }
  19008. if (!force && this.isSynchronized(true)) {
  19009. this._currentRenderId = this.getScene().getRenderId();
  19010. return this._worldMatrix;
  19011. }
  19012. this._cache.position.copyFrom(this.position);
  19013. this._cache.scaling.copyFrom(this.scaling);
  19014. this._cache.pivotMatrixUpdated = false;
  19015. this._cache.billboardMode = this.billboardMode;
  19016. this._currentRenderId = this.getScene().getRenderId();
  19017. this._childRenderId = this.getScene().getRenderId();
  19018. this._isDirty = false;
  19019. // Scaling
  19020. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19021. // Rotation
  19022. //rotate, if quaternion is set and rotation was used
  19023. if (this.rotationQuaternion) {
  19024. var len = this.rotation.length();
  19025. if (len) {
  19026. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19027. this.rotation.copyFromFloats(0, 0, 0);
  19028. }
  19029. }
  19030. if (this.rotationQuaternion) {
  19031. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19032. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19033. }
  19034. else {
  19035. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19036. this._cache.rotation.copyFrom(this.rotation);
  19037. }
  19038. // Translation
  19039. var camera = this.getScene().activeCamera;
  19040. if (this.infiniteDistance && !this.parent && camera) {
  19041. var cameraWorldMatrix = camera.getWorldMatrix();
  19042. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19043. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19044. }
  19045. else {
  19046. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19047. }
  19048. // Composing transformations
  19049. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19050. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19051. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19052. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19053. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19054. // Need to decompose each rotation here
  19055. var currentPosition = BABYLON.Tmp.Vector3[3];
  19056. if (this.parent && this.parent.getWorldMatrix) {
  19057. if (this._transformToBoneReferal) {
  19058. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19059. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19060. }
  19061. else {
  19062. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19063. }
  19064. }
  19065. else {
  19066. currentPosition.copyFrom(this.position);
  19067. }
  19068. currentPosition.subtractInPlace(camera.globalPosition);
  19069. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19070. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19071. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19072. }
  19073. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19074. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19075. }
  19076. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19077. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19078. }
  19079. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19080. }
  19081. else {
  19082. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19083. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19084. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19085. }
  19086. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19087. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19088. }
  19089. // Local world
  19090. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19091. // Parent
  19092. if (this.parent && this.parent.getWorldMatrix) {
  19093. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19094. if (this._transformToBoneReferal) {
  19095. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19096. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19097. }
  19098. else {
  19099. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19100. }
  19101. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19102. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19103. this._worldMatrix.copyFrom(this._localWorld);
  19104. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19105. }
  19106. else {
  19107. if (this._transformToBoneReferal) {
  19108. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19109. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19110. }
  19111. else {
  19112. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19113. }
  19114. }
  19115. this._markSyncedWithParent();
  19116. }
  19117. else {
  19118. this._worldMatrix.copyFrom(this._localWorld);
  19119. }
  19120. // Post multiply inverse of pivotMatrix
  19121. if (this._postMultiplyPivotMatrix) {
  19122. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19123. }
  19124. // Normal matrix
  19125. if (this.scaling.isNonUniform) {
  19126. this._updateNonUniformScalingState(true);
  19127. }
  19128. else if (this.parent && this.parent._nonUniformScaling) {
  19129. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19130. }
  19131. else {
  19132. this._updateNonUniformScalingState(false);
  19133. }
  19134. this._afterComputeWorldMatrix();
  19135. // Absolute position
  19136. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19137. // Callbacks
  19138. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19139. if (!this._poseMatrix) {
  19140. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19141. }
  19142. // Cache the determinant
  19143. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19144. return this._worldMatrix;
  19145. };
  19146. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19147. };
  19148. /**
  19149. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19150. * @param func: callback function to add
  19151. *
  19152. * Returns the TransformNode.
  19153. */
  19154. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19155. this.onAfterWorldMatrixUpdateObservable.add(func);
  19156. return this;
  19157. };
  19158. /**
  19159. * Removes a registered callback function.
  19160. * Returns the TransformNode.
  19161. */
  19162. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19163. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19164. return this;
  19165. };
  19166. /**
  19167. * Clone the current transform node
  19168. * Returns the new transform node
  19169. * @param name Name of the new clone
  19170. * @param newParent New parent for the clone
  19171. * @param doNotCloneChildren Do not clone children hierarchy
  19172. */
  19173. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19174. var _this = this;
  19175. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19176. result.name = name;
  19177. result.id = name;
  19178. if (newParent) {
  19179. result.parent = newParent;
  19180. }
  19181. if (!doNotCloneChildren) {
  19182. // Children
  19183. var directDescendants = this.getDescendants(true);
  19184. for (var index = 0; index < directDescendants.length; index++) {
  19185. var child = directDescendants[index];
  19186. if (child.clone) {
  19187. child.clone(name + "." + child.name, result);
  19188. }
  19189. }
  19190. }
  19191. return result;
  19192. };
  19193. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19194. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19195. serializationObject.type = this.getClassName();
  19196. // Parent
  19197. if (this.parent) {
  19198. serializationObject.parentId = this.parent.id;
  19199. }
  19200. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19201. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19202. }
  19203. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19204. serializationObject.isEnabled = this.isEnabled();
  19205. // Parent
  19206. if (this.parent) {
  19207. serializationObject.parentId = this.parent.id;
  19208. }
  19209. return serializationObject;
  19210. };
  19211. // Statics
  19212. /**
  19213. * Returns a new TransformNode object parsed from the source provided.
  19214. * The parameter `parsedMesh` is the source.
  19215. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19216. */
  19217. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19218. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19219. if (BABYLON.Tags) {
  19220. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19221. }
  19222. if (parsedTransformNode.localMatrix) {
  19223. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19224. }
  19225. else if (parsedTransformNode.pivotMatrix) {
  19226. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19227. }
  19228. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19229. // Parent
  19230. if (parsedTransformNode.parentId) {
  19231. transformNode._waitingParentId = parsedTransformNode.parentId;
  19232. }
  19233. return transformNode;
  19234. };
  19235. /**
  19236. * Releases resources associated with this transform node.
  19237. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19238. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19239. */
  19240. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19241. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19242. // Animations
  19243. this.getScene().stopAnimation(this);
  19244. // Remove from scene
  19245. this.getScene().removeTransformNode(this);
  19246. this.onAfterWorldMatrixUpdateObservable.clear();
  19247. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19248. };
  19249. // Statics
  19250. TransformNode.BILLBOARDMODE_NONE = 0;
  19251. TransformNode.BILLBOARDMODE_X = 1;
  19252. TransformNode.BILLBOARDMODE_Y = 2;
  19253. TransformNode.BILLBOARDMODE_Z = 4;
  19254. TransformNode.BILLBOARDMODE_ALL = 7;
  19255. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19256. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19257. __decorate([
  19258. BABYLON.serializeAsVector3()
  19259. ], TransformNode.prototype, "_rotation", void 0);
  19260. __decorate([
  19261. BABYLON.serializeAsQuaternion()
  19262. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19263. __decorate([
  19264. BABYLON.serializeAsVector3()
  19265. ], TransformNode.prototype, "_scaling", void 0);
  19266. __decorate([
  19267. BABYLON.serialize()
  19268. ], TransformNode.prototype, "billboardMode", void 0);
  19269. __decorate([
  19270. BABYLON.serialize()
  19271. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19272. __decorate([
  19273. BABYLON.serialize()
  19274. ], TransformNode.prototype, "infiniteDistance", void 0);
  19275. __decorate([
  19276. BABYLON.serializeAsVector3()
  19277. ], TransformNode.prototype, "position", void 0);
  19278. return TransformNode;
  19279. }(BABYLON.Node));
  19280. BABYLON.TransformNode = TransformNode;
  19281. })(BABYLON || (BABYLON = {}));
  19282. //# sourceMappingURL=babylon.transformNode.js.map
  19283. var BABYLON;
  19284. (function (BABYLON) {
  19285. /**
  19286. * Class used to store all common mesh properties
  19287. */
  19288. var AbstractMesh = /** @class */ (function (_super) {
  19289. __extends(AbstractMesh, _super);
  19290. // Constructor
  19291. /**
  19292. * Creates a new AbstractMesh
  19293. * @param name defines the name of the mesh
  19294. * @param scene defines the hosting scene
  19295. */
  19296. function AbstractMesh(name, scene) {
  19297. if (scene === void 0) { scene = null; }
  19298. var _this = _super.call(this, name, scene, false) || this;
  19299. _this._facetNb = 0; // facet number
  19300. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19301. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19302. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19303. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19304. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19305. _this._subDiv = {
  19306. max: 1,
  19307. X: 1,
  19308. Y: 1,
  19309. Z: 1
  19310. };
  19311. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19312. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19313. // Events
  19314. /**
  19315. * An event triggered when this mesh collides with another one
  19316. */
  19317. _this.onCollideObservable = new BABYLON.Observable();
  19318. /**
  19319. * An event triggered when the collision's position changes
  19320. */
  19321. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19322. /**
  19323. * An event triggered when material is changed
  19324. */
  19325. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19326. // Properties
  19327. /**
  19328. * Gets or sets the orientation for POV movement & rotation
  19329. */
  19330. _this.definedFacingForward = true;
  19331. /**
  19332. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19333. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19334. * * 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.
  19335. * @see http://doc.babylonjs.com/features/occlusionquery
  19336. */
  19337. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19338. /**
  19339. * 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:
  19340. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19341. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19342. * * 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.
  19343. * @see http://doc.babylonjs.com/features/occlusionquery
  19344. */
  19345. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19346. /**
  19347. * 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.
  19348. * The default value is -1 which means don't break the query and wait till the result
  19349. * @see http://doc.babylonjs.com/features/occlusionquery
  19350. */
  19351. _this.occlusionRetryCount = -1;
  19352. _this._occlusionInternalRetryCounter = 0;
  19353. _this._isOccluded = false;
  19354. _this._isOcclusionQueryInProgress = false;
  19355. _this._visibility = 1.0;
  19356. /** Gets or sets the alpha index used to sort transparent meshes
  19357. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19358. */
  19359. _this.alphaIndex = Number.MAX_VALUE;
  19360. /**
  19361. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19362. */
  19363. _this.isVisible = true;
  19364. /**
  19365. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19366. */
  19367. _this.isPickable = true;
  19368. /**
  19369. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19370. */
  19371. _this.showBoundingBox = false;
  19372. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19373. _this.showSubMeshesBoundingBox = false;
  19374. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19375. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19376. */
  19377. _this.isBlocker = false;
  19378. /**
  19379. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19380. */
  19381. _this.enablePointerMoveEvents = false;
  19382. /**
  19383. * Specifies the rendering group id for this mesh (0 by default)
  19384. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19385. */
  19386. _this.renderingGroupId = 0;
  19387. _this._receiveShadows = false;
  19388. /**
  19389. * Gets or sets a boolean indicating if the outline must be rendered as well
  19390. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19391. */
  19392. _this.renderOutline = false;
  19393. /** Defines color to use when rendering outline */
  19394. _this.outlineColor = BABYLON.Color3.Red();
  19395. /** Define width to use when rendering outline */
  19396. _this.outlineWidth = 0.02;
  19397. /**
  19398. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19399. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19400. */
  19401. _this.renderOverlay = false;
  19402. /** Defines color to use when rendering overlay */
  19403. _this.overlayColor = BABYLON.Color3.Red();
  19404. /** Defines alpha to use when rendering overlay */
  19405. _this.overlayAlpha = 0.5;
  19406. _this._hasVertexAlpha = false;
  19407. _this._useVertexColors = true;
  19408. _this._computeBonesUsingShaders = true;
  19409. _this._numBoneInfluencers = 4;
  19410. _this._applyFog = true;
  19411. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19412. _this.useOctreeForRenderingSelection = true;
  19413. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19414. _this.useOctreeForPicking = true;
  19415. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19416. _this.useOctreeForCollisions = true;
  19417. _this._layerMask = 0x0FFFFFFF;
  19418. /**
  19419. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19420. */
  19421. _this.alwaysSelectAsActiveMesh = false;
  19422. /**
  19423. * Gets or sets the current action manager
  19424. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19425. */
  19426. _this.actionManager = null;
  19427. /**
  19428. * Gets or sets impostor used for physic simulation
  19429. * @see http://doc.babylonjs.com/features/physics_engine
  19430. */
  19431. _this.physicsImpostor = null;
  19432. // Collisions
  19433. _this._checkCollisions = false;
  19434. _this._collisionMask = -1;
  19435. _this._collisionGroup = -1;
  19436. /**
  19437. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19438. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19439. */
  19440. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19441. /**
  19442. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19443. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19444. */
  19445. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19446. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19447. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19448. // Edges
  19449. /**
  19450. * Defines edge width used when edgesRenderer is enabled
  19451. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19452. */
  19453. _this.edgesWidth = 1;
  19454. /**
  19455. * Defines edge color used when edgesRenderer is enabled
  19456. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19457. */
  19458. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19459. // Cache
  19460. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19461. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19462. /** @hidden */
  19463. _this._renderId = 0;
  19464. /** @hidden */
  19465. _this._intersectionsInProgress = new Array();
  19466. /** @hidden */
  19467. _this._unIndexed = false;
  19468. /** @hidden */
  19469. _this._lightSources = new Array();
  19470. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19471. if (collidedMesh === void 0) { collidedMesh = null; }
  19472. //TODO move this to the collision coordinator!
  19473. if (_this.getScene().workerCollisions)
  19474. newPosition.multiplyInPlace(_this._collider._radius);
  19475. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19476. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19477. _this.position.addInPlace(_this._diffPositionForCollisions);
  19478. }
  19479. if (collidedMesh) {
  19480. _this.onCollideObservable.notifyObservers(collidedMesh);
  19481. }
  19482. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19483. };
  19484. _this.getScene().addMesh(_this);
  19485. _this._resyncLightSources();
  19486. return _this;
  19487. }
  19488. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19489. /**
  19490. * No billboard
  19491. */
  19492. get: function () {
  19493. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19494. },
  19495. enumerable: true,
  19496. configurable: true
  19497. });
  19498. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19499. /** Billboard on X axis */
  19500. get: function () {
  19501. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19502. },
  19503. enumerable: true,
  19504. configurable: true
  19505. });
  19506. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19507. /** Billboard on Y axis */
  19508. get: function () {
  19509. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19510. },
  19511. enumerable: true,
  19512. configurable: true
  19513. });
  19514. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19515. /** Billboard on Z axis */
  19516. get: function () {
  19517. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19518. },
  19519. enumerable: true,
  19520. configurable: true
  19521. });
  19522. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19523. /** Billboard on all axes */
  19524. get: function () {
  19525. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19526. },
  19527. enumerable: true,
  19528. configurable: true
  19529. });
  19530. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19531. /**
  19532. * Gets the number of facets in the mesh
  19533. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19534. */
  19535. get: function () {
  19536. return this._facetNb;
  19537. },
  19538. enumerable: true,
  19539. configurable: true
  19540. });
  19541. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19542. /**
  19543. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19544. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19545. */
  19546. get: function () {
  19547. return this._partitioningSubdivisions;
  19548. },
  19549. set: function (nb) {
  19550. this._partitioningSubdivisions = nb;
  19551. },
  19552. enumerable: true,
  19553. configurable: true
  19554. });
  19555. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19556. /**
  19557. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19558. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19559. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19560. */
  19561. get: function () {
  19562. return this._partitioningBBoxRatio;
  19563. },
  19564. set: function (ratio) {
  19565. this._partitioningBBoxRatio = ratio;
  19566. },
  19567. enumerable: true,
  19568. configurable: true
  19569. });
  19570. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19571. /**
  19572. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19573. * Works only for updatable meshes.
  19574. * Doesn't work with multi-materials
  19575. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19576. */
  19577. get: function () {
  19578. return this._facetDepthSort;
  19579. },
  19580. set: function (sort) {
  19581. this._facetDepthSort = sort;
  19582. },
  19583. enumerable: true,
  19584. configurable: true
  19585. });
  19586. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19587. /**
  19588. * The location (Vector3) where the facet depth sort must be computed from.
  19589. * By default, the active camera position.
  19590. * Used only when facet depth sort is enabled
  19591. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19592. */
  19593. get: function () {
  19594. return this._facetDepthSortFrom;
  19595. },
  19596. set: function (location) {
  19597. this._facetDepthSortFrom = location;
  19598. },
  19599. enumerable: true,
  19600. configurable: true
  19601. });
  19602. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19603. /**
  19604. * gets a boolean indicating if facetData is enabled
  19605. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19606. */
  19607. get: function () {
  19608. return this._facetDataEnabled;
  19609. },
  19610. enumerable: true,
  19611. configurable: true
  19612. });
  19613. /** @hidden */
  19614. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19615. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19616. return false;
  19617. }
  19618. this._markSubMeshesAsMiscDirty();
  19619. return true;
  19620. };
  19621. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19622. /** Set a function to call when this mesh collides with another one */
  19623. set: function (callback) {
  19624. if (this._onCollideObserver) {
  19625. this.onCollideObservable.remove(this._onCollideObserver);
  19626. }
  19627. this._onCollideObserver = this.onCollideObservable.add(callback);
  19628. },
  19629. enumerable: true,
  19630. configurable: true
  19631. });
  19632. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19633. /** Set a function to call when the collision's position changes */
  19634. set: function (callback) {
  19635. if (this._onCollisionPositionChangeObserver) {
  19636. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19637. }
  19638. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19639. },
  19640. enumerable: true,
  19641. configurable: true
  19642. });
  19643. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19644. /**
  19645. * 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
  19646. * @see http://doc.babylonjs.com/features/occlusionquery
  19647. */
  19648. get: function () {
  19649. return this._isOccluded;
  19650. },
  19651. set: function (value) {
  19652. this._isOccluded = value;
  19653. },
  19654. enumerable: true,
  19655. configurable: true
  19656. });
  19657. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19658. /**
  19659. * Flag to check the progress status of the query
  19660. * @see http://doc.babylonjs.com/features/occlusionquery
  19661. */
  19662. get: function () {
  19663. return this._isOcclusionQueryInProgress;
  19664. },
  19665. enumerable: true,
  19666. configurable: true
  19667. });
  19668. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19669. /**
  19670. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19671. */
  19672. get: function () {
  19673. return this._visibility;
  19674. },
  19675. /**
  19676. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19677. */
  19678. set: function (value) {
  19679. if (this._visibility === value) {
  19680. return;
  19681. }
  19682. this._visibility = value;
  19683. this._markSubMeshesAsMiscDirty();
  19684. },
  19685. enumerable: true,
  19686. configurable: true
  19687. });
  19688. Object.defineProperty(AbstractMesh.prototype, "material", {
  19689. /** Gets or sets current material */
  19690. get: function () {
  19691. return this._material;
  19692. },
  19693. set: function (value) {
  19694. if (this._material === value) {
  19695. return;
  19696. }
  19697. this._material = value;
  19698. if (this.onMaterialChangedObservable.hasObservers) {
  19699. this.onMaterialChangedObservable.notifyObservers(this);
  19700. }
  19701. if (!this.subMeshes) {
  19702. return;
  19703. }
  19704. this._unBindEffect();
  19705. },
  19706. enumerable: true,
  19707. configurable: true
  19708. });
  19709. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19710. /**
  19711. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19712. * @see http://doc.babylonjs.com/babylon101/shadows
  19713. */
  19714. get: function () {
  19715. return this._receiveShadows;
  19716. },
  19717. set: function (value) {
  19718. if (this._receiveShadows === value) {
  19719. return;
  19720. }
  19721. this._receiveShadows = value;
  19722. this._markSubMeshesAsLightDirty();
  19723. },
  19724. enumerable: true,
  19725. configurable: true
  19726. });
  19727. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19728. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19729. get: function () {
  19730. return this._hasVertexAlpha;
  19731. },
  19732. set: function (value) {
  19733. if (this._hasVertexAlpha === value) {
  19734. return;
  19735. }
  19736. this._hasVertexAlpha = value;
  19737. this._markSubMeshesAsAttributesDirty();
  19738. this._markSubMeshesAsMiscDirty();
  19739. },
  19740. enumerable: true,
  19741. configurable: true
  19742. });
  19743. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19744. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  19745. get: function () {
  19746. return this._useVertexColors;
  19747. },
  19748. set: function (value) {
  19749. if (this._useVertexColors === value) {
  19750. return;
  19751. }
  19752. this._useVertexColors = value;
  19753. this._markSubMeshesAsAttributesDirty();
  19754. },
  19755. enumerable: true,
  19756. configurable: true
  19757. });
  19758. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19759. /**
  19760. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19761. */
  19762. get: function () {
  19763. return this._computeBonesUsingShaders;
  19764. },
  19765. set: function (value) {
  19766. if (this._computeBonesUsingShaders === value) {
  19767. return;
  19768. }
  19769. this._computeBonesUsingShaders = value;
  19770. this._markSubMeshesAsAttributesDirty();
  19771. },
  19772. enumerable: true,
  19773. configurable: true
  19774. });
  19775. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19776. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19777. get: function () {
  19778. return this._numBoneInfluencers;
  19779. },
  19780. set: function (value) {
  19781. if (this._numBoneInfluencers === value) {
  19782. return;
  19783. }
  19784. this._numBoneInfluencers = value;
  19785. this._markSubMeshesAsAttributesDirty();
  19786. },
  19787. enumerable: true,
  19788. configurable: true
  19789. });
  19790. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19791. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19792. get: function () {
  19793. return this._applyFog;
  19794. },
  19795. set: function (value) {
  19796. if (this._applyFog === value) {
  19797. return;
  19798. }
  19799. this._applyFog = value;
  19800. this._markSubMeshesAsMiscDirty();
  19801. },
  19802. enumerable: true,
  19803. configurable: true
  19804. });
  19805. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19806. /**
  19807. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19808. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19809. */
  19810. get: function () {
  19811. return this._layerMask;
  19812. },
  19813. set: function (value) {
  19814. if (value === this._layerMask) {
  19815. return;
  19816. }
  19817. this._layerMask = value;
  19818. this._resyncLightSources();
  19819. },
  19820. enumerable: true,
  19821. configurable: true
  19822. });
  19823. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19824. /**
  19825. * Gets or sets a collision mask used to mask collisions (default is -1).
  19826. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19827. */
  19828. get: function () {
  19829. return this._collisionMask;
  19830. },
  19831. set: function (mask) {
  19832. this._collisionMask = !isNaN(mask) ? mask : -1;
  19833. },
  19834. enumerable: true,
  19835. configurable: true
  19836. });
  19837. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19838. /**
  19839. * Gets or sets the current collision group mask (-1 by default).
  19840. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19841. */
  19842. get: function () {
  19843. return this._collisionGroup;
  19844. },
  19845. set: function (mask) {
  19846. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19847. },
  19848. enumerable: true,
  19849. configurable: true
  19850. });
  19851. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19852. /** @hidden */
  19853. get: function () {
  19854. return null;
  19855. },
  19856. enumerable: true,
  19857. configurable: true
  19858. });
  19859. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19860. get: function () {
  19861. return this._skeleton;
  19862. },
  19863. /**
  19864. * Gets or sets a skeleton to apply skining transformations
  19865. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19866. */
  19867. set: function (value) {
  19868. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19869. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19870. }
  19871. if (value && value.needInitialSkinMatrix) {
  19872. value._registerMeshWithPoseMatrix(this);
  19873. }
  19874. this._skeleton = value;
  19875. if (!this._skeleton) {
  19876. this._bonesTransformMatrices = null;
  19877. }
  19878. this._markSubMeshesAsAttributesDirty();
  19879. },
  19880. enumerable: true,
  19881. configurable: true
  19882. });
  19883. /**
  19884. * Returns the string "AbstractMesh"
  19885. * @returns "AbstractMesh"
  19886. */
  19887. AbstractMesh.prototype.getClassName = function () {
  19888. return "AbstractMesh";
  19889. };
  19890. /**
  19891. * Gets a string representation of the current mesh
  19892. * @param fullDetails defines a boolean indicating if full details must be included
  19893. * @returns a string representation of the current mesh
  19894. */
  19895. AbstractMesh.prototype.toString = function (fullDetails) {
  19896. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19897. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19898. if (this._skeleton) {
  19899. ret += ", skeleton: " + this._skeleton.name;
  19900. }
  19901. if (fullDetails) {
  19902. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19903. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19904. }
  19905. return ret;
  19906. };
  19907. /** @hidden */
  19908. AbstractMesh.prototype._rebuild = function () {
  19909. if (this._occlusionQuery) {
  19910. this._occlusionQuery = null;
  19911. }
  19912. if (this._edgesRenderer) {
  19913. this._edgesRenderer._rebuild();
  19914. }
  19915. if (!this.subMeshes) {
  19916. return;
  19917. }
  19918. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19919. var subMesh = _a[_i];
  19920. subMesh._rebuild();
  19921. }
  19922. };
  19923. /** @hidden */
  19924. AbstractMesh.prototype._resyncLightSources = function () {
  19925. this._lightSources.length = 0;
  19926. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19927. var light = _a[_i];
  19928. if (!light.isEnabled()) {
  19929. continue;
  19930. }
  19931. if (light.canAffectMesh(this)) {
  19932. this._lightSources.push(light);
  19933. }
  19934. }
  19935. this._markSubMeshesAsLightDirty();
  19936. };
  19937. /** @hidden */
  19938. AbstractMesh.prototype._resyncLighSource = function (light) {
  19939. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19940. var index = this._lightSources.indexOf(light);
  19941. if (index === -1) {
  19942. if (!isIn) {
  19943. return;
  19944. }
  19945. this._lightSources.push(light);
  19946. }
  19947. else {
  19948. if (isIn) {
  19949. return;
  19950. }
  19951. this._lightSources.splice(index, 1);
  19952. }
  19953. this._markSubMeshesAsLightDirty();
  19954. };
  19955. /** @hidden */
  19956. AbstractMesh.prototype._unBindEffect = function () {
  19957. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19958. var subMesh = _a[_i];
  19959. subMesh.setEffect(null);
  19960. }
  19961. };
  19962. /** @hidden */
  19963. AbstractMesh.prototype._removeLightSource = function (light) {
  19964. var index = this._lightSources.indexOf(light);
  19965. if (index === -1) {
  19966. return;
  19967. }
  19968. this._lightSources.splice(index, 1);
  19969. this._markSubMeshesAsLightDirty();
  19970. };
  19971. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19972. if (!this.subMeshes) {
  19973. return;
  19974. }
  19975. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19976. var subMesh = _a[_i];
  19977. if (subMesh._materialDefines) {
  19978. func(subMesh._materialDefines);
  19979. }
  19980. }
  19981. };
  19982. /** @hidden */
  19983. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19984. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19985. };
  19986. /** @hidden */
  19987. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19988. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19989. };
  19990. /** @hidden */
  19991. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19992. if (!this.subMeshes) {
  19993. return;
  19994. }
  19995. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19996. var subMesh = _a[_i];
  19997. var material = subMesh.getMaterial();
  19998. if (material) {
  19999. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20000. }
  20001. }
  20002. };
  20003. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20004. /**
  20005. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20006. */
  20007. get: function () {
  20008. return this._scaling;
  20009. },
  20010. set: function (newScaling) {
  20011. this._scaling = newScaling;
  20012. if (this.physicsImpostor) {
  20013. this.physicsImpostor.forceUpdate();
  20014. }
  20015. },
  20016. enumerable: true,
  20017. configurable: true
  20018. });
  20019. // Methods
  20020. /**
  20021. * Disables the mesh edge rendering mode
  20022. * @returns the currentAbstractMesh
  20023. */
  20024. AbstractMesh.prototype.disableEdgesRendering = function () {
  20025. if (this._edgesRenderer) {
  20026. this._edgesRenderer.dispose();
  20027. this._edgesRenderer = null;
  20028. }
  20029. return this;
  20030. };
  20031. /**
  20032. * Enables the edge rendering mode on the mesh.
  20033. * This mode makes the mesh edges visible
  20034. * @param epsilon defines the maximal distance between two angles to detect a face
  20035. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20036. * @returns the currentAbstractMesh
  20037. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20038. */
  20039. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20040. if (epsilon === void 0) { epsilon = 0.95; }
  20041. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20042. this.disableEdgesRendering();
  20043. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20044. return this;
  20045. };
  20046. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20047. /**
  20048. * Returns true if the mesh is blocked. Implemented by child classes
  20049. */
  20050. get: function () {
  20051. return false;
  20052. },
  20053. enumerable: true,
  20054. configurable: true
  20055. });
  20056. /**
  20057. * Returns the mesh itself by default. Implemented by child classes
  20058. * @param camera defines the camera to use to pick the right LOD level
  20059. * @returns the currentAbstractMesh
  20060. */
  20061. AbstractMesh.prototype.getLOD = function (camera) {
  20062. return this;
  20063. };
  20064. /**
  20065. * Returns 0 by default. Implemented by child classes
  20066. * @returns an integer
  20067. */
  20068. AbstractMesh.prototype.getTotalVertices = function () {
  20069. return 0;
  20070. };
  20071. /**
  20072. * Returns null by default. Implemented by child classes
  20073. * @returns null
  20074. */
  20075. AbstractMesh.prototype.getIndices = function () {
  20076. return null;
  20077. };
  20078. /**
  20079. * Returns the array of the requested vertex data kind. Implemented by child classes
  20080. * @param kind defines the vertex data kind to use
  20081. * @returns null
  20082. */
  20083. AbstractMesh.prototype.getVerticesData = function (kind) {
  20084. return null;
  20085. };
  20086. /**
  20087. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20088. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20089. * Note that a new underlying VertexBuffer object is created each call.
  20090. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20091. * @param kind defines vertex data kind:
  20092. * * BABYLON.VertexBuffer.PositionKind
  20093. * * BABYLON.VertexBuffer.UVKind
  20094. * * BABYLON.VertexBuffer.UV2Kind
  20095. * * BABYLON.VertexBuffer.UV3Kind
  20096. * * BABYLON.VertexBuffer.UV4Kind
  20097. * * BABYLON.VertexBuffer.UV5Kind
  20098. * * BABYLON.VertexBuffer.UV6Kind
  20099. * * BABYLON.VertexBuffer.ColorKind
  20100. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20101. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20102. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20103. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20104. * @param data defines the data source
  20105. * @param updatable defines if the data must be flagged as updatable (or static)
  20106. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20107. * @returns the current mesh
  20108. */
  20109. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20110. return this;
  20111. };
  20112. /**
  20113. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20114. * If the mesh has no geometry, it is simply returned as it is.
  20115. * @param kind defines vertex data kind:
  20116. * * BABYLON.VertexBuffer.PositionKind
  20117. * * BABYLON.VertexBuffer.UVKind
  20118. * * BABYLON.VertexBuffer.UV2Kind
  20119. * * BABYLON.VertexBuffer.UV3Kind
  20120. * * BABYLON.VertexBuffer.UV4Kind
  20121. * * BABYLON.VertexBuffer.UV5Kind
  20122. * * BABYLON.VertexBuffer.UV6Kind
  20123. * * BABYLON.VertexBuffer.ColorKind
  20124. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20125. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20126. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20127. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20128. * @param data defines the data source
  20129. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20130. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20131. * @returns the current mesh
  20132. */
  20133. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20134. return this;
  20135. };
  20136. /**
  20137. * Sets the mesh indices,
  20138. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20139. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20140. * @param totalVertices Defines the total number of vertices
  20141. * @returns the current mesh
  20142. */
  20143. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20144. return this;
  20145. };
  20146. /**
  20147. * Gets a boolean indicating if specific vertex data is present
  20148. * @param kind defines the vertex data kind to use
  20149. * @returns true is data kind is present
  20150. */
  20151. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20152. return false;
  20153. };
  20154. /**
  20155. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20156. * @returns a BoundingInfo
  20157. */
  20158. AbstractMesh.prototype.getBoundingInfo = function () {
  20159. if (this._masterMesh) {
  20160. return this._masterMesh.getBoundingInfo();
  20161. }
  20162. if (!this._boundingInfo) {
  20163. // this._boundingInfo is being created here
  20164. this._updateBoundingInfo();
  20165. }
  20166. // cannot be null.
  20167. return this._boundingInfo;
  20168. };
  20169. /**
  20170. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20171. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20172. * @returns the current mesh
  20173. */
  20174. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20175. if (includeDescendants === void 0) { includeDescendants = true; }
  20176. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20177. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20178. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20179. if (maxDimension === 0) {
  20180. return this;
  20181. }
  20182. var scale = 1 / maxDimension;
  20183. this.scaling.scaleInPlace(scale);
  20184. return this;
  20185. };
  20186. /**
  20187. * Overwrite the current bounding info
  20188. * @param boundingInfo defines the new bounding info
  20189. * @returns the current mesh
  20190. */
  20191. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20192. this._boundingInfo = boundingInfo;
  20193. return this;
  20194. };
  20195. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20196. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20197. get: function () {
  20198. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20199. },
  20200. enumerable: true,
  20201. configurable: true
  20202. });
  20203. /** @hidden */
  20204. AbstractMesh.prototype._preActivate = function () {
  20205. };
  20206. /** @hidden */
  20207. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20208. };
  20209. /** @hidden */
  20210. AbstractMesh.prototype._activate = function (renderId) {
  20211. this._renderId = renderId;
  20212. };
  20213. /**
  20214. * Gets the current world matrix
  20215. * @returns a Matrix
  20216. */
  20217. AbstractMesh.prototype.getWorldMatrix = function () {
  20218. if (this._masterMesh) {
  20219. return this._masterMesh.getWorldMatrix();
  20220. }
  20221. return _super.prototype.getWorldMatrix.call(this);
  20222. };
  20223. /** @hidden */
  20224. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20225. if (this._masterMesh) {
  20226. return this._masterMesh._getWorldMatrixDeterminant();
  20227. }
  20228. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20229. };
  20230. // ================================== Point of View Movement =================================
  20231. /**
  20232. * Perform relative position change from the point of view of behind the front of the mesh.
  20233. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20234. * Supports definition of mesh facing forward or backward
  20235. * @param amountRight defines the distance on the right axis
  20236. * @param amountUp defines the distance on the up axis
  20237. * @param amountForward defines the distance on the forward axis
  20238. * @returns the current mesh
  20239. */
  20240. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20241. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20242. return this;
  20243. };
  20244. /**
  20245. * Calculate relative position change from the point of view of behind the front of the mesh.
  20246. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20247. * Supports definition of mesh facing forward or backward
  20248. * @param amountRight defines the distance on the right axis
  20249. * @param amountUp defines the distance on the up axis
  20250. * @param amountForward defines the distance on the forward axis
  20251. * @returns the new displacement vector
  20252. */
  20253. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20254. var rotMatrix = new BABYLON.Matrix();
  20255. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20256. rotQuaternion.toRotationMatrix(rotMatrix);
  20257. var translationDelta = BABYLON.Vector3.Zero();
  20258. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20259. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20260. return translationDelta;
  20261. };
  20262. // ================================== Point of View Rotation =================================
  20263. /**
  20264. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20265. * Supports definition of mesh facing forward or backward
  20266. * @param flipBack defines the flip
  20267. * @param twirlClockwise defines the twirl
  20268. * @param tiltRight defines the tilt
  20269. * @returns the current mesh
  20270. */
  20271. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20272. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20273. return this;
  20274. };
  20275. /**
  20276. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20277. * Supports definition of mesh facing forward or backward.
  20278. * @param flipBack defines the flip
  20279. * @param twirlClockwise defines the twirl
  20280. * @param tiltRight defines the tilt
  20281. * @returns the new rotation vector
  20282. */
  20283. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20284. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20285. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20286. };
  20287. /**
  20288. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20289. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20290. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20291. * @returns the new bounding vectors
  20292. */
  20293. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20294. if (includeDescendants === void 0) { includeDescendants = true; }
  20295. if (predicate === void 0) { predicate = null; }
  20296. // Ensures that all world matrix will be recomputed.
  20297. this.getScene().incrementRenderId();
  20298. this.computeWorldMatrix(true);
  20299. var min;
  20300. var max;
  20301. var boundingInfo = this.getBoundingInfo();
  20302. if (!this.subMeshes) {
  20303. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20304. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20305. }
  20306. else {
  20307. min = boundingInfo.boundingBox.minimumWorld;
  20308. max = boundingInfo.boundingBox.maximumWorld;
  20309. }
  20310. if (includeDescendants) {
  20311. var descendants = this.getDescendants(false);
  20312. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20313. var descendant = descendants_1[_i];
  20314. var childMesh = descendant;
  20315. childMesh.computeWorldMatrix(true);
  20316. // Filters meshes based on custom predicate function.
  20317. if (predicate && !predicate(childMesh)) {
  20318. continue;
  20319. }
  20320. //make sure we have the needed params to get mix and max
  20321. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20322. continue;
  20323. }
  20324. var childBoundingInfo = childMesh.getBoundingInfo();
  20325. var boundingBox = childBoundingInfo.boundingBox;
  20326. var minBox = boundingBox.minimumWorld;
  20327. var maxBox = boundingBox.maximumWorld;
  20328. BABYLON.Tools.CheckExtends(minBox, min, max);
  20329. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20330. }
  20331. }
  20332. return {
  20333. min: min,
  20334. max: max
  20335. };
  20336. };
  20337. /** @hidden */
  20338. AbstractMesh.prototype._updateBoundingInfo = function () {
  20339. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20340. this._boundingInfo.update(this.worldMatrixFromCache);
  20341. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20342. return this;
  20343. };
  20344. /** @hidden */
  20345. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20346. if (!this.subMeshes) {
  20347. return this;
  20348. }
  20349. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20350. var subMesh = this.subMeshes[subIndex];
  20351. if (!subMesh.IsGlobal) {
  20352. subMesh.updateBoundingInfo(matrix);
  20353. }
  20354. }
  20355. return this;
  20356. };
  20357. /** @hidden */
  20358. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20359. // Bounding info
  20360. this._updateBoundingInfo();
  20361. };
  20362. /**
  20363. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20364. * A mesh is in the frustum if its bounding box intersects the frustum
  20365. * @param frustumPlanes defines the frustum to test
  20366. * @returns true if the mesh is in the frustum planes
  20367. */
  20368. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20369. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20370. };
  20371. /**
  20372. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20373. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20374. * @param frustumPlanes defines the frustum to test
  20375. * @returns true if the mesh is completely in the frustum planes
  20376. */
  20377. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20378. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20379. };
  20380. /**
  20381. * True if the mesh intersects another mesh or a SolidParticle object
  20382. * @param mesh defines a target mesh or SolidParticle to test
  20383. * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  20384. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20385. * @returns true if there is an intersection
  20386. */
  20387. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20388. if (precise === void 0) { precise = false; }
  20389. if (!this._boundingInfo || !mesh._boundingInfo) {
  20390. return false;
  20391. }
  20392. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20393. return true;
  20394. }
  20395. if (includeDescendants) {
  20396. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20397. var child = _a[_i];
  20398. if (child.intersectsMesh(mesh, precise, true)) {
  20399. return true;
  20400. }
  20401. }
  20402. }
  20403. return false;
  20404. };
  20405. /**
  20406. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20407. * @param point defines the point to test
  20408. * @returns true if there is an intersection
  20409. */
  20410. AbstractMesh.prototype.intersectsPoint = function (point) {
  20411. if (!this._boundingInfo) {
  20412. return false;
  20413. }
  20414. return this._boundingInfo.intersectsPoint(point);
  20415. };
  20416. /**
  20417. * Gets the current physics impostor
  20418. * @see http://doc.babylonjs.com/features/physics_engine
  20419. * @returns a physics impostor or null
  20420. */
  20421. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20422. return this.physicsImpostor;
  20423. };
  20424. /**
  20425. * Gets the position of the current mesh in camera space
  20426. * @param camera defines the camera to use
  20427. * @returns a position
  20428. */
  20429. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20430. if (camera === void 0) { camera = null; }
  20431. if (!camera) {
  20432. camera = this.getScene().activeCamera;
  20433. }
  20434. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20435. };
  20436. /**
  20437. * Returns the distance from the mesh to the active camera
  20438. * @param camera defines the camera to use
  20439. * @returns the distance
  20440. */
  20441. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20442. if (camera === void 0) { camera = null; }
  20443. if (!camera) {
  20444. camera = this.getScene().activeCamera;
  20445. }
  20446. return this.absolutePosition.subtract(camera.position).length();
  20447. };
  20448. /**
  20449. * Apply a physic impulse to the mesh
  20450. * @param force defines the force to apply
  20451. * @param contactPoint defines where to apply the force
  20452. * @returns the current mesh
  20453. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20454. */
  20455. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20456. if (!this.physicsImpostor) {
  20457. return this;
  20458. }
  20459. this.physicsImpostor.applyImpulse(force, contactPoint);
  20460. return this;
  20461. };
  20462. /**
  20463. * Creates a physic joint between two meshes
  20464. * @param otherMesh defines the other mesh to use
  20465. * @param pivot1 defines the pivot to use on this mesh
  20466. * @param pivot2 defines the pivot to use on the other mesh
  20467. * @param options defines additional options (can be plugin dependent)
  20468. * @returns the current mesh
  20469. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20470. */
  20471. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20472. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20473. return this;
  20474. }
  20475. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20476. mainPivot: pivot1,
  20477. connectedPivot: pivot2,
  20478. nativeParams: options
  20479. });
  20480. return this;
  20481. };
  20482. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20483. // Collisions
  20484. /**
  20485. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20486. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20487. */
  20488. get: function () {
  20489. return this._checkCollisions;
  20490. },
  20491. set: function (collisionEnabled) {
  20492. this._checkCollisions = collisionEnabled;
  20493. if (this.getScene().workerCollisions) {
  20494. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20495. }
  20496. },
  20497. enumerable: true,
  20498. configurable: true
  20499. });
  20500. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20501. /**
  20502. * Gets Collider object used to compute collisions (not physics)
  20503. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20504. */
  20505. get: function () {
  20506. return this._collider;
  20507. },
  20508. enumerable: true,
  20509. configurable: true
  20510. });
  20511. /**
  20512. * Move the mesh using collision engine
  20513. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20514. * @param displacement defines the requested displacement vector
  20515. * @returns the current mesh
  20516. */
  20517. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20518. var globalPosition = this.getAbsolutePosition();
  20519. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20520. if (!this._collider) {
  20521. this._collider = new BABYLON.Collider();
  20522. }
  20523. this._collider._radius = this.ellipsoid;
  20524. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20525. return this;
  20526. };
  20527. // Submeshes octree
  20528. /**
  20529. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20530. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20531. * @param maxCapacity defines the maximum size of each block (64 by default)
  20532. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20533. * @returns the new octree
  20534. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20535. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20536. */
  20537. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20538. if (maxCapacity === void 0) { maxCapacity = 64; }
  20539. if (maxDepth === void 0) { maxDepth = 2; }
  20540. if (!this._submeshesOctree) {
  20541. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20542. }
  20543. this.computeWorldMatrix(true);
  20544. var boundingInfo = this.getBoundingInfo();
  20545. // Update octree
  20546. var bbox = boundingInfo.boundingBox;
  20547. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20548. return this._submeshesOctree;
  20549. };
  20550. // Collisions
  20551. /** @hidden */
  20552. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20553. this._generatePointsArray();
  20554. if (!this._positions) {
  20555. return this;
  20556. }
  20557. // Transformation
  20558. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20559. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20560. subMesh._lastColliderWorldVertices = [];
  20561. subMesh._trianglePlanes = [];
  20562. var start = subMesh.verticesStart;
  20563. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20564. for (var i = start; i < end; i++) {
  20565. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20566. }
  20567. }
  20568. // Collide
  20569. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20570. if (collider.collisionFound) {
  20571. collider.collidedMesh = this;
  20572. }
  20573. return this;
  20574. };
  20575. /** @hidden */
  20576. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20577. var subMeshes;
  20578. var len;
  20579. // Octrees
  20580. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20581. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20582. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20583. len = intersections.length;
  20584. subMeshes = intersections.data;
  20585. }
  20586. else {
  20587. subMeshes = this.subMeshes;
  20588. len = subMeshes.length;
  20589. }
  20590. for (var index = 0; index < len; index++) {
  20591. var subMesh = subMeshes[index];
  20592. // Bounding test
  20593. if (len > 1 && !subMesh._checkCollision(collider))
  20594. continue;
  20595. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20596. }
  20597. return this;
  20598. };
  20599. /** @hidden */
  20600. AbstractMesh.prototype._checkCollision = function (collider) {
  20601. // Bounding box test
  20602. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20603. return this;
  20604. // Transformation matrix
  20605. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20606. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20607. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20608. return this;
  20609. };
  20610. // Picking
  20611. /** @hidden */
  20612. AbstractMesh.prototype._generatePointsArray = function () {
  20613. return false;
  20614. };
  20615. /**
  20616. * Checks if the passed Ray intersects with the mesh
  20617. * @param ray defines the ray to use
  20618. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20619. * @returns the picking info
  20620. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20621. */
  20622. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20623. var pickingInfo = new BABYLON.PickingInfo();
  20624. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20625. return pickingInfo;
  20626. }
  20627. if (!this._generatePointsArray()) {
  20628. return pickingInfo;
  20629. }
  20630. var intersectInfo = null;
  20631. // Octrees
  20632. var subMeshes;
  20633. var len;
  20634. if (this._submeshesOctree && this.useOctreeForPicking) {
  20635. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20636. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20637. len = intersections.length;
  20638. subMeshes = intersections.data;
  20639. }
  20640. else {
  20641. subMeshes = this.subMeshes;
  20642. len = subMeshes.length;
  20643. }
  20644. for (var index = 0; index < len; index++) {
  20645. var subMesh = subMeshes[index];
  20646. // Bounding test
  20647. if (len > 1 && !subMesh.canIntersects(ray))
  20648. continue;
  20649. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20650. if (currentIntersectInfo) {
  20651. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20652. intersectInfo = currentIntersectInfo;
  20653. intersectInfo.subMeshId = index;
  20654. if (fastCheck) {
  20655. break;
  20656. }
  20657. }
  20658. }
  20659. }
  20660. if (intersectInfo) {
  20661. // Get picked point
  20662. var world = this.getWorldMatrix();
  20663. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20664. var direction = ray.direction.clone();
  20665. direction = direction.scale(intersectInfo.distance);
  20666. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20667. var pickedPoint = worldOrigin.add(worldDirection);
  20668. // Return result
  20669. pickingInfo.hit = true;
  20670. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20671. pickingInfo.pickedPoint = pickedPoint;
  20672. pickingInfo.pickedMesh = this;
  20673. pickingInfo.bu = intersectInfo.bu || 0;
  20674. pickingInfo.bv = intersectInfo.bv || 0;
  20675. pickingInfo.faceId = intersectInfo.faceId;
  20676. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20677. return pickingInfo;
  20678. }
  20679. return pickingInfo;
  20680. };
  20681. /**
  20682. * Clones the current mesh
  20683. * @param name defines the mesh name
  20684. * @param newParent defines the new mesh parent
  20685. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20686. * @returns the new mesh
  20687. */
  20688. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20689. return null;
  20690. };
  20691. /**
  20692. * Disposes all the submeshes of the current meshnp
  20693. * @returns the current mesh
  20694. */
  20695. AbstractMesh.prototype.releaseSubMeshes = function () {
  20696. if (this.subMeshes) {
  20697. while (this.subMeshes.length) {
  20698. this.subMeshes[0].dispose();
  20699. }
  20700. }
  20701. else {
  20702. this.subMeshes = new Array();
  20703. }
  20704. return this;
  20705. };
  20706. /**
  20707. * Releases resources associated with this abstract mesh.
  20708. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20709. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20710. */
  20711. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20712. var _this = this;
  20713. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20714. var index;
  20715. // Smart Array Retainers.
  20716. this.getScene().freeActiveMeshes();
  20717. this.getScene().freeRenderingGroups();
  20718. // Action manager
  20719. if (this.actionManager !== undefined && this.actionManager !== null) {
  20720. this.actionManager.dispose();
  20721. this.actionManager = null;
  20722. }
  20723. // Skeleton
  20724. this._skeleton = null;
  20725. // Physics
  20726. if (this.physicsImpostor) {
  20727. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20728. }
  20729. // Intersections in progress
  20730. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20731. var other = this._intersectionsInProgress[index];
  20732. var pos = other._intersectionsInProgress.indexOf(this);
  20733. other._intersectionsInProgress.splice(pos, 1);
  20734. }
  20735. this._intersectionsInProgress = [];
  20736. // Lights
  20737. var lights = this.getScene().lights;
  20738. lights.forEach(function (light) {
  20739. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20740. if (meshIndex !== -1) {
  20741. light.includedOnlyMeshes.splice(meshIndex, 1);
  20742. }
  20743. meshIndex = light.excludedMeshes.indexOf(_this);
  20744. if (meshIndex !== -1) {
  20745. light.excludedMeshes.splice(meshIndex, 1);
  20746. }
  20747. // Shadow generators
  20748. var generator = light.getShadowGenerator();
  20749. if (generator) {
  20750. var shadowMap = generator.getShadowMap();
  20751. if (shadowMap && shadowMap.renderList) {
  20752. meshIndex = shadowMap.renderList.indexOf(_this);
  20753. if (meshIndex !== -1) {
  20754. shadowMap.renderList.splice(meshIndex, 1);
  20755. }
  20756. }
  20757. }
  20758. });
  20759. // Edges
  20760. if (this._edgesRenderer) {
  20761. this._edgesRenderer.dispose();
  20762. this._edgesRenderer = null;
  20763. }
  20764. // SubMeshes
  20765. if (this.getClassName() !== "InstancedMesh") {
  20766. this.releaseSubMeshes();
  20767. }
  20768. // Octree
  20769. var sceneOctree = this.getScene().selectionOctree;
  20770. if (sceneOctree !== undefined && sceneOctree !== null) {
  20771. var index = sceneOctree.dynamicContent.indexOf(this);
  20772. if (index !== -1) {
  20773. sceneOctree.dynamicContent.splice(index, 1);
  20774. }
  20775. }
  20776. // Query
  20777. var engine = this.getScene().getEngine();
  20778. if (this._occlusionQuery) {
  20779. this._isOcclusionQueryInProgress = false;
  20780. engine.deleteQuery(this._occlusionQuery);
  20781. this._occlusionQuery = null;
  20782. }
  20783. // Engine
  20784. engine.wipeCaches();
  20785. // Remove from scene
  20786. this.getScene().removeMesh(this);
  20787. if (disposeMaterialAndTextures) {
  20788. if (this.material) {
  20789. this.material.dispose(false, true);
  20790. }
  20791. }
  20792. if (!doNotRecurse) {
  20793. // Particles
  20794. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20795. if (this.getScene().particleSystems[index].emitter === this) {
  20796. this.getScene().particleSystems[index].dispose();
  20797. index--;
  20798. }
  20799. }
  20800. }
  20801. // facet data
  20802. if (this._facetDataEnabled) {
  20803. this.disableFacetData();
  20804. }
  20805. this.onAfterWorldMatrixUpdateObservable.clear();
  20806. this.onCollideObservable.clear();
  20807. this.onCollisionPositionChangeObservable.clear();
  20808. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20809. };
  20810. /**
  20811. * Adds the passed mesh as a child to the current mesh
  20812. * @param mesh defines the child mesh
  20813. * @returns the current mesh
  20814. */
  20815. AbstractMesh.prototype.addChild = function (mesh) {
  20816. mesh.setParent(this);
  20817. return this;
  20818. };
  20819. /**
  20820. * Removes the passed mesh from the current mesh children list
  20821. * @param mesh defines the child mesh
  20822. * @returns the current mesh
  20823. */
  20824. AbstractMesh.prototype.removeChild = function (mesh) {
  20825. mesh.setParent(null);
  20826. return this;
  20827. };
  20828. // Facet data
  20829. /** @hidden */
  20830. AbstractMesh.prototype._initFacetData = function () {
  20831. if (!this._facetNormals) {
  20832. this._facetNormals = new Array();
  20833. }
  20834. if (!this._facetPositions) {
  20835. this._facetPositions = new Array();
  20836. }
  20837. if (!this._facetPartitioning) {
  20838. this._facetPartitioning = new Array();
  20839. }
  20840. this._facetNb = (this.getIndices().length / 3) | 0;
  20841. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20842. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20843. for (var f = 0; f < this._facetNb; f++) {
  20844. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20845. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20846. }
  20847. this._facetDataEnabled = true;
  20848. return this;
  20849. };
  20850. /**
  20851. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20852. * This method can be called within the render loop.
  20853. * 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
  20854. * @returns the current mesh
  20855. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20856. */
  20857. AbstractMesh.prototype.updateFacetData = function () {
  20858. if (!this._facetDataEnabled) {
  20859. this._initFacetData();
  20860. }
  20861. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20862. var indices = this.getIndices();
  20863. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20864. var bInfo = this.getBoundingInfo();
  20865. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20866. // init arrays, matrix and sort function on first call
  20867. this._facetDepthSortEnabled = true;
  20868. if (indices instanceof Uint16Array) {
  20869. this._depthSortedIndices = new Uint16Array(indices);
  20870. }
  20871. else if (indices instanceof Uint32Array) {
  20872. this._depthSortedIndices = new Uint32Array(indices);
  20873. }
  20874. else {
  20875. var needs32bits = false;
  20876. for (var i = 0; i < indices.length; i++) {
  20877. if (indices[i] > 65535) {
  20878. needs32bits = true;
  20879. break;
  20880. }
  20881. }
  20882. if (needs32bits) {
  20883. this._depthSortedIndices = new Uint32Array(indices);
  20884. }
  20885. else {
  20886. this._depthSortedIndices = new Uint16Array(indices);
  20887. }
  20888. }
  20889. this._facetDepthSortFunction = function (f1, f2) {
  20890. return (f2.sqDistance - f1.sqDistance);
  20891. };
  20892. if (!this._facetDepthSortFrom) {
  20893. var camera = this.getScene().activeCamera;
  20894. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20895. }
  20896. this._depthSortedFacets = [];
  20897. for (var f = 0; f < this._facetNb; f++) {
  20898. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20899. this._depthSortedFacets.push(depthSortedFacet);
  20900. }
  20901. this._invertedMatrix = BABYLON.Matrix.Identity();
  20902. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20903. }
  20904. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20905. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20906. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20907. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20908. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20909. this._subDiv.max = this._partitioningSubdivisions;
  20910. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20911. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20912. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20913. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20914. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20915. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20916. // set the parameters for ComputeNormals()
  20917. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20918. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20919. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20920. this._facetParameters.bInfo = bInfo;
  20921. this._facetParameters.bbSize = this._bbSize;
  20922. this._facetParameters.subDiv = this._subDiv;
  20923. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20924. this._facetParameters.depthSort = this._facetDepthSort;
  20925. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20926. this.computeWorldMatrix(true);
  20927. this._worldMatrix.invertToRef(this._invertedMatrix);
  20928. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20929. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20930. }
  20931. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20932. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20933. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20934. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20935. var l = (this._depthSortedIndices.length / 3) | 0;
  20936. for (var f = 0; f < l; f++) {
  20937. var sind = this._depthSortedFacets[f].ind;
  20938. this._depthSortedIndices[f * 3] = indices[sind];
  20939. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20940. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20941. }
  20942. this.updateIndices(this._depthSortedIndices);
  20943. }
  20944. return this;
  20945. };
  20946. /**
  20947. * Returns the facetLocalNormals array.
  20948. * The normals are expressed in the mesh local spac
  20949. * @returns an array of Vector3
  20950. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20951. */
  20952. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20953. if (!this._facetNormals) {
  20954. this.updateFacetData();
  20955. }
  20956. return this._facetNormals;
  20957. };
  20958. /**
  20959. * Returns the facetLocalPositions array.
  20960. * The facet positions are expressed in the mesh local space
  20961. * @returns an array of Vector3
  20962. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20963. */
  20964. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20965. if (!this._facetPositions) {
  20966. this.updateFacetData();
  20967. }
  20968. return this._facetPositions;
  20969. };
  20970. /**
  20971. * Returns the facetLocalPartioning array
  20972. * @returns an array of array of numbers
  20973. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20974. */
  20975. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20976. if (!this._facetPartitioning) {
  20977. this.updateFacetData();
  20978. }
  20979. return this._facetPartitioning;
  20980. };
  20981. /**
  20982. * Returns the i-th facet position in the world system.
  20983. * This method allocates a new Vector3 per call
  20984. * @param i defines the facet index
  20985. * @returns a new Vector3
  20986. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20987. */
  20988. AbstractMesh.prototype.getFacetPosition = function (i) {
  20989. var pos = BABYLON.Vector3.Zero();
  20990. this.getFacetPositionToRef(i, pos);
  20991. return pos;
  20992. };
  20993. /**
  20994. * Sets the reference Vector3 with the i-th facet position in the world system
  20995. * @param i defines the facet index
  20996. * @param ref defines the target vector
  20997. * @returns the current mesh
  20998. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20999. */
  21000. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21001. var localPos = (this.getFacetLocalPositions())[i];
  21002. var world = this.getWorldMatrix();
  21003. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21004. return this;
  21005. };
  21006. /**
  21007. * Returns the i-th facet normal in the world system.
  21008. * This method allocates a new Vector3 per call
  21009. * @param i defines the facet index
  21010. * @returns a new Vector3
  21011. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21012. */
  21013. AbstractMesh.prototype.getFacetNormal = function (i) {
  21014. var norm = BABYLON.Vector3.Zero();
  21015. this.getFacetNormalToRef(i, norm);
  21016. return norm;
  21017. };
  21018. /**
  21019. * Sets the reference Vector3 with the i-th facet normal in the world system
  21020. * @param i defines the facet index
  21021. * @param ref defines the target vector
  21022. * @returns the current mesh
  21023. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21024. */
  21025. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21026. var localNorm = (this.getFacetLocalNormals())[i];
  21027. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21028. return this;
  21029. };
  21030. /**
  21031. * 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)
  21032. * @param x defines x coordinate
  21033. * @param y defines y coordinate
  21034. * @param z defines z coordinate
  21035. * @returns the array of facet indexes
  21036. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21037. */
  21038. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21039. var bInfo = this.getBoundingInfo();
  21040. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21041. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21042. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21043. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21044. return null;
  21045. }
  21046. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21047. };
  21048. /**
  21049. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21050. * @param projected sets as the (x,y,z) world projection on the facet
  21051. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21052. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21053. * @param x defines x coordinate
  21054. * @param y defines y coordinate
  21055. * @param z defines z coordinate
  21056. * @returns the face index if found (or null instead)
  21057. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21058. */
  21059. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21060. if (checkFace === void 0) { checkFace = false; }
  21061. if (facing === void 0) { facing = true; }
  21062. var world = this.getWorldMatrix();
  21063. var invMat = BABYLON.Tmp.Matrix[5];
  21064. world.invertToRef(invMat);
  21065. var invVect = BABYLON.Tmp.Vector3[8];
  21066. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21067. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21068. if (projected) {
  21069. // tranform the local computed projected vector to world coordinates
  21070. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21071. }
  21072. return closest;
  21073. };
  21074. /**
  21075. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21076. * @param projected sets as the (x,y,z) local projection on the facet
  21077. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21078. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21079. * @param x defines x coordinate
  21080. * @param y defines y coordinate
  21081. * @param z defines z coordinate
  21082. * @returns the face index if found (or null instead)
  21083. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21084. */
  21085. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21086. if (checkFace === void 0) { checkFace = false; }
  21087. if (facing === void 0) { facing = true; }
  21088. var closest = null;
  21089. var tmpx = 0.0;
  21090. var tmpy = 0.0;
  21091. var tmpz = 0.0;
  21092. var d = 0.0; // tmp dot facet normal * facet position
  21093. var t0 = 0.0;
  21094. var projx = 0.0;
  21095. var projy = 0.0;
  21096. var projz = 0.0;
  21097. // Get all the facets in the same partitioning block than (x, y, z)
  21098. var facetPositions = this.getFacetLocalPositions();
  21099. var facetNormals = this.getFacetLocalNormals();
  21100. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21101. if (!facetsInBlock) {
  21102. return null;
  21103. }
  21104. // Get the closest facet to (x, y, z)
  21105. var shortest = Number.MAX_VALUE; // init distance vars
  21106. var tmpDistance = shortest;
  21107. var fib; // current facet in the block
  21108. var norm; // current facet normal
  21109. var p0; // current facet barycenter position
  21110. // loop on all the facets in the current partitioning block
  21111. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21112. fib = facetsInBlock[idx];
  21113. norm = facetNormals[fib];
  21114. p0 = facetPositions[fib];
  21115. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21116. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21117. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21118. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21119. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21120. projx = x + norm.x * t0;
  21121. projy = y + norm.y * t0;
  21122. projz = z + norm.z * t0;
  21123. tmpx = projx - x;
  21124. tmpy = projy - y;
  21125. tmpz = projz - z;
  21126. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21127. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21128. shortest = tmpDistance;
  21129. closest = fib;
  21130. if (projected) {
  21131. projected.x = projx;
  21132. projected.y = projy;
  21133. projected.z = projz;
  21134. }
  21135. }
  21136. }
  21137. }
  21138. return closest;
  21139. };
  21140. /**
  21141. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21142. * @returns the parameters
  21143. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21144. */
  21145. AbstractMesh.prototype.getFacetDataParameters = function () {
  21146. return this._facetParameters;
  21147. };
  21148. /**
  21149. * Disables the feature FacetData and frees the related memory
  21150. * @returns the current mesh
  21151. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21152. */
  21153. AbstractMesh.prototype.disableFacetData = function () {
  21154. if (this._facetDataEnabled) {
  21155. this._facetDataEnabled = false;
  21156. this._facetPositions = new Array();
  21157. this._facetNormals = new Array();
  21158. this._facetPartitioning = new Array();
  21159. this._facetParameters = null;
  21160. this._depthSortedIndices = new Uint32Array(0);
  21161. }
  21162. return this;
  21163. };
  21164. /**
  21165. * Updates the AbstractMesh indices array
  21166. * @param indices defines the data source
  21167. * @returns the current mesh
  21168. */
  21169. AbstractMesh.prototype.updateIndices = function (indices) {
  21170. return this;
  21171. };
  21172. /**
  21173. * Creates new normals data for the mesh
  21174. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21175. * @returns the current mesh
  21176. */
  21177. AbstractMesh.prototype.createNormals = function (updatable) {
  21178. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21179. var indices = this.getIndices();
  21180. var normals;
  21181. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21182. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21183. }
  21184. else {
  21185. normals = [];
  21186. }
  21187. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21188. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21189. return this;
  21190. };
  21191. /**
  21192. * Align the mesh with a normal
  21193. * @param normal defines the normal to use
  21194. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21195. * @returns the current mesh
  21196. */
  21197. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21198. if (!upDirection) {
  21199. upDirection = BABYLON.Axis.Y;
  21200. }
  21201. var axisX = BABYLON.Tmp.Vector3[0];
  21202. var axisZ = BABYLON.Tmp.Vector3[1];
  21203. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21204. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21205. if (this.rotationQuaternion) {
  21206. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21207. }
  21208. else {
  21209. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21210. }
  21211. return this;
  21212. };
  21213. /** @hidden */
  21214. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21215. var engine = this.getEngine();
  21216. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21217. this._isOccluded = false;
  21218. return;
  21219. }
  21220. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21221. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21222. if (isOcclusionQueryAvailable) {
  21223. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21224. this._isOcclusionQueryInProgress = false;
  21225. this._occlusionInternalRetryCounter = 0;
  21226. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21227. }
  21228. else {
  21229. this._occlusionInternalRetryCounter++;
  21230. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21231. this._isOcclusionQueryInProgress = false;
  21232. this._occlusionInternalRetryCounter = 0;
  21233. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21234. // if strict continue the last state of the object.
  21235. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21236. }
  21237. else {
  21238. return;
  21239. }
  21240. }
  21241. }
  21242. var scene = this.getScene();
  21243. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21244. if (!this._occlusionQuery) {
  21245. this._occlusionQuery = engine.createQuery();
  21246. }
  21247. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21248. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21249. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21250. this._isOcclusionQueryInProgress = true;
  21251. };
  21252. /** No occlusion */
  21253. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21254. /** Occlusion set to optimisitic */
  21255. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21256. /** Occlusion set to strict */
  21257. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21258. /** Use an accurante occlusion algorithm */
  21259. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21260. /** Use a conservative occlusion algorithm */
  21261. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21262. return AbstractMesh;
  21263. }(BABYLON.TransformNode));
  21264. BABYLON.AbstractMesh = AbstractMesh;
  21265. })(BABYLON || (BABYLON = {}));
  21266. //# sourceMappingURL=babylon.abstractMesh.js.map
  21267. var BABYLON;
  21268. (function (BABYLON) {
  21269. /**
  21270. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21271. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21272. * 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.
  21273. */
  21274. var Light = /** @class */ (function (_super) {
  21275. __extends(Light, _super);
  21276. /**
  21277. * Creates a Light object in the scene.
  21278. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21279. * @param name The firendly name of the light
  21280. * @param scene The scene the light belongs too
  21281. */
  21282. function Light(name, scene) {
  21283. var _this = _super.call(this, name, scene) || this;
  21284. /**
  21285. * Diffuse gives the basic color to an object.
  21286. */
  21287. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21288. /**
  21289. * Specular produces a highlight color on an object.
  21290. * Note: This is note affecting PBR materials.
  21291. */
  21292. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21293. /**
  21294. * Strength of the light.
  21295. * Note: By default it is define in the framework own unit.
  21296. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21297. */
  21298. _this.intensity = 1.0;
  21299. /**
  21300. * Defines how far from the source the light is impacting in scene units.
  21301. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21302. */
  21303. _this.range = Number.MAX_VALUE;
  21304. /**
  21305. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21306. * of light.
  21307. */
  21308. _this._photometricScale = 1.0;
  21309. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21310. _this._radius = 0.00001;
  21311. /**
  21312. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21313. * exceeding the number allowed of the materials.
  21314. */
  21315. _this.renderPriority = 0;
  21316. _this._shadowEnabled = true;
  21317. _this._excludeWithLayerMask = 0;
  21318. _this._includeOnlyWithLayerMask = 0;
  21319. _this._lightmapMode = 0;
  21320. /**
  21321. * @hidden Internal use only.
  21322. */
  21323. _this._excludedMeshesIds = new Array();
  21324. /**
  21325. * @hidden Internal use only.
  21326. */
  21327. _this._includedOnlyMeshesIds = new Array();
  21328. _this.getScene().addLight(_this);
  21329. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21330. _this._buildUniformLayout();
  21331. _this.includedOnlyMeshes = new Array();
  21332. _this.excludedMeshes = new Array();
  21333. _this._resyncMeshes();
  21334. return _this;
  21335. }
  21336. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21337. /**
  21338. * If every light affecting the material is in this lightmapMode,
  21339. * material.lightmapTexture adds or multiplies
  21340. * (depends on material.useLightmapAsShadowmap)
  21341. * after every other light calculations.
  21342. */
  21343. get: function () {
  21344. return Light._LIGHTMAP_DEFAULT;
  21345. },
  21346. enumerable: true,
  21347. configurable: true
  21348. });
  21349. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21350. /**
  21351. * material.lightmapTexture as only diffuse lighting from this light
  21352. * adds only specular lighting from this light
  21353. * adds dynamic shadows
  21354. */
  21355. get: function () {
  21356. return Light._LIGHTMAP_SPECULAR;
  21357. },
  21358. enumerable: true,
  21359. configurable: true
  21360. });
  21361. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21362. /**
  21363. * material.lightmapTexture as only lighting
  21364. * no light calculation from this light
  21365. * only adds dynamic shadows from this light
  21366. */
  21367. get: function () {
  21368. return Light._LIGHTMAP_SHADOWSONLY;
  21369. },
  21370. enumerable: true,
  21371. configurable: true
  21372. });
  21373. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21374. /**
  21375. * Each light type uses the default quantity according to its type:
  21376. * point/spot lights use luminous intensity
  21377. * directional lights use illuminance
  21378. */
  21379. get: function () {
  21380. return Light._INTENSITYMODE_AUTOMATIC;
  21381. },
  21382. enumerable: true,
  21383. configurable: true
  21384. });
  21385. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21386. /**
  21387. * lumen (lm)
  21388. */
  21389. get: function () {
  21390. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21391. },
  21392. enumerable: true,
  21393. configurable: true
  21394. });
  21395. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21396. /**
  21397. * candela (lm/sr)
  21398. */
  21399. get: function () {
  21400. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21401. },
  21402. enumerable: true,
  21403. configurable: true
  21404. });
  21405. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21406. /**
  21407. * lux (lm/m^2)
  21408. */
  21409. get: function () {
  21410. return Light._INTENSITYMODE_ILLUMINANCE;
  21411. },
  21412. enumerable: true,
  21413. configurable: true
  21414. });
  21415. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21416. /**
  21417. * nit (cd/m^2)
  21418. */
  21419. get: function () {
  21420. return Light._INTENSITYMODE_LUMINANCE;
  21421. },
  21422. enumerable: true,
  21423. configurable: true
  21424. });
  21425. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21426. /**
  21427. * Light type const id of the point light.
  21428. */
  21429. get: function () {
  21430. return Light._LIGHTTYPEID_POINTLIGHT;
  21431. },
  21432. enumerable: true,
  21433. configurable: true
  21434. });
  21435. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21436. /**
  21437. * Light type const id of the directional light.
  21438. */
  21439. get: function () {
  21440. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21441. },
  21442. enumerable: true,
  21443. configurable: true
  21444. });
  21445. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21446. /**
  21447. * Light type const id of the spot light.
  21448. */
  21449. get: function () {
  21450. return Light._LIGHTTYPEID_SPOTLIGHT;
  21451. },
  21452. enumerable: true,
  21453. configurable: true
  21454. });
  21455. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21456. /**
  21457. * Light type const id of the hemispheric light.
  21458. */
  21459. get: function () {
  21460. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21461. },
  21462. enumerable: true,
  21463. configurable: true
  21464. });
  21465. Object.defineProperty(Light.prototype, "intensityMode", {
  21466. /**
  21467. * Gets the photometric scale used to interpret the intensity.
  21468. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21469. */
  21470. get: function () {
  21471. return this._intensityMode;
  21472. },
  21473. /**
  21474. * Sets the photometric scale used to interpret the intensity.
  21475. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21476. */
  21477. set: function (value) {
  21478. this._intensityMode = value;
  21479. this._computePhotometricScale();
  21480. },
  21481. enumerable: true,
  21482. configurable: true
  21483. });
  21484. ;
  21485. ;
  21486. Object.defineProperty(Light.prototype, "radius", {
  21487. /**
  21488. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21489. */
  21490. get: function () {
  21491. return this._radius;
  21492. },
  21493. /**
  21494. * sets the light radius used by PBR Materials to simulate soft area lights.
  21495. */
  21496. set: function (value) {
  21497. this._radius = value;
  21498. this._computePhotometricScale();
  21499. },
  21500. enumerable: true,
  21501. configurable: true
  21502. });
  21503. ;
  21504. ;
  21505. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21506. /**
  21507. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21508. * the current shadow generator.
  21509. */
  21510. get: function () {
  21511. return this._shadowEnabled;
  21512. },
  21513. /**
  21514. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21515. * the current shadow generator.
  21516. */
  21517. set: function (value) {
  21518. if (this._shadowEnabled === value) {
  21519. return;
  21520. }
  21521. this._shadowEnabled = value;
  21522. this._markMeshesAsLightDirty();
  21523. },
  21524. enumerable: true,
  21525. configurable: true
  21526. });
  21527. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21528. /**
  21529. * Gets the only meshes impacted by this light.
  21530. */
  21531. get: function () {
  21532. return this._includedOnlyMeshes;
  21533. },
  21534. /**
  21535. * Sets the only meshes impacted by this light.
  21536. */
  21537. set: function (value) {
  21538. this._includedOnlyMeshes = value;
  21539. this._hookArrayForIncludedOnly(value);
  21540. },
  21541. enumerable: true,
  21542. configurable: true
  21543. });
  21544. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21545. /**
  21546. * Gets the meshes not impacted by this light.
  21547. */
  21548. get: function () {
  21549. return this._excludedMeshes;
  21550. },
  21551. /**
  21552. * Sets the meshes not impacted by this light.
  21553. */
  21554. set: function (value) {
  21555. this._excludedMeshes = value;
  21556. this._hookArrayForExcluded(value);
  21557. },
  21558. enumerable: true,
  21559. configurable: true
  21560. });
  21561. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21562. /**
  21563. * Gets the layer id use to find what meshes are not impacted by the light.
  21564. * Inactive if 0
  21565. */
  21566. get: function () {
  21567. return this._excludeWithLayerMask;
  21568. },
  21569. /**
  21570. * Sets the layer id use to find what meshes are not impacted by the light.
  21571. * Inactive if 0
  21572. */
  21573. set: function (value) {
  21574. this._excludeWithLayerMask = value;
  21575. this._resyncMeshes();
  21576. },
  21577. enumerable: true,
  21578. configurable: true
  21579. });
  21580. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21581. /**
  21582. * Gets the layer id use to find what meshes are impacted by the light.
  21583. * Inactive if 0
  21584. */
  21585. get: function () {
  21586. return this._includeOnlyWithLayerMask;
  21587. },
  21588. /**
  21589. * Sets the layer id use to find what meshes are impacted by the light.
  21590. * Inactive if 0
  21591. */
  21592. set: function (value) {
  21593. this._includeOnlyWithLayerMask = value;
  21594. this._resyncMeshes();
  21595. },
  21596. enumerable: true,
  21597. configurable: true
  21598. });
  21599. Object.defineProperty(Light.prototype, "lightmapMode", {
  21600. /**
  21601. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21602. */
  21603. get: function () {
  21604. return this._lightmapMode;
  21605. },
  21606. /**
  21607. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21608. */
  21609. set: function (value) {
  21610. if (this._lightmapMode === value) {
  21611. return;
  21612. }
  21613. this._lightmapMode = value;
  21614. this._markMeshesAsLightDirty();
  21615. },
  21616. enumerable: true,
  21617. configurable: true
  21618. });
  21619. /**
  21620. * Returns the string "Light".
  21621. * @returns the class name
  21622. */
  21623. Light.prototype.getClassName = function () {
  21624. return "Light";
  21625. };
  21626. /**
  21627. * Converts the light information to a readable string for debug purpose.
  21628. * @param fullDetails Supports for multiple levels of logging within scene loading
  21629. * @returns the human readable light info
  21630. */
  21631. Light.prototype.toString = function (fullDetails) {
  21632. var ret = "Name: " + this.name;
  21633. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21634. if (this.animations) {
  21635. for (var i = 0; i < this.animations.length; i++) {
  21636. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21637. }
  21638. }
  21639. if (fullDetails) {
  21640. }
  21641. return ret;
  21642. };
  21643. /**
  21644. * Set the enabled state of this node.
  21645. * @param value - the new enabled state
  21646. */
  21647. Light.prototype.setEnabled = function (value) {
  21648. _super.prototype.setEnabled.call(this, value);
  21649. this._resyncMeshes();
  21650. };
  21651. /**
  21652. * Returns the Light associated shadow generator if any.
  21653. * @return the associated shadow generator.
  21654. */
  21655. Light.prototype.getShadowGenerator = function () {
  21656. return this._shadowGenerator;
  21657. };
  21658. /**
  21659. * Returns a Vector3, the absolute light position in the World.
  21660. * @returns the world space position of the light
  21661. */
  21662. Light.prototype.getAbsolutePosition = function () {
  21663. return BABYLON.Vector3.Zero();
  21664. };
  21665. /**
  21666. * Specifies if the light will affect the passed mesh.
  21667. * @param mesh The mesh to test against the light
  21668. * @return true the mesh is affected otherwise, false.
  21669. */
  21670. Light.prototype.canAffectMesh = function (mesh) {
  21671. if (!mesh) {
  21672. return true;
  21673. }
  21674. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21675. return false;
  21676. }
  21677. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21678. return false;
  21679. }
  21680. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21681. return false;
  21682. }
  21683. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21684. return false;
  21685. }
  21686. return true;
  21687. };
  21688. /**
  21689. * Computes and Returns the light World matrix.
  21690. * @returns the world matrix
  21691. */
  21692. Light.prototype.getWorldMatrix = function () {
  21693. this._currentRenderId = this.getScene().getRenderId();
  21694. this._childRenderId = this._currentRenderId;
  21695. var worldMatrix = this._getWorldMatrix();
  21696. if (this.parent && this.parent.getWorldMatrix) {
  21697. if (!this._parentedWorldMatrix) {
  21698. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21699. }
  21700. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21701. this._markSyncedWithParent();
  21702. return this._parentedWorldMatrix;
  21703. }
  21704. return worldMatrix;
  21705. };
  21706. /**
  21707. * Sort function to order lights for rendering.
  21708. * @param a First Light object to compare to second.
  21709. * @param b Second Light object to compare first.
  21710. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21711. */
  21712. Light.CompareLightsPriority = function (a, b) {
  21713. //shadow-casting lights have priority over non-shadow-casting lights
  21714. //the renderPrioirty is a secondary sort criterion
  21715. if (a.shadowEnabled !== b.shadowEnabled) {
  21716. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21717. }
  21718. return b.renderPriority - a.renderPriority;
  21719. };
  21720. /**
  21721. * Releases resources associated with this node.
  21722. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21723. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21724. */
  21725. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21726. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21727. if (this._shadowGenerator) {
  21728. this._shadowGenerator.dispose();
  21729. this._shadowGenerator = null;
  21730. }
  21731. // Animations
  21732. this.getScene().stopAnimation(this);
  21733. // Remove from meshes
  21734. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21735. var mesh = _a[_i];
  21736. mesh._removeLightSource(this);
  21737. }
  21738. this._uniformBuffer.dispose();
  21739. // Remove from scene
  21740. this.getScene().removeLight(this);
  21741. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21742. };
  21743. /**
  21744. * Returns the light type ID (integer).
  21745. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21746. */
  21747. Light.prototype.getTypeID = function () {
  21748. return 0;
  21749. };
  21750. /**
  21751. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21752. * @returns the scaled intensity in intensity mode unit
  21753. */
  21754. Light.prototype.getScaledIntensity = function () {
  21755. return this._photometricScale * this.intensity;
  21756. };
  21757. /**
  21758. * Returns a new Light object, named "name", from the current one.
  21759. * @param name The name of the cloned light
  21760. * @returns the new created light
  21761. */
  21762. Light.prototype.clone = function (name) {
  21763. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21764. if (!constructor) {
  21765. return null;
  21766. }
  21767. return BABYLON.SerializationHelper.Clone(constructor, this);
  21768. };
  21769. /**
  21770. * Serializes the current light into a Serialization object.
  21771. * @returns the serialized object.
  21772. */
  21773. Light.prototype.serialize = function () {
  21774. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21775. // Type
  21776. serializationObject.type = this.getTypeID();
  21777. // Parent
  21778. if (this.parent) {
  21779. serializationObject.parentId = this.parent.id;
  21780. }
  21781. // Inclusion / exclusions
  21782. if (this.excludedMeshes.length > 0) {
  21783. serializationObject.excludedMeshesIds = [];
  21784. this.excludedMeshes.forEach(function (mesh) {
  21785. serializationObject.excludedMeshesIds.push(mesh.id);
  21786. });
  21787. }
  21788. if (this.includedOnlyMeshes.length > 0) {
  21789. serializationObject.includedOnlyMeshesIds = [];
  21790. this.includedOnlyMeshes.forEach(function (mesh) {
  21791. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21792. });
  21793. }
  21794. // Animations
  21795. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21796. serializationObject.ranges = this.serializeAnimationRanges();
  21797. return serializationObject;
  21798. };
  21799. /**
  21800. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21801. * This new light is named "name" and added to the passed scene.
  21802. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21803. * @param name The friendly name of the light
  21804. * @param scene The scene the new light will belong to
  21805. * @returns the constructor function
  21806. */
  21807. Light.GetConstructorFromName = function (type, name, scene) {
  21808. switch (type) {
  21809. case 0:
  21810. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21811. case 1:
  21812. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21813. case 2:
  21814. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21815. case 3:
  21816. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21817. }
  21818. return null;
  21819. };
  21820. /**
  21821. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21822. * @param parsedLight The JSON representation of the light
  21823. * @param scene The scene to create the parsed light in
  21824. * @returns the created light after parsing
  21825. */
  21826. Light.Parse = function (parsedLight, scene) {
  21827. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21828. if (!constructor) {
  21829. return null;
  21830. }
  21831. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21832. // Inclusion / exclusions
  21833. if (parsedLight.excludedMeshesIds) {
  21834. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21835. }
  21836. if (parsedLight.includedOnlyMeshesIds) {
  21837. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21838. }
  21839. // Parent
  21840. if (parsedLight.parentId) {
  21841. light._waitingParentId = parsedLight.parentId;
  21842. }
  21843. // Animations
  21844. if (parsedLight.animations) {
  21845. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21846. var parsedAnimation = parsedLight.animations[animationIndex];
  21847. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21848. }
  21849. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21850. }
  21851. if (parsedLight.autoAnimate) {
  21852. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21853. }
  21854. return light;
  21855. };
  21856. Light.prototype._hookArrayForExcluded = function (array) {
  21857. var _this = this;
  21858. var oldPush = array.push;
  21859. array.push = function () {
  21860. var items = [];
  21861. for (var _i = 0; _i < arguments.length; _i++) {
  21862. items[_i] = arguments[_i];
  21863. }
  21864. var result = oldPush.apply(array, items);
  21865. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21866. var item = items_1[_a];
  21867. item._resyncLighSource(_this);
  21868. }
  21869. return result;
  21870. };
  21871. var oldSplice = array.splice;
  21872. array.splice = function (index, deleteCount) {
  21873. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21874. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21875. var item = deleted_1[_i];
  21876. item._resyncLighSource(_this);
  21877. }
  21878. return deleted;
  21879. };
  21880. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21881. var item = array_1[_i];
  21882. item._resyncLighSource(this);
  21883. }
  21884. };
  21885. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21886. var _this = this;
  21887. var oldPush = array.push;
  21888. array.push = function () {
  21889. var items = [];
  21890. for (var _i = 0; _i < arguments.length; _i++) {
  21891. items[_i] = arguments[_i];
  21892. }
  21893. var result = oldPush.apply(array, items);
  21894. _this._resyncMeshes();
  21895. return result;
  21896. };
  21897. var oldSplice = array.splice;
  21898. array.splice = function (index, deleteCount) {
  21899. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21900. _this._resyncMeshes();
  21901. return deleted;
  21902. };
  21903. this._resyncMeshes();
  21904. };
  21905. Light.prototype._resyncMeshes = function () {
  21906. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21907. var mesh = _a[_i];
  21908. mesh._resyncLighSource(this);
  21909. }
  21910. };
  21911. /**
  21912. * Forces the meshes to update their light related information in their rendering used effects
  21913. * @hidden Internal Use Only
  21914. */
  21915. Light.prototype._markMeshesAsLightDirty = function () {
  21916. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21917. var mesh = _a[_i];
  21918. if (mesh._lightSources.indexOf(this) !== -1) {
  21919. mesh._markSubMeshesAsLightDirty();
  21920. }
  21921. }
  21922. };
  21923. /**
  21924. * Recomputes the cached photometric scale if needed.
  21925. */
  21926. Light.prototype._computePhotometricScale = function () {
  21927. this._photometricScale = this._getPhotometricScale();
  21928. this.getScene().resetCachedMaterial();
  21929. };
  21930. /**
  21931. * Returns the Photometric Scale according to the light type and intensity mode.
  21932. */
  21933. Light.prototype._getPhotometricScale = function () {
  21934. var photometricScale = 0.0;
  21935. var lightTypeID = this.getTypeID();
  21936. //get photometric mode
  21937. var photometricMode = this.intensityMode;
  21938. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21939. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21940. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21941. }
  21942. else {
  21943. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21944. }
  21945. }
  21946. //compute photometric scale
  21947. switch (lightTypeID) {
  21948. case Light.LIGHTTYPEID_POINTLIGHT:
  21949. case Light.LIGHTTYPEID_SPOTLIGHT:
  21950. switch (photometricMode) {
  21951. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21952. photometricScale = 1.0 / (4.0 * Math.PI);
  21953. break;
  21954. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21955. photometricScale = 1.0;
  21956. break;
  21957. case Light.INTENSITYMODE_LUMINANCE:
  21958. photometricScale = this.radius * this.radius;
  21959. break;
  21960. }
  21961. break;
  21962. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21963. switch (photometricMode) {
  21964. case Light.INTENSITYMODE_ILLUMINANCE:
  21965. photometricScale = 1.0;
  21966. break;
  21967. case Light.INTENSITYMODE_LUMINANCE:
  21968. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21969. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21970. var apexAngleRadians = this.radius;
  21971. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21972. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21973. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21974. photometricScale = solidAngle;
  21975. break;
  21976. }
  21977. break;
  21978. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21979. // No fall off in hemisperic light.
  21980. photometricScale = 1.0;
  21981. break;
  21982. }
  21983. return photometricScale;
  21984. };
  21985. /**
  21986. * Reorder the light in the scene according to their defined priority.
  21987. * @hidden Internal Use Only
  21988. */
  21989. Light.prototype._reorderLightsInScene = function () {
  21990. var scene = this.getScene();
  21991. if (this._renderPriority != 0) {
  21992. scene.requireLightSorting = true;
  21993. }
  21994. this.getScene().sortLightsByPriority();
  21995. };
  21996. //lightmapMode Consts
  21997. Light._LIGHTMAP_DEFAULT = 0;
  21998. Light._LIGHTMAP_SPECULAR = 1;
  21999. Light._LIGHTMAP_SHADOWSONLY = 2;
  22000. // Intensity Mode Consts
  22001. Light._INTENSITYMODE_AUTOMATIC = 0;
  22002. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22003. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22004. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22005. Light._INTENSITYMODE_LUMINANCE = 4;
  22006. // Light types ids const.
  22007. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22008. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22009. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22010. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22011. __decorate([
  22012. BABYLON.serializeAsColor3()
  22013. ], Light.prototype, "diffuse", void 0);
  22014. __decorate([
  22015. BABYLON.serializeAsColor3()
  22016. ], Light.prototype, "specular", void 0);
  22017. __decorate([
  22018. BABYLON.serialize()
  22019. ], Light.prototype, "intensity", void 0);
  22020. __decorate([
  22021. BABYLON.serialize()
  22022. ], Light.prototype, "range", void 0);
  22023. __decorate([
  22024. BABYLON.serialize()
  22025. ], Light.prototype, "intensityMode", null);
  22026. __decorate([
  22027. BABYLON.serialize()
  22028. ], Light.prototype, "radius", null);
  22029. __decorate([
  22030. BABYLON.serialize()
  22031. ], Light.prototype, "_renderPriority", void 0);
  22032. __decorate([
  22033. BABYLON.expandToProperty("_reorderLightsInScene")
  22034. ], Light.prototype, "renderPriority", void 0);
  22035. __decorate([
  22036. BABYLON.serialize("shadowEnabled")
  22037. ], Light.prototype, "_shadowEnabled", void 0);
  22038. __decorate([
  22039. BABYLON.serialize("excludeWithLayerMask")
  22040. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22041. __decorate([
  22042. BABYLON.serialize("includeOnlyWithLayerMask")
  22043. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22044. __decorate([
  22045. BABYLON.serialize("lightmapMode")
  22046. ], Light.prototype, "_lightmapMode", void 0);
  22047. return Light;
  22048. }(BABYLON.Node));
  22049. BABYLON.Light = Light;
  22050. })(BABYLON || (BABYLON = {}));
  22051. //# sourceMappingURL=babylon.light.js.map
  22052. var BABYLON;
  22053. (function (BABYLON) {
  22054. var Camera = /** @class */ (function (_super) {
  22055. __extends(Camera, _super);
  22056. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22057. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22058. var _this = _super.call(this, name, scene) || this;
  22059. /**
  22060. * The vector the camera should consider as up.
  22061. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22062. */
  22063. _this.upVector = BABYLON.Vector3.Up();
  22064. _this.orthoLeft = null;
  22065. _this.orthoRight = null;
  22066. _this.orthoBottom = null;
  22067. _this.orthoTop = null;
  22068. /**
  22069. * FOV is set in Radians. (default is 0.8)
  22070. */
  22071. _this.fov = 0.8;
  22072. _this.minZ = 1;
  22073. _this.maxZ = 10000.0;
  22074. _this.inertia = 0.9;
  22075. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22076. _this.isIntermediate = false;
  22077. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22078. /**
  22079. * Restricts the camera to viewing objects with the same layerMask.
  22080. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22081. */
  22082. _this.layerMask = 0x0FFFFFFF;
  22083. /**
  22084. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22085. */
  22086. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22087. // Camera rig members
  22088. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22089. _this._rigCameras = new Array();
  22090. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22091. _this._skipRendering = false;
  22092. _this.customRenderTargets = new Array();
  22093. // Observables
  22094. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22095. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22096. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22097. _this.onRestoreStateObservable = new BABYLON.Observable();
  22098. // Cache
  22099. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22100. _this._projectionMatrix = new BABYLON.Matrix();
  22101. _this._doNotComputeProjectionMatrix = false;
  22102. _this._worldMatrix = BABYLON.Matrix.Identity();
  22103. _this._postProcesses = new Array();
  22104. _this._transformMatrix = BABYLON.Matrix.Zero();
  22105. _this._activeMeshes = new BABYLON.SmartArray(256);
  22106. _this._globalPosition = BABYLON.Vector3.Zero();
  22107. _this._refreshFrustumPlanes = true;
  22108. _this.getScene().addCamera(_this);
  22109. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22110. _this.getScene().activeCamera = _this;
  22111. }
  22112. _this.position = position;
  22113. return _this;
  22114. }
  22115. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22116. get: function () {
  22117. return Camera._PERSPECTIVE_CAMERA;
  22118. },
  22119. enumerable: true,
  22120. configurable: true
  22121. });
  22122. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22123. get: function () {
  22124. return Camera._ORTHOGRAPHIC_CAMERA;
  22125. },
  22126. enumerable: true,
  22127. configurable: true
  22128. });
  22129. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22130. /**
  22131. * This is the default FOV mode for perspective cameras.
  22132. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22133. *
  22134. */
  22135. get: function () {
  22136. return Camera._FOVMODE_VERTICAL_FIXED;
  22137. },
  22138. enumerable: true,
  22139. configurable: true
  22140. });
  22141. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22142. /**
  22143. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22144. *
  22145. */
  22146. get: function () {
  22147. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22148. },
  22149. enumerable: true,
  22150. configurable: true
  22151. });
  22152. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22153. get: function () {
  22154. return Camera._RIG_MODE_NONE;
  22155. },
  22156. enumerable: true,
  22157. configurable: true
  22158. });
  22159. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22160. get: function () {
  22161. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22162. },
  22163. enumerable: true,
  22164. configurable: true
  22165. });
  22166. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22167. get: function () {
  22168. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22169. },
  22170. enumerable: true,
  22171. configurable: true
  22172. });
  22173. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22174. get: function () {
  22175. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22176. },
  22177. enumerable: true,
  22178. configurable: true
  22179. });
  22180. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22181. get: function () {
  22182. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22183. },
  22184. enumerable: true,
  22185. configurable: true
  22186. });
  22187. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22188. get: function () {
  22189. return Camera._RIG_MODE_VR;
  22190. },
  22191. enumerable: true,
  22192. configurable: true
  22193. });
  22194. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22195. get: function () {
  22196. return Camera._RIG_MODE_WEBVR;
  22197. },
  22198. enumerable: true,
  22199. configurable: true
  22200. });
  22201. /**
  22202. * Store current camera state (fov, position, etc..)
  22203. */
  22204. Camera.prototype.storeState = function () {
  22205. this._stateStored = true;
  22206. this._storedFov = this.fov;
  22207. return this;
  22208. };
  22209. /**
  22210. * Restores the camera state values if it has been stored. You must call storeState() first
  22211. */
  22212. Camera.prototype._restoreStateValues = function () {
  22213. if (!this._stateStored) {
  22214. return false;
  22215. }
  22216. this.fov = this._storedFov;
  22217. return true;
  22218. };
  22219. /**
  22220. * Restored camera state. You must call storeState() first
  22221. */
  22222. Camera.prototype.restoreState = function () {
  22223. if (this._restoreStateValues()) {
  22224. this.onRestoreStateObservable.notifyObservers(this);
  22225. return true;
  22226. }
  22227. return false;
  22228. };
  22229. Camera.prototype.getClassName = function () {
  22230. return "Camera";
  22231. };
  22232. /**
  22233. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22234. */
  22235. Camera.prototype.toString = function (fullDetails) {
  22236. var ret = "Name: " + this.name;
  22237. ret += ", type: " + this.getClassName();
  22238. if (this.animations) {
  22239. for (var i = 0; i < this.animations.length; i++) {
  22240. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22241. }
  22242. }
  22243. if (fullDetails) {
  22244. }
  22245. return ret;
  22246. };
  22247. Object.defineProperty(Camera.prototype, "globalPosition", {
  22248. get: function () {
  22249. return this._globalPosition;
  22250. },
  22251. enumerable: true,
  22252. configurable: true
  22253. });
  22254. Camera.prototype.getActiveMeshes = function () {
  22255. return this._activeMeshes;
  22256. };
  22257. Camera.prototype.isActiveMesh = function (mesh) {
  22258. return (this._activeMeshes.indexOf(mesh) !== -1);
  22259. };
  22260. /**
  22261. * Is this camera ready to be used/rendered
  22262. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22263. * @return true if the camera is ready
  22264. */
  22265. Camera.prototype.isReady = function (completeCheck) {
  22266. if (completeCheck === void 0) { completeCheck = false; }
  22267. if (completeCheck) {
  22268. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22269. var pp = _a[_i];
  22270. if (pp && !pp.isReady()) {
  22271. return false;
  22272. }
  22273. }
  22274. }
  22275. return _super.prototype.isReady.call(this, completeCheck);
  22276. };
  22277. //Cache
  22278. Camera.prototype._initCache = function () {
  22279. _super.prototype._initCache.call(this);
  22280. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22281. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22282. this._cache.mode = undefined;
  22283. this._cache.minZ = undefined;
  22284. this._cache.maxZ = undefined;
  22285. this._cache.fov = undefined;
  22286. this._cache.fovMode = undefined;
  22287. this._cache.aspectRatio = undefined;
  22288. this._cache.orthoLeft = undefined;
  22289. this._cache.orthoRight = undefined;
  22290. this._cache.orthoBottom = undefined;
  22291. this._cache.orthoTop = undefined;
  22292. this._cache.renderWidth = undefined;
  22293. this._cache.renderHeight = undefined;
  22294. };
  22295. Camera.prototype._updateCache = function (ignoreParentClass) {
  22296. if (!ignoreParentClass) {
  22297. _super.prototype._updateCache.call(this);
  22298. }
  22299. this._cache.position.copyFrom(this.position);
  22300. this._cache.upVector.copyFrom(this.upVector);
  22301. };
  22302. // Synchronized
  22303. Camera.prototype._isSynchronized = function () {
  22304. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22305. };
  22306. Camera.prototype._isSynchronizedViewMatrix = function () {
  22307. if (!_super.prototype._isSynchronized.call(this))
  22308. return false;
  22309. return this._cache.position.equals(this.position)
  22310. && this._cache.upVector.equals(this.upVector)
  22311. && this.isSynchronizedWithParent();
  22312. };
  22313. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22314. var check = this._cache.mode === this.mode
  22315. && this._cache.minZ === this.minZ
  22316. && this._cache.maxZ === this.maxZ;
  22317. if (!check) {
  22318. return false;
  22319. }
  22320. var engine = this.getEngine();
  22321. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22322. check = this._cache.fov === this.fov
  22323. && this._cache.fovMode === this.fovMode
  22324. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22325. }
  22326. else {
  22327. check = this._cache.orthoLeft === this.orthoLeft
  22328. && this._cache.orthoRight === this.orthoRight
  22329. && this._cache.orthoBottom === this.orthoBottom
  22330. && this._cache.orthoTop === this.orthoTop
  22331. && this._cache.renderWidth === engine.getRenderWidth()
  22332. && this._cache.renderHeight === engine.getRenderHeight();
  22333. }
  22334. return check;
  22335. };
  22336. // Controls
  22337. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22338. };
  22339. Camera.prototype.detachControl = function (element) {
  22340. };
  22341. Camera.prototype.update = function () {
  22342. this._checkInputs();
  22343. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22344. this._updateRigCameras();
  22345. }
  22346. };
  22347. Camera.prototype._checkInputs = function () {
  22348. this.onAfterCheckInputsObservable.notifyObservers(this);
  22349. };
  22350. Object.defineProperty(Camera.prototype, "rigCameras", {
  22351. get: function () {
  22352. return this._rigCameras;
  22353. },
  22354. enumerable: true,
  22355. configurable: true
  22356. });
  22357. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22358. get: function () {
  22359. return this._rigPostProcess;
  22360. },
  22361. enumerable: true,
  22362. configurable: true
  22363. });
  22364. /**
  22365. * Internal, gets the first post proces.
  22366. * @returns the first post process to be run on this camera.
  22367. */
  22368. Camera.prototype._getFirstPostProcess = function () {
  22369. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22370. if (this._postProcesses[ppIndex] !== null) {
  22371. return this._postProcesses[ppIndex];
  22372. }
  22373. }
  22374. return null;
  22375. };
  22376. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22377. // invalidate framebuffer
  22378. var firstPostProcess = this._getFirstPostProcess();
  22379. if (firstPostProcess) {
  22380. firstPostProcess.markTextureDirty();
  22381. }
  22382. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22383. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22384. var cam = this._rigCameras[i];
  22385. var rigPostProcess = cam._rigPostProcess;
  22386. // for VR rig, there does not have to be a post process
  22387. if (rigPostProcess) {
  22388. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22389. if (isPass) {
  22390. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22391. cam.isIntermediate = this._postProcesses.length === 0;
  22392. }
  22393. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22394. rigPostProcess.markTextureDirty();
  22395. }
  22396. else {
  22397. cam._postProcesses = this._postProcesses.slice(0);
  22398. }
  22399. }
  22400. };
  22401. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22402. if (insertAt === void 0) { insertAt = null; }
  22403. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22404. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22405. return 0;
  22406. }
  22407. if (insertAt == null || insertAt < 0) {
  22408. this._postProcesses.push(postProcess);
  22409. }
  22410. else if (this._postProcesses[insertAt] === null) {
  22411. this._postProcesses[insertAt] = postProcess;
  22412. }
  22413. else {
  22414. this._postProcesses.splice(insertAt, 0, postProcess);
  22415. }
  22416. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22417. return this._postProcesses.indexOf(postProcess);
  22418. };
  22419. Camera.prototype.detachPostProcess = function (postProcess) {
  22420. var idx = this._postProcesses.indexOf(postProcess);
  22421. if (idx !== -1) {
  22422. this._postProcesses[idx] = null;
  22423. }
  22424. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22425. };
  22426. Camera.prototype.getWorldMatrix = function () {
  22427. if (this._isSynchronizedViewMatrix()) {
  22428. return this._worldMatrix;
  22429. }
  22430. // Getting the the view matrix will also compute the world matrix.
  22431. this.getViewMatrix();
  22432. return this._worldMatrix;
  22433. };
  22434. Camera.prototype._getViewMatrix = function () {
  22435. return BABYLON.Matrix.Identity();
  22436. };
  22437. Camera.prototype.getViewMatrix = function (force) {
  22438. if (!force && this._isSynchronizedViewMatrix()) {
  22439. return this._computedViewMatrix;
  22440. }
  22441. this.updateCache();
  22442. this._computedViewMatrix = this._getViewMatrix();
  22443. this._currentRenderId = this.getScene().getRenderId();
  22444. this._childRenderId = this._currentRenderId;
  22445. this._refreshFrustumPlanes = true;
  22446. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22447. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22448. }
  22449. this.onViewMatrixChangedObservable.notifyObservers(this);
  22450. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22451. return this._computedViewMatrix;
  22452. };
  22453. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22454. this._doNotComputeProjectionMatrix = true;
  22455. if (projection !== undefined) {
  22456. this._projectionMatrix = projection;
  22457. }
  22458. };
  22459. ;
  22460. Camera.prototype.unfreezeProjectionMatrix = function () {
  22461. this._doNotComputeProjectionMatrix = false;
  22462. };
  22463. ;
  22464. Camera.prototype.getProjectionMatrix = function (force) {
  22465. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22466. return this._projectionMatrix;
  22467. }
  22468. // Cache
  22469. this._cache.mode = this.mode;
  22470. this._cache.minZ = this.minZ;
  22471. this._cache.maxZ = this.maxZ;
  22472. // Matrix
  22473. this._refreshFrustumPlanes = true;
  22474. var engine = this.getEngine();
  22475. var scene = this.getScene();
  22476. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22477. this._cache.fov = this.fov;
  22478. this._cache.fovMode = this.fovMode;
  22479. this._cache.aspectRatio = engine.getAspectRatio(this);
  22480. if (this.minZ <= 0) {
  22481. this.minZ = 0.1;
  22482. }
  22483. if (scene.useRightHandedSystem) {
  22484. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22485. }
  22486. else {
  22487. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22488. }
  22489. }
  22490. else {
  22491. var halfWidth = engine.getRenderWidth() / 2.0;
  22492. var halfHeight = engine.getRenderHeight() / 2.0;
  22493. if (scene.useRightHandedSystem) {
  22494. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22495. }
  22496. else {
  22497. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22498. }
  22499. this._cache.orthoLeft = this.orthoLeft;
  22500. this._cache.orthoRight = this.orthoRight;
  22501. this._cache.orthoBottom = this.orthoBottom;
  22502. this._cache.orthoTop = this.orthoTop;
  22503. this._cache.renderWidth = engine.getRenderWidth();
  22504. this._cache.renderHeight = engine.getRenderHeight();
  22505. }
  22506. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22507. return this._projectionMatrix;
  22508. };
  22509. Camera.prototype.getTranformationMatrix = function () {
  22510. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22511. return this._transformMatrix;
  22512. };
  22513. Camera.prototype.updateFrustumPlanes = function () {
  22514. if (!this._refreshFrustumPlanes) {
  22515. return;
  22516. }
  22517. this.getTranformationMatrix();
  22518. if (!this._frustumPlanes) {
  22519. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22520. }
  22521. else {
  22522. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22523. }
  22524. this._refreshFrustumPlanes = false;
  22525. };
  22526. Camera.prototype.isInFrustum = function (target) {
  22527. this.updateFrustumPlanes();
  22528. return target.isInFrustum(this._frustumPlanes);
  22529. };
  22530. Camera.prototype.isCompletelyInFrustum = function (target) {
  22531. this.updateFrustumPlanes();
  22532. return target.isCompletelyInFrustum(this._frustumPlanes);
  22533. };
  22534. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22535. if (length === void 0) { length = 100; }
  22536. if (!transform) {
  22537. transform = this.getWorldMatrix();
  22538. }
  22539. if (!origin) {
  22540. origin = this.position;
  22541. }
  22542. var forward = new BABYLON.Vector3(0, 0, 1);
  22543. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22544. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22545. return new BABYLON.Ray(origin, direction, length);
  22546. };
  22547. /**
  22548. * Releases resources associated with this node.
  22549. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22550. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22551. */
  22552. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22553. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22554. // Observables
  22555. this.onViewMatrixChangedObservable.clear();
  22556. this.onProjectionMatrixChangedObservable.clear();
  22557. this.onAfterCheckInputsObservable.clear();
  22558. this.onRestoreStateObservable.clear();
  22559. // Inputs
  22560. if (this.inputs) {
  22561. this.inputs.clear();
  22562. }
  22563. // Animations
  22564. this.getScene().stopAnimation(this);
  22565. // Remove from scene
  22566. this.getScene().removeCamera(this);
  22567. while (this._rigCameras.length > 0) {
  22568. var camera = this._rigCameras.pop();
  22569. if (camera) {
  22570. camera.dispose();
  22571. }
  22572. }
  22573. // Postprocesses
  22574. if (this._rigPostProcess) {
  22575. this._rigPostProcess.dispose(this);
  22576. this._rigPostProcess = null;
  22577. this._postProcesses = [];
  22578. }
  22579. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22580. this._rigPostProcess = null;
  22581. this._postProcesses = [];
  22582. }
  22583. else {
  22584. var i = this._postProcesses.length;
  22585. while (--i >= 0) {
  22586. var postProcess = this._postProcesses[i];
  22587. if (postProcess) {
  22588. postProcess.dispose(this);
  22589. }
  22590. }
  22591. }
  22592. // Render targets
  22593. var i = this.customRenderTargets.length;
  22594. while (--i >= 0) {
  22595. this.customRenderTargets[i].dispose();
  22596. }
  22597. this.customRenderTargets = [];
  22598. // Active Meshes
  22599. this._activeMeshes.dispose();
  22600. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22601. };
  22602. Object.defineProperty(Camera.prototype, "leftCamera", {
  22603. // ---- Camera rigs section ----
  22604. get: function () {
  22605. if (this._rigCameras.length < 1) {
  22606. return null;
  22607. }
  22608. return this._rigCameras[0];
  22609. },
  22610. enumerable: true,
  22611. configurable: true
  22612. });
  22613. Object.defineProperty(Camera.prototype, "rightCamera", {
  22614. get: function () {
  22615. if (this._rigCameras.length < 2) {
  22616. return null;
  22617. }
  22618. return this._rigCameras[1];
  22619. },
  22620. enumerable: true,
  22621. configurable: true
  22622. });
  22623. Camera.prototype.getLeftTarget = function () {
  22624. if (this._rigCameras.length < 1) {
  22625. return null;
  22626. }
  22627. return this._rigCameras[0].getTarget();
  22628. };
  22629. Camera.prototype.getRightTarget = function () {
  22630. if (this._rigCameras.length < 2) {
  22631. return null;
  22632. }
  22633. return this._rigCameras[1].getTarget();
  22634. };
  22635. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22636. if (this.cameraRigMode === mode) {
  22637. return;
  22638. }
  22639. while (this._rigCameras.length > 0) {
  22640. var camera = this._rigCameras.pop();
  22641. if (camera) {
  22642. camera.dispose();
  22643. }
  22644. }
  22645. this.cameraRigMode = mode;
  22646. this._cameraRigParams = {};
  22647. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22648. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22649. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22650. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22651. // create the rig cameras, unless none
  22652. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22653. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22654. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22655. if (leftCamera && rightCamera) {
  22656. this._rigCameras.push(leftCamera);
  22657. this._rigCameras.push(rightCamera);
  22658. }
  22659. }
  22660. switch (this.cameraRigMode) {
  22661. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22662. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22663. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22664. break;
  22665. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22666. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22667. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22668. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22669. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22670. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22671. break;
  22672. case Camera.RIG_MODE_VR:
  22673. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22674. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22675. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22676. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22677. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22678. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22679. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22680. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22681. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22682. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22683. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22684. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22685. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22686. if (metrics.compensateDistortion) {
  22687. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22688. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22689. }
  22690. break;
  22691. case Camera.RIG_MODE_WEBVR:
  22692. if (rigParams.vrDisplay) {
  22693. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22694. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22695. //Left eye
  22696. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22697. this._rigCameras[0].setCameraRigParameter("left", true);
  22698. //leaving this for future reference
  22699. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22700. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22701. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22702. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22703. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22704. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22705. this._rigCameras[0].parent = this;
  22706. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22707. //Right eye
  22708. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22709. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22710. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22711. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22712. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22713. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22714. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22715. this._rigCameras[1].parent = this;
  22716. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22717. if (Camera.UseAlternateWebVRRendering) {
  22718. this._rigCameras[1]._skipRendering = true;
  22719. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22720. }
  22721. }
  22722. break;
  22723. }
  22724. this._cascadePostProcessesToRigCams();
  22725. this.update();
  22726. };
  22727. Camera.prototype._getVRProjectionMatrix = function () {
  22728. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22729. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22730. return this._projectionMatrix;
  22731. };
  22732. Camera.prototype._updateCameraRotationMatrix = function () {
  22733. //Here for WebVR
  22734. };
  22735. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22736. //Here for WebVR
  22737. };
  22738. /**
  22739. * This function MUST be overwritten by the different WebVR cameras available.
  22740. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22741. */
  22742. Camera.prototype._getWebVRProjectionMatrix = function () {
  22743. return BABYLON.Matrix.Identity();
  22744. };
  22745. /**
  22746. * This function MUST be overwritten by the different WebVR cameras available.
  22747. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22748. */
  22749. Camera.prototype._getWebVRViewMatrix = function () {
  22750. return BABYLON.Matrix.Identity();
  22751. };
  22752. Camera.prototype.setCameraRigParameter = function (name, value) {
  22753. if (!this._cameraRigParams) {
  22754. this._cameraRigParams = {};
  22755. }
  22756. this._cameraRigParams[name] = value;
  22757. //provisionnally:
  22758. if (name === "interaxialDistance") {
  22759. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22760. }
  22761. };
  22762. /**
  22763. * needs to be overridden by children so sub has required properties to be copied
  22764. */
  22765. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22766. return null;
  22767. };
  22768. /**
  22769. * May need to be overridden by children
  22770. */
  22771. Camera.prototype._updateRigCameras = function () {
  22772. for (var i = 0; i < this._rigCameras.length; i++) {
  22773. this._rigCameras[i].minZ = this.minZ;
  22774. this._rigCameras[i].maxZ = this.maxZ;
  22775. this._rigCameras[i].fov = this.fov;
  22776. }
  22777. // only update viewport when ANAGLYPH
  22778. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22779. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22780. }
  22781. };
  22782. Camera.prototype._setupInputs = function () {
  22783. };
  22784. Camera.prototype.serialize = function () {
  22785. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22786. // Type
  22787. serializationObject.type = this.getClassName();
  22788. // Parent
  22789. if (this.parent) {
  22790. serializationObject.parentId = this.parent.id;
  22791. }
  22792. if (this.inputs) {
  22793. this.inputs.serialize(serializationObject);
  22794. }
  22795. // Animations
  22796. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22797. serializationObject.ranges = this.serializeAnimationRanges();
  22798. return serializationObject;
  22799. };
  22800. Camera.prototype.clone = function (name) {
  22801. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22802. };
  22803. Camera.prototype.getDirection = function (localAxis) {
  22804. var result = BABYLON.Vector3.Zero();
  22805. this.getDirectionToRef(localAxis, result);
  22806. return result;
  22807. };
  22808. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22809. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22810. };
  22811. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22812. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22813. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22814. switch (type) {
  22815. case "ArcRotateCamera":
  22816. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22817. case "DeviceOrientationCamera":
  22818. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22819. case "FollowCamera":
  22820. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22821. case "ArcFollowCamera":
  22822. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22823. case "GamepadCamera":
  22824. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22825. case "TouchCamera":
  22826. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22827. case "VirtualJoysticksCamera":
  22828. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22829. case "WebVRFreeCamera":
  22830. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22831. case "WebVRGamepadCamera":
  22832. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22833. case "VRDeviceOrientationFreeCamera":
  22834. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22835. case "VRDeviceOrientationGamepadCamera":
  22836. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22837. case "AnaglyphArcRotateCamera":
  22838. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22839. case "AnaglyphFreeCamera":
  22840. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22841. case "AnaglyphGamepadCamera":
  22842. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22843. case "AnaglyphUniversalCamera":
  22844. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22845. case "StereoscopicArcRotateCamera":
  22846. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22847. case "StereoscopicFreeCamera":
  22848. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22849. case "StereoscopicGamepadCamera":
  22850. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22851. case "StereoscopicUniversalCamera":
  22852. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22853. case "FreeCamera": // Forcing Universal here
  22854. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22855. default: // Universal Camera is the default value
  22856. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22857. }
  22858. };
  22859. Camera.prototype.computeWorldMatrix = function () {
  22860. return this.getWorldMatrix();
  22861. };
  22862. Camera.Parse = function (parsedCamera, scene) {
  22863. var type = parsedCamera.type;
  22864. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22865. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22866. // Parent
  22867. if (parsedCamera.parentId) {
  22868. camera._waitingParentId = parsedCamera.parentId;
  22869. }
  22870. //If camera has an input manager, let it parse inputs settings
  22871. if (camera.inputs) {
  22872. camera.inputs.parse(parsedCamera);
  22873. camera._setupInputs();
  22874. }
  22875. if (camera.setPosition) { // need to force position
  22876. camera.position.copyFromFloats(0, 0, 0);
  22877. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22878. }
  22879. // Target
  22880. if (parsedCamera.target) {
  22881. if (camera.setTarget) {
  22882. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22883. }
  22884. }
  22885. // Apply 3d rig, when found
  22886. if (parsedCamera.cameraRigMode) {
  22887. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22888. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22889. }
  22890. // Animations
  22891. if (parsedCamera.animations) {
  22892. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22893. var parsedAnimation = parsedCamera.animations[animationIndex];
  22894. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22895. }
  22896. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22897. }
  22898. if (parsedCamera.autoAnimate) {
  22899. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22900. }
  22901. return camera;
  22902. };
  22903. // Statics
  22904. Camera._PERSPECTIVE_CAMERA = 0;
  22905. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22906. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22907. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22908. Camera._RIG_MODE_NONE = 0;
  22909. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22910. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22911. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22912. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22913. Camera._RIG_MODE_VR = 20;
  22914. Camera._RIG_MODE_WEBVR = 21;
  22915. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22916. Camera.UseAlternateWebVRRendering = false;
  22917. __decorate([
  22918. BABYLON.serializeAsVector3()
  22919. ], Camera.prototype, "position", void 0);
  22920. __decorate([
  22921. BABYLON.serializeAsVector3()
  22922. ], Camera.prototype, "upVector", void 0);
  22923. __decorate([
  22924. BABYLON.serialize()
  22925. ], Camera.prototype, "orthoLeft", void 0);
  22926. __decorate([
  22927. BABYLON.serialize()
  22928. ], Camera.prototype, "orthoRight", void 0);
  22929. __decorate([
  22930. BABYLON.serialize()
  22931. ], Camera.prototype, "orthoBottom", void 0);
  22932. __decorate([
  22933. BABYLON.serialize()
  22934. ], Camera.prototype, "orthoTop", void 0);
  22935. __decorate([
  22936. BABYLON.serialize()
  22937. ], Camera.prototype, "fov", void 0);
  22938. __decorate([
  22939. BABYLON.serialize()
  22940. ], Camera.prototype, "minZ", void 0);
  22941. __decorate([
  22942. BABYLON.serialize()
  22943. ], Camera.prototype, "maxZ", void 0);
  22944. __decorate([
  22945. BABYLON.serialize()
  22946. ], Camera.prototype, "inertia", void 0);
  22947. __decorate([
  22948. BABYLON.serialize()
  22949. ], Camera.prototype, "mode", void 0);
  22950. __decorate([
  22951. BABYLON.serialize()
  22952. ], Camera.prototype, "layerMask", void 0);
  22953. __decorate([
  22954. BABYLON.serialize()
  22955. ], Camera.prototype, "fovMode", void 0);
  22956. __decorate([
  22957. BABYLON.serialize()
  22958. ], Camera.prototype, "cameraRigMode", void 0);
  22959. __decorate([
  22960. BABYLON.serialize()
  22961. ], Camera.prototype, "interaxialDistance", void 0);
  22962. __decorate([
  22963. BABYLON.serialize()
  22964. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22965. return Camera;
  22966. }(BABYLON.Node));
  22967. BABYLON.Camera = Camera;
  22968. })(BABYLON || (BABYLON = {}));
  22969. //# sourceMappingURL=babylon.camera.js.map
  22970. var BABYLON;
  22971. (function (BABYLON) {
  22972. var RenderingManager = /** @class */ (function () {
  22973. function RenderingManager(scene) {
  22974. this._renderingGroups = new Array();
  22975. this._autoClearDepthStencil = {};
  22976. this._customOpaqueSortCompareFn = {};
  22977. this._customAlphaTestSortCompareFn = {};
  22978. this._customTransparentSortCompareFn = {};
  22979. this._renderinGroupInfo = null;
  22980. this._scene = scene;
  22981. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22982. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22983. }
  22984. }
  22985. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22986. if (depth === void 0) { depth = true; }
  22987. if (stencil === void 0) { stencil = true; }
  22988. if (this._depthStencilBufferAlreadyCleaned) {
  22989. return;
  22990. }
  22991. this._scene.getEngine().clear(null, false, depth, stencil);
  22992. this._depthStencilBufferAlreadyCleaned = true;
  22993. };
  22994. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22995. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22996. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22997. var info = null;
  22998. if (observable) {
  22999. if (!this._renderinGroupInfo) {
  23000. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23001. }
  23002. info = this._renderinGroupInfo;
  23003. info.scene = this._scene;
  23004. info.camera = this._scene.activeCamera;
  23005. }
  23006. // Dispatch sprites
  23007. if (renderSprites) {
  23008. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23009. var manager = this._scene.spriteManagers[index];
  23010. this.dispatchSprites(manager);
  23011. }
  23012. }
  23013. // Render
  23014. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23015. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23016. var renderingGroup = this._renderingGroups[index];
  23017. if (!renderingGroup && !observable)
  23018. continue;
  23019. var renderingGroupMask = 0;
  23020. // Fire PRECLEAR stage
  23021. if (observable && info) {
  23022. renderingGroupMask = Math.pow(2, index);
  23023. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23024. info.renderingGroupId = index;
  23025. observable.notifyObservers(info, renderingGroupMask);
  23026. }
  23027. // Clear depth/stencil if needed
  23028. if (RenderingManager.AUTOCLEAR) {
  23029. var autoClear = this._autoClearDepthStencil[index];
  23030. if (autoClear && autoClear.autoClear) {
  23031. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23032. }
  23033. }
  23034. if (observable && info) {
  23035. // Fire PREOPAQUE stage
  23036. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23037. observable.notifyObservers(info, renderingGroupMask);
  23038. // Fire PRETRANSPARENT stage
  23039. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23040. observable.notifyObservers(info, renderingGroupMask);
  23041. }
  23042. if (renderingGroup)
  23043. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23044. // Fire POSTTRANSPARENT stage
  23045. if (observable && info) {
  23046. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23047. observable.notifyObservers(info, renderingGroupMask);
  23048. }
  23049. }
  23050. };
  23051. RenderingManager.prototype.reset = function () {
  23052. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23053. var renderingGroup = this._renderingGroups[index];
  23054. if (renderingGroup) {
  23055. renderingGroup.prepare();
  23056. }
  23057. }
  23058. };
  23059. RenderingManager.prototype.dispose = function () {
  23060. this.freeRenderingGroups();
  23061. this._renderingGroups.length = 0;
  23062. };
  23063. /**
  23064. * Clear the info related to rendering groups preventing retention points during dispose.
  23065. */
  23066. RenderingManager.prototype.freeRenderingGroups = function () {
  23067. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23068. var renderingGroup = this._renderingGroups[index];
  23069. if (renderingGroup) {
  23070. renderingGroup.dispose();
  23071. }
  23072. }
  23073. };
  23074. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23075. if (this._renderingGroups[renderingGroupId] === undefined) {
  23076. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23077. }
  23078. };
  23079. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23080. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23081. this._prepareRenderingGroup(renderingGroupId);
  23082. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23083. };
  23084. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23085. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23086. this._prepareRenderingGroup(renderingGroupId);
  23087. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23088. };
  23089. /**
  23090. * @param subMesh The submesh to dispatch
  23091. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23092. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23093. */
  23094. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23095. if (mesh === undefined) {
  23096. mesh = subMesh.getMesh();
  23097. }
  23098. var renderingGroupId = mesh.renderingGroupId || 0;
  23099. this._prepareRenderingGroup(renderingGroupId);
  23100. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23101. };
  23102. /**
  23103. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23104. * This allowed control for front to back rendering or reversly depending of the special needs.
  23105. *
  23106. * @param renderingGroupId The rendering group id corresponding to its index
  23107. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23108. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23109. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23110. */
  23111. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23112. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23113. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23114. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23115. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23116. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23117. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23118. if (this._renderingGroups[renderingGroupId]) {
  23119. var group = this._renderingGroups[renderingGroupId];
  23120. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23121. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23122. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23123. }
  23124. };
  23125. /**
  23126. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23127. *
  23128. * @param renderingGroupId The rendering group id corresponding to its index
  23129. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23130. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23131. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23132. */
  23133. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23134. if (depth === void 0) { depth = true; }
  23135. if (stencil === void 0) { stencil = true; }
  23136. this._autoClearDepthStencil[renderingGroupId] = {
  23137. autoClear: autoClearDepthStencil,
  23138. depth: depth,
  23139. stencil: stencil
  23140. };
  23141. };
  23142. /**
  23143. * The max id used for rendering groups (not included)
  23144. */
  23145. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23146. /**
  23147. * The min id used for rendering groups (included)
  23148. */
  23149. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23150. /**
  23151. * Used to globally prevent autoclearing scenes.
  23152. */
  23153. RenderingManager.AUTOCLEAR = true;
  23154. return RenderingManager;
  23155. }());
  23156. BABYLON.RenderingManager = RenderingManager;
  23157. })(BABYLON || (BABYLON = {}));
  23158. //# sourceMappingURL=babylon.renderingManager.js.map
  23159. var BABYLON;
  23160. (function (BABYLON) {
  23161. var RenderingGroup = /** @class */ (function () {
  23162. /**
  23163. * Creates a new rendering group.
  23164. * @param index The rendering group index
  23165. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23166. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23167. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23168. */
  23169. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23170. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23171. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23172. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23173. this.index = index;
  23174. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23175. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23176. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23177. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23178. this._particleSystems = new BABYLON.SmartArray(256);
  23179. this._spriteManagers = new BABYLON.SmartArray(256);
  23180. this._edgesRenderers = new BABYLON.SmartArray(16);
  23181. this._scene = scene;
  23182. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23183. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23184. this.transparentSortCompareFn = transparentSortCompareFn;
  23185. }
  23186. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23187. /**
  23188. * Set the opaque sort comparison function.
  23189. * If null the sub meshes will be render in the order they were created
  23190. */
  23191. set: function (value) {
  23192. this._opaqueSortCompareFn = value;
  23193. if (value) {
  23194. this._renderOpaque = this.renderOpaqueSorted;
  23195. }
  23196. else {
  23197. this._renderOpaque = RenderingGroup.renderUnsorted;
  23198. }
  23199. },
  23200. enumerable: true,
  23201. configurable: true
  23202. });
  23203. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23204. /**
  23205. * Set the alpha test sort comparison function.
  23206. * If null the sub meshes will be render in the order they were created
  23207. */
  23208. set: function (value) {
  23209. this._alphaTestSortCompareFn = value;
  23210. if (value) {
  23211. this._renderAlphaTest = this.renderAlphaTestSorted;
  23212. }
  23213. else {
  23214. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23215. }
  23216. },
  23217. enumerable: true,
  23218. configurable: true
  23219. });
  23220. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23221. /**
  23222. * Set the transparent sort comparison function.
  23223. * If null the sub meshes will be render in the order they were created
  23224. */
  23225. set: function (value) {
  23226. if (value) {
  23227. this._transparentSortCompareFn = value;
  23228. }
  23229. else {
  23230. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23231. }
  23232. this._renderTransparent = this.renderTransparentSorted;
  23233. },
  23234. enumerable: true,
  23235. configurable: true
  23236. });
  23237. /**
  23238. * Render all the sub meshes contained in the group.
  23239. * @param customRenderFunction Used to override the default render behaviour of the group.
  23240. * @returns true if rendered some submeshes.
  23241. */
  23242. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23243. if (customRenderFunction) {
  23244. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23245. return;
  23246. }
  23247. var engine = this._scene.getEngine();
  23248. // Depth only
  23249. if (this._depthOnlySubMeshes.length !== 0) {
  23250. engine.setColorWrite(false);
  23251. this._renderAlphaTest(this._depthOnlySubMeshes);
  23252. engine.setColorWrite(true);
  23253. }
  23254. // Opaque
  23255. if (this._opaqueSubMeshes.length !== 0) {
  23256. this._renderOpaque(this._opaqueSubMeshes);
  23257. }
  23258. // Alpha test
  23259. if (this._alphaTestSubMeshes.length !== 0) {
  23260. this._renderAlphaTest(this._alphaTestSubMeshes);
  23261. }
  23262. var stencilState = engine.getStencilBuffer();
  23263. engine.setStencilBuffer(false);
  23264. // Sprites
  23265. if (renderSprites) {
  23266. this._renderSprites();
  23267. }
  23268. // Particles
  23269. if (renderParticles) {
  23270. this._renderParticles(activeMeshes);
  23271. }
  23272. if (this.onBeforeTransparentRendering) {
  23273. this.onBeforeTransparentRendering();
  23274. }
  23275. // Transparent
  23276. if (this._transparentSubMeshes.length !== 0) {
  23277. this._renderTransparent(this._transparentSubMeshes);
  23278. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23279. }
  23280. // Set back stencil to false in case it changes before the edge renderer.
  23281. engine.setStencilBuffer(false);
  23282. // Edges
  23283. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23284. this._edgesRenderers.data[edgesRendererIndex].render();
  23285. }
  23286. // Restore Stencil state.
  23287. engine.setStencilBuffer(stencilState);
  23288. };
  23289. /**
  23290. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23291. * @param subMeshes The submeshes to render
  23292. */
  23293. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23294. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23295. };
  23296. /**
  23297. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23298. * @param subMeshes The submeshes to render
  23299. */
  23300. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23301. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23302. };
  23303. /**
  23304. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23305. * @param subMeshes The submeshes to render
  23306. */
  23307. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23308. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23309. };
  23310. /**
  23311. * Renders the submeshes in a specified order.
  23312. * @param subMeshes The submeshes to sort before render
  23313. * @param sortCompareFn The comparison function use to sort
  23314. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23315. * @param transparent Specifies to activate blending if true
  23316. */
  23317. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23318. var subIndex = 0;
  23319. var subMesh;
  23320. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23321. for (; subIndex < subMeshes.length; subIndex++) {
  23322. subMesh = subMeshes.data[subIndex];
  23323. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23324. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23325. }
  23326. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23327. if (sortCompareFn) {
  23328. sortedArray.sort(sortCompareFn);
  23329. }
  23330. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23331. subMesh = sortedArray[subIndex];
  23332. if (transparent) {
  23333. var material = subMesh.getMaterial();
  23334. if (material && material.needDepthPrePass) {
  23335. var engine = material.getScene().getEngine();
  23336. engine.setColorWrite(false);
  23337. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23338. subMesh.render(false);
  23339. engine.setColorWrite(true);
  23340. }
  23341. }
  23342. subMesh.render(transparent);
  23343. }
  23344. };
  23345. /**
  23346. * Renders the submeshes in the order they were dispatched (no sort applied).
  23347. * @param subMeshes The submeshes to render
  23348. */
  23349. RenderingGroup.renderUnsorted = function (subMeshes) {
  23350. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23351. var submesh = subMeshes.data[subIndex];
  23352. submesh.render(false);
  23353. }
  23354. };
  23355. /**
  23356. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23357. * are rendered back to front if in the same alpha index.
  23358. *
  23359. * @param a The first submesh
  23360. * @param b The second submesh
  23361. * @returns The result of the comparison
  23362. */
  23363. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23364. // Alpha index first
  23365. if (a._alphaIndex > b._alphaIndex) {
  23366. return 1;
  23367. }
  23368. if (a._alphaIndex < b._alphaIndex) {
  23369. return -1;
  23370. }
  23371. // Then distance to camera
  23372. return RenderingGroup.backToFrontSortCompare(a, b);
  23373. };
  23374. /**
  23375. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23376. * are rendered back to front.
  23377. *
  23378. * @param a The first submesh
  23379. * @param b The second submesh
  23380. * @returns The result of the comparison
  23381. */
  23382. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23383. // Then distance to camera
  23384. if (a._distanceToCamera < b._distanceToCamera) {
  23385. return 1;
  23386. }
  23387. if (a._distanceToCamera > b._distanceToCamera) {
  23388. return -1;
  23389. }
  23390. return 0;
  23391. };
  23392. /**
  23393. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23394. * are rendered front to back (prevent overdraw).
  23395. *
  23396. * @param a The first submesh
  23397. * @param b The second submesh
  23398. * @returns The result of the comparison
  23399. */
  23400. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23401. // Then distance to camera
  23402. if (a._distanceToCamera < b._distanceToCamera) {
  23403. return -1;
  23404. }
  23405. if (a._distanceToCamera > b._distanceToCamera) {
  23406. return 1;
  23407. }
  23408. return 0;
  23409. };
  23410. /**
  23411. * Resets the different lists of submeshes to prepare a new frame.
  23412. */
  23413. RenderingGroup.prototype.prepare = function () {
  23414. this._opaqueSubMeshes.reset();
  23415. this._transparentSubMeshes.reset();
  23416. this._alphaTestSubMeshes.reset();
  23417. this._depthOnlySubMeshes.reset();
  23418. this._particleSystems.reset();
  23419. this._spriteManagers.reset();
  23420. this._edgesRenderers.reset();
  23421. };
  23422. RenderingGroup.prototype.dispose = function () {
  23423. this._opaqueSubMeshes.dispose();
  23424. this._transparentSubMeshes.dispose();
  23425. this._alphaTestSubMeshes.dispose();
  23426. this._depthOnlySubMeshes.dispose();
  23427. this._particleSystems.dispose();
  23428. this._spriteManagers.dispose();
  23429. this._edgesRenderers.dispose();
  23430. };
  23431. /**
  23432. * Inserts the submesh in its correct queue depending on its material.
  23433. * @param subMesh The submesh to dispatch
  23434. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23435. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23436. */
  23437. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23438. // Get mesh and materials if not provided
  23439. if (mesh === undefined) {
  23440. mesh = subMesh.getMesh();
  23441. }
  23442. if (material === undefined) {
  23443. material = subMesh.getMaterial();
  23444. }
  23445. if (material === null || material === undefined) {
  23446. return;
  23447. }
  23448. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23449. this._transparentSubMeshes.push(subMesh);
  23450. }
  23451. else if (material.needAlphaTesting()) { // Alpha test
  23452. if (material.needDepthPrePass) {
  23453. this._depthOnlySubMeshes.push(subMesh);
  23454. }
  23455. this._alphaTestSubMeshes.push(subMesh);
  23456. }
  23457. else {
  23458. if (material.needDepthPrePass) {
  23459. this._depthOnlySubMeshes.push(subMesh);
  23460. }
  23461. this._opaqueSubMeshes.push(subMesh); // Opaque
  23462. }
  23463. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23464. this._edgesRenderers.push(mesh._edgesRenderer);
  23465. }
  23466. };
  23467. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23468. this._spriteManagers.push(spriteManager);
  23469. };
  23470. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23471. this._particleSystems.push(particleSystem);
  23472. };
  23473. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23474. if (this._particleSystems.length === 0) {
  23475. return;
  23476. }
  23477. // Particles
  23478. var activeCamera = this._scene.activeCamera;
  23479. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23480. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23481. var particleSystem = this._particleSystems.data[particleIndex];
  23482. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23483. continue;
  23484. }
  23485. var emitter = particleSystem.emitter;
  23486. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23487. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23488. }
  23489. }
  23490. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23491. };
  23492. RenderingGroup.prototype._renderSprites = function () {
  23493. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23494. return;
  23495. }
  23496. // Sprites
  23497. var activeCamera = this._scene.activeCamera;
  23498. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23499. for (var id = 0; id < this._spriteManagers.length; id++) {
  23500. var spriteManager = this._spriteManagers.data[id];
  23501. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23502. spriteManager.render();
  23503. }
  23504. }
  23505. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23506. };
  23507. return RenderingGroup;
  23508. }());
  23509. BABYLON.RenderingGroup = RenderingGroup;
  23510. })(BABYLON || (BABYLON = {}));
  23511. //# sourceMappingURL=babylon.renderingGroup.js.map
  23512. var BABYLON;
  23513. (function (BABYLON) {
  23514. /** @hidden */
  23515. var ClickInfo = /** @class */ (function () {
  23516. function ClickInfo() {
  23517. this._singleClick = false;
  23518. this._doubleClick = false;
  23519. this._hasSwiped = false;
  23520. this._ignore = false;
  23521. }
  23522. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23523. get: function () {
  23524. return this._singleClick;
  23525. },
  23526. set: function (b) {
  23527. this._singleClick = b;
  23528. },
  23529. enumerable: true,
  23530. configurable: true
  23531. });
  23532. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23533. get: function () {
  23534. return this._doubleClick;
  23535. },
  23536. set: function (b) {
  23537. this._doubleClick = b;
  23538. },
  23539. enumerable: true,
  23540. configurable: true
  23541. });
  23542. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23543. get: function () {
  23544. return this._hasSwiped;
  23545. },
  23546. set: function (b) {
  23547. this._hasSwiped = b;
  23548. },
  23549. enumerable: true,
  23550. configurable: true
  23551. });
  23552. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23553. get: function () {
  23554. return this._ignore;
  23555. },
  23556. set: function (b) {
  23557. this._ignore = b;
  23558. },
  23559. enumerable: true,
  23560. configurable: true
  23561. });
  23562. return ClickInfo;
  23563. }());
  23564. /**
  23565. * This class is used by the onRenderingGroupObservable
  23566. */
  23567. var RenderingGroupInfo = /** @class */ (function () {
  23568. function RenderingGroupInfo() {
  23569. }
  23570. /**
  23571. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23572. * This stage will be fired no matter what
  23573. */
  23574. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23575. /**
  23576. * Called before opaque object are rendered.
  23577. * This stage will be fired only if there's 3D Opaque content to render
  23578. */
  23579. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23580. /**
  23581. * Called after the opaque objects are rendered and before the transparent ones
  23582. * This stage will be fired only if there's 3D transparent content to render
  23583. */
  23584. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23585. /**
  23586. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23587. * This stage will be fired no matter what
  23588. */
  23589. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23590. return RenderingGroupInfo;
  23591. }());
  23592. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23593. /**
  23594. * Represents a scene to be rendered by the engine.
  23595. * @see http://doc.babylonjs.com/features/scene
  23596. */
  23597. var Scene = /** @class */ (function () {
  23598. /**
  23599. * Creates a new Scene
  23600. * @param engine defines the engine to use to render this scene
  23601. */
  23602. function Scene(engine) {
  23603. // Members
  23604. /**
  23605. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23606. */
  23607. this.autoClear = true;
  23608. /**
  23609. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23610. */
  23611. this.autoClearDepthAndStencil = true;
  23612. /**
  23613. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23614. */
  23615. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23616. /**
  23617. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23618. */
  23619. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23620. this._forceWireframe = false;
  23621. this._forcePointsCloud = false;
  23622. /**
  23623. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23624. */
  23625. this.forceShowBoundingBoxes = false;
  23626. /**
  23627. * Gets or sets a boolean indicating if animations are enabled
  23628. */
  23629. this.animationsEnabled = true;
  23630. this._animationPropertiesOverride = null;
  23631. /**
  23632. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23633. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23634. */
  23635. this.useConstantAnimationDeltaTime = false;
  23636. /**
  23637. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23638. * Please note that it requires to run a ray cast through the scene on every frame
  23639. */
  23640. this.constantlyUpdateMeshUnderPointer = false;
  23641. /**
  23642. * Defines the HTML cursor to use when hovering over interactive elements
  23643. */
  23644. this.hoverCursor = "pointer";
  23645. /**
  23646. * Defines the HTML default cursor to use (empty by default)
  23647. */
  23648. this.defaultCursor = "";
  23649. /**
  23650. * This is used to call preventDefault() on pointer down
  23651. * in order to block unwanted artifacts like system double clicks
  23652. */
  23653. this.preventDefaultOnPointerDown = true;
  23654. // Metadata
  23655. /**
  23656. * Gets or sets user defined metadata
  23657. */
  23658. this.metadata = null;
  23659. /**
  23660. * Use this array to add regular expressions used to disable offline support for specific urls
  23661. */
  23662. this.disableOfflineSupportExceptionRules = new Array();
  23663. /**
  23664. * An event triggered when the scene is disposed.
  23665. */
  23666. this.onDisposeObservable = new BABYLON.Observable();
  23667. this._onDisposeObserver = null;
  23668. /**
  23669. * An event triggered before rendering the scene (right after animations and physics)
  23670. */
  23671. this.onBeforeRenderObservable = new BABYLON.Observable();
  23672. this._onBeforeRenderObserver = null;
  23673. /**
  23674. * An event triggered after rendering the scene
  23675. */
  23676. this.onAfterRenderObservable = new BABYLON.Observable();
  23677. this._onAfterRenderObserver = null;
  23678. /**
  23679. * An event triggered before animating the scene
  23680. */
  23681. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23682. /**
  23683. * An event triggered after animations processing
  23684. */
  23685. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23686. /**
  23687. * An event triggered before draw calls are ready to be sent
  23688. */
  23689. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23690. /**
  23691. * An event triggered after draw calls have been sent
  23692. */
  23693. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23694. /**
  23695. * An event triggered when physic simulation is about to be run
  23696. */
  23697. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23698. /**
  23699. * An event triggered when physic simulation has been done
  23700. */
  23701. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23702. /**
  23703. * An event triggered when the scene is ready
  23704. */
  23705. this.onReadyObservable = new BABYLON.Observable();
  23706. /**
  23707. * An event triggered before rendering a camera
  23708. */
  23709. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23710. this._onBeforeCameraRenderObserver = null;
  23711. /**
  23712. * An event triggered after rendering a camera
  23713. */
  23714. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23715. this._onAfterCameraRenderObserver = null;
  23716. /**
  23717. * An event triggered when active meshes evaluation is about to start
  23718. */
  23719. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23720. /**
  23721. * An event triggered when active meshes evaluation is done
  23722. */
  23723. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23724. /**
  23725. * An event triggered when particles rendering is about to start
  23726. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23727. */
  23728. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23729. /**
  23730. * An event triggered when particles rendering is done
  23731. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23732. */
  23733. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23734. /**
  23735. * An event triggered when sprites rendering is about to start
  23736. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23737. */
  23738. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23739. /**
  23740. * An event triggered when sprites rendering is done
  23741. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23742. */
  23743. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23744. /**
  23745. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23746. */
  23747. this.onDataLoadedObservable = new BABYLON.Observable();
  23748. /**
  23749. * An event triggered when a camera is created
  23750. */
  23751. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23752. /**
  23753. * An event triggered when a camera is removed
  23754. */
  23755. this.onCameraRemovedObservable = new BABYLON.Observable();
  23756. /**
  23757. * An event triggered when a light is created
  23758. */
  23759. this.onNewLightAddedObservable = new BABYLON.Observable();
  23760. /**
  23761. * An event triggered when a light is removed
  23762. */
  23763. this.onLightRemovedObservable = new BABYLON.Observable();
  23764. /**
  23765. * An event triggered when a geometry is created
  23766. */
  23767. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23768. /**
  23769. * An event triggered when a geometry is removed
  23770. */
  23771. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23772. /**
  23773. * An event triggered when a transform node is created
  23774. */
  23775. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23776. /**
  23777. * An event triggered when a transform node is removed
  23778. */
  23779. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23780. /**
  23781. * An event triggered when a mesh is created
  23782. */
  23783. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23784. /**
  23785. * An event triggered when a mesh is removed
  23786. */
  23787. this.onMeshRemovedObservable = new BABYLON.Observable();
  23788. /**
  23789. * An event triggered when render targets are about to be rendered
  23790. * Can happen multiple times per frame.
  23791. */
  23792. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23793. /**
  23794. * An event triggered when render targets were rendered.
  23795. * Can happen multiple times per frame.
  23796. */
  23797. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23798. /**
  23799. * An event triggered before calculating deterministic simulation step
  23800. */
  23801. this.onBeforeStepObservable = new BABYLON.Observable();
  23802. /**
  23803. * An event triggered after calculating deterministic simulation step
  23804. */
  23805. this.onAfterStepObservable = new BABYLON.Observable();
  23806. /**
  23807. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23808. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23809. * 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)
  23810. */
  23811. this.onRenderingGroupObservable = new BABYLON.Observable();
  23812. // Animations
  23813. /**
  23814. * Gets a list of Animations associated with the scene
  23815. */
  23816. this.animations = [];
  23817. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23818. /**
  23819. * 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).
  23820. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23821. */
  23822. this.onPrePointerObservable = new BABYLON.Observable();
  23823. /**
  23824. * Observable event triggered each time an input event is received from the rendering canvas
  23825. */
  23826. this.onPointerObservable = new BABYLON.Observable();
  23827. this._meshPickProceed = false;
  23828. this._currentPickResult = null;
  23829. this._previousPickResult = null;
  23830. this._totalPointersPressed = 0;
  23831. this._doubleClickOccured = false;
  23832. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23833. this.cameraToUseForPointers = null;
  23834. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23835. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23836. this._startingPointerTime = 0;
  23837. this._previousStartingPointerTime = 0;
  23838. this._pointerCaptures = {};
  23839. // Deterministic lockstep
  23840. this._timeAccumulator = 0;
  23841. this._currentStepId = 0;
  23842. this._currentInternalStep = 0;
  23843. // Keyboard
  23844. /**
  23845. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23846. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23847. */
  23848. this.onPreKeyboardObservable = new BABYLON.Observable();
  23849. /**
  23850. * Observable event triggered each time an keyboard event is received from the hosting window
  23851. */
  23852. this.onKeyboardObservable = new BABYLON.Observable();
  23853. // Coordinates system
  23854. this._useRightHandedSystem = false;
  23855. // Fog
  23856. this._fogEnabled = true;
  23857. this._fogMode = Scene.FOGMODE_NONE;
  23858. /**
  23859. * Gets or sets the fog color to use
  23860. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23861. */
  23862. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23863. /**
  23864. * Gets or sets the fog density to use
  23865. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23866. */
  23867. this.fogDensity = 0.1;
  23868. /**
  23869. * Gets or sets the fog start distance to use
  23870. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23871. */
  23872. this.fogStart = 0;
  23873. /**
  23874. * Gets or sets the fog end distance to use
  23875. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23876. */
  23877. this.fogEnd = 1000.0;
  23878. // Lights
  23879. this._shadowsEnabled = true;
  23880. this._lightsEnabled = true;
  23881. /**
  23882. * All of the lights added to this scene
  23883. * @see http://doc.babylonjs.com/babylon101/lights
  23884. */
  23885. this.lights = new Array();
  23886. // Cameras
  23887. /** All of the cameras added to this scene.
  23888. * @see http://doc.babylonjs.com/babylon101/cameras
  23889. */
  23890. this.cameras = new Array();
  23891. /** All of the active cameras added to this scene. */
  23892. this.activeCameras = new Array();
  23893. // Meshes
  23894. /**
  23895. * All of the tranform nodes added to this scene
  23896. * @see http://doc.babylonjs.com/how_to/transformnode
  23897. */
  23898. this.transformNodes = new Array();
  23899. /**
  23900. * All of the (abstract) meshes added to this scene
  23901. */
  23902. this.meshes = new Array();
  23903. /**
  23904. * All of the animation groups added to this scene
  23905. * @see http://doc.babylonjs.com/how_to/group
  23906. */
  23907. this.animationGroups = new Array();
  23908. // Geometries
  23909. this._geometries = new Array();
  23910. /**
  23911. * All of the materials added to this scene
  23912. * @see http://doc.babylonjs.com/babylon101/materials
  23913. */
  23914. this.materials = new Array();
  23915. /**
  23916. * All of the multi-materials added to this scene
  23917. * @see http://doc.babylonjs.com/how_to/multi_materials
  23918. */
  23919. this.multiMaterials = new Array();
  23920. // Textures
  23921. this._texturesEnabled = true;
  23922. /**
  23923. * All of the textures added to this scene
  23924. */
  23925. this.textures = new Array();
  23926. // Particles
  23927. /**
  23928. * Gets or sets a boolean indicating if particles are enabled on this scene
  23929. */
  23930. this.particlesEnabled = true;
  23931. /**
  23932. * All of the particle systems added to this scene
  23933. * @see http://doc.babylonjs.com/babylon101/particles
  23934. */
  23935. this.particleSystems = new Array();
  23936. // Sprites
  23937. /**
  23938. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23939. */
  23940. this.spritesEnabled = true;
  23941. /**
  23942. * All of the sprite managers added to this scene
  23943. * @see http://doc.babylonjs.com/babylon101/sprites
  23944. */
  23945. this.spriteManagers = new Array();
  23946. /**
  23947. * The list of layers (background and foreground) of the scene
  23948. */
  23949. this.layers = new Array();
  23950. /**
  23951. * The list of effect layers (highlights/glow) added to the scene
  23952. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23953. * @see http://doc.babylonjs.com/how_to/glow_layer
  23954. */
  23955. this.effectLayers = new Array();
  23956. // Skeletons
  23957. this._skeletonsEnabled = true;
  23958. /**
  23959. * The list of skeletons added to the scene
  23960. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23961. */
  23962. this.skeletons = new Array();
  23963. // Morph targets
  23964. /**
  23965. * The list of morph target managers added to the scene
  23966. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23967. */
  23968. this.morphTargetManagers = new Array();
  23969. // Lens flares
  23970. /**
  23971. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23972. */
  23973. this.lensFlaresEnabled = true;
  23974. /**
  23975. * The list of lens flare system added to the scene
  23976. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23977. */
  23978. this.lensFlareSystems = new Array();
  23979. // Collisions
  23980. /**
  23981. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23982. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23983. */
  23984. this.collisionsEnabled = true;
  23985. /**
  23986. * Defines the gravity applied to this scene (used only for collisions)
  23987. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23988. */
  23989. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23990. // Postprocesses
  23991. /**
  23992. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23993. */
  23994. this.postProcessesEnabled = true;
  23995. /**
  23996. * The list of postprocesses added to the scene
  23997. */
  23998. this.postProcesses = new Array();
  23999. // Customs render targets
  24000. /**
  24001. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24002. */
  24003. this.renderTargetsEnabled = true;
  24004. /**
  24005. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24006. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24007. */
  24008. this.dumpNextRenderTargets = false;
  24009. /**
  24010. * The list of user defined render targets added to the scene
  24011. */
  24012. this.customRenderTargets = new Array();
  24013. /**
  24014. * Gets the list of meshes imported to the scene through SceneLoader
  24015. */
  24016. this.importedMeshesFiles = new Array();
  24017. // Probes
  24018. /**
  24019. * Gets or sets a boolean indicating if probes are enabled on this scene
  24020. */
  24021. this.probesEnabled = true;
  24022. /**
  24023. * The list of reflection probes added to the scene
  24024. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24025. */
  24026. this.reflectionProbes = new Array();
  24027. /** @hidden */
  24028. this._actionManagers = new Array();
  24029. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24030. // Procedural textures
  24031. /**
  24032. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24033. */
  24034. this.proceduralTexturesEnabled = true;
  24035. /**
  24036. * The list of procedural textures added to the scene
  24037. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24038. */
  24039. this.proceduralTextures = new Array();
  24040. /**
  24041. * The list of sound tracks added to the scene
  24042. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24043. */
  24044. this.soundTracks = new Array();
  24045. this._audioEnabled = true;
  24046. this._headphone = false;
  24047. // Performance counters
  24048. this._totalVertices = new BABYLON.PerfCounter();
  24049. /** @hidden */
  24050. this._activeIndices = new BABYLON.PerfCounter();
  24051. /** @hidden */
  24052. this._activeParticles = new BABYLON.PerfCounter();
  24053. /** @hidden */
  24054. this._activeBones = new BABYLON.PerfCounter();
  24055. this._animationTime = 0;
  24056. /**
  24057. * Gets or sets a general scale for animation speed
  24058. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24059. */
  24060. this.animationTimeScale = 1;
  24061. this._renderId = 0;
  24062. this._executeWhenReadyTimeoutId = -1;
  24063. this._intermediateRendering = false;
  24064. this._viewUpdateFlag = -1;
  24065. this._projectionUpdateFlag = -1;
  24066. this._alternateViewUpdateFlag = -1;
  24067. this._alternateProjectionUpdateFlag = -1;
  24068. /** @hidden */
  24069. this._toBeDisposed = new BABYLON.SmartArray(256);
  24070. this._activeRequests = new Array();
  24071. this._pendingData = new Array();
  24072. this._isDisposed = false;
  24073. /**
  24074. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24075. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24076. */
  24077. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24078. this._activeMeshes = new BABYLON.SmartArray(256);
  24079. this._processedMaterials = new BABYLON.SmartArray(256);
  24080. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24081. /** @hidden */
  24082. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24083. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24084. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24085. /** @hidden */
  24086. this._activeAnimatables = new Array();
  24087. this._transformMatrix = BABYLON.Matrix.Zero();
  24088. this._useAlternateCameraConfiguration = false;
  24089. this._alternateRendering = false;
  24090. /**
  24091. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24092. * This is useful if there are more lights that the maximum simulteanous authorized
  24093. */
  24094. this.requireLightSorting = false;
  24095. this._depthRenderer = {};
  24096. this._activeMeshesFrozen = false;
  24097. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24098. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24099. this._engine.scenes.push(this);
  24100. this._uid = null;
  24101. this._renderingManager = new BABYLON.RenderingManager(this);
  24102. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24103. if (BABYLON.OutlineRenderer) {
  24104. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24105. }
  24106. if (BABYLON.Tools.IsWindowObjectExist()) {
  24107. this.attachControl();
  24108. }
  24109. //simplification queue
  24110. if (BABYLON.SimplificationQueue) {
  24111. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24112. }
  24113. //collision coordinator initialization. For now legacy per default.
  24114. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24115. // Uniform Buffer
  24116. this._createUbo();
  24117. // Default Image processing definition.
  24118. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24119. }
  24120. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24121. /** The fog is deactivated */
  24122. get: function () {
  24123. return Scene._FOGMODE_NONE;
  24124. },
  24125. enumerable: true,
  24126. configurable: true
  24127. });
  24128. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24129. /** The fog density is following an exponential function */
  24130. get: function () {
  24131. return Scene._FOGMODE_EXP;
  24132. },
  24133. enumerable: true,
  24134. configurable: true
  24135. });
  24136. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24137. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24138. get: function () {
  24139. return Scene._FOGMODE_EXP2;
  24140. },
  24141. enumerable: true,
  24142. configurable: true
  24143. });
  24144. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24145. /** The fog density is following a linear function. */
  24146. get: function () {
  24147. return Scene._FOGMODE_LINEAR;
  24148. },
  24149. enumerable: true,
  24150. configurable: true
  24151. });
  24152. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24153. /**
  24154. * Texture used in all pbr material as the reflection texture.
  24155. * As in the majority of the scene they are the same (exception for multi room and so on),
  24156. * this is easier to reference from here than from all the materials.
  24157. */
  24158. get: function () {
  24159. return this._environmentTexture;
  24160. },
  24161. /**
  24162. * Texture used in all pbr material as the reflection texture.
  24163. * As in the majority of the scene they are the same (exception for multi room and so on),
  24164. * this is easier to set here than in all the materials.
  24165. */
  24166. set: function (value) {
  24167. if (this._environmentTexture === value) {
  24168. return;
  24169. }
  24170. this._environmentTexture = value;
  24171. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24172. },
  24173. enumerable: true,
  24174. configurable: true
  24175. });
  24176. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24177. /**
  24178. * Default image processing configuration used either in the rendering
  24179. * Forward main pass or through the imageProcessingPostProcess if present.
  24180. * As in the majority of the scene they are the same (exception for multi camera),
  24181. * this is easier to reference from here than from all the materials and post process.
  24182. *
  24183. * No setter as we it is a shared configuration, you can set the values instead.
  24184. */
  24185. get: function () {
  24186. return this._imageProcessingConfiguration;
  24187. },
  24188. enumerable: true,
  24189. configurable: true
  24190. });
  24191. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24192. get: function () {
  24193. return this._forceWireframe;
  24194. },
  24195. /**
  24196. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24197. */
  24198. set: function (value) {
  24199. if (this._forceWireframe === value) {
  24200. return;
  24201. }
  24202. this._forceWireframe = value;
  24203. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24204. },
  24205. enumerable: true,
  24206. configurable: true
  24207. });
  24208. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24209. get: function () {
  24210. return this._forcePointsCloud;
  24211. },
  24212. /**
  24213. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24214. */
  24215. set: function (value) {
  24216. if (this._forcePointsCloud === value) {
  24217. return;
  24218. }
  24219. this._forcePointsCloud = value;
  24220. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24221. },
  24222. enumerable: true,
  24223. configurable: true
  24224. });
  24225. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24226. /**
  24227. * Gets or sets the animation properties override
  24228. */
  24229. get: function () {
  24230. return this._animationPropertiesOverride;
  24231. },
  24232. set: function (value) {
  24233. this._animationPropertiesOverride = value;
  24234. },
  24235. enumerable: true,
  24236. configurable: true
  24237. });
  24238. Object.defineProperty(Scene.prototype, "onDispose", {
  24239. /** Sets a function to be executed when this scene is disposed. */
  24240. set: function (callback) {
  24241. if (this._onDisposeObserver) {
  24242. this.onDisposeObservable.remove(this._onDisposeObserver);
  24243. }
  24244. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24245. },
  24246. enumerable: true,
  24247. configurable: true
  24248. });
  24249. Object.defineProperty(Scene.prototype, "beforeRender", {
  24250. /** Sets a function to be executed before rendering this scene */
  24251. set: function (callback) {
  24252. if (this._onBeforeRenderObserver) {
  24253. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24254. }
  24255. if (callback) {
  24256. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24257. }
  24258. },
  24259. enumerable: true,
  24260. configurable: true
  24261. });
  24262. Object.defineProperty(Scene.prototype, "afterRender", {
  24263. /** Sets a function to be executed after rendering this scene */
  24264. set: function (callback) {
  24265. if (this._onAfterRenderObserver) {
  24266. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24267. }
  24268. if (callback) {
  24269. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24270. }
  24271. },
  24272. enumerable: true,
  24273. configurable: true
  24274. });
  24275. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24276. /** Sets a function to be executed before rendering a camera*/
  24277. set: function (callback) {
  24278. if (this._onBeforeCameraRenderObserver) {
  24279. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24280. }
  24281. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24282. },
  24283. enumerable: true,
  24284. configurable: true
  24285. });
  24286. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24287. /** Sets a function to be executed after rendering a camera*/
  24288. set: function (callback) {
  24289. if (this._onAfterCameraRenderObserver) {
  24290. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24291. }
  24292. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24293. },
  24294. enumerable: true,
  24295. configurable: true
  24296. });
  24297. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24298. /**
  24299. * Gets the gamepad manager associated with the scene
  24300. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24301. */
  24302. get: function () {
  24303. if (!this._gamepadManager) {
  24304. this._gamepadManager = new BABYLON.GamepadManager(this);
  24305. }
  24306. return this._gamepadManager;
  24307. },
  24308. enumerable: true,
  24309. configurable: true
  24310. });
  24311. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24312. /**
  24313. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24314. */
  24315. get: function () {
  24316. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24317. },
  24318. enumerable: true,
  24319. configurable: true
  24320. });
  24321. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24322. get: function () {
  24323. return this._useRightHandedSystem;
  24324. },
  24325. /**
  24326. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24327. */
  24328. set: function (value) {
  24329. if (this._useRightHandedSystem === value) {
  24330. return;
  24331. }
  24332. this._useRightHandedSystem = value;
  24333. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24334. },
  24335. enumerable: true,
  24336. configurable: true
  24337. });
  24338. /**
  24339. * Sets the step Id used by deterministic lock step
  24340. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24341. * @param newStepId defines the step Id
  24342. */
  24343. Scene.prototype.setStepId = function (newStepId) {
  24344. this._currentStepId = newStepId;
  24345. };
  24346. ;
  24347. /**
  24348. * Gets the step Id used by deterministic lock step
  24349. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24350. * @returns the step Id
  24351. */
  24352. Scene.prototype.getStepId = function () {
  24353. return this._currentStepId;
  24354. };
  24355. ;
  24356. /**
  24357. * Gets the internal step used by deterministic lock step
  24358. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24359. * @returns the internal step
  24360. */
  24361. Scene.prototype.getInternalStep = function () {
  24362. return this._currentInternalStep;
  24363. };
  24364. ;
  24365. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24366. get: function () {
  24367. return this._fogEnabled;
  24368. },
  24369. /**
  24370. * Gets or sets a boolean indicating if fog is enabled on this scene
  24371. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24372. */
  24373. set: function (value) {
  24374. if (this._fogEnabled === value) {
  24375. return;
  24376. }
  24377. this._fogEnabled = value;
  24378. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24379. },
  24380. enumerable: true,
  24381. configurable: true
  24382. });
  24383. Object.defineProperty(Scene.prototype, "fogMode", {
  24384. get: function () {
  24385. return this._fogMode;
  24386. },
  24387. /**
  24388. * Gets or sets the fog mode to use
  24389. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24390. */
  24391. set: function (value) {
  24392. if (this._fogMode === value) {
  24393. return;
  24394. }
  24395. this._fogMode = value;
  24396. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24397. },
  24398. enumerable: true,
  24399. configurable: true
  24400. });
  24401. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24402. get: function () {
  24403. return this._shadowsEnabled;
  24404. },
  24405. /**
  24406. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24407. */
  24408. set: function (value) {
  24409. if (this._shadowsEnabled === value) {
  24410. return;
  24411. }
  24412. this._shadowsEnabled = value;
  24413. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24414. },
  24415. enumerable: true,
  24416. configurable: true
  24417. });
  24418. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24419. get: function () {
  24420. return this._lightsEnabled;
  24421. },
  24422. /**
  24423. * Gets or sets a boolean indicating if lights are enabled on this scene
  24424. */
  24425. set: function (value) {
  24426. if (this._lightsEnabled === value) {
  24427. return;
  24428. }
  24429. this._lightsEnabled = value;
  24430. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24431. },
  24432. enumerable: true,
  24433. configurable: true
  24434. });
  24435. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24436. /** The default material used on meshes when no material is affected */
  24437. get: function () {
  24438. if (!this._defaultMaterial) {
  24439. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24440. }
  24441. return this._defaultMaterial;
  24442. },
  24443. /** The default material used on meshes when no material is affected */
  24444. set: function (value) {
  24445. this._defaultMaterial = value;
  24446. },
  24447. enumerable: true,
  24448. configurable: true
  24449. });
  24450. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24451. get: function () {
  24452. return this._texturesEnabled;
  24453. },
  24454. /**
  24455. * Gets or sets a boolean indicating if textures are enabled on this scene
  24456. */
  24457. set: function (value) {
  24458. if (this._texturesEnabled === value) {
  24459. return;
  24460. }
  24461. this._texturesEnabled = value;
  24462. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24463. },
  24464. enumerable: true,
  24465. configurable: true
  24466. });
  24467. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24468. get: function () {
  24469. return this._skeletonsEnabled;
  24470. },
  24471. /**
  24472. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24473. */
  24474. set: function (value) {
  24475. if (this._skeletonsEnabled === value) {
  24476. return;
  24477. }
  24478. this._skeletonsEnabled = value;
  24479. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24480. },
  24481. enumerable: true,
  24482. configurable: true
  24483. });
  24484. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24485. /**
  24486. * Gets the postprocess render pipeline manager
  24487. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24488. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24489. */
  24490. get: function () {
  24491. if (!this._postProcessRenderPipelineManager) {
  24492. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24493. }
  24494. return this._postProcessRenderPipelineManager;
  24495. },
  24496. enumerable: true,
  24497. configurable: true
  24498. });
  24499. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24500. /**
  24501. * Gets the main soundtrack associated with the scene
  24502. */
  24503. get: function () {
  24504. if (!this._mainSoundTrack) {
  24505. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24506. }
  24507. return this._mainSoundTrack;
  24508. },
  24509. enumerable: true,
  24510. configurable: true
  24511. });
  24512. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24513. /** @hidden */
  24514. get: function () {
  24515. return this._alternateRendering;
  24516. },
  24517. enumerable: true,
  24518. configurable: true
  24519. });
  24520. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24521. /**
  24522. * Gets the list of frustum planes (built from the active camera)
  24523. */
  24524. get: function () {
  24525. return this._frustumPlanes;
  24526. },
  24527. enumerable: true,
  24528. configurable: true
  24529. });
  24530. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24531. /**
  24532. * Gets the current geometry buffer associated to the scene.
  24533. */
  24534. get: function () {
  24535. return this._geometryBufferRenderer;
  24536. },
  24537. /**
  24538. * Sets the current geometry buffer for the scene.
  24539. */
  24540. set: function (geometryBufferRenderer) {
  24541. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24542. this._geometryBufferRenderer = geometryBufferRenderer;
  24543. }
  24544. },
  24545. enumerable: true,
  24546. configurable: true
  24547. });
  24548. Object.defineProperty(Scene.prototype, "debugLayer", {
  24549. /**
  24550. * Gets the debug layer associated with the scene
  24551. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24552. */
  24553. get: function () {
  24554. if (!this._debugLayer) {
  24555. this._debugLayer = new BABYLON.DebugLayer(this);
  24556. }
  24557. return this._debugLayer;
  24558. },
  24559. enumerable: true,
  24560. configurable: true
  24561. });
  24562. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24563. /**
  24564. * Gets a boolean indicating if collisions are processed on a web worker
  24565. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24566. */
  24567. get: function () {
  24568. return this._workerCollisions;
  24569. },
  24570. set: function (enabled) {
  24571. if (!BABYLON.CollisionCoordinatorLegacy) {
  24572. return;
  24573. }
  24574. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24575. this._workerCollisions = enabled;
  24576. if (this.collisionCoordinator) {
  24577. this.collisionCoordinator.destroy();
  24578. }
  24579. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24580. this.collisionCoordinator.init(this);
  24581. },
  24582. enumerable: true,
  24583. configurable: true
  24584. });
  24585. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24586. /**
  24587. * Gets the octree used to boost mesh selection (picking)
  24588. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24589. */
  24590. get: function () {
  24591. return this._selectionOctree;
  24592. },
  24593. enumerable: true,
  24594. configurable: true
  24595. });
  24596. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24597. /**
  24598. * Gets the mesh that is currently under the pointer
  24599. */
  24600. get: function () {
  24601. return this._pointerOverMesh;
  24602. },
  24603. enumerable: true,
  24604. configurable: true
  24605. });
  24606. Object.defineProperty(Scene.prototype, "pointerX", {
  24607. /**
  24608. * Gets the current on-screen X position of the pointer
  24609. */
  24610. get: function () {
  24611. return this._pointerX;
  24612. },
  24613. enumerable: true,
  24614. configurable: true
  24615. });
  24616. Object.defineProperty(Scene.prototype, "pointerY", {
  24617. /**
  24618. * Gets the current on-screen Y position of the pointer
  24619. */
  24620. get: function () {
  24621. return this._pointerY;
  24622. },
  24623. enumerable: true,
  24624. configurable: true
  24625. });
  24626. /**
  24627. * Gets the cached material (ie. the latest rendered one)
  24628. * @returns the cached material
  24629. */
  24630. Scene.prototype.getCachedMaterial = function () {
  24631. return this._cachedMaterial;
  24632. };
  24633. /**
  24634. * Gets the cached effect (ie. the latest rendered one)
  24635. * @returns the cached effect
  24636. */
  24637. Scene.prototype.getCachedEffect = function () {
  24638. return this._cachedEffect;
  24639. };
  24640. /**
  24641. * Gets the cached visibility state (ie. the latest rendered one)
  24642. * @returns the cached visibility state
  24643. */
  24644. Scene.prototype.getCachedVisibility = function () {
  24645. return this._cachedVisibility;
  24646. };
  24647. /**
  24648. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24649. * @param material defines the current material
  24650. * @param effect defines the current effect
  24651. * @param visibility defines the current visibility state
  24652. * @returns true if one parameter is not cached
  24653. */
  24654. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24655. if (visibility === void 0) { visibility = 1; }
  24656. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24657. };
  24658. /**
  24659. * Gets the bounding box renderer associated with the scene
  24660. * @returns a BoundingBoxRenderer
  24661. */
  24662. Scene.prototype.getBoundingBoxRenderer = function () {
  24663. if (!this._boundingBoxRenderer) {
  24664. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24665. }
  24666. return this._boundingBoxRenderer;
  24667. };
  24668. /**
  24669. * Gets the outline renderer associated with the scene
  24670. * @returns a OutlineRenderer
  24671. */
  24672. Scene.prototype.getOutlineRenderer = function () {
  24673. return this._outlineRenderer;
  24674. };
  24675. /**
  24676. * Gets the engine associated with the scene
  24677. * @returns an Engine
  24678. */
  24679. Scene.prototype.getEngine = function () {
  24680. return this._engine;
  24681. };
  24682. /**
  24683. * Gets the total number of vertices rendered per frame
  24684. * @returns the total number of vertices rendered per frame
  24685. */
  24686. Scene.prototype.getTotalVertices = function () {
  24687. return this._totalVertices.current;
  24688. };
  24689. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24690. /**
  24691. * Gets the performance counter for total vertices
  24692. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24693. */
  24694. get: function () {
  24695. return this._totalVertices;
  24696. },
  24697. enumerable: true,
  24698. configurable: true
  24699. });
  24700. /**
  24701. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24702. * @returns the total number of active indices rendered per frame
  24703. */
  24704. Scene.prototype.getActiveIndices = function () {
  24705. return this._activeIndices.current;
  24706. };
  24707. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24708. /**
  24709. * Gets the performance counter for active indices
  24710. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24711. */
  24712. get: function () {
  24713. return this._activeIndices;
  24714. },
  24715. enumerable: true,
  24716. configurable: true
  24717. });
  24718. /**
  24719. * Gets the total number of active particles rendered per frame
  24720. * @returns the total number of active particles rendered per frame
  24721. */
  24722. Scene.prototype.getActiveParticles = function () {
  24723. return this._activeParticles.current;
  24724. };
  24725. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24726. /**
  24727. * Gets the performance counter for active particles
  24728. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24729. */
  24730. get: function () {
  24731. return this._activeParticles;
  24732. },
  24733. enumerable: true,
  24734. configurable: true
  24735. });
  24736. /**
  24737. * Gets the total number of active bones rendered per frame
  24738. * @returns the total number of active bones rendered per frame
  24739. */
  24740. Scene.prototype.getActiveBones = function () {
  24741. return this._activeBones.current;
  24742. };
  24743. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24744. /**
  24745. * Gets the performance counter for active bones
  24746. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24747. */
  24748. get: function () {
  24749. return this._activeBones;
  24750. },
  24751. enumerable: true,
  24752. configurable: true
  24753. });
  24754. /** @hidden */
  24755. Scene.prototype.getInterFramePerfCounter = function () {
  24756. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24757. return 0;
  24758. };
  24759. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24760. /** @hidden */
  24761. get: function () {
  24762. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24763. return null;
  24764. },
  24765. enumerable: true,
  24766. configurable: true
  24767. });
  24768. /** @hidden */
  24769. Scene.prototype.getLastFrameDuration = function () {
  24770. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24771. return 0;
  24772. };
  24773. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24774. /** @hidden */
  24775. get: function () {
  24776. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24777. return null;
  24778. },
  24779. enumerable: true,
  24780. configurable: true
  24781. });
  24782. /** @hidden */
  24783. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24784. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24785. return 0;
  24786. };
  24787. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24788. /** @hidden */
  24789. get: function () {
  24790. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24791. return null;
  24792. },
  24793. enumerable: true,
  24794. configurable: true
  24795. });
  24796. /**
  24797. * Gets the array of active meshes
  24798. * @returns an array of AbstractMesh
  24799. */
  24800. Scene.prototype.getActiveMeshes = function () {
  24801. return this._activeMeshes;
  24802. };
  24803. /** @hidden */
  24804. Scene.prototype.getRenderTargetsDuration = function () {
  24805. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24806. return 0;
  24807. };
  24808. /** @hidden */
  24809. Scene.prototype.getRenderDuration = function () {
  24810. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24811. return 0;
  24812. };
  24813. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24814. /** @hidden */
  24815. get: function () {
  24816. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24817. return null;
  24818. },
  24819. enumerable: true,
  24820. configurable: true
  24821. });
  24822. /** @hidden */
  24823. Scene.prototype.getParticlesDuration = function () {
  24824. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24825. return 0;
  24826. };
  24827. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24828. /** @hidden */
  24829. get: function () {
  24830. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24831. return null;
  24832. },
  24833. enumerable: true,
  24834. configurable: true
  24835. });
  24836. /** @hidden */
  24837. Scene.prototype.getSpritesDuration = function () {
  24838. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24839. return 0;
  24840. };
  24841. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24842. /** @hidden */
  24843. get: function () {
  24844. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24845. return null;
  24846. },
  24847. enumerable: true,
  24848. configurable: true
  24849. });
  24850. /**
  24851. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24852. * @returns a number
  24853. */
  24854. Scene.prototype.getAnimationRatio = function () {
  24855. return this._animationRatio;
  24856. };
  24857. /**
  24858. * Gets an unique Id for the current frame
  24859. * @returns a number
  24860. */
  24861. Scene.prototype.getRenderId = function () {
  24862. return this._renderId;
  24863. };
  24864. /** Call this function if you want to manually increment the render Id*/
  24865. Scene.prototype.incrementRenderId = function () {
  24866. this._renderId++;
  24867. };
  24868. Scene.prototype._updatePointerPosition = function (evt) {
  24869. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24870. if (!canvasRect) {
  24871. return;
  24872. }
  24873. this._pointerX = evt.clientX - canvasRect.left;
  24874. this._pointerY = evt.clientY - canvasRect.top;
  24875. this._unTranslatedPointerX = this._pointerX;
  24876. this._unTranslatedPointerY = this._pointerY;
  24877. };
  24878. Scene.prototype._createUbo = function () {
  24879. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24880. this._sceneUbo.addUniform("viewProjection", 16);
  24881. this._sceneUbo.addUniform("view", 16);
  24882. };
  24883. Scene.prototype._createAlternateUbo = function () {
  24884. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24885. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24886. this._alternateSceneUbo.addUniform("view", 16);
  24887. };
  24888. // Pointers handling
  24889. /**
  24890. * Use this method to simulate a pointer move on a mesh
  24891. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24892. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24893. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24894. * @returns the current scene
  24895. */
  24896. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24897. var evt = new PointerEvent("pointermove", pointerEventInit);
  24898. return this._processPointerMove(pickResult, evt);
  24899. };
  24900. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24901. var canvas = this._engine.getRenderingCanvas();
  24902. if (!canvas) {
  24903. return this;
  24904. }
  24905. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24906. this.setPointerOverSprite(null);
  24907. this.setPointerOverMesh(pickResult.pickedMesh);
  24908. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24909. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24910. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24911. }
  24912. else {
  24913. canvas.style.cursor = this.hoverCursor;
  24914. }
  24915. }
  24916. else {
  24917. canvas.style.cursor = this.defaultCursor;
  24918. }
  24919. }
  24920. else {
  24921. this.setPointerOverMesh(null);
  24922. // Sprites
  24923. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24924. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24925. this.setPointerOverSprite(pickResult.pickedSprite);
  24926. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24927. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24928. }
  24929. else {
  24930. canvas.style.cursor = this.hoverCursor;
  24931. }
  24932. }
  24933. else {
  24934. this.setPointerOverSprite(null);
  24935. // Restore pointer
  24936. canvas.style.cursor = this.defaultCursor;
  24937. }
  24938. }
  24939. if (pickResult) {
  24940. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24941. if (this.onPointerMove) {
  24942. this.onPointerMove(evt, pickResult, type);
  24943. }
  24944. if (this.onPointerObservable.hasObservers()) {
  24945. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24946. this.onPointerObservable.notifyObservers(pi, type);
  24947. }
  24948. }
  24949. return this;
  24950. };
  24951. /**
  24952. * Use this method to simulate a pointer down on a mesh
  24953. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24954. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24955. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24956. * @returns the current scene
  24957. */
  24958. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24959. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24960. return this._processPointerDown(pickResult, evt);
  24961. };
  24962. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24963. var _this = this;
  24964. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24965. this._pickedDownMesh = pickResult.pickedMesh;
  24966. var actionManager = pickResult.pickedMesh.actionManager;
  24967. if (actionManager) {
  24968. if (actionManager.hasPickTriggers) {
  24969. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24970. switch (evt.button) {
  24971. case 0:
  24972. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24973. break;
  24974. case 1:
  24975. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24976. break;
  24977. case 2:
  24978. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24979. break;
  24980. }
  24981. }
  24982. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24983. window.setTimeout(function () {
  24984. 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);
  24985. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24986. if (_this._totalPointersPressed !== 0 &&
  24987. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24988. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24989. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24990. _this._startingPointerTime = 0;
  24991. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24992. }
  24993. }
  24994. }, Scene.LongPressDelay);
  24995. }
  24996. }
  24997. }
  24998. if (pickResult) {
  24999. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25000. if (this.onPointerDown) {
  25001. this.onPointerDown(evt, pickResult, type);
  25002. }
  25003. if (this.onPointerObservable.hasObservers()) {
  25004. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25005. this.onPointerObservable.notifyObservers(pi, type);
  25006. }
  25007. }
  25008. return this;
  25009. };
  25010. /**
  25011. * Use this method to simulate a pointer up on a mesh
  25012. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25013. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25014. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25015. * @returns the current scene
  25016. */
  25017. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25018. var evt = new PointerEvent("pointerup", pointerEventInit);
  25019. var clickInfo = new ClickInfo();
  25020. clickInfo.singleClick = true;
  25021. clickInfo.ignore = true;
  25022. return this._processPointerUp(pickResult, evt, clickInfo);
  25023. };
  25024. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25025. if (pickResult && pickResult && pickResult.pickedMesh) {
  25026. this._pickedUpMesh = pickResult.pickedMesh;
  25027. if (this._pickedDownMesh === this._pickedUpMesh) {
  25028. if (this.onPointerPick) {
  25029. this.onPointerPick(evt, pickResult);
  25030. }
  25031. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25032. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25033. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25034. this.onPointerObservable.notifyObservers(pi, type_1);
  25035. }
  25036. }
  25037. if (pickResult.pickedMesh.actionManager) {
  25038. if (clickInfo.ignore) {
  25039. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25040. }
  25041. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25042. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25043. }
  25044. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25045. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25046. }
  25047. }
  25048. }
  25049. if (this._pickedDownMesh &&
  25050. this._pickedDownMesh.actionManager &&
  25051. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25052. this._pickedDownMesh !== this._pickedUpMesh) {
  25053. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25054. }
  25055. var type = BABYLON.PointerEventTypes.POINTERUP;
  25056. if (this.onPointerObservable.hasObservers()) {
  25057. if (!clickInfo.ignore) {
  25058. if (!clickInfo.hasSwiped) {
  25059. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25060. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25061. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25062. this.onPointerObservable.notifyObservers(pi, type_2);
  25063. }
  25064. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25065. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25066. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25067. this.onPointerObservable.notifyObservers(pi, type_3);
  25068. }
  25069. }
  25070. }
  25071. else {
  25072. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25073. this.onPointerObservable.notifyObservers(pi, type);
  25074. }
  25075. }
  25076. if (this.onPointerUp) {
  25077. this.onPointerUp(evt, pickResult, type);
  25078. }
  25079. return this;
  25080. };
  25081. /**
  25082. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25083. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25084. * @returns true if the pointer was captured
  25085. */
  25086. Scene.prototype.isPointerCaptured = function (pointerId) {
  25087. if (pointerId === void 0) { pointerId = 0; }
  25088. return this._pointerCaptures[pointerId];
  25089. };
  25090. /**
  25091. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25092. * @param attachUp defines if you want to attach events to pointerup
  25093. * @param attachDown defines if you want to attach events to pointerdown
  25094. * @param attachMove defines if you want to attach events to pointermove
  25095. */
  25096. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25097. var _this = this;
  25098. if (attachUp === void 0) { attachUp = true; }
  25099. if (attachDown === void 0) { attachDown = true; }
  25100. if (attachMove === void 0) { attachMove = true; }
  25101. this._initActionManager = function (act, clickInfo) {
  25102. if (!_this._meshPickProceed) {
  25103. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25104. _this._currentPickResult = pickResult;
  25105. if (pickResult) {
  25106. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25107. }
  25108. _this._meshPickProceed = true;
  25109. }
  25110. return act;
  25111. };
  25112. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25113. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25114. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25115. btn !== _this._previousButtonPressed) {
  25116. _this._doubleClickOccured = false;
  25117. clickInfo.singleClick = true;
  25118. clickInfo.ignore = false;
  25119. cb(clickInfo, _this._currentPickResult);
  25120. }
  25121. };
  25122. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25123. var clickInfo = new ClickInfo();
  25124. _this._currentPickResult = null;
  25125. var act = null;
  25126. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25127. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25128. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25129. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25130. act = _this._initActionManager(act, clickInfo);
  25131. if (act)
  25132. checkPicking = act.hasPickTriggers;
  25133. }
  25134. if (checkPicking) {
  25135. var btn = evt.button;
  25136. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25137. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25138. if (!clickInfo.hasSwiped) {
  25139. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25140. if (!checkSingleClickImmediately) {
  25141. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25142. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25143. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25144. act = _this._initActionManager(act, clickInfo);
  25145. if (act)
  25146. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25147. }
  25148. }
  25149. if (checkSingleClickImmediately) {
  25150. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25151. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25152. btn !== _this._previousButtonPressed) {
  25153. clickInfo.singleClick = true;
  25154. cb(clickInfo, _this._currentPickResult);
  25155. }
  25156. }
  25157. // at least one double click is required to be check and exclusive double click is enabled
  25158. else {
  25159. // wait that no double click has been raised during the double click delay
  25160. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25161. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25162. }
  25163. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25164. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25165. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25166. act = _this._initActionManager(act, clickInfo);
  25167. if (act)
  25168. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25169. }
  25170. if (checkDoubleClick) {
  25171. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25172. if (btn === _this._previousButtonPressed &&
  25173. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25174. !_this._doubleClickOccured) {
  25175. // pointer has not moved for 2 clicks, it's a double click
  25176. if (!clickInfo.hasSwiped &&
  25177. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25178. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25179. _this._previousStartingPointerTime = 0;
  25180. _this._doubleClickOccured = true;
  25181. clickInfo.doubleClick = true;
  25182. clickInfo.ignore = false;
  25183. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25184. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25185. }
  25186. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25187. cb(clickInfo, _this._currentPickResult);
  25188. }
  25189. // if the two successive clicks are too far, it's just two simple clicks
  25190. else {
  25191. _this._doubleClickOccured = false;
  25192. _this._previousStartingPointerTime = _this._startingPointerTime;
  25193. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25194. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25195. _this._previousButtonPressed = btn;
  25196. if (Scene.ExclusiveDoubleClickMode) {
  25197. if (_this._previousDelayedSimpleClickTimeout) {
  25198. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25199. }
  25200. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25201. cb(clickInfo, _this._previousPickResult);
  25202. }
  25203. else {
  25204. cb(clickInfo, _this._currentPickResult);
  25205. }
  25206. }
  25207. }
  25208. // just the first click of the double has been raised
  25209. else {
  25210. _this._doubleClickOccured = false;
  25211. _this._previousStartingPointerTime = _this._startingPointerTime;
  25212. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25213. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25214. _this._previousButtonPressed = btn;
  25215. }
  25216. }
  25217. }
  25218. }
  25219. clickInfo.ignore = true;
  25220. cb(clickInfo, _this._currentPickResult);
  25221. };
  25222. this._spritePredicate = function (sprite) {
  25223. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25224. };
  25225. this._onPointerMove = function (evt) {
  25226. _this._updatePointerPosition(evt);
  25227. // PreObservable support
  25228. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25229. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25230. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25231. _this.onPrePointerObservable.notifyObservers(pi, type);
  25232. if (pi.skipOnPointerObservable) {
  25233. return;
  25234. }
  25235. }
  25236. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25237. return;
  25238. }
  25239. if (!_this.pointerMovePredicate) {
  25240. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25241. }
  25242. // Meshes
  25243. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25244. _this._processPointerMove(pickResult, evt);
  25245. };
  25246. this._onPointerDown = function (evt) {
  25247. _this._totalPointersPressed++;
  25248. _this._pickedDownMesh = null;
  25249. _this._meshPickProceed = false;
  25250. _this._updatePointerPosition(evt);
  25251. if (_this.preventDefaultOnPointerDown && canvas) {
  25252. evt.preventDefault();
  25253. canvas.focus();
  25254. }
  25255. // PreObservable support
  25256. if (_this.onPrePointerObservable.hasObservers()) {
  25257. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25258. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25259. _this.onPrePointerObservable.notifyObservers(pi, type);
  25260. if (pi.skipOnPointerObservable) {
  25261. return;
  25262. }
  25263. }
  25264. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25265. return;
  25266. }
  25267. _this._pointerCaptures[evt.pointerId] = true;
  25268. _this._startingPointerPosition.x = _this._pointerX;
  25269. _this._startingPointerPosition.y = _this._pointerY;
  25270. _this._startingPointerTime = Date.now();
  25271. if (!_this.pointerDownPredicate) {
  25272. _this.pointerDownPredicate = function (mesh) {
  25273. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25274. };
  25275. }
  25276. // Meshes
  25277. _this._pickedDownMesh = null;
  25278. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25279. _this._processPointerDown(pickResult, evt);
  25280. // Sprites
  25281. _this._pickedDownSprite = null;
  25282. if (_this.spriteManagers.length > 0) {
  25283. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25284. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25285. if (pickResult.pickedSprite.actionManager) {
  25286. _this._pickedDownSprite = pickResult.pickedSprite;
  25287. switch (evt.button) {
  25288. case 0:
  25289. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25290. break;
  25291. case 1:
  25292. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25293. break;
  25294. case 2:
  25295. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25296. break;
  25297. }
  25298. if (pickResult.pickedSprite.actionManager) {
  25299. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25300. }
  25301. }
  25302. }
  25303. }
  25304. };
  25305. this._onPointerUp = function (evt) {
  25306. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25307. return; // So we need to test it the pointer down was pressed before.
  25308. }
  25309. _this._totalPointersPressed--;
  25310. _this._pickedUpMesh = null;
  25311. _this._meshPickProceed = false;
  25312. _this._updatePointerPosition(evt);
  25313. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25314. // PreObservable support
  25315. if (_this.onPrePointerObservable.hasObservers()) {
  25316. if (!clickInfo.ignore) {
  25317. if (!clickInfo.hasSwiped) {
  25318. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25319. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25320. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25321. _this.onPrePointerObservable.notifyObservers(pi, type);
  25322. if (pi.skipOnPointerObservable) {
  25323. return;
  25324. }
  25325. }
  25326. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25327. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25328. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25329. _this.onPrePointerObservable.notifyObservers(pi, type);
  25330. if (pi.skipOnPointerObservable) {
  25331. return;
  25332. }
  25333. }
  25334. }
  25335. }
  25336. else {
  25337. var type = BABYLON.PointerEventTypes.POINTERUP;
  25338. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25339. _this.onPrePointerObservable.notifyObservers(pi, type);
  25340. if (pi.skipOnPointerObservable) {
  25341. return;
  25342. }
  25343. }
  25344. }
  25345. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25346. return;
  25347. }
  25348. _this._pointerCaptures[evt.pointerId] = false;
  25349. if (!_this.pointerUpPredicate) {
  25350. _this.pointerUpPredicate = function (mesh) {
  25351. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25352. };
  25353. }
  25354. // Meshes
  25355. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25356. _this._initActionManager(null, clickInfo);
  25357. }
  25358. if (!pickResult) {
  25359. pickResult = _this._currentPickResult;
  25360. }
  25361. _this._processPointerUp(pickResult, evt, clickInfo);
  25362. // Sprites
  25363. if (!clickInfo.ignore) {
  25364. if (_this.spriteManagers.length > 0) {
  25365. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25366. if (spritePickResult) {
  25367. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25368. if (spritePickResult.pickedSprite.actionManager) {
  25369. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25370. if (spritePickResult.pickedSprite.actionManager) {
  25371. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25372. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25373. }
  25374. }
  25375. }
  25376. }
  25377. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25378. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25379. }
  25380. }
  25381. }
  25382. }
  25383. _this._previousPickResult = _this._currentPickResult;
  25384. });
  25385. };
  25386. this._onKeyDown = function (evt) {
  25387. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25388. if (_this.onPreKeyboardObservable.hasObservers()) {
  25389. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25390. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25391. if (pi.skipOnPointerObservable) {
  25392. return;
  25393. }
  25394. }
  25395. if (_this.onKeyboardObservable.hasObservers()) {
  25396. var pi = new BABYLON.KeyboardInfo(type, evt);
  25397. _this.onKeyboardObservable.notifyObservers(pi, type);
  25398. }
  25399. if (_this.actionManager) {
  25400. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25401. }
  25402. };
  25403. this._onKeyUp = function (evt) {
  25404. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25405. if (_this.onPreKeyboardObservable.hasObservers()) {
  25406. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25407. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25408. if (pi.skipOnPointerObservable) {
  25409. return;
  25410. }
  25411. }
  25412. if (_this.onKeyboardObservable.hasObservers()) {
  25413. var pi = new BABYLON.KeyboardInfo(type, evt);
  25414. _this.onKeyboardObservable.notifyObservers(pi, type);
  25415. }
  25416. if (_this.actionManager) {
  25417. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25418. }
  25419. };
  25420. var engine = this.getEngine();
  25421. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25422. if (!canvas) {
  25423. return;
  25424. }
  25425. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25426. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25427. });
  25428. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25429. if (!canvas) {
  25430. return;
  25431. }
  25432. canvas.removeEventListener("keydown", _this._onKeyDown);
  25433. canvas.removeEventListener("keyup", _this._onKeyUp);
  25434. });
  25435. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25436. var canvas = this._engine.getRenderingCanvas();
  25437. if (!canvas) {
  25438. return;
  25439. }
  25440. if (attachMove) {
  25441. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25442. // Wheel
  25443. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25444. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25445. }
  25446. if (attachDown) {
  25447. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25448. }
  25449. if (attachUp) {
  25450. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25451. }
  25452. canvas.tabIndex = 1;
  25453. };
  25454. /** Detaches all event handlers*/
  25455. Scene.prototype.detachControl = function () {
  25456. var engine = this.getEngine();
  25457. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25458. var canvas = engine.getRenderingCanvas();
  25459. if (!canvas) {
  25460. return;
  25461. }
  25462. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25463. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25464. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25465. if (this._onCanvasBlurObserver) {
  25466. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25467. }
  25468. if (this._onCanvasFocusObserver) {
  25469. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25470. }
  25471. // Wheel
  25472. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25473. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25474. // Keyboard
  25475. canvas.removeEventListener("keydown", this._onKeyDown);
  25476. canvas.removeEventListener("keyup", this._onKeyUp);
  25477. // Observables
  25478. this.onKeyboardObservable.clear();
  25479. this.onPreKeyboardObservable.clear();
  25480. this.onPointerObservable.clear();
  25481. this.onPrePointerObservable.clear();
  25482. };
  25483. /**
  25484. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25485. * Delay loaded resources are not taking in account
  25486. * @return true if all required resources are ready
  25487. */
  25488. Scene.prototype.isReady = function () {
  25489. if (this._isDisposed) {
  25490. return false;
  25491. }
  25492. if (this._pendingData.length > 0) {
  25493. return false;
  25494. }
  25495. var index;
  25496. var engine = this.getEngine();
  25497. // Geometries
  25498. for (index = 0; index < this._geometries.length; index++) {
  25499. var geometry = this._geometries[index];
  25500. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25501. return false;
  25502. }
  25503. }
  25504. // Meshes
  25505. for (index = 0; index < this.meshes.length; index++) {
  25506. var mesh = this.meshes[index];
  25507. if (!mesh.isEnabled()) {
  25508. continue;
  25509. }
  25510. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25511. continue;
  25512. }
  25513. if (!mesh.isReady(true)) {
  25514. return false;
  25515. }
  25516. // Effect layers
  25517. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25518. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25519. var layer = _a[_i];
  25520. if (!layer.hasMesh(mesh)) {
  25521. continue;
  25522. }
  25523. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25524. var subMesh = _c[_b];
  25525. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25526. return false;
  25527. }
  25528. }
  25529. }
  25530. }
  25531. // Post-processes
  25532. if (this.activeCameras && this.activeCameras.length > 0) {
  25533. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25534. var camera = _e[_d];
  25535. if (!camera.isReady(true)) {
  25536. return false;
  25537. }
  25538. }
  25539. }
  25540. else if (this.activeCamera) {
  25541. if (!this.activeCamera.isReady(true)) {
  25542. return false;
  25543. }
  25544. }
  25545. // Particles
  25546. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25547. var particleSystem = _g[_f];
  25548. if (!particleSystem.isReady()) {
  25549. return false;
  25550. }
  25551. }
  25552. return true;
  25553. };
  25554. /** Resets all cached information relative to material (including effect and visibility) */
  25555. Scene.prototype.resetCachedMaterial = function () {
  25556. this._cachedMaterial = null;
  25557. this._cachedEffect = null;
  25558. this._cachedVisibility = null;
  25559. };
  25560. /**
  25561. * Registers a function to be called before every frame render
  25562. * @param func defines the function to register
  25563. */
  25564. Scene.prototype.registerBeforeRender = function (func) {
  25565. this.onBeforeRenderObservable.add(func);
  25566. };
  25567. /**
  25568. * Unregisters a function called before every frame render
  25569. * @param func defines the function to unregister
  25570. */
  25571. Scene.prototype.unregisterBeforeRender = function (func) {
  25572. this.onBeforeRenderObservable.removeCallback(func);
  25573. };
  25574. /**
  25575. * Registers a function to be called after every frame render
  25576. * @param func defines the function to register
  25577. */
  25578. Scene.prototype.registerAfterRender = function (func) {
  25579. this.onAfterRenderObservable.add(func);
  25580. };
  25581. /**
  25582. * Unregisters a function called after every frame render
  25583. * @param func defines the function to unregister
  25584. */
  25585. Scene.prototype.unregisterAfterRender = function (func) {
  25586. this.onAfterRenderObservable.removeCallback(func);
  25587. };
  25588. Scene.prototype._executeOnceBeforeRender = function (func) {
  25589. var _this = this;
  25590. var execFunc = function () {
  25591. func();
  25592. setTimeout(function () {
  25593. _this.unregisterBeforeRender(execFunc);
  25594. });
  25595. };
  25596. this.registerBeforeRender(execFunc);
  25597. };
  25598. /**
  25599. * The provided function will run before render once and will be disposed afterwards.
  25600. * A timeout delay can be provided so that the function will be executed in N ms.
  25601. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25602. * @param func The function to be executed.
  25603. * @param timeout optional delay in ms
  25604. */
  25605. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25606. var _this = this;
  25607. if (timeout !== undefined) {
  25608. setTimeout(function () {
  25609. _this._executeOnceBeforeRender(func);
  25610. }, timeout);
  25611. }
  25612. else {
  25613. this._executeOnceBeforeRender(func);
  25614. }
  25615. };
  25616. /** @hidden */
  25617. Scene.prototype._addPendingData = function (data) {
  25618. this._pendingData.push(data);
  25619. };
  25620. /** @hidden */
  25621. Scene.prototype._removePendingData = function (data) {
  25622. var wasLoading = this.isLoading;
  25623. var index = this._pendingData.indexOf(data);
  25624. if (index !== -1) {
  25625. this._pendingData.splice(index, 1);
  25626. }
  25627. if (wasLoading && !this.isLoading) {
  25628. this.onDataLoadedObservable.notifyObservers(this);
  25629. }
  25630. };
  25631. /**
  25632. * Returns the number of items waiting to be loaded
  25633. * @returns the number of items waiting to be loaded
  25634. */
  25635. Scene.prototype.getWaitingItemsCount = function () {
  25636. return this._pendingData.length;
  25637. };
  25638. Object.defineProperty(Scene.prototype, "isLoading", {
  25639. /**
  25640. * Returns a boolean indicating if the scene is still loading data
  25641. */
  25642. get: function () {
  25643. return this._pendingData.length > 0;
  25644. },
  25645. enumerable: true,
  25646. configurable: true
  25647. });
  25648. /**
  25649. * Registers a function to be executed when the scene is ready
  25650. * @param {Function} func - the function to be executed
  25651. */
  25652. Scene.prototype.executeWhenReady = function (func) {
  25653. var _this = this;
  25654. this.onReadyObservable.add(func);
  25655. if (this._executeWhenReadyTimeoutId !== -1) {
  25656. return;
  25657. }
  25658. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25659. _this._checkIsReady();
  25660. }, 150);
  25661. };
  25662. /**
  25663. * Returns a promise that resolves when the scene is ready
  25664. * @returns A promise that resolves when the scene is ready
  25665. */
  25666. Scene.prototype.whenReadyAsync = function () {
  25667. var _this = this;
  25668. return new Promise(function (resolve) {
  25669. _this.executeWhenReady(function () {
  25670. resolve();
  25671. });
  25672. });
  25673. };
  25674. /** @hidden */
  25675. Scene.prototype._checkIsReady = function () {
  25676. var _this = this;
  25677. if (this.isReady()) {
  25678. this.onReadyObservable.notifyObservers(this);
  25679. this.onReadyObservable.clear();
  25680. this._executeWhenReadyTimeoutId = -1;
  25681. return;
  25682. }
  25683. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25684. _this._checkIsReady();
  25685. }, 150);
  25686. };
  25687. // Animations
  25688. /**
  25689. * Will start the animation sequence of a given target
  25690. * @param target defines the target
  25691. * @param from defines from which frame should animation start
  25692. * @param to defines until which frame should animation run.
  25693. * @param weight defines the weight to apply to the animation (1.0 by default)
  25694. * @param loop defines if the animation loops
  25695. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25696. * @param onAnimationEnd defines the function to be executed when the animation ends
  25697. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25698. * @returns the animatable object created for this animation
  25699. */
  25700. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25701. if (weight === void 0) { weight = 1.0; }
  25702. if (speedRatio === void 0) { speedRatio = 1.0; }
  25703. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25704. returnedAnimatable.weight = weight;
  25705. return returnedAnimatable;
  25706. };
  25707. /**
  25708. * Will start the animation sequence of a given target
  25709. * @param target defines the target
  25710. * @param from defines from which frame should animation start
  25711. * @param to defines until which frame should animation run.
  25712. * @param loop defines if the animation loops
  25713. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25714. * @param onAnimationEnd defines the function to be executed when the animation ends
  25715. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25716. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25717. * @returns the animatable object created for this animation
  25718. */
  25719. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25720. if (speedRatio === void 0) { speedRatio = 1.0; }
  25721. if (stopCurrent === void 0) { stopCurrent = true; }
  25722. if (from > to && speedRatio > 0) {
  25723. speedRatio *= -1;
  25724. }
  25725. if (stopCurrent) {
  25726. this.stopAnimation(target);
  25727. }
  25728. if (!animatable) {
  25729. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25730. }
  25731. // Local animations
  25732. if (target.animations) {
  25733. animatable.appendAnimations(target, target.animations);
  25734. }
  25735. // Children animations
  25736. if (target.getAnimatables) {
  25737. var animatables = target.getAnimatables();
  25738. for (var index = 0; index < animatables.length; index++) {
  25739. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25740. }
  25741. }
  25742. animatable.reset();
  25743. return animatable;
  25744. };
  25745. /**
  25746. * Begin a new animation on a given node
  25747. * @param target defines the target where the animation will take place
  25748. * @param animations defines the list of animations to start
  25749. * @param from defines the initial value
  25750. * @param to defines the final value
  25751. * @param loop defines if you want animation to loop (off by default)
  25752. * @param speedRatio defines the speed ratio to apply to all animations
  25753. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25754. * @returns the list of created animatables
  25755. */
  25756. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25757. if (speedRatio === undefined) {
  25758. speedRatio = 1.0;
  25759. }
  25760. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25761. return animatable;
  25762. };
  25763. /**
  25764. * Begin a new animation on a given node and its hierarchy
  25765. * @param target defines the root node where the animation will take place
  25766. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  25767. * @param animations defines the list of animations to start
  25768. * @param from defines the initial value
  25769. * @param to defines the final value
  25770. * @param loop defines if you want animation to loop (off by default)
  25771. * @param speedRatio defines the speed ratio to apply to all animations
  25772. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25773. * @returns the list of animatables created for all nodes
  25774. */
  25775. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25776. var children = target.getDescendants(directDescendantsOnly);
  25777. var result = [];
  25778. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25779. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25780. var child = children_1[_i];
  25781. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25782. }
  25783. return result;
  25784. };
  25785. /**
  25786. * Gets the animatable associated with a specific target
  25787. * @param target defines the target of the animatable
  25788. * @returns the required animatable if found
  25789. */
  25790. Scene.prototype.getAnimatableByTarget = function (target) {
  25791. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25792. if (this._activeAnimatables[index].target === target) {
  25793. return this._activeAnimatables[index];
  25794. }
  25795. }
  25796. return null;
  25797. };
  25798. /**
  25799. * Gets all animatables associated with a given target
  25800. * @param target defines the target to look animatables for
  25801. * @returns an array of Animatables
  25802. */
  25803. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25804. var result = [];
  25805. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25806. if (this._activeAnimatables[index].target === target) {
  25807. result.push(this._activeAnimatables[index]);
  25808. }
  25809. }
  25810. return result;
  25811. };
  25812. Object.defineProperty(Scene.prototype, "animatables", {
  25813. /**
  25814. * Gets all animatable attached to the scene
  25815. */
  25816. get: function () {
  25817. return this._activeAnimatables;
  25818. },
  25819. enumerable: true,
  25820. configurable: true
  25821. });
  25822. /**
  25823. * Will stop the animation of the given target
  25824. * @param target - the target
  25825. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25826. */
  25827. Scene.prototype.stopAnimation = function (target, animationName) {
  25828. var animatables = this.getAllAnimatablesByTarget(target);
  25829. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25830. var animatable = animatables_1[_i];
  25831. animatable.stop(animationName);
  25832. }
  25833. };
  25834. /**
  25835. * Stops and removes all animations that have been applied to the scene
  25836. */
  25837. Scene.prototype.stopAllAnimations = function () {
  25838. if (this._activeAnimatables) {
  25839. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25840. this._activeAnimatables[i].stop();
  25841. }
  25842. this._activeAnimatables = [];
  25843. }
  25844. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25845. var group = _a[_i];
  25846. group.stop();
  25847. }
  25848. };
  25849. Scene.prototype._animate = function () {
  25850. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25851. return;
  25852. }
  25853. // Getting time
  25854. var now = BABYLON.Tools.Now;
  25855. if (!this._animationTimeLast) {
  25856. if (this._pendingData.length > 0) {
  25857. return;
  25858. }
  25859. this._animationTimeLast = now;
  25860. }
  25861. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25862. this._animationTime += deltaTime;
  25863. this._animationTimeLast = now;
  25864. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25865. this._activeAnimatables[index]._animate(this._animationTime);
  25866. }
  25867. // Late animation bindings
  25868. this._processLateAnimationBindings();
  25869. };
  25870. /** @hidden */
  25871. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25872. var target = runtimeAnimation.target;
  25873. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25874. if (!target._lateAnimationHolders) {
  25875. target._lateAnimationHolders = {};
  25876. }
  25877. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25878. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25879. totalWeight: 0,
  25880. animations: [],
  25881. originalValue: originalValue
  25882. };
  25883. }
  25884. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25885. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25886. };
  25887. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25888. var normalizer = 1.0;
  25889. var finalPosition = BABYLON.Tmp.Vector3[0];
  25890. var finalScaling = BABYLON.Tmp.Vector3[1];
  25891. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25892. var startIndex = 0;
  25893. var originalAnimation = holder.animations[0];
  25894. var originalValue = holder.originalValue;
  25895. var scale = 1;
  25896. if (holder.totalWeight < 1.0) {
  25897. // We need to mix the original value in
  25898. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25899. scale = 1.0 - holder.totalWeight;
  25900. }
  25901. else {
  25902. startIndex = 1;
  25903. // We need to normalize the weights
  25904. normalizer = holder.totalWeight;
  25905. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25906. scale = originalAnimation.weight / normalizer;
  25907. if (scale == 1) {
  25908. return originalAnimation.currentValue;
  25909. }
  25910. }
  25911. finalScaling.scaleInPlace(scale);
  25912. finalPosition.scaleInPlace(scale);
  25913. finalQuaternion.scaleInPlace(scale);
  25914. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25915. var runtimeAnimation = holder.animations[animIndex];
  25916. var scale = runtimeAnimation.weight / normalizer;
  25917. var currentPosition = BABYLON.Tmp.Vector3[2];
  25918. var currentScaling = BABYLON.Tmp.Vector3[3];
  25919. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25920. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25921. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25922. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25923. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25924. }
  25925. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25926. return originalAnimation._workValue;
  25927. };
  25928. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25929. var originalAnimation = holder.animations[0];
  25930. var originalValue = holder.originalValue;
  25931. if (holder.animations.length === 1) {
  25932. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25933. }
  25934. var normalizer = 1.0;
  25935. var quaternions;
  25936. var weights;
  25937. if (holder.totalWeight < 1.0) {
  25938. var scale = 1.0 - holder.totalWeight;
  25939. quaternions = [];
  25940. weights = [];
  25941. quaternions.push(originalValue);
  25942. weights.push(scale);
  25943. }
  25944. else {
  25945. if (holder.animations.length === 2) { // Slerp as soon as we can
  25946. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  25947. }
  25948. quaternions = [];
  25949. weights = [];
  25950. normalizer = holder.totalWeight;
  25951. }
  25952. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25953. var runtimeAnimation = holder.animations[animIndex];
  25954. quaternions.push(runtimeAnimation.currentValue);
  25955. weights.push(runtimeAnimation.weight / normalizer);
  25956. }
  25957. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  25958. var cumulativeAmount = 0;
  25959. var cumulativeQuaternion = null;
  25960. for (var index = 0; index < quaternions.length;) {
  25961. if (!cumulativeQuaternion) {
  25962. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  25963. cumulativeAmount = weights[index] + weights[index + 1];
  25964. index += 2;
  25965. continue;
  25966. }
  25967. cumulativeAmount += weights[index];
  25968. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  25969. index++;
  25970. }
  25971. return cumulativeQuaternion;
  25972. };
  25973. Scene.prototype._processLateAnimationBindings = function () {
  25974. if (!this._registeredForLateAnimationBindings.length) {
  25975. return;
  25976. }
  25977. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25978. var target = this._registeredForLateAnimationBindings.data[index];
  25979. for (var path in target._lateAnimationHolders) {
  25980. var holder = target._lateAnimationHolders[path];
  25981. var originalAnimation = holder.animations[0];
  25982. var originalValue = holder.originalValue;
  25983. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25984. var finalValue = void 0;
  25985. if (matrixDecomposeMode) {
  25986. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  25987. }
  25988. else {
  25989. var quaternionMode = originalValue.w !== undefined;
  25990. if (quaternionMode) {
  25991. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  25992. }
  25993. else {
  25994. var startIndex = 0;
  25995. var normalizer = 1.0;
  25996. if (holder.totalWeight < 1.0) {
  25997. // We need to mix the original value in
  25998. if (originalValue.scale) {
  25999. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26000. }
  26001. else {
  26002. finalValue = originalValue * (1.0 - holder.totalWeight);
  26003. }
  26004. }
  26005. else {
  26006. // We need to normalize the weights
  26007. normalizer = holder.totalWeight;
  26008. var scale_1 = originalAnimation.weight / normalizer;
  26009. if (scale_1 !== 1) {
  26010. if (originalAnimation.currentValue.scale) {
  26011. finalValue = originalAnimation.currentValue.scale(scale_1);
  26012. }
  26013. else {
  26014. finalValue = originalAnimation.currentValue * scale_1;
  26015. }
  26016. }
  26017. else {
  26018. finalValue = originalAnimation.currentValue;
  26019. }
  26020. startIndex = 1;
  26021. }
  26022. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26023. var runtimeAnimation = holder.animations[animIndex];
  26024. var scale = runtimeAnimation.weight / normalizer;
  26025. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26026. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26027. }
  26028. else {
  26029. finalValue += runtimeAnimation.currentValue * scale;
  26030. }
  26031. }
  26032. }
  26033. }
  26034. target[path] = finalValue;
  26035. }
  26036. target._lateAnimationHolders = {};
  26037. }
  26038. this._registeredForLateAnimationBindings.reset();
  26039. };
  26040. // Matrix
  26041. /** @hidden */
  26042. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26043. this._useAlternateCameraConfiguration = active;
  26044. };
  26045. /**
  26046. * Gets the current view matrix
  26047. * @returns a Matrix
  26048. */
  26049. Scene.prototype.getViewMatrix = function () {
  26050. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26051. };
  26052. /**
  26053. * Gets the current projection matrix
  26054. * @returns a Matrix
  26055. */
  26056. Scene.prototype.getProjectionMatrix = function () {
  26057. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26058. };
  26059. /**
  26060. * Gets the current transform matrix
  26061. * @returns a Matrix made of View * Projection
  26062. */
  26063. Scene.prototype.getTransformMatrix = function () {
  26064. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26065. };
  26066. /**
  26067. * Sets the current transform matrix
  26068. * @param view defines the View matrix to use
  26069. * @param projection defines the Projection matrix to use
  26070. */
  26071. Scene.prototype.setTransformMatrix = function (view, projection) {
  26072. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26073. return;
  26074. }
  26075. this._viewUpdateFlag = view.updateFlag;
  26076. this._projectionUpdateFlag = projection.updateFlag;
  26077. this._viewMatrix = view;
  26078. this._projectionMatrix = projection;
  26079. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26080. // Update frustum
  26081. if (!this._frustumPlanes) {
  26082. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26083. }
  26084. else {
  26085. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26086. }
  26087. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26088. var otherCamera = this.activeCamera._alternateCamera;
  26089. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26090. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26091. }
  26092. if (this._sceneUbo.useUbo) {
  26093. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26094. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26095. this._sceneUbo.update();
  26096. }
  26097. };
  26098. /** @hidden */
  26099. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26100. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26101. return;
  26102. }
  26103. this._alternateViewUpdateFlag = view.updateFlag;
  26104. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26105. this._alternateViewMatrix = view;
  26106. this._alternateProjectionMatrix = projection;
  26107. if (!this._alternateTransformMatrix) {
  26108. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26109. }
  26110. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26111. if (!this._alternateSceneUbo) {
  26112. this._createAlternateUbo();
  26113. }
  26114. if (this._alternateSceneUbo.useUbo) {
  26115. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26116. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26117. this._alternateSceneUbo.update();
  26118. }
  26119. };
  26120. /**
  26121. * Gets the uniform buffer used to store scene data
  26122. * @returns a UniformBuffer
  26123. */
  26124. Scene.prototype.getSceneUniformBuffer = function () {
  26125. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26126. };
  26127. /**
  26128. * Gets an unique (relatively to the current scene) Id
  26129. * @returns an unique number for the scene
  26130. */
  26131. Scene.prototype.getUniqueId = function () {
  26132. var result = Scene._uniqueIdCounter;
  26133. Scene._uniqueIdCounter++;
  26134. return result;
  26135. };
  26136. /**
  26137. * Add a mesh to the list of scene's meshes
  26138. * @param newMesh defines the mesh to add
  26139. */
  26140. Scene.prototype.addMesh = function (newMesh) {
  26141. this.meshes.push(newMesh);
  26142. //notify the collision coordinator
  26143. if (this.collisionCoordinator) {
  26144. this.collisionCoordinator.onMeshAdded(newMesh);
  26145. }
  26146. newMesh._resyncLightSources();
  26147. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26148. };
  26149. /**
  26150. * Remove a mesh for the list of scene's meshes
  26151. * @param toRemove defines the mesh to remove
  26152. * @param recursive if all child meshes should also be removed from the scene
  26153. * @returns the index where the mesh was in the mesh list
  26154. */
  26155. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26156. var _this = this;
  26157. if (recursive === void 0) { recursive = false; }
  26158. var index = this.meshes.indexOf(toRemove);
  26159. if (index !== -1) {
  26160. // Remove from the scene if mesh found
  26161. this.meshes.splice(index, 1);
  26162. }
  26163. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26164. if (recursive) {
  26165. toRemove.getChildMeshes().forEach(function (m) {
  26166. _this.removeMesh(m);
  26167. });
  26168. }
  26169. return index;
  26170. };
  26171. /**
  26172. * Add a transform node to the list of scene's transform nodes
  26173. * @param newTransformNode defines the transform node to add
  26174. */
  26175. Scene.prototype.addTransformNode = function (newTransformNode) {
  26176. this.transformNodes.push(newTransformNode);
  26177. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26178. };
  26179. /**
  26180. * Remove a transform node for the list of scene's transform nodes
  26181. * @param toRemove defines the transform node to remove
  26182. * @returns the index where the transform node was in the transform node list
  26183. */
  26184. Scene.prototype.removeTransformNode = function (toRemove) {
  26185. var index = this.transformNodes.indexOf(toRemove);
  26186. if (index !== -1) {
  26187. // Remove from the scene if found
  26188. this.transformNodes.splice(index, 1);
  26189. }
  26190. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26191. return index;
  26192. };
  26193. /**
  26194. * Remove a skeleton for the list of scene's skeletons
  26195. * @param toRemove defines the skeleton to remove
  26196. * @returns the index where the skeleton was in the skeleton list
  26197. */
  26198. Scene.prototype.removeSkeleton = function (toRemove) {
  26199. var index = this.skeletons.indexOf(toRemove);
  26200. if (index !== -1) {
  26201. // Remove from the scene if found
  26202. this.skeletons.splice(index, 1);
  26203. }
  26204. return index;
  26205. };
  26206. /**
  26207. * Remove a morph target for the list of scene's morph targets
  26208. * @param toRemove defines the morph target to remove
  26209. * @returns the index where the morph target was in the morph target list
  26210. */
  26211. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26212. var index = this.morphTargetManagers.indexOf(toRemove);
  26213. if (index !== -1) {
  26214. // Remove from the scene if found
  26215. this.morphTargetManagers.splice(index, 1);
  26216. }
  26217. return index;
  26218. };
  26219. /**
  26220. * Remove a light for the list of scene's lights
  26221. * @param toRemove defines the light to remove
  26222. * @returns the index where the light was in the light list
  26223. */
  26224. Scene.prototype.removeLight = function (toRemove) {
  26225. var index = this.lights.indexOf(toRemove);
  26226. if (index !== -1) {
  26227. // Remove from meshes
  26228. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26229. var mesh = _a[_i];
  26230. mesh._removeLightSource(toRemove);
  26231. }
  26232. // Remove from the scene if mesh found
  26233. this.lights.splice(index, 1);
  26234. this.sortLightsByPriority();
  26235. }
  26236. this.onLightRemovedObservable.notifyObservers(toRemove);
  26237. return index;
  26238. };
  26239. /**
  26240. * Remove a camera for the list of scene's cameras
  26241. * @param toRemove defines the camera to remove
  26242. * @returns the index where the camera was in the camera list
  26243. */
  26244. Scene.prototype.removeCamera = function (toRemove) {
  26245. var index = this.cameras.indexOf(toRemove);
  26246. if (index !== -1) {
  26247. // Remove from the scene if mesh found
  26248. this.cameras.splice(index, 1);
  26249. }
  26250. // Remove from activeCameras
  26251. var index2 = this.activeCameras.indexOf(toRemove);
  26252. if (index2 !== -1) {
  26253. // Remove from the scene if mesh found
  26254. this.activeCameras.splice(index2, 1);
  26255. }
  26256. // Reset the activeCamera
  26257. if (this.activeCamera === toRemove) {
  26258. if (this.cameras.length > 0) {
  26259. this.activeCamera = this.cameras[0];
  26260. }
  26261. else {
  26262. this.activeCamera = null;
  26263. }
  26264. }
  26265. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26266. return index;
  26267. };
  26268. /**
  26269. * Remove a particle system for the list of scene's particle systems
  26270. * @param toRemove defines the particle system to remove
  26271. * @returns the index where the particle system was in the particle system list
  26272. */
  26273. Scene.prototype.removeParticleSystem = function (toRemove) {
  26274. var index = this.particleSystems.indexOf(toRemove);
  26275. if (index !== -1) {
  26276. this.particleSystems.splice(index, 1);
  26277. }
  26278. return index;
  26279. };
  26280. /**
  26281. * Remove a animation for the list of scene's animations
  26282. * @param toRemove defines the animation to remove
  26283. * @returns the index where the animation was in the animation list
  26284. */
  26285. Scene.prototype.removeAnimation = function (toRemove) {
  26286. var index = this.animations.indexOf(toRemove);
  26287. if (index !== -1) {
  26288. this.animations.splice(index, 1);
  26289. }
  26290. return index;
  26291. };
  26292. /**
  26293. * Removes the given animation group from this scene.
  26294. * @param toRemove The animation group to remove
  26295. * @returns The index of the removed animation group
  26296. */
  26297. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26298. var index = this.animationGroups.indexOf(toRemove);
  26299. if (index !== -1) {
  26300. this.animationGroups.splice(index, 1);
  26301. }
  26302. return index;
  26303. };
  26304. /**
  26305. * Removes the given multi-material from this scene.
  26306. * @param toRemove The multi-material to remove
  26307. * @returns The index of the removed multi-material
  26308. */
  26309. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26310. var index = this.multiMaterials.indexOf(toRemove);
  26311. if (index !== -1) {
  26312. this.multiMaterials.splice(index, 1);
  26313. }
  26314. return index;
  26315. };
  26316. /**
  26317. * Removes the given material from this scene.
  26318. * @param toRemove The material to remove
  26319. * @returns The index of the removed material
  26320. */
  26321. Scene.prototype.removeMaterial = function (toRemove) {
  26322. var index = this.materials.indexOf(toRemove);
  26323. if (index !== -1) {
  26324. this.materials.splice(index, 1);
  26325. }
  26326. return index;
  26327. };
  26328. /**
  26329. * Removes the given lens flare system from this scene.
  26330. * @param toRemove The lens flare system to remove
  26331. * @returns The index of the removed lens flare system
  26332. */
  26333. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26334. var index = this.lensFlareSystems.indexOf(toRemove);
  26335. if (index !== -1) {
  26336. this.lensFlareSystems.splice(index, 1);
  26337. }
  26338. return index;
  26339. };
  26340. /**
  26341. * Removes the given action manager from this scene.
  26342. * @param toRemove The action manager to remove
  26343. * @returns The index of the removed action manager
  26344. */
  26345. Scene.prototype.removeActionManager = function (toRemove) {
  26346. var index = this._actionManagers.indexOf(toRemove);
  26347. if (index !== -1) {
  26348. this._actionManagers.splice(index, 1);
  26349. }
  26350. return index;
  26351. };
  26352. /**
  26353. * Removes the given effect layer from this scene.
  26354. * @param toRemove defines the effect layer to remove
  26355. * @returns the index of the removed effect layer
  26356. */
  26357. Scene.prototype.removeEffectLayer = function (toRemove) {
  26358. var index = this.effectLayers.indexOf(toRemove);
  26359. if (index !== -1) {
  26360. this.effectLayers.splice(index, 1);
  26361. }
  26362. return index;
  26363. };
  26364. /**
  26365. * Removes the given texture from this scene.
  26366. * @param toRemove The texture to remove
  26367. * @returns The index of the removed texture
  26368. */
  26369. Scene.prototype.removeTexture = function (toRemove) {
  26370. var index = this.textures.indexOf(toRemove);
  26371. if (index !== -1) {
  26372. this.textures.splice(index, 1);
  26373. }
  26374. return index;
  26375. };
  26376. /**
  26377. * Adds the given light to this scene
  26378. * @param newLight The light to add
  26379. */
  26380. Scene.prototype.addLight = function (newLight) {
  26381. this.lights.push(newLight);
  26382. this.sortLightsByPriority();
  26383. // Add light to all meshes (To support if the light is removed and then readded)
  26384. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26385. var mesh = _a[_i];
  26386. if (mesh._lightSources.indexOf(newLight) === -1) {
  26387. mesh._lightSources.push(newLight);
  26388. mesh._resyncLightSources();
  26389. }
  26390. }
  26391. this.onNewLightAddedObservable.notifyObservers(newLight);
  26392. };
  26393. /**
  26394. * Sorts the list list based on light priorities
  26395. */
  26396. Scene.prototype.sortLightsByPriority = function () {
  26397. if (this.requireLightSorting) {
  26398. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26399. }
  26400. };
  26401. /**
  26402. * Adds the given camera to this scene
  26403. * @param newCamera The camera to add
  26404. */
  26405. Scene.prototype.addCamera = function (newCamera) {
  26406. this.cameras.push(newCamera);
  26407. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26408. };
  26409. /**
  26410. * Adds the given skeleton to this scene
  26411. * @param newSkeleton The skeleton to add
  26412. */
  26413. Scene.prototype.addSkeleton = function (newSkeleton) {
  26414. this.skeletons.push(newSkeleton);
  26415. };
  26416. /**
  26417. * Adds the given particle system to this scene
  26418. * @param newParticleSystem The particle system to add
  26419. */
  26420. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26421. this.particleSystems.push(newParticleSystem);
  26422. };
  26423. /**
  26424. * Adds the given animation to this scene
  26425. * @param newAnimation The animation to add
  26426. */
  26427. Scene.prototype.addAnimation = function (newAnimation) {
  26428. this.animations.push(newAnimation);
  26429. };
  26430. /**
  26431. * Adds the given animation group to this scene.
  26432. * @param newAnimationGroup The animation group to add
  26433. */
  26434. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26435. this.animationGroups.push(newAnimationGroup);
  26436. };
  26437. /**
  26438. * Adds the given multi-material to this scene
  26439. * @param newMultiMaterial The multi-material to add
  26440. */
  26441. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26442. this.multiMaterials.push(newMultiMaterial);
  26443. };
  26444. /**
  26445. * Adds the given material to this scene
  26446. * @param newMaterial The material to add
  26447. */
  26448. Scene.prototype.addMaterial = function (newMaterial) {
  26449. this.materials.push(newMaterial);
  26450. };
  26451. /**
  26452. * Adds the given morph target to this scene
  26453. * @param newMorphTargetManager The morph target to add
  26454. */
  26455. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26456. this.morphTargetManagers.push(newMorphTargetManager);
  26457. };
  26458. /**
  26459. * Adds the given geometry to this scene
  26460. * @param newGeometry The geometry to add
  26461. */
  26462. Scene.prototype.addGeometry = function (newGeometry) {
  26463. this._geometries.push(newGeometry);
  26464. };
  26465. /**
  26466. * Adds the given lens flare system to this scene
  26467. * @param newLensFlareSystem The lens flare system to add
  26468. */
  26469. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26470. this.lensFlareSystems.push(newLensFlareSystem);
  26471. };
  26472. /**
  26473. * Adds the given effect layer to this scene
  26474. * @param newEffectLayer defines the effect layer to add
  26475. */
  26476. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26477. this.effectLayers.push(newEffectLayer);
  26478. };
  26479. /**
  26480. * Adds the given action manager to this scene
  26481. * @param newActionManager The action manager to add
  26482. */
  26483. Scene.prototype.addActionManager = function (newActionManager) {
  26484. this._actionManagers.push(newActionManager);
  26485. };
  26486. /**
  26487. * Adds the given texture to this scene.
  26488. * @param newTexture The texture to add
  26489. */
  26490. Scene.prototype.addTexture = function (newTexture) {
  26491. this.textures.push(newTexture);
  26492. };
  26493. /**
  26494. * Switch active camera
  26495. * @param newCamera defines the new active camera
  26496. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26497. */
  26498. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26499. if (attachControl === void 0) { attachControl = true; }
  26500. var canvas = this._engine.getRenderingCanvas();
  26501. if (!canvas) {
  26502. return;
  26503. }
  26504. if (this.activeCamera) {
  26505. this.activeCamera.detachControl(canvas);
  26506. }
  26507. this.activeCamera = newCamera;
  26508. if (attachControl) {
  26509. newCamera.attachControl(canvas);
  26510. }
  26511. };
  26512. /**
  26513. * sets the active camera of the scene using its ID
  26514. * @param id defines the camera's ID
  26515. * @return the new active camera or null if none found.
  26516. */
  26517. Scene.prototype.setActiveCameraByID = function (id) {
  26518. var camera = this.getCameraByID(id);
  26519. if (camera) {
  26520. this.activeCamera = camera;
  26521. return camera;
  26522. }
  26523. return null;
  26524. };
  26525. /**
  26526. * sets the active camera of the scene using its name
  26527. * @param name defines the camera's name
  26528. * @returns the new active camera or null if none found.
  26529. */
  26530. Scene.prototype.setActiveCameraByName = function (name) {
  26531. var camera = this.getCameraByName(name);
  26532. if (camera) {
  26533. this.activeCamera = camera;
  26534. return camera;
  26535. }
  26536. return null;
  26537. };
  26538. /**
  26539. * get an animation group using its name
  26540. * @param name defines the material's name
  26541. * @return the animation group or null if none found.
  26542. */
  26543. Scene.prototype.getAnimationGroupByName = function (name) {
  26544. for (var index = 0; index < this.animationGroups.length; index++) {
  26545. if (this.animationGroups[index].name === name) {
  26546. return this.animationGroups[index];
  26547. }
  26548. }
  26549. return null;
  26550. };
  26551. /**
  26552. * get a material using its id
  26553. * @param id defines the material's ID
  26554. * @return the material or null if none found.
  26555. */
  26556. Scene.prototype.getMaterialByID = function (id) {
  26557. for (var index = 0; index < this.materials.length; index++) {
  26558. if (this.materials[index].id === id) {
  26559. return this.materials[index];
  26560. }
  26561. }
  26562. return null;
  26563. };
  26564. /**
  26565. * Gets a material using its name
  26566. * @param name defines the material's name
  26567. * @return the material or null if none found.
  26568. */
  26569. Scene.prototype.getMaterialByName = function (name) {
  26570. for (var index = 0; index < this.materials.length; index++) {
  26571. if (this.materials[index].name === name) {
  26572. return this.materials[index];
  26573. }
  26574. }
  26575. return null;
  26576. };
  26577. /**
  26578. * Gets a lens flare system using its name
  26579. * @param name defines the name to look for
  26580. * @returns the lens flare system or null if not found
  26581. */
  26582. Scene.prototype.getLensFlareSystemByName = function (name) {
  26583. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26584. if (this.lensFlareSystems[index].name === name) {
  26585. return this.lensFlareSystems[index];
  26586. }
  26587. }
  26588. return null;
  26589. };
  26590. /**
  26591. * Gets a lens flare system using its id
  26592. * @param id defines the id to look for
  26593. * @returns the lens flare system or null if not found
  26594. */
  26595. Scene.prototype.getLensFlareSystemByID = function (id) {
  26596. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26597. if (this.lensFlareSystems[index].id === id) {
  26598. return this.lensFlareSystems[index];
  26599. }
  26600. }
  26601. return null;
  26602. };
  26603. /**
  26604. * Gets a camera using its id
  26605. * @param id defines the id to look for
  26606. * @returns the camera or null if not found
  26607. */
  26608. Scene.prototype.getCameraByID = function (id) {
  26609. for (var index = 0; index < this.cameras.length; index++) {
  26610. if (this.cameras[index].id === id) {
  26611. return this.cameras[index];
  26612. }
  26613. }
  26614. return null;
  26615. };
  26616. /**
  26617. * Gets a camera using its unique id
  26618. * @param uniqueId defines the unique id to look for
  26619. * @returns the camera or null if not found
  26620. */
  26621. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26622. for (var index = 0; index < this.cameras.length; index++) {
  26623. if (this.cameras[index].uniqueId === uniqueId) {
  26624. return this.cameras[index];
  26625. }
  26626. }
  26627. return null;
  26628. };
  26629. /**
  26630. * Gets a camera using its name
  26631. * @param name defines the camera's name
  26632. * @return the camera or null if none found.
  26633. */
  26634. Scene.prototype.getCameraByName = function (name) {
  26635. for (var index = 0; index < this.cameras.length; index++) {
  26636. if (this.cameras[index].name === name) {
  26637. return this.cameras[index];
  26638. }
  26639. }
  26640. return null;
  26641. };
  26642. /**
  26643. * Gets a bone using its id
  26644. * @param id defines the bone's id
  26645. * @return the bone or null if not found
  26646. */
  26647. Scene.prototype.getBoneByID = function (id) {
  26648. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26649. var skeleton = this.skeletons[skeletonIndex];
  26650. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26651. if (skeleton.bones[boneIndex].id === id) {
  26652. return skeleton.bones[boneIndex];
  26653. }
  26654. }
  26655. }
  26656. return null;
  26657. };
  26658. /**
  26659. * Gets a bone using its id
  26660. * @param name defines the bone's name
  26661. * @return the bone or null if not found
  26662. */
  26663. Scene.prototype.getBoneByName = function (name) {
  26664. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26665. var skeleton = this.skeletons[skeletonIndex];
  26666. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26667. if (skeleton.bones[boneIndex].name === name) {
  26668. return skeleton.bones[boneIndex];
  26669. }
  26670. }
  26671. }
  26672. return null;
  26673. };
  26674. /**
  26675. * Gets a light node using its name
  26676. * @param name defines the the light's name
  26677. * @return the light or null if none found.
  26678. */
  26679. Scene.prototype.getLightByName = function (name) {
  26680. for (var index = 0; index < this.lights.length; index++) {
  26681. if (this.lights[index].name === name) {
  26682. return this.lights[index];
  26683. }
  26684. }
  26685. return null;
  26686. };
  26687. /**
  26688. * Gets a light node using its id
  26689. * @param id defines the light's id
  26690. * @return the light or null if none found.
  26691. */
  26692. Scene.prototype.getLightByID = function (id) {
  26693. for (var index = 0; index < this.lights.length; index++) {
  26694. if (this.lights[index].id === id) {
  26695. return this.lights[index];
  26696. }
  26697. }
  26698. return null;
  26699. };
  26700. /**
  26701. * Gets a light node using its scene-generated unique ID
  26702. * @param uniqueId defines the light's unique id
  26703. * @return the light or null if none found.
  26704. */
  26705. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26706. for (var index = 0; index < this.lights.length; index++) {
  26707. if (this.lights[index].uniqueId === uniqueId) {
  26708. return this.lights[index];
  26709. }
  26710. }
  26711. return null;
  26712. };
  26713. /**
  26714. * Gets a particle system by id
  26715. * @param id defines the particle system id
  26716. * @return the corresponding system or null if none found
  26717. */
  26718. Scene.prototype.getParticleSystemByID = function (id) {
  26719. for (var index = 0; index < this.particleSystems.length; index++) {
  26720. if (this.particleSystems[index].id === id) {
  26721. return this.particleSystems[index];
  26722. }
  26723. }
  26724. return null;
  26725. };
  26726. /**
  26727. * Gets a geometry using its ID
  26728. * @param id defines the geometry's id
  26729. * @return the geometry or null if none found.
  26730. */
  26731. Scene.prototype.getGeometryByID = function (id) {
  26732. for (var index = 0; index < this._geometries.length; index++) {
  26733. if (this._geometries[index].id === id) {
  26734. return this._geometries[index];
  26735. }
  26736. }
  26737. return null;
  26738. };
  26739. /**
  26740. * Add a new geometry to this scene
  26741. * @param geometry defines the geometry to be added to the scene.
  26742. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26743. * @return a boolean defining if the geometry was added or not
  26744. */
  26745. Scene.prototype.pushGeometry = function (geometry, force) {
  26746. if (!force && this.getGeometryByID(geometry.id)) {
  26747. return false;
  26748. }
  26749. this._geometries.push(geometry);
  26750. //notify the collision coordinator
  26751. if (this.collisionCoordinator) {
  26752. this.collisionCoordinator.onGeometryAdded(geometry);
  26753. }
  26754. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26755. return true;
  26756. };
  26757. /**
  26758. * Removes an existing geometry
  26759. * @param geometry defines the geometry to be removed from the scene
  26760. * @return a boolean defining if the geometry was removed or not
  26761. */
  26762. Scene.prototype.removeGeometry = function (geometry) {
  26763. var index = this._geometries.indexOf(geometry);
  26764. if (index > -1) {
  26765. this._geometries.splice(index, 1);
  26766. //notify the collision coordinator
  26767. if (this.collisionCoordinator) {
  26768. this.collisionCoordinator.onGeometryDeleted(geometry);
  26769. }
  26770. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26771. return true;
  26772. }
  26773. return false;
  26774. };
  26775. /**
  26776. * Gets the list of geometries attached to the scene
  26777. * @returns an array of Geometry
  26778. */
  26779. Scene.prototype.getGeometries = function () {
  26780. return this._geometries;
  26781. };
  26782. /**
  26783. * Gets the first added mesh found of a given ID
  26784. * @param id defines the id to search for
  26785. * @return the mesh found or null if not found at all
  26786. */
  26787. Scene.prototype.getMeshByID = function (id) {
  26788. for (var index = 0; index < this.meshes.length; index++) {
  26789. if (this.meshes[index].id === id) {
  26790. return this.meshes[index];
  26791. }
  26792. }
  26793. return null;
  26794. };
  26795. /**
  26796. * Gets a list of meshes using their id
  26797. * @param id defines the id to search for
  26798. * @returns a list of meshes
  26799. */
  26800. Scene.prototype.getMeshesByID = function (id) {
  26801. return this.meshes.filter(function (m) {
  26802. return m.id === id;
  26803. });
  26804. };
  26805. /**
  26806. * Gets the first added transform node found of a given ID
  26807. * @param id defines the id to search for
  26808. * @return the found transform node or null if not found at all.
  26809. */
  26810. Scene.prototype.getTransformNodeByID = function (id) {
  26811. for (var index = 0; index < this.transformNodes.length; index++) {
  26812. if (this.transformNodes[index].id === id) {
  26813. return this.transformNodes[index];
  26814. }
  26815. }
  26816. return null;
  26817. };
  26818. /**
  26819. * Gets a list of transform nodes using their id
  26820. * @param id defines the id to search for
  26821. * @returns a list of transform nodes
  26822. */
  26823. Scene.prototype.getTransformNodesByID = function (id) {
  26824. return this.transformNodes.filter(function (m) {
  26825. return m.id === id;
  26826. });
  26827. };
  26828. /**
  26829. * Gets a mesh with its auto-generated unique id
  26830. * @param uniqueId defines the unique id to search for
  26831. * @return the found mesh or null if not found at all.
  26832. */
  26833. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26834. for (var index = 0; index < this.meshes.length; index++) {
  26835. if (this.meshes[index].uniqueId === uniqueId) {
  26836. return this.meshes[index];
  26837. }
  26838. }
  26839. return null;
  26840. };
  26841. /**
  26842. * Gets a the last added mesh using a given id
  26843. * @param id defines the id to search for
  26844. * @return the found mesh or null if not found at all.
  26845. */
  26846. Scene.prototype.getLastMeshByID = function (id) {
  26847. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26848. if (this.meshes[index].id === id) {
  26849. return this.meshes[index];
  26850. }
  26851. }
  26852. return null;
  26853. };
  26854. /**
  26855. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26856. * @param id defines the id to search for
  26857. * @return the found node or null if not found at all
  26858. */
  26859. Scene.prototype.getLastEntryByID = function (id) {
  26860. var index;
  26861. for (index = this.meshes.length - 1; index >= 0; index--) {
  26862. if (this.meshes[index].id === id) {
  26863. return this.meshes[index];
  26864. }
  26865. }
  26866. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26867. if (this.transformNodes[index].id === id) {
  26868. return this.transformNodes[index];
  26869. }
  26870. }
  26871. for (index = this.cameras.length - 1; index >= 0; index--) {
  26872. if (this.cameras[index].id === id) {
  26873. return this.cameras[index];
  26874. }
  26875. }
  26876. for (index = this.lights.length - 1; index >= 0; index--) {
  26877. if (this.lights[index].id === id) {
  26878. return this.lights[index];
  26879. }
  26880. }
  26881. return null;
  26882. };
  26883. /**
  26884. * Gets a node (Mesh, Camera, Light) using a given id
  26885. * @param id defines the id to search for
  26886. * @return the found node or null if not found at all
  26887. */
  26888. Scene.prototype.getNodeByID = function (id) {
  26889. var mesh = this.getMeshByID(id);
  26890. if (mesh) {
  26891. return mesh;
  26892. }
  26893. var light = this.getLightByID(id);
  26894. if (light) {
  26895. return light;
  26896. }
  26897. var camera = this.getCameraByID(id);
  26898. if (camera) {
  26899. return camera;
  26900. }
  26901. var bone = this.getBoneByID(id);
  26902. return bone;
  26903. };
  26904. /**
  26905. * Gets a node (Mesh, Camera, Light) using a given name
  26906. * @param name defines the name to search for
  26907. * @return the found node or null if not found at all.
  26908. */
  26909. Scene.prototype.getNodeByName = function (name) {
  26910. var mesh = this.getMeshByName(name);
  26911. if (mesh) {
  26912. return mesh;
  26913. }
  26914. var light = this.getLightByName(name);
  26915. if (light) {
  26916. return light;
  26917. }
  26918. var camera = this.getCameraByName(name);
  26919. if (camera) {
  26920. return camera;
  26921. }
  26922. var bone = this.getBoneByName(name);
  26923. return bone;
  26924. };
  26925. /**
  26926. * Gets a mesh using a given name
  26927. * @param name defines the name to search for
  26928. * @return the found mesh or null if not found at all.
  26929. */
  26930. Scene.prototype.getMeshByName = function (name) {
  26931. for (var index = 0; index < this.meshes.length; index++) {
  26932. if (this.meshes[index].name === name) {
  26933. return this.meshes[index];
  26934. }
  26935. }
  26936. return null;
  26937. };
  26938. /**
  26939. * Gets a transform node using a given name
  26940. * @param name defines the name to search for
  26941. * @return the found transform node or null if not found at all.
  26942. */
  26943. Scene.prototype.getTransformNodeByName = function (name) {
  26944. for (var index = 0; index < this.transformNodes.length; index++) {
  26945. if (this.transformNodes[index].name === name) {
  26946. return this.transformNodes[index];
  26947. }
  26948. }
  26949. return null;
  26950. };
  26951. /**
  26952. * Gets a sound using a given name
  26953. * @param name defines the name to search for
  26954. * @return the found sound or null if not found at all.
  26955. */
  26956. Scene.prototype.getSoundByName = function (name) {
  26957. var index;
  26958. if (BABYLON.AudioEngine) {
  26959. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26960. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26961. return this.mainSoundTrack.soundCollection[index];
  26962. }
  26963. }
  26964. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26965. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26966. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26967. return this.soundTracks[sdIndex].soundCollection[index];
  26968. }
  26969. }
  26970. }
  26971. }
  26972. return null;
  26973. };
  26974. /**
  26975. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26976. * @param id defines the id to search for
  26977. * @return the found skeleton or null if not found at all.
  26978. */
  26979. Scene.prototype.getLastSkeletonByID = function (id) {
  26980. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26981. if (this.skeletons[index].id === id) {
  26982. return this.skeletons[index];
  26983. }
  26984. }
  26985. return null;
  26986. };
  26987. /**
  26988. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26989. * @param id defines the id to search for
  26990. * @return the found skeleton or null if not found at all.
  26991. */
  26992. Scene.prototype.getSkeletonById = function (id) {
  26993. for (var index = 0; index < this.skeletons.length; index++) {
  26994. if (this.skeletons[index].id === id) {
  26995. return this.skeletons[index];
  26996. }
  26997. }
  26998. return null;
  26999. };
  27000. /**
  27001. * Gets a skeleton using a given name
  27002. * @param name defines the name to search for
  27003. * @return the found skeleton or null if not found at all.
  27004. */
  27005. Scene.prototype.getSkeletonByName = function (name) {
  27006. for (var index = 0; index < this.skeletons.length; index++) {
  27007. if (this.skeletons[index].name === name) {
  27008. return this.skeletons[index];
  27009. }
  27010. }
  27011. return null;
  27012. };
  27013. /**
  27014. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27015. * @param id defines the id to search for
  27016. * @return the found morph target manager or null if not found at all.
  27017. */
  27018. Scene.prototype.getMorphTargetManagerById = function (id) {
  27019. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27020. if (this.morphTargetManagers[index].uniqueId === id) {
  27021. return this.morphTargetManagers[index];
  27022. }
  27023. }
  27024. return null;
  27025. };
  27026. /**
  27027. * Gets a boolean indicating if the given mesh is active
  27028. * @param mesh defines the mesh to look for
  27029. * @returns true if the mesh is in the active list
  27030. */
  27031. Scene.prototype.isActiveMesh = function (mesh) {
  27032. return (this._activeMeshes.indexOf(mesh) !== -1);
  27033. };
  27034. /**
  27035. * Return a the first highlight layer of the scene with a given name.
  27036. * @param name The name of the highlight layer to look for.
  27037. * @return The highlight layer if found otherwise null.
  27038. */
  27039. Scene.prototype.getHighlightLayerByName = function (name) {
  27040. for (var index = 0; index < this.effectLayers.length; index++) {
  27041. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27042. return this.effectLayers[index];
  27043. }
  27044. }
  27045. return null;
  27046. };
  27047. /**
  27048. * Return a the first highlight layer of the scene with a given name.
  27049. * @param name The name of the highlight layer to look for.
  27050. * @return The highlight layer if found otherwise null.
  27051. */
  27052. Scene.prototype.getGlowLayerByName = function (name) {
  27053. for (var index = 0; index < this.effectLayers.length; index++) {
  27054. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27055. return this.effectLayers[index];
  27056. }
  27057. }
  27058. return null;
  27059. };
  27060. Object.defineProperty(Scene.prototype, "uid", {
  27061. /**
  27062. * Return a unique id as a string which can serve as an identifier for the scene
  27063. */
  27064. get: function () {
  27065. if (!this._uid) {
  27066. this._uid = BABYLON.Tools.RandomId();
  27067. }
  27068. return this._uid;
  27069. },
  27070. enumerable: true,
  27071. configurable: true
  27072. });
  27073. /**
  27074. * Add an externaly attached data from its key.
  27075. * This method call will fail and return false, if such key already exists.
  27076. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27077. * @param key the unique key that identifies the data
  27078. * @param data the data object to associate to the key for this Engine instance
  27079. * @return true if no such key were already present and the data was added successfully, false otherwise
  27080. */
  27081. Scene.prototype.addExternalData = function (key, data) {
  27082. if (!this._externalData) {
  27083. this._externalData = new BABYLON.StringDictionary();
  27084. }
  27085. return this._externalData.add(key, data);
  27086. };
  27087. /**
  27088. * Get an externaly attached data from its key
  27089. * @param key the unique key that identifies the data
  27090. * @return the associated data, if present (can be null), or undefined if not present
  27091. */
  27092. Scene.prototype.getExternalData = function (key) {
  27093. if (!this._externalData) {
  27094. return null;
  27095. }
  27096. return this._externalData.get(key);
  27097. };
  27098. /**
  27099. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27100. * @param key the unique key that identifies the data
  27101. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27102. * @return the associated data, can be null if the factory returned null.
  27103. */
  27104. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27105. if (!this._externalData) {
  27106. this._externalData = new BABYLON.StringDictionary();
  27107. }
  27108. return this._externalData.getOrAddWithFactory(key, factory);
  27109. };
  27110. /**
  27111. * Remove an externaly attached data from the Engine instance
  27112. * @param key the unique key that identifies the data
  27113. * @return true if the data was successfully removed, false if it doesn't exist
  27114. */
  27115. Scene.prototype.removeExternalData = function (key) {
  27116. return this._externalData.remove(key);
  27117. };
  27118. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27119. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27120. if (mesh.showSubMeshesBoundingBox) {
  27121. var boundingInfo = subMesh.getBoundingInfo();
  27122. if (boundingInfo !== null && boundingInfo !== undefined) {
  27123. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27124. }
  27125. }
  27126. var material = subMesh.getMaterial();
  27127. if (material !== null && material !== undefined) {
  27128. // Render targets
  27129. if (material.getRenderTargetTextures !== undefined) {
  27130. if (this._processedMaterials.indexOf(material) === -1) {
  27131. this._processedMaterials.push(material);
  27132. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27133. }
  27134. }
  27135. // Dispatch
  27136. this._activeIndices.addCount(subMesh.indexCount, false);
  27137. this._renderingManager.dispatch(subMesh, mesh, material);
  27138. }
  27139. }
  27140. };
  27141. /**
  27142. * Clear the processed materials smart array preventing retention point in material dispose.
  27143. */
  27144. Scene.prototype.freeProcessedMaterials = function () {
  27145. this._processedMaterials.dispose();
  27146. };
  27147. /**
  27148. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27149. */
  27150. Scene.prototype.freeActiveMeshes = function () {
  27151. this._activeMeshes.dispose();
  27152. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27153. this.activeCamera._activeMeshes.dispose();
  27154. }
  27155. if (this.activeCameras) {
  27156. for (var i = 0; i < this.activeCameras.length; i++) {
  27157. var activeCamera = this.activeCameras[i];
  27158. if (activeCamera && activeCamera._activeMeshes) {
  27159. activeCamera._activeMeshes.dispose();
  27160. }
  27161. }
  27162. }
  27163. };
  27164. /**
  27165. * Clear the info related to rendering groups preventing retention points during dispose.
  27166. */
  27167. Scene.prototype.freeRenderingGroups = function () {
  27168. if (this._renderingManager) {
  27169. this._renderingManager.freeRenderingGroups();
  27170. }
  27171. if (this.textures) {
  27172. for (var i = 0; i < this.textures.length; i++) {
  27173. var texture = this.textures[i];
  27174. if (texture && texture.renderList) {
  27175. texture.freeRenderingGroups();
  27176. }
  27177. }
  27178. }
  27179. };
  27180. /** @hidden */
  27181. Scene.prototype._isInIntermediateRendering = function () {
  27182. return this._intermediateRendering;
  27183. };
  27184. /**
  27185. * Defines the current active mesh candidate provider
  27186. * @param provider defines the provider to use
  27187. */
  27188. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27189. this._activeMeshCandidateProvider = provider;
  27190. };
  27191. /**
  27192. * Gets the current active mesh candidate provider
  27193. * @returns the current active mesh candidate provider
  27194. */
  27195. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27196. return this._activeMeshCandidateProvider;
  27197. };
  27198. /**
  27199. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27200. * @returns the current scene
  27201. */
  27202. Scene.prototype.freezeActiveMeshes = function () {
  27203. if (!this.activeCamera) {
  27204. return this;
  27205. }
  27206. if (!this._frustumPlanes) {
  27207. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27208. }
  27209. this._evaluateActiveMeshes();
  27210. this._activeMeshesFrozen = true;
  27211. return this;
  27212. };
  27213. /**
  27214. * Use this function to restart evaluating active meshes on every frame
  27215. * @returns the current scene
  27216. */
  27217. Scene.prototype.unfreezeActiveMeshes = function () {
  27218. this._activeMeshesFrozen = false;
  27219. return this;
  27220. };
  27221. Scene.prototype._evaluateActiveMeshes = function () {
  27222. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27223. return;
  27224. }
  27225. if (!this.activeCamera) {
  27226. return;
  27227. }
  27228. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27229. this.activeCamera._activeMeshes.reset();
  27230. this._activeMeshes.reset();
  27231. this._renderingManager.reset();
  27232. this._processedMaterials.reset();
  27233. this._activeParticleSystems.reset();
  27234. this._activeSkeletons.reset();
  27235. this._softwareSkinnedMeshes.reset();
  27236. if (this._boundingBoxRenderer) {
  27237. this._boundingBoxRenderer.reset();
  27238. }
  27239. // Meshes
  27240. var meshes;
  27241. var len;
  27242. var checkIsEnabled = true;
  27243. // Determine mesh candidates
  27244. if (this._activeMeshCandidateProvider !== undefined) {
  27245. // Use _activeMeshCandidateProvider
  27246. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27247. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27248. if (meshes !== undefined) {
  27249. len = meshes.length;
  27250. }
  27251. else {
  27252. len = 0;
  27253. }
  27254. }
  27255. else if (this._selectionOctree !== undefined) {
  27256. // Octree
  27257. var selection = this._selectionOctree.select(this._frustumPlanes);
  27258. meshes = selection.data;
  27259. len = selection.length;
  27260. }
  27261. else {
  27262. // Full scene traversal
  27263. len = this.meshes.length;
  27264. meshes = this.meshes;
  27265. }
  27266. // Check each mesh
  27267. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27268. mesh = meshes[meshIndex];
  27269. if (mesh.isBlocked) {
  27270. continue;
  27271. }
  27272. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27273. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27274. continue;
  27275. }
  27276. mesh.computeWorldMatrix();
  27277. // Intersections
  27278. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27279. this._meshesForIntersections.pushNoDuplicate(mesh);
  27280. }
  27281. // Switch to current LOD
  27282. meshLOD = mesh.getLOD(this.activeCamera);
  27283. if (meshLOD === undefined || meshLOD === null) {
  27284. continue;
  27285. }
  27286. mesh._preActivate();
  27287. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27288. this._activeMeshes.push(mesh);
  27289. this.activeCamera._activeMeshes.push(mesh);
  27290. mesh._activate(this._renderId);
  27291. if (meshLOD !== mesh) {
  27292. meshLOD._activate(this._renderId);
  27293. }
  27294. this._activeMesh(mesh, meshLOD);
  27295. }
  27296. }
  27297. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27298. // Particle systems
  27299. if (this.particlesEnabled) {
  27300. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27301. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27302. var particleSystem = this.particleSystems[particleIndex];
  27303. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27304. continue;
  27305. }
  27306. var emitter = particleSystem.emitter;
  27307. if (!emitter.position || emitter.isEnabled()) {
  27308. this._activeParticleSystems.push(particleSystem);
  27309. particleSystem.animate();
  27310. this._renderingManager.dispatchParticles(particleSystem);
  27311. }
  27312. }
  27313. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27314. }
  27315. };
  27316. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27317. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27318. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27319. mesh.skeleton.prepare();
  27320. }
  27321. if (!mesh.computeBonesUsingShaders) {
  27322. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27323. }
  27324. }
  27325. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27326. var boundingInfo = sourceMesh.getBoundingInfo();
  27327. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27328. }
  27329. if (mesh !== undefined && mesh !== null
  27330. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27331. // Submeshes Octrees
  27332. var len;
  27333. var subMeshes;
  27334. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27335. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27336. len = intersections.length;
  27337. subMeshes = intersections.data;
  27338. }
  27339. else {
  27340. subMeshes = mesh.subMeshes;
  27341. len = subMeshes.length;
  27342. }
  27343. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27344. subMesh = subMeshes[subIndex];
  27345. this._evaluateSubMesh(subMesh, mesh);
  27346. }
  27347. }
  27348. };
  27349. /**
  27350. * Update the transform matrix to update from the current active camera
  27351. * @param force defines a boolean used to force the update even if cache is up to date
  27352. */
  27353. Scene.prototype.updateTransformMatrix = function (force) {
  27354. if (!this.activeCamera) {
  27355. return;
  27356. }
  27357. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27358. };
  27359. /**
  27360. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  27361. * @param alternateCamera defines the camera to use
  27362. */
  27363. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27364. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27365. };
  27366. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27367. if (camera && camera._skipRendering) {
  27368. return;
  27369. }
  27370. var engine = this._engine;
  27371. this.activeCamera = camera;
  27372. if (!this.activeCamera)
  27373. throw new Error("Active camera not set");
  27374. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27375. // Viewport
  27376. engine.setViewport(this.activeCamera.viewport);
  27377. // Camera
  27378. this.resetCachedMaterial();
  27379. this._renderId++;
  27380. this.updateTransformMatrix();
  27381. if (camera._alternateCamera) {
  27382. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27383. this._alternateRendering = true;
  27384. }
  27385. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27386. // Meshes
  27387. this._evaluateActiveMeshes();
  27388. // Software skinning
  27389. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27390. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27391. mesh.applySkeleton(mesh.skeleton);
  27392. }
  27393. // Render targets
  27394. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27395. var needsRestoreFrameBuffer = false;
  27396. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27397. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27398. }
  27399. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27400. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27401. }
  27402. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27403. this._intermediateRendering = true;
  27404. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27405. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27406. var renderTarget = this._renderTargets.data[renderIndex];
  27407. if (renderTarget._shouldRender()) {
  27408. this._renderId++;
  27409. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27410. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27411. }
  27412. }
  27413. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27414. this._intermediateRendering = false;
  27415. this._renderId++;
  27416. needsRestoreFrameBuffer = true; // Restore back buffer
  27417. }
  27418. // Render EffecttLayer Texture
  27419. var stencilState = this._engine.getStencilBuffer();
  27420. var renderEffects = false;
  27421. var needStencil = false;
  27422. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27423. this._intermediateRendering = true;
  27424. for (var i = 0; i < this.effectLayers.length; i++) {
  27425. var effectLayer = this.effectLayers[i];
  27426. if (effectLayer.shouldRender() &&
  27427. (!effectLayer.camera ||
  27428. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27429. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27430. renderEffects = true;
  27431. needStencil = needStencil || effectLayer.needStencil();
  27432. var renderTarget = effectLayer._mainTexture;
  27433. if (renderTarget._shouldRender()) {
  27434. this._renderId++;
  27435. renderTarget.render(false, false);
  27436. needsRestoreFrameBuffer = true;
  27437. }
  27438. }
  27439. }
  27440. this._intermediateRendering = false;
  27441. this._renderId++;
  27442. }
  27443. if (needsRestoreFrameBuffer) {
  27444. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27445. }
  27446. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27447. // Prepare Frame
  27448. this.postProcessManager._prepareFrame();
  27449. // Backgrounds
  27450. var layerIndex;
  27451. var layer;
  27452. if (this.layers.length) {
  27453. engine.setDepthBuffer(false);
  27454. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27455. layer = this.layers[layerIndex];
  27456. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27457. layer.render();
  27458. }
  27459. }
  27460. engine.setDepthBuffer(true);
  27461. }
  27462. // Activate effect Layer stencil
  27463. if (needStencil) {
  27464. this._engine.setStencilBuffer(true);
  27465. }
  27466. // Render
  27467. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27468. this._renderingManager.render(null, null, true, true);
  27469. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27470. // Restore effect Layer stencil
  27471. if (needStencil) {
  27472. this._engine.setStencilBuffer(stencilState);
  27473. }
  27474. // Bounding boxes
  27475. if (this._boundingBoxRenderer) {
  27476. this._boundingBoxRenderer.render();
  27477. }
  27478. // Lens flares
  27479. if (this.lensFlaresEnabled) {
  27480. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27481. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27482. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27483. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27484. lensFlareSystem.render();
  27485. }
  27486. }
  27487. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27488. }
  27489. // Effect Layer
  27490. if (renderEffects) {
  27491. engine.setDepthBuffer(false);
  27492. for (var i = 0; i < this.effectLayers.length; i++) {
  27493. if (this.effectLayers[i].shouldRender()) {
  27494. this.effectLayers[i].render();
  27495. }
  27496. }
  27497. engine.setDepthBuffer(true);
  27498. }
  27499. // Foregrounds
  27500. if (this.layers.length) {
  27501. engine.setDepthBuffer(false);
  27502. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27503. layer = this.layers[layerIndex];
  27504. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27505. layer.render();
  27506. }
  27507. }
  27508. engine.setDepthBuffer(true);
  27509. }
  27510. // Finalize frame
  27511. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27512. // Reset some special arrays
  27513. this._renderTargets.reset();
  27514. this._alternateRendering = false;
  27515. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27516. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27517. };
  27518. Scene.prototype._processSubCameras = function (camera) {
  27519. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27520. this._renderForCamera(camera);
  27521. return;
  27522. }
  27523. // rig cameras
  27524. for (var index = 0; index < camera._rigCameras.length; index++) {
  27525. this._renderForCamera(camera._rigCameras[index], camera);
  27526. }
  27527. this.activeCamera = camera;
  27528. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27529. };
  27530. Scene.prototype._checkIntersections = function () {
  27531. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27532. var sourceMesh = this._meshesForIntersections.data[index];
  27533. if (!sourceMesh.actionManager) {
  27534. continue;
  27535. }
  27536. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27537. var action = sourceMesh.actionManager.actions[actionIndex];
  27538. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27539. var parameters = action.getTriggerParameter();
  27540. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27541. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27542. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27543. if (areIntersecting && currentIntersectionInProgress === -1) {
  27544. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27545. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27546. sourceMesh._intersectionsInProgress.push(otherMesh);
  27547. }
  27548. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27549. sourceMesh._intersectionsInProgress.push(otherMesh);
  27550. }
  27551. }
  27552. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27553. //They intersected, and now they don't.
  27554. //is this trigger an exit trigger? execute an event.
  27555. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27556. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27557. }
  27558. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27559. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27560. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27561. return otherMesh === parameterMesh;
  27562. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27563. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27564. }
  27565. }
  27566. }
  27567. }
  27568. }
  27569. };
  27570. /**
  27571. * Render the scene
  27572. */
  27573. Scene.prototype.render = function () {
  27574. if (this.isDisposed) {
  27575. return;
  27576. }
  27577. this._activeParticles.fetchNewFrame();
  27578. this._totalVertices.fetchNewFrame();
  27579. this._activeIndices.fetchNewFrame();
  27580. this._activeBones.fetchNewFrame();
  27581. this._meshesForIntersections.reset();
  27582. this.resetCachedMaterial();
  27583. this.onBeforeAnimationsObservable.notifyObservers(this);
  27584. // Actions
  27585. if (this.actionManager) {
  27586. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27587. }
  27588. //Simplification Queue
  27589. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27590. this.simplificationQueue.executeNext();
  27591. }
  27592. if (this._engine.isDeterministicLockStep()) {
  27593. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27594. var defaultFPS = (60.0 / 1000.0);
  27595. var defaultFrameTime = 1000 / 60; // frame time in MS
  27596. if (this._physicsEngine) {
  27597. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27598. }
  27599. var stepsTaken = 0;
  27600. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27601. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27602. internalSteps = Math.min(internalSteps, maxSubSteps);
  27603. do {
  27604. this.onBeforeStepObservable.notifyObservers(this);
  27605. // Animations
  27606. this._animationRatio = defaultFrameTime * defaultFPS;
  27607. this._animate();
  27608. this.onAfterAnimationsObservable.notifyObservers(this);
  27609. // Physics
  27610. if (this._physicsEngine) {
  27611. this.onBeforePhysicsObservable.notifyObservers(this);
  27612. this._physicsEngine._step(defaultFrameTime / 1000);
  27613. this.onAfterPhysicsObservable.notifyObservers(this);
  27614. }
  27615. this.onAfterStepObservable.notifyObservers(this);
  27616. this._currentStepId++;
  27617. stepsTaken++;
  27618. deltaTime -= defaultFrameTime;
  27619. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27620. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27621. }
  27622. else {
  27623. // Animations
  27624. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27625. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27626. this._animate();
  27627. this.onAfterAnimationsObservable.notifyObservers(this);
  27628. // Physics
  27629. if (this._physicsEngine) {
  27630. this.onBeforePhysicsObservable.notifyObservers(this);
  27631. this._physicsEngine._step(deltaTime / 1000.0);
  27632. this.onAfterPhysicsObservable.notifyObservers(this);
  27633. }
  27634. }
  27635. // update gamepad manager
  27636. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27637. this._gamepadManager._checkGamepadsStatus();
  27638. }
  27639. // Update Cameras
  27640. if (this.activeCameras.length > 0) {
  27641. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27642. var camera = this.activeCameras[cameraIndex];
  27643. camera.update();
  27644. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27645. // rig cameras
  27646. for (var index = 0; index < camera._rigCameras.length; index++) {
  27647. camera._rigCameras[index].update();
  27648. }
  27649. }
  27650. }
  27651. }
  27652. else if (this.activeCamera) {
  27653. this.activeCamera.update();
  27654. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27655. // rig cameras
  27656. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27657. this.activeCamera._rigCameras[index].update();
  27658. }
  27659. }
  27660. }
  27661. // Before render
  27662. this.onBeforeRenderObservable.notifyObservers(this);
  27663. // Customs render targets
  27664. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27665. var engine = this.getEngine();
  27666. var currentActiveCamera = this.activeCamera;
  27667. if (this.renderTargetsEnabled) {
  27668. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27669. this._intermediateRendering = true;
  27670. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27671. var renderTarget = this.customRenderTargets[customIndex];
  27672. if (renderTarget._shouldRender()) {
  27673. this._renderId++;
  27674. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27675. if (!this.activeCamera)
  27676. throw new Error("Active camera not set");
  27677. // Viewport
  27678. engine.setViewport(this.activeCamera.viewport);
  27679. // Camera
  27680. this.updateTransformMatrix();
  27681. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27682. }
  27683. }
  27684. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27685. this._intermediateRendering = false;
  27686. this._renderId++;
  27687. }
  27688. // Restore back buffer
  27689. if (this.customRenderTargets.length > 0) {
  27690. engine.restoreDefaultFramebuffer();
  27691. }
  27692. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27693. this.activeCamera = currentActiveCamera;
  27694. // Procedural textures
  27695. if (this.proceduralTexturesEnabled) {
  27696. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27697. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27698. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27699. if (proceduralTexture._shouldRender()) {
  27700. proceduralTexture.render();
  27701. }
  27702. }
  27703. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27704. }
  27705. // Clear
  27706. if (this.autoClearDepthAndStencil || this.autoClear) {
  27707. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27708. }
  27709. // Shadows
  27710. if (this.shadowsEnabled) {
  27711. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27712. var light = this.lights[lightIndex];
  27713. var shadowGenerator = light.getShadowGenerator();
  27714. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27715. var shadowMap = (shadowGenerator.getShadowMap());
  27716. if (this.textures.indexOf(shadowMap) !== -1) {
  27717. this._renderTargets.push(shadowMap);
  27718. }
  27719. }
  27720. }
  27721. }
  27722. // Depth renderer
  27723. for (var key in this._depthRenderer) {
  27724. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27725. }
  27726. // Geometry renderer
  27727. if (this._geometryBufferRenderer) {
  27728. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27729. }
  27730. // RenderPipeline
  27731. if (this._postProcessRenderPipelineManager) {
  27732. this._postProcessRenderPipelineManager.update();
  27733. }
  27734. // Multi-cameras?
  27735. if (this.activeCameras.length > 0) {
  27736. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27737. if (cameraIndex > 0) {
  27738. this._engine.clear(null, false, true, true);
  27739. }
  27740. this._processSubCameras(this.activeCameras[cameraIndex]);
  27741. }
  27742. }
  27743. else {
  27744. if (!this.activeCamera) {
  27745. throw new Error("No camera defined");
  27746. }
  27747. this._processSubCameras(this.activeCamera);
  27748. }
  27749. // Intersection checks
  27750. this._checkIntersections();
  27751. // Update the audio listener attached to the camera
  27752. if (BABYLON.AudioEngine) {
  27753. this._updateAudioParameters();
  27754. }
  27755. // After render
  27756. if (this.afterRender) {
  27757. this.afterRender();
  27758. }
  27759. this.onAfterRenderObservable.notifyObservers(this);
  27760. // Cleaning
  27761. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27762. var data = this._toBeDisposed.data[index];
  27763. if (data) {
  27764. data.dispose();
  27765. }
  27766. this._toBeDisposed[index] = null;
  27767. }
  27768. this._toBeDisposed.reset();
  27769. if (this.dumpNextRenderTargets) {
  27770. this.dumpNextRenderTargets = false;
  27771. }
  27772. this._activeBones.addCount(0, true);
  27773. this._activeIndices.addCount(0, true);
  27774. this._activeParticles.addCount(0, true);
  27775. };
  27776. Scene.prototype._updateAudioParameters = function () {
  27777. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27778. return;
  27779. }
  27780. var listeningCamera;
  27781. var audioEngine = BABYLON.Engine.audioEngine;
  27782. if (this.activeCameras.length > 0) {
  27783. listeningCamera = this.activeCameras[0];
  27784. }
  27785. else {
  27786. listeningCamera = this.activeCamera;
  27787. }
  27788. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27789. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27790. // for VR cameras
  27791. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27792. listeningCamera = listeningCamera.rigCameras[0];
  27793. }
  27794. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27795. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27796. cameraDirection.normalize();
  27797. // To avoid some errors on GearVR
  27798. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27799. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27800. }
  27801. var i;
  27802. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27803. var sound = this.mainSoundTrack.soundCollection[i];
  27804. if (sound.useCustomAttenuation) {
  27805. sound.updateDistanceFromListener();
  27806. }
  27807. }
  27808. for (i = 0; i < this.soundTracks.length; i++) {
  27809. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27810. sound = this.soundTracks[i].soundCollection[j];
  27811. if (sound.useCustomAttenuation) {
  27812. sound.updateDistanceFromListener();
  27813. }
  27814. }
  27815. }
  27816. }
  27817. };
  27818. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27819. // Audio
  27820. /**
  27821. * Gets or sets if audio support is enabled
  27822. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27823. */
  27824. get: function () {
  27825. return this._audioEnabled;
  27826. },
  27827. set: function (value) {
  27828. this._audioEnabled = value;
  27829. if (BABYLON.AudioEngine) {
  27830. if (this._audioEnabled) {
  27831. this._enableAudio();
  27832. }
  27833. else {
  27834. this._disableAudio();
  27835. }
  27836. }
  27837. },
  27838. enumerable: true,
  27839. configurable: true
  27840. });
  27841. Scene.prototype._disableAudio = function () {
  27842. var i;
  27843. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27844. this.mainSoundTrack.soundCollection[i].pause();
  27845. }
  27846. for (i = 0; i < this.soundTracks.length; i++) {
  27847. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27848. this.soundTracks[i].soundCollection[j].pause();
  27849. }
  27850. }
  27851. };
  27852. Scene.prototype._enableAudio = function () {
  27853. var i;
  27854. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27855. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27856. this.mainSoundTrack.soundCollection[i].play();
  27857. }
  27858. }
  27859. for (i = 0; i < this.soundTracks.length; i++) {
  27860. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27861. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27862. this.soundTracks[i].soundCollection[j].play();
  27863. }
  27864. }
  27865. }
  27866. };
  27867. Object.defineProperty(Scene.prototype, "headphone", {
  27868. /**
  27869. * Gets or sets if audio will be output to headphones
  27870. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27871. */
  27872. get: function () {
  27873. return this._headphone;
  27874. },
  27875. set: function (value) {
  27876. this._headphone = value;
  27877. if (BABYLON.AudioEngine) {
  27878. if (this._headphone) {
  27879. this._switchAudioModeForHeadphones();
  27880. }
  27881. else {
  27882. this._switchAudioModeForNormalSpeakers();
  27883. }
  27884. }
  27885. },
  27886. enumerable: true,
  27887. configurable: true
  27888. });
  27889. Scene.prototype._switchAudioModeForHeadphones = function () {
  27890. this.mainSoundTrack.switchPanningModelToHRTF();
  27891. for (var i = 0; i < this.soundTracks.length; i++) {
  27892. this.soundTracks[i].switchPanningModelToHRTF();
  27893. }
  27894. };
  27895. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27896. this.mainSoundTrack.switchPanningModelToEqualPower();
  27897. for (var i = 0; i < this.soundTracks.length; i++) {
  27898. this.soundTracks[i].switchPanningModelToEqualPower();
  27899. }
  27900. };
  27901. /**
  27902. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27903. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27904. * @returns the created depth renderer
  27905. */
  27906. Scene.prototype.enableDepthRenderer = function (camera) {
  27907. camera = camera || this.activeCamera;
  27908. if (!camera) {
  27909. throw "No camera available to enable depth renderer";
  27910. }
  27911. if (!this._depthRenderer[camera.id]) {
  27912. var textureType = 0;
  27913. if (this._engine.getCaps().textureHalfFloatRender) {
  27914. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27915. }
  27916. else if (this._engine.getCaps().textureFloatRender) {
  27917. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27918. }
  27919. else {
  27920. throw "Depth renderer does not support int texture type";
  27921. }
  27922. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27923. }
  27924. return this._depthRenderer[camera.id];
  27925. };
  27926. /**
  27927. * Disables a depth renderer for a given camera
  27928. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27929. */
  27930. Scene.prototype.disableDepthRenderer = function (camera) {
  27931. camera = camera || this.activeCamera;
  27932. if (!camera || !this._depthRenderer[camera.id]) {
  27933. return;
  27934. }
  27935. this._depthRenderer[camera.id].dispose();
  27936. delete this._depthRenderer[camera.id];
  27937. };
  27938. /**
  27939. * Enables a GeometryBufferRender and associates it with the scene
  27940. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27941. * @returns the GeometryBufferRenderer
  27942. */
  27943. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27944. if (ratio === void 0) { ratio = 1; }
  27945. if (this._geometryBufferRenderer) {
  27946. return this._geometryBufferRenderer;
  27947. }
  27948. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27949. if (!this._geometryBufferRenderer.isSupported) {
  27950. this._geometryBufferRenderer = null;
  27951. }
  27952. return this._geometryBufferRenderer;
  27953. };
  27954. /**
  27955. * Disables the GeometryBufferRender associated with the scene
  27956. */
  27957. Scene.prototype.disableGeometryBufferRenderer = function () {
  27958. if (!this._geometryBufferRenderer) {
  27959. return;
  27960. }
  27961. this._geometryBufferRenderer.dispose();
  27962. this._geometryBufferRenderer = null;
  27963. };
  27964. /**
  27965. * Freeze all materials
  27966. * A frozen material will not be updatable but should be faster to render
  27967. */
  27968. Scene.prototype.freezeMaterials = function () {
  27969. for (var i = 0; i < this.materials.length; i++) {
  27970. this.materials[i].freeze();
  27971. }
  27972. };
  27973. /**
  27974. * Unfreeze all materials
  27975. * A frozen material will not be updatable but should be faster to render
  27976. */
  27977. Scene.prototype.unfreezeMaterials = function () {
  27978. for (var i = 0; i < this.materials.length; i++) {
  27979. this.materials[i].unfreeze();
  27980. }
  27981. };
  27982. /**
  27983. * Releases all held ressources
  27984. */
  27985. Scene.prototype.dispose = function () {
  27986. this.beforeRender = null;
  27987. this.afterRender = null;
  27988. this.skeletons = [];
  27989. this.morphTargetManagers = [];
  27990. this.importedMeshesFiles = new Array();
  27991. this.stopAllAnimations();
  27992. this.resetCachedMaterial();
  27993. for (var key in this._depthRenderer) {
  27994. this._depthRenderer[key].dispose();
  27995. }
  27996. if (this._gamepadManager) {
  27997. this._gamepadManager.dispose();
  27998. this._gamepadManager = null;
  27999. }
  28000. // Smart arrays
  28001. if (this.activeCamera) {
  28002. this.activeCamera._activeMeshes.dispose();
  28003. this.activeCamera = null;
  28004. }
  28005. this._activeMeshes.dispose();
  28006. this._renderingManager.dispose();
  28007. this._processedMaterials.dispose();
  28008. this._activeParticleSystems.dispose();
  28009. this._activeSkeletons.dispose();
  28010. this._softwareSkinnedMeshes.dispose();
  28011. this._renderTargets.dispose();
  28012. this._registeredForLateAnimationBindings.dispose();
  28013. if (this._boundingBoxRenderer) {
  28014. this._boundingBoxRenderer.dispose();
  28015. }
  28016. this._meshesForIntersections.dispose();
  28017. this._toBeDisposed.dispose();
  28018. // Abort active requests
  28019. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28020. var request = _a[_i];
  28021. request.abort();
  28022. }
  28023. // Debug layer
  28024. if (this._debugLayer) {
  28025. this._debugLayer.hide();
  28026. }
  28027. // Events
  28028. this.onDisposeObservable.notifyObservers(this);
  28029. this.onDisposeObservable.clear();
  28030. this.onBeforeRenderObservable.clear();
  28031. this.onAfterRenderObservable.clear();
  28032. this.onBeforeRenderTargetsRenderObservable.clear();
  28033. this.onAfterRenderTargetsRenderObservable.clear();
  28034. this.onAfterStepObservable.clear();
  28035. this.onBeforeStepObservable.clear();
  28036. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28037. this.onAfterActiveMeshesEvaluationObservable.clear();
  28038. this.onBeforeParticlesRenderingObservable.clear();
  28039. this.onAfterParticlesRenderingObservable.clear();
  28040. this.onBeforeSpritesRenderingObservable.clear();
  28041. this.onAfterSpritesRenderingObservable.clear();
  28042. this.onBeforeDrawPhaseObservable.clear();
  28043. this.onAfterDrawPhaseObservable.clear();
  28044. this.onBeforePhysicsObservable.clear();
  28045. this.onAfterPhysicsObservable.clear();
  28046. this.onBeforeAnimationsObservable.clear();
  28047. this.onAfterAnimationsObservable.clear();
  28048. this.onDataLoadedObservable.clear();
  28049. this.detachControl();
  28050. // Release sounds & sounds tracks
  28051. if (BABYLON.AudioEngine) {
  28052. this.disposeSounds();
  28053. }
  28054. // VR Helper
  28055. if (this.VRHelper) {
  28056. this.VRHelper.dispose();
  28057. }
  28058. // Detach cameras
  28059. var canvas = this._engine.getRenderingCanvas();
  28060. if (canvas) {
  28061. var index;
  28062. for (index = 0; index < this.cameras.length; index++) {
  28063. this.cameras[index].detachControl(canvas);
  28064. }
  28065. }
  28066. // Release animation groups
  28067. while (this.animationGroups.length) {
  28068. this.animationGroups[0].dispose();
  28069. }
  28070. // Release lights
  28071. while (this.lights.length) {
  28072. this.lights[0].dispose();
  28073. }
  28074. // Release meshes
  28075. while (this.meshes.length) {
  28076. this.meshes[0].dispose(true);
  28077. }
  28078. while (this.transformNodes.length) {
  28079. this.removeTransformNode(this.transformNodes[0]);
  28080. }
  28081. // Release cameras
  28082. while (this.cameras.length) {
  28083. this.cameras[0].dispose();
  28084. }
  28085. // Release materials
  28086. if (this.defaultMaterial) {
  28087. this.defaultMaterial.dispose();
  28088. }
  28089. while (this.multiMaterials.length) {
  28090. this.multiMaterials[0].dispose();
  28091. }
  28092. while (this.materials.length) {
  28093. this.materials[0].dispose();
  28094. }
  28095. // Release particles
  28096. while (this.particleSystems.length) {
  28097. this.particleSystems[0].dispose();
  28098. }
  28099. // Release sprites
  28100. while (this.spriteManagers.length) {
  28101. this.spriteManagers[0].dispose();
  28102. }
  28103. // Release postProcesses
  28104. while (this.postProcesses.length) {
  28105. this.postProcesses[0].dispose();
  28106. }
  28107. // Release layers
  28108. while (this.layers.length) {
  28109. this.layers[0].dispose();
  28110. }
  28111. while (this.effectLayers.length) {
  28112. this.effectLayers[0].dispose();
  28113. }
  28114. // Release textures
  28115. while (this.textures.length) {
  28116. this.textures[0].dispose();
  28117. }
  28118. // Release UBO
  28119. this._sceneUbo.dispose();
  28120. if (this._alternateSceneUbo) {
  28121. this._alternateSceneUbo.dispose();
  28122. }
  28123. // Post-processes
  28124. this.postProcessManager.dispose();
  28125. if (this._postProcessRenderPipelineManager) {
  28126. this._postProcessRenderPipelineManager.dispose();
  28127. }
  28128. // Physics
  28129. if (this._physicsEngine) {
  28130. this.disablePhysicsEngine();
  28131. }
  28132. // Remove from engine
  28133. index = this._engine.scenes.indexOf(this);
  28134. if (index > -1) {
  28135. this._engine.scenes.splice(index, 1);
  28136. }
  28137. this._engine.wipeCaches(true);
  28138. this._isDisposed = true;
  28139. };
  28140. Object.defineProperty(Scene.prototype, "isDisposed", {
  28141. /**
  28142. * Gets if the scene is already disposed
  28143. */
  28144. get: function () {
  28145. return this._isDisposed;
  28146. },
  28147. enumerable: true,
  28148. configurable: true
  28149. });
  28150. /**
  28151. * Releases sounds & soundtracks
  28152. */
  28153. Scene.prototype.disposeSounds = function () {
  28154. if (!this._mainSoundTrack) {
  28155. return;
  28156. }
  28157. this.mainSoundTrack.dispose();
  28158. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28159. this.soundTracks[scIndex].dispose();
  28160. }
  28161. };
  28162. // Octrees
  28163. /**
  28164. * Get the world extend vectors with an optional filter
  28165. *
  28166. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28167. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28168. */
  28169. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28170. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28171. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28172. filterPredicate = filterPredicate || (function () { return true; });
  28173. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28174. mesh.computeWorldMatrix(true);
  28175. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28176. return;
  28177. }
  28178. var boundingInfo = mesh.getBoundingInfo();
  28179. var minBox = boundingInfo.boundingBox.minimumWorld;
  28180. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28181. BABYLON.Tools.CheckExtends(minBox, min, max);
  28182. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28183. });
  28184. return {
  28185. min: min,
  28186. max: max
  28187. };
  28188. };
  28189. /**
  28190. * Creates or updates the octree used to boost selection (picking)
  28191. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28192. * @param maxCapacity defines the maximum capacity per leaf
  28193. * @param maxDepth defines the maximum depth of the octree
  28194. * @returns an octree of AbstractMesh
  28195. */
  28196. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28197. if (maxCapacity === void 0) { maxCapacity = 64; }
  28198. if (maxDepth === void 0) { maxDepth = 2; }
  28199. if (!this._selectionOctree) {
  28200. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28201. }
  28202. var worldExtends = this.getWorldExtends();
  28203. // Update octree
  28204. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28205. return this._selectionOctree;
  28206. };
  28207. // Picking
  28208. /**
  28209. * Creates a ray that can be used to pick in the scene
  28210. * @param x defines the x coordinate of the origin (on-screen)
  28211. * @param y defines the y coordinate of the origin (on-screen)
  28212. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28213. * @param camera defines the camera to use for the picking
  28214. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28215. * @returns a Ray
  28216. */
  28217. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28218. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28219. var result = BABYLON.Ray.Zero();
  28220. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28221. return result;
  28222. };
  28223. /**
  28224. * Creates a ray that can be used to pick in the scene
  28225. * @param x defines the x coordinate of the origin (on-screen)
  28226. * @param y defines the y coordinate of the origin (on-screen)
  28227. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28228. * @param result defines the ray where to store the picking ray
  28229. * @param camera defines the camera to use for the picking
  28230. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28231. * @returns the current scene
  28232. */
  28233. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28234. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28235. var engine = this._engine;
  28236. if (!camera) {
  28237. if (!this.activeCamera)
  28238. throw new Error("Active camera not set");
  28239. camera = this.activeCamera;
  28240. }
  28241. var cameraViewport = camera.viewport;
  28242. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28243. // Moving coordinates to local viewport world
  28244. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28245. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28246. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28247. return this;
  28248. };
  28249. /**
  28250. * Creates a ray that can be used to pick in the scene
  28251. * @param x defines the x coordinate of the origin (on-screen)
  28252. * @param y defines the y coordinate of the origin (on-screen)
  28253. * @param camera defines the camera to use for the picking
  28254. * @returns a Ray
  28255. */
  28256. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28257. var result = BABYLON.Ray.Zero();
  28258. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28259. return result;
  28260. };
  28261. /**
  28262. * Creates a ray that can be used to pick in the scene
  28263. * @param x defines the x coordinate of the origin (on-screen)
  28264. * @param y defines the y coordinate of the origin (on-screen)
  28265. * @param result defines the ray where to store the picking ray
  28266. * @param camera defines the camera to use for the picking
  28267. * @returns the current scene
  28268. */
  28269. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28270. if (!BABYLON.PickingInfo) {
  28271. return this;
  28272. }
  28273. var engine = this._engine;
  28274. if (!camera) {
  28275. if (!this.activeCamera)
  28276. throw new Error("Active camera not set");
  28277. camera = this.activeCamera;
  28278. }
  28279. var cameraViewport = camera.viewport;
  28280. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28281. var identity = BABYLON.Matrix.Identity();
  28282. // Moving coordinates to local viewport world
  28283. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28284. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28285. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28286. return this;
  28287. };
  28288. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28289. if (!BABYLON.PickingInfo) {
  28290. return null;
  28291. }
  28292. var pickingInfo = null;
  28293. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28294. var mesh = this.meshes[meshIndex];
  28295. if (predicate) {
  28296. if (!predicate(mesh)) {
  28297. continue;
  28298. }
  28299. }
  28300. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28301. continue;
  28302. }
  28303. var world = mesh.getWorldMatrix();
  28304. var ray = rayFunction(world);
  28305. var result = mesh.intersects(ray, fastCheck);
  28306. if (!result || !result.hit)
  28307. continue;
  28308. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28309. continue;
  28310. pickingInfo = result;
  28311. if (fastCheck) {
  28312. break;
  28313. }
  28314. }
  28315. return pickingInfo || new BABYLON.PickingInfo();
  28316. };
  28317. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28318. if (!BABYLON.PickingInfo) {
  28319. return null;
  28320. }
  28321. var pickingInfos = new Array();
  28322. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28323. var mesh = this.meshes[meshIndex];
  28324. if (predicate) {
  28325. if (!predicate(mesh)) {
  28326. continue;
  28327. }
  28328. }
  28329. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28330. continue;
  28331. }
  28332. var world = mesh.getWorldMatrix();
  28333. var ray = rayFunction(world);
  28334. var result = mesh.intersects(ray, false);
  28335. if (!result || !result.hit)
  28336. continue;
  28337. pickingInfos.push(result);
  28338. }
  28339. return pickingInfos;
  28340. };
  28341. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28342. if (!BABYLON.PickingInfo) {
  28343. return null;
  28344. }
  28345. var pickingInfo = null;
  28346. if (!camera) {
  28347. if (!this.activeCamera) {
  28348. return null;
  28349. }
  28350. camera = this.activeCamera;
  28351. }
  28352. if (this.spriteManagers.length > 0) {
  28353. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28354. var spriteManager = this.spriteManagers[spriteIndex];
  28355. if (!spriteManager.isPickable) {
  28356. continue;
  28357. }
  28358. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28359. if (!result || !result.hit)
  28360. continue;
  28361. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28362. continue;
  28363. pickingInfo = result;
  28364. if (fastCheck) {
  28365. break;
  28366. }
  28367. }
  28368. }
  28369. return pickingInfo || new BABYLON.PickingInfo();
  28370. };
  28371. /** Launch a ray to try to pick a mesh in the scene
  28372. * @param x position on screen
  28373. * @param y position on screen
  28374. * @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
  28375. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28376. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28377. * @returns a PickingInfo
  28378. */
  28379. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28380. var _this = this;
  28381. if (!BABYLON.PickingInfo) {
  28382. return null;
  28383. }
  28384. return this._internalPick(function (world) {
  28385. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28386. return _this._tempPickingRay;
  28387. }, predicate, fastCheck);
  28388. };
  28389. /** Launch a ray to try to pick a sprite in the scene
  28390. * @param x position on screen
  28391. * @param y position on screen
  28392. * @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
  28393. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28394. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28395. * @returns a PickingInfo
  28396. */
  28397. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28398. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28399. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28400. };
  28401. /** Use the given ray to pick a mesh in the scene
  28402. * @param ray The ray to use to pick meshes
  28403. * @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
  28404. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28405. * @returns a PickingInfo
  28406. */
  28407. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28408. var _this = this;
  28409. return this._internalPick(function (world) {
  28410. if (!_this._pickWithRayInverseMatrix) {
  28411. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28412. }
  28413. world.invertToRef(_this._pickWithRayInverseMatrix);
  28414. if (!_this._cachedRayForTransform) {
  28415. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28416. }
  28417. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28418. return _this._cachedRayForTransform;
  28419. }, predicate, fastCheck);
  28420. };
  28421. /**
  28422. * Launch a ray to try to pick a mesh in the scene
  28423. * @param x X position on screen
  28424. * @param y Y position on screen
  28425. * @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
  28426. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28427. * @returns an array of PickingInfo
  28428. */
  28429. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28430. var _this = this;
  28431. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28432. };
  28433. /**
  28434. * Launch a ray to try to pick a mesh in the scene
  28435. * @param ray Ray to use
  28436. * @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
  28437. * @returns an array of PickingInfo
  28438. */
  28439. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28440. var _this = this;
  28441. return this._internalMultiPick(function (world) {
  28442. if (!_this._pickWithRayInverseMatrix) {
  28443. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28444. }
  28445. world.invertToRef(_this._pickWithRayInverseMatrix);
  28446. if (!_this._cachedRayForTransform) {
  28447. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28448. }
  28449. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28450. return _this._cachedRayForTransform;
  28451. }, predicate);
  28452. };
  28453. /**
  28454. * Force the value of meshUnderPointer
  28455. * @param mesh defines the mesh to use
  28456. */
  28457. Scene.prototype.setPointerOverMesh = function (mesh) {
  28458. if (this._pointerOverMesh === mesh) {
  28459. return;
  28460. }
  28461. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28462. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28463. }
  28464. this._pointerOverMesh = mesh;
  28465. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28466. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28467. }
  28468. };
  28469. /**
  28470. * Gets the mesh under the pointer
  28471. * @returns a Mesh or null if no mesh is under the pointer
  28472. */
  28473. Scene.prototype.getPointerOverMesh = function () {
  28474. return this._pointerOverMesh;
  28475. };
  28476. /**
  28477. * Force the sprite under the pointer
  28478. * @param sprite defines the sprite to use
  28479. */
  28480. Scene.prototype.setPointerOverSprite = function (sprite) {
  28481. if (this._pointerOverSprite === sprite) {
  28482. return;
  28483. }
  28484. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28485. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28486. }
  28487. this._pointerOverSprite = sprite;
  28488. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28489. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28490. }
  28491. };
  28492. /**
  28493. * Gets the sprite under the pointer
  28494. * @returns a Sprite or null if no sprite is under the pointer
  28495. */
  28496. Scene.prototype.getPointerOverSprite = function () {
  28497. return this._pointerOverSprite;
  28498. };
  28499. // Physics
  28500. /**
  28501. * Gets the current physics engine
  28502. * @returns a PhysicsEngine or null if none attached
  28503. */
  28504. Scene.prototype.getPhysicsEngine = function () {
  28505. return this._physicsEngine;
  28506. };
  28507. /**
  28508. * Enables physics to the current scene
  28509. * @param gravity defines the scene's gravity for the physics engine
  28510. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28511. * @return a boolean indicating if the physics engine was initialized
  28512. */
  28513. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28514. if (gravity === void 0) { gravity = null; }
  28515. if (this._physicsEngine) {
  28516. return true;
  28517. }
  28518. try {
  28519. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28520. return true;
  28521. }
  28522. catch (e) {
  28523. BABYLON.Tools.Error(e.message);
  28524. return false;
  28525. }
  28526. };
  28527. /**
  28528. * Disables and disposes the physics engine associated with the scene
  28529. */
  28530. Scene.prototype.disablePhysicsEngine = function () {
  28531. if (!this._physicsEngine) {
  28532. return;
  28533. }
  28534. this._physicsEngine.dispose();
  28535. this._physicsEngine = null;
  28536. };
  28537. /**
  28538. * Gets a boolean indicating if there is an active physics engine
  28539. * @returns a boolean indicating if there is an active physics engine
  28540. */
  28541. Scene.prototype.isPhysicsEnabled = function () {
  28542. return this._physicsEngine !== undefined;
  28543. };
  28544. /**
  28545. * Deletes a physics compound impostor
  28546. * @param compound defines the compound to delete
  28547. */
  28548. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28549. var mesh = compound.parts[0].mesh;
  28550. if (mesh.physicsImpostor) {
  28551. mesh.physicsImpostor.dispose( /*true*/);
  28552. mesh.physicsImpostor = null;
  28553. }
  28554. };
  28555. // Misc.
  28556. /** @hidden */
  28557. Scene.prototype._rebuildGeometries = function () {
  28558. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28559. var geometry = _a[_i];
  28560. geometry._rebuild();
  28561. }
  28562. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28563. var mesh = _c[_b];
  28564. mesh._rebuild();
  28565. }
  28566. if (this.postProcessManager) {
  28567. this.postProcessManager._rebuild();
  28568. }
  28569. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28570. var layer = _e[_d];
  28571. layer._rebuild();
  28572. }
  28573. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28574. var effectLayer = _g[_f];
  28575. effectLayer._rebuild();
  28576. }
  28577. if (this._boundingBoxRenderer) {
  28578. this._boundingBoxRenderer._rebuild();
  28579. }
  28580. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28581. var system = _j[_h];
  28582. system.rebuild();
  28583. }
  28584. if (this._postProcessRenderPipelineManager) {
  28585. this._postProcessRenderPipelineManager._rebuild();
  28586. }
  28587. };
  28588. /** @hidden */
  28589. Scene.prototype._rebuildTextures = function () {
  28590. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28591. var texture = _a[_i];
  28592. texture._rebuild();
  28593. }
  28594. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28595. };
  28596. /**
  28597. * Creates a default light for the scene.
  28598. * @param replace Whether to replace the existing lights in the scene.
  28599. */
  28600. Scene.prototype.createDefaultLight = function (replace) {
  28601. if (replace === void 0) { replace = false; }
  28602. // Dispose existing light in replace mode.
  28603. if (replace) {
  28604. if (this.lights) {
  28605. for (var i = 0; i < this.lights.length; i++) {
  28606. this.lights[i].dispose();
  28607. }
  28608. }
  28609. }
  28610. // Light
  28611. if (this.lights.length === 0) {
  28612. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28613. }
  28614. };
  28615. /**
  28616. * Creates a default camera for the scene.
  28617. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28618. * @param replace Whether to replace the existing active camera in the scene.
  28619. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28620. */
  28621. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28622. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28623. if (replace === void 0) { replace = false; }
  28624. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28625. // Dispose existing camera in replace mode.
  28626. if (replace) {
  28627. if (this.activeCamera) {
  28628. this.activeCamera.dispose();
  28629. this.activeCamera = null;
  28630. }
  28631. }
  28632. // Camera
  28633. if (!this.activeCamera) {
  28634. var worldExtends = this.getWorldExtends();
  28635. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28636. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28637. var camera;
  28638. var radius = worldSize.length() * 1.5;
  28639. // empty scene scenario!
  28640. if (!isFinite(radius)) {
  28641. radius = 1;
  28642. worldCenter.copyFromFloats(0, 0, 0);
  28643. }
  28644. if (createArcRotateCamera) {
  28645. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28646. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28647. arcRotateCamera.wheelPrecision = 100 / radius;
  28648. camera = arcRotateCamera;
  28649. }
  28650. else {
  28651. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28652. freeCamera.setTarget(worldCenter);
  28653. camera = freeCamera;
  28654. }
  28655. camera.minZ = radius * 0.01;
  28656. camera.maxZ = radius * 1000;
  28657. camera.speed = radius * 0.2;
  28658. this.activeCamera = camera;
  28659. var canvas = this.getEngine().getRenderingCanvas();
  28660. if (attachCameraControls && canvas) {
  28661. camera.attachControl(canvas);
  28662. }
  28663. }
  28664. };
  28665. /**
  28666. * Creates a default camera and a default light
  28667. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28668. * @param replace defines if the camera and/or light will replace the existing ones
  28669. * @param attachCameraControls defines if attachControl will be called on the new camera
  28670. */
  28671. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28672. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28673. if (replace === void 0) { replace = false; }
  28674. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28675. this.createDefaultLight(replace);
  28676. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28677. };
  28678. /**
  28679. * Creates a new sky box
  28680. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28681. * @param environmentTexture defines the texture to use as environment texture
  28682. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28683. * @param scale defines the overall scale of the skybox
  28684. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28685. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28686. * @returns a new mesh holding the sky box
  28687. */
  28688. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28689. if (pbr === void 0) { pbr = false; }
  28690. if (scale === void 0) { scale = 1000; }
  28691. if (blur === void 0) { blur = 0; }
  28692. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28693. if (!environmentTexture) {
  28694. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28695. return null;
  28696. }
  28697. if (setGlobalEnvTexture) {
  28698. if (environmentTexture) {
  28699. this.environmentTexture = environmentTexture;
  28700. }
  28701. }
  28702. // Skybox
  28703. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28704. if (pbr) {
  28705. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28706. hdrSkyboxMaterial.backFaceCulling = false;
  28707. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28708. if (hdrSkyboxMaterial.reflectionTexture) {
  28709. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28710. }
  28711. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28712. hdrSkyboxMaterial.disableLighting = true;
  28713. hdrSkyboxMaterial.twoSidedLighting = true;
  28714. hdrSkybox.infiniteDistance = true;
  28715. hdrSkybox.material = hdrSkyboxMaterial;
  28716. }
  28717. else {
  28718. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28719. skyboxMaterial.backFaceCulling = false;
  28720. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28721. if (skyboxMaterial.reflectionTexture) {
  28722. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28723. }
  28724. skyboxMaterial.disableLighting = true;
  28725. hdrSkybox.infiniteDistance = true;
  28726. hdrSkybox.material = skyboxMaterial;
  28727. }
  28728. return hdrSkybox;
  28729. };
  28730. /**
  28731. * Creates a new environment
  28732. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28733. * @param options defines the options you can use to configure the environment
  28734. * @returns the new EnvironmentHelper
  28735. */
  28736. Scene.prototype.createDefaultEnvironment = function (options) {
  28737. if (BABYLON.EnvironmentHelper) {
  28738. return new BABYLON.EnvironmentHelper(options, this);
  28739. }
  28740. return null;
  28741. };
  28742. /**
  28743. * Creates a new VREXperienceHelper
  28744. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28745. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28746. * @returns a new VREXperienceHelper
  28747. */
  28748. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28749. if (webVROptions === void 0) { webVROptions = {}; }
  28750. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28751. };
  28752. // Tags
  28753. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28754. if (tagsQuery === undefined) {
  28755. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28756. return list;
  28757. }
  28758. var listByTags = [];
  28759. forEach = forEach || (function (item) { return; });
  28760. for (var i in list) {
  28761. var item = list[i];
  28762. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28763. listByTags.push(item);
  28764. forEach(item);
  28765. }
  28766. }
  28767. return listByTags;
  28768. };
  28769. /**
  28770. * Get a list of meshes by tags
  28771. * @param tagsQuery defines the tags query to use
  28772. * @param forEach defines a predicate used to filter results
  28773. * @returns an array of Mesh
  28774. */
  28775. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28776. return this._getByTags(this.meshes, tagsQuery, forEach);
  28777. };
  28778. /**
  28779. * Get a list of cameras by tags
  28780. * @param tagsQuery defines the tags query to use
  28781. * @param forEach defines a predicate used to filter results
  28782. * @returns an array of Camera
  28783. */
  28784. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28785. return this._getByTags(this.cameras, tagsQuery, forEach);
  28786. };
  28787. /**
  28788. * Get a list of lights by tags
  28789. * @param tagsQuery defines the tags query to use
  28790. * @param forEach defines a predicate used to filter results
  28791. * @returns an array of Light
  28792. */
  28793. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28794. return this._getByTags(this.lights, tagsQuery, forEach);
  28795. };
  28796. /**
  28797. * Get a list of materials by tags
  28798. * @param tagsQuery defines the tags query to use
  28799. * @param forEach defines a predicate used to filter results
  28800. * @returns an array of Material
  28801. */
  28802. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28803. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28804. };
  28805. /**
  28806. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28807. * This allowed control for front to back rendering or reversly depending of the special needs.
  28808. *
  28809. * @param renderingGroupId The rendering group id corresponding to its index
  28810. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28811. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28812. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28813. */
  28814. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28815. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28816. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28817. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28818. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28819. };
  28820. /**
  28821. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28822. *
  28823. * @param renderingGroupId The rendering group id corresponding to its index
  28824. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28825. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28826. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28827. */
  28828. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28829. if (depth === void 0) { depth = true; }
  28830. if (stencil === void 0) { stencil = true; }
  28831. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28832. };
  28833. /**
  28834. * Will flag all materials as dirty to trigger new shader compilation
  28835. * @param flag defines the flag used to specify which material part must be marked as dirty
  28836. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28837. */
  28838. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28839. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28840. var material = _a[_i];
  28841. if (predicate && !predicate(material)) {
  28842. continue;
  28843. }
  28844. material.markAsDirty(flag);
  28845. }
  28846. };
  28847. /** @hidden */
  28848. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28849. var _this = this;
  28850. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28851. this._activeRequests.push(request);
  28852. request.onCompleteObservable.add(function (request) {
  28853. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28854. });
  28855. return request;
  28856. };
  28857. /** @hidden */
  28858. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28859. var _this = this;
  28860. return new Promise(function (resolve, reject) {
  28861. _this._loadFile(url, function (data) {
  28862. resolve(data);
  28863. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28864. reject(exception);
  28865. });
  28866. });
  28867. };
  28868. // Statics
  28869. Scene._FOGMODE_NONE = 0;
  28870. Scene._FOGMODE_EXP = 1;
  28871. Scene._FOGMODE_EXP2 = 2;
  28872. Scene._FOGMODE_LINEAR = 3;
  28873. Scene._uniqueIdCounter = 0;
  28874. /**
  28875. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28876. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28877. */
  28878. Scene.MinDeltaTime = 1.0;
  28879. /**
  28880. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28881. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28882. */
  28883. Scene.MaxDeltaTime = 1000.0;
  28884. /** The distance in pixel that you have to move to prevent some events */
  28885. Scene.DragMovementThreshold = 10; // in pixels
  28886. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28887. Scene.LongPressDelay = 500; // in milliseconds
  28888. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28889. Scene.DoubleClickDelay = 300; // in milliseconds
  28890. /** If you need to check double click without raising a single click at first click, enable this flag */
  28891. Scene.ExclusiveDoubleClickMode = false;
  28892. return Scene;
  28893. }());
  28894. BABYLON.Scene = Scene;
  28895. })(BABYLON || (BABYLON = {}));
  28896. //# sourceMappingURL=babylon.scene.js.map
  28897. var BABYLON;
  28898. (function (BABYLON) {
  28899. /**
  28900. * Set of assets to keep when moving a scene into an asset container.
  28901. */
  28902. var KeepAssets = /** @class */ (function () {
  28903. function KeepAssets() {
  28904. /**
  28905. * Cameras to keep.
  28906. */
  28907. this.cameras = new Array();
  28908. /**
  28909. * Lights to keep.
  28910. */
  28911. this.lights = new Array();
  28912. /**
  28913. * Meshes to keep.
  28914. */
  28915. this.meshes = new Array();
  28916. /**
  28917. * Skeletons to keep.
  28918. */
  28919. this.skeletons = new Array();
  28920. /**
  28921. * ParticleSystems to keep.
  28922. */
  28923. this.particleSystems = new Array();
  28924. /**
  28925. * Animations to keep.
  28926. */
  28927. this.animations = new Array();
  28928. /**
  28929. * AnimationGroups to keep.
  28930. */
  28931. this.animationGroups = new Array();
  28932. /**
  28933. * MultiMaterials to keep.
  28934. */
  28935. this.multiMaterials = new Array();
  28936. /**
  28937. * Materials to keep.
  28938. */
  28939. this.materials = new Array();
  28940. /**
  28941. * MorphTargetManagers to keep.
  28942. */
  28943. this.morphTargetManagers = new Array();
  28944. /**
  28945. * Geometries to keep.
  28946. */
  28947. this.geometries = new Array();
  28948. /**
  28949. * TransformNodes to keep.
  28950. */
  28951. this.transformNodes = new Array();
  28952. /**
  28953. * LensFlareSystems to keep.
  28954. */
  28955. this.lensFlareSystems = new Array();
  28956. /**
  28957. * ShadowGenerators to keep.
  28958. */
  28959. this.shadowGenerators = new Array();
  28960. /**
  28961. * ActionManagers to keep.
  28962. */
  28963. this.actionManagers = new Array();
  28964. /**
  28965. * Sounds to keep.
  28966. */
  28967. this.sounds = new Array();
  28968. /**
  28969. * Textures to keep.
  28970. */
  28971. this.textures = new Array();
  28972. /**
  28973. * Effect layers to keep.
  28974. */
  28975. this.effectLayers = new Array();
  28976. }
  28977. return KeepAssets;
  28978. }());
  28979. BABYLON.KeepAssets = KeepAssets;
  28980. /**
  28981. * Container with a set of assets that can be added or removed from a scene.
  28982. */
  28983. var AssetContainer = /** @class */ (function () {
  28984. /**
  28985. * Instantiates an AssetContainer.
  28986. * @param scene The scene the AssetContainer belongs to.
  28987. */
  28988. function AssetContainer(scene) {
  28989. // Objects
  28990. /**
  28991. * Cameras populated in the container.
  28992. */
  28993. this.cameras = new Array();
  28994. /**
  28995. * Lights populated in the container.
  28996. */
  28997. this.lights = new Array();
  28998. /**
  28999. * Meshes populated in the container.
  29000. */
  29001. this.meshes = new Array();
  29002. /**
  29003. * Skeletons populated in the container.
  29004. */
  29005. this.skeletons = new Array();
  29006. /**
  29007. * ParticleSystems populated in the container.
  29008. */
  29009. this.particleSystems = new Array();
  29010. /**
  29011. * Animations populated in the container.
  29012. */
  29013. this.animations = new Array();
  29014. /**
  29015. * AnimationGroups populated in the container.
  29016. */
  29017. this.animationGroups = new Array();
  29018. /**
  29019. * MultiMaterials populated in the container.
  29020. */
  29021. this.multiMaterials = new Array();
  29022. /**
  29023. * Materials populated in the container.
  29024. */
  29025. this.materials = new Array();
  29026. /**
  29027. * MorphTargetManagers populated in the container.
  29028. */
  29029. this.morphTargetManagers = new Array();
  29030. /**
  29031. * Geometries populated in the container.
  29032. */
  29033. this.geometries = new Array();
  29034. /**
  29035. * TransformNodes populated in the container.
  29036. */
  29037. this.transformNodes = new Array();
  29038. /**
  29039. * LensFlareSystems populated in the container.
  29040. */
  29041. this.lensFlareSystems = new Array();
  29042. /**
  29043. * ShadowGenerators populated in the container.
  29044. */
  29045. this.shadowGenerators = new Array();
  29046. /**
  29047. * ActionManagers populated in the container.
  29048. */
  29049. this.actionManagers = new Array();
  29050. /**
  29051. * Sounds populated in the container.
  29052. */
  29053. this.sounds = new Array();
  29054. /**
  29055. * Textures populated in the container.
  29056. */
  29057. this.textures = new Array();
  29058. /**
  29059. * Effect layers populated in the container.
  29060. */
  29061. this.effectLayers = new Array();
  29062. this.scene = scene;
  29063. }
  29064. /**
  29065. * Adds all the assets from the container to the scene.
  29066. */
  29067. AssetContainer.prototype.addAllToScene = function () {
  29068. var _this = this;
  29069. this.cameras.forEach(function (o) {
  29070. _this.scene.addCamera(o);
  29071. });
  29072. this.lights.forEach(function (o) {
  29073. _this.scene.addLight(o);
  29074. });
  29075. this.meshes.forEach(function (o) {
  29076. _this.scene.addMesh(o);
  29077. });
  29078. this.skeletons.forEach(function (o) {
  29079. _this.scene.addSkeleton(o);
  29080. });
  29081. this.particleSystems.forEach(function (o) {
  29082. _this.scene.addParticleSystem(o);
  29083. });
  29084. this.animations.forEach(function (o) {
  29085. _this.scene.addAnimation(o);
  29086. });
  29087. this.animationGroups.forEach(function (o) {
  29088. _this.scene.addAnimationGroup(o);
  29089. });
  29090. this.multiMaterials.forEach(function (o) {
  29091. _this.scene.addMultiMaterial(o);
  29092. });
  29093. this.materials.forEach(function (o) {
  29094. _this.scene.addMaterial(o);
  29095. });
  29096. this.morphTargetManagers.forEach(function (o) {
  29097. _this.scene.addMorphTargetManager(o);
  29098. });
  29099. this.geometries.forEach(function (o) {
  29100. _this.scene.addGeometry(o);
  29101. });
  29102. this.transformNodes.forEach(function (o) {
  29103. _this.scene.addTransformNode(o);
  29104. });
  29105. this.lensFlareSystems.forEach(function (o) {
  29106. _this.scene.addLensFlareSystem(o);
  29107. });
  29108. this.actionManagers.forEach(function (o) {
  29109. _this.scene.addActionManager(o);
  29110. });
  29111. this.sounds.forEach(function (o) {
  29112. o.play();
  29113. o.autoplay = true;
  29114. _this.scene.mainSoundTrack.AddSound(o);
  29115. });
  29116. this.textures.forEach(function (o) {
  29117. _this.scene.addTexture(o);
  29118. });
  29119. this.effectLayers.forEach(function (o) {
  29120. _this.scene.addEffectLayer(o);
  29121. });
  29122. };
  29123. /**
  29124. * Removes all the assets in the container from the scene
  29125. */
  29126. AssetContainer.prototype.removeAllFromScene = function () {
  29127. var _this = this;
  29128. this.cameras.forEach(function (o) {
  29129. _this.scene.removeCamera(o);
  29130. });
  29131. this.lights.forEach(function (o) {
  29132. _this.scene.removeLight(o);
  29133. });
  29134. this.meshes.forEach(function (o) {
  29135. _this.scene.removeMesh(o);
  29136. });
  29137. this.skeletons.forEach(function (o) {
  29138. _this.scene.removeSkeleton(o);
  29139. });
  29140. this.particleSystems.forEach(function (o) {
  29141. _this.scene.removeParticleSystem(o);
  29142. });
  29143. this.animations.forEach(function (o) {
  29144. _this.scene.removeAnimation(o);
  29145. });
  29146. this.animationGroups.forEach(function (o) {
  29147. _this.scene.removeAnimationGroup(o);
  29148. });
  29149. this.multiMaterials.forEach(function (o) {
  29150. _this.scene.removeMultiMaterial(o);
  29151. });
  29152. this.materials.forEach(function (o) {
  29153. _this.scene.removeMaterial(o);
  29154. });
  29155. this.morphTargetManagers.forEach(function (o) {
  29156. _this.scene.removeMorphTargetManager(o);
  29157. });
  29158. this.geometries.forEach(function (o) {
  29159. _this.scene.removeGeometry(o);
  29160. });
  29161. this.transformNodes.forEach(function (o) {
  29162. _this.scene.removeTransformNode(o);
  29163. });
  29164. this.lensFlareSystems.forEach(function (o) {
  29165. _this.scene.removeLensFlareSystem(o);
  29166. });
  29167. this.actionManagers.forEach(function (o) {
  29168. _this.scene.removeActionManager(o);
  29169. });
  29170. this.sounds.forEach(function (o) {
  29171. o.stop();
  29172. o.autoplay = false;
  29173. _this.scene.mainSoundTrack.RemoveSound(o);
  29174. });
  29175. this.textures.forEach(function (o) {
  29176. _this.scene.removeTexture(o);
  29177. });
  29178. this.effectLayers.forEach(function (o) {
  29179. _this.scene.removeEffectLayer(o);
  29180. });
  29181. };
  29182. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29183. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29184. var asset = sourceAssets_1[_i];
  29185. var move = true;
  29186. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29187. var keepAsset = keepAssets_1[_a];
  29188. if (asset === keepAsset) {
  29189. move = false;
  29190. break;
  29191. }
  29192. }
  29193. if (move) {
  29194. targetAssets.push(asset);
  29195. }
  29196. }
  29197. };
  29198. /**
  29199. * Removes all the assets contained in the scene and adds them to the container.
  29200. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29201. */
  29202. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29203. if (keepAssets === undefined) {
  29204. keepAssets = new KeepAssets();
  29205. }
  29206. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29207. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29208. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29209. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29210. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29211. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29212. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29213. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29214. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29215. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29216. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29217. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29218. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29219. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29220. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29221. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29222. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29223. this.removeAllFromScene();
  29224. };
  29225. return AssetContainer;
  29226. }());
  29227. BABYLON.AssetContainer = AssetContainer;
  29228. })(BABYLON || (BABYLON = {}));
  29229. //# sourceMappingURL=babylon.assetContainer.js.map
  29230. var BABYLON;
  29231. (function (BABYLON) {
  29232. var Buffer = /** @class */ (function () {
  29233. /**
  29234. * Constructor
  29235. * @param engine the engine
  29236. * @param data the data to use for this buffer
  29237. * @param updatable whether the data is updatable
  29238. * @param stride the stride (optional)
  29239. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29240. * @param instanced whether the buffer is instanced (optional)
  29241. * @param useBytes set to true if the stride in in bytes (optional)
  29242. */
  29243. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29244. if (stride === void 0) { stride = 0; }
  29245. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29246. if (instanced === void 0) { instanced = false; }
  29247. if (useBytes === void 0) { useBytes = false; }
  29248. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29249. this._engine = engine.getScene().getEngine();
  29250. }
  29251. else {
  29252. this._engine = engine;
  29253. }
  29254. this._updatable = updatable;
  29255. this._instanced = instanced;
  29256. this._data = data;
  29257. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29258. if (!postponeInternalCreation) { // by default
  29259. this.create();
  29260. }
  29261. }
  29262. /**
  29263. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29264. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29265. * @param offset defines offset in the buffer (0 by default)
  29266. * @param size defines the size in floats of attributes (position is 3 for instance)
  29267. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29268. * @param instanced defines if the vertex buffer contains indexed data
  29269. * @param useBytes defines if the offset and stride are in bytes
  29270. * @returns the new vertex buffer
  29271. */
  29272. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29273. if (useBytes === void 0) { useBytes = false; }
  29274. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29275. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29276. // a lot of these parameters are ignored as they are overriden by the buffer
  29277. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29278. };
  29279. // Properties
  29280. Buffer.prototype.isUpdatable = function () {
  29281. return this._updatable;
  29282. };
  29283. Buffer.prototype.getData = function () {
  29284. return this._data;
  29285. };
  29286. Buffer.prototype.getBuffer = function () {
  29287. return this._buffer;
  29288. };
  29289. /**
  29290. * Gets the stride in float32 units (i.e. byte stride / 4).
  29291. * May not be an integer if the byte stride is not divisible by 4.
  29292. * DEPRECATED. Use byteStride instead.
  29293. * @returns the stride in float32 units
  29294. */
  29295. Buffer.prototype.getStrideSize = function () {
  29296. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29297. };
  29298. // Methods
  29299. Buffer.prototype.create = function (data) {
  29300. if (data === void 0) { data = null; }
  29301. if (!data && this._buffer) {
  29302. return; // nothing to do
  29303. }
  29304. data = data || this._data;
  29305. if (!data) {
  29306. return;
  29307. }
  29308. if (!this._buffer) { // create buffer
  29309. if (this._updatable) {
  29310. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29311. this._data = data;
  29312. }
  29313. else {
  29314. this._buffer = this._engine.createVertexBuffer(data);
  29315. }
  29316. }
  29317. else if (this._updatable) { // update buffer
  29318. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29319. this._data = data;
  29320. }
  29321. };
  29322. Buffer.prototype._rebuild = function () {
  29323. this._buffer = null;
  29324. this.create(this._data);
  29325. };
  29326. Buffer.prototype.update = function (data) {
  29327. this.create(data);
  29328. };
  29329. /**
  29330. * Updates the data directly.
  29331. * @param data the new data
  29332. * @param offset the new offset
  29333. * @param vertexCount the vertex count (optional)
  29334. * @param useBytes set to true if the offset is in bytes
  29335. */
  29336. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29337. if (useBytes === void 0) { useBytes = false; }
  29338. if (!this._buffer) {
  29339. return;
  29340. }
  29341. if (this._updatable) { // update buffer
  29342. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29343. this._data = null;
  29344. }
  29345. };
  29346. Buffer.prototype.dispose = function () {
  29347. if (!this._buffer) {
  29348. return;
  29349. }
  29350. if (this._engine._releaseBuffer(this._buffer)) {
  29351. this._buffer = null;
  29352. }
  29353. };
  29354. return Buffer;
  29355. }());
  29356. BABYLON.Buffer = Buffer;
  29357. })(BABYLON || (BABYLON = {}));
  29358. //# sourceMappingURL=babylon.buffer.js.map
  29359. var BABYLON;
  29360. (function (BABYLON) {
  29361. var VertexBuffer = /** @class */ (function () {
  29362. /**
  29363. * Constructor
  29364. * @param engine the engine
  29365. * @param data the data to use for this vertex buffer
  29366. * @param kind the vertex buffer kind
  29367. * @param updatable whether the data is updatable
  29368. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29369. * @param stride the stride (optional)
  29370. * @param instanced whether the buffer is instanced (optional)
  29371. * @param offset the offset of the data (optional)
  29372. * @param size the number of components (optional)
  29373. * @param type the type of the component (optional)
  29374. * @param normalized whether the data contains normalized data (optional)
  29375. * @param useBytes set to true if stride and offset are in bytes (optional)
  29376. */
  29377. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29378. if (normalized === void 0) { normalized = false; }
  29379. if (useBytes === void 0) { useBytes = false; }
  29380. if (data instanceof BABYLON.Buffer) {
  29381. this._buffer = data;
  29382. this._ownsBuffer = false;
  29383. }
  29384. else {
  29385. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29386. this._ownsBuffer = true;
  29387. }
  29388. this._kind = kind;
  29389. if (type == undefined) {
  29390. var data_1 = this.getData();
  29391. this.type = VertexBuffer.FLOAT;
  29392. if (data_1 instanceof Int8Array)
  29393. this.type = VertexBuffer.BYTE;
  29394. else if (data_1 instanceof Uint8Array)
  29395. this.type = VertexBuffer.UNSIGNED_BYTE;
  29396. else if (data_1 instanceof Int16Array)
  29397. this.type = VertexBuffer.SHORT;
  29398. else if (data_1 instanceof Uint16Array)
  29399. this.type = VertexBuffer.UNSIGNED_SHORT;
  29400. else if (data_1 instanceof Int32Array)
  29401. this.type = VertexBuffer.INT;
  29402. else if (data_1 instanceof Uint32Array)
  29403. this.type = VertexBuffer.UNSIGNED_INT;
  29404. }
  29405. else {
  29406. this.type = type;
  29407. }
  29408. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29409. if (useBytes) {
  29410. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29411. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29412. this.byteOffset = offset || 0;
  29413. }
  29414. else {
  29415. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29416. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29417. this.byteOffset = (offset || 0) * typeByteLength;
  29418. }
  29419. this.normalized = normalized;
  29420. this._instanced = instanced !== undefined ? instanced : false;
  29421. this._instanceDivisor = instanced ? 1 : 0;
  29422. }
  29423. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29424. /**
  29425. * Gets or sets the instance divisor when in instanced mode
  29426. */
  29427. get: function () {
  29428. return this._instanceDivisor;
  29429. },
  29430. set: function (value) {
  29431. this._instanceDivisor = value;
  29432. if (value == 0) {
  29433. this._instanced = false;
  29434. }
  29435. else {
  29436. this._instanced = true;
  29437. }
  29438. },
  29439. enumerable: true,
  29440. configurable: true
  29441. });
  29442. VertexBuffer.prototype._rebuild = function () {
  29443. if (!this._buffer) {
  29444. return;
  29445. }
  29446. this._buffer._rebuild();
  29447. };
  29448. /**
  29449. * Returns the kind of the VertexBuffer (string).
  29450. */
  29451. VertexBuffer.prototype.getKind = function () {
  29452. return this._kind;
  29453. };
  29454. // Properties
  29455. /**
  29456. * Boolean : is the VertexBuffer updatable ?
  29457. */
  29458. VertexBuffer.prototype.isUpdatable = function () {
  29459. return this._buffer.isUpdatable();
  29460. };
  29461. /**
  29462. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29463. */
  29464. VertexBuffer.prototype.getData = function () {
  29465. return this._buffer.getData();
  29466. };
  29467. /**
  29468. * Returns the WebGLBuffer associated to the VertexBuffer.
  29469. */
  29470. VertexBuffer.prototype.getBuffer = function () {
  29471. return this._buffer.getBuffer();
  29472. };
  29473. /**
  29474. * Returns the stride as a multiple of the type byte length.
  29475. * DEPRECATED. Use byteStride instead.
  29476. */
  29477. VertexBuffer.prototype.getStrideSize = function () {
  29478. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29479. };
  29480. /**
  29481. * Returns the offset as a multiple of the type byte length.
  29482. * DEPRECATED. Use byteOffset instead.
  29483. */
  29484. VertexBuffer.prototype.getOffset = function () {
  29485. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29486. };
  29487. /**
  29488. * Returns the number of components per vertex attribute (integer).
  29489. */
  29490. VertexBuffer.prototype.getSize = function () {
  29491. return this._size;
  29492. };
  29493. /**
  29494. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29495. */
  29496. VertexBuffer.prototype.getIsInstanced = function () {
  29497. return this._instanced;
  29498. };
  29499. /**
  29500. * Returns the instancing divisor, zero for non-instanced (integer).
  29501. */
  29502. VertexBuffer.prototype.getInstanceDivisor = function () {
  29503. return this._instanceDivisor;
  29504. };
  29505. // Methods
  29506. /**
  29507. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29508. * Returns the created WebGLBuffer.
  29509. */
  29510. VertexBuffer.prototype.create = function (data) {
  29511. return this._buffer.create(data);
  29512. };
  29513. /**
  29514. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29515. * This function will create a new buffer if the current one is not updatable
  29516. * Returns the updated WebGLBuffer.
  29517. */
  29518. VertexBuffer.prototype.update = function (data) {
  29519. return this._buffer.update(data);
  29520. };
  29521. /**
  29522. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29523. * Returns the directly updated WebGLBuffer.
  29524. * @param data the new data
  29525. * @param offset the new offset
  29526. * @param useBytes set to true if the offset is in bytes
  29527. */
  29528. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29529. if (useBytes === void 0) { useBytes = false; }
  29530. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29531. };
  29532. /**
  29533. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29534. */
  29535. VertexBuffer.prototype.dispose = function () {
  29536. if (this._ownsBuffer) {
  29537. this._buffer.dispose();
  29538. }
  29539. };
  29540. /**
  29541. * Enumerates each value of this vertex buffer as numbers.
  29542. * @param count the number of values to enumerate
  29543. * @param callback the callback function called for each value
  29544. */
  29545. VertexBuffer.prototype.forEach = function (count, callback) {
  29546. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29547. };
  29548. Object.defineProperty(VertexBuffer, "PositionKind", {
  29549. get: function () {
  29550. return VertexBuffer._PositionKind;
  29551. },
  29552. enumerable: true,
  29553. configurable: true
  29554. });
  29555. Object.defineProperty(VertexBuffer, "NormalKind", {
  29556. get: function () {
  29557. return VertexBuffer._NormalKind;
  29558. },
  29559. enumerable: true,
  29560. configurable: true
  29561. });
  29562. Object.defineProperty(VertexBuffer, "TangentKind", {
  29563. get: function () {
  29564. return VertexBuffer._TangentKind;
  29565. },
  29566. enumerable: true,
  29567. configurable: true
  29568. });
  29569. Object.defineProperty(VertexBuffer, "UVKind", {
  29570. get: function () {
  29571. return VertexBuffer._UVKind;
  29572. },
  29573. enumerable: true,
  29574. configurable: true
  29575. });
  29576. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29577. get: function () {
  29578. return VertexBuffer._UV2Kind;
  29579. },
  29580. enumerable: true,
  29581. configurable: true
  29582. });
  29583. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29584. get: function () {
  29585. return VertexBuffer._UV3Kind;
  29586. },
  29587. enumerable: true,
  29588. configurable: true
  29589. });
  29590. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29591. get: function () {
  29592. return VertexBuffer._UV4Kind;
  29593. },
  29594. enumerable: true,
  29595. configurable: true
  29596. });
  29597. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29598. get: function () {
  29599. return VertexBuffer._UV5Kind;
  29600. },
  29601. enumerable: true,
  29602. configurable: true
  29603. });
  29604. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29605. get: function () {
  29606. return VertexBuffer._UV6Kind;
  29607. },
  29608. enumerable: true,
  29609. configurable: true
  29610. });
  29611. Object.defineProperty(VertexBuffer, "ColorKind", {
  29612. get: function () {
  29613. return VertexBuffer._ColorKind;
  29614. },
  29615. enumerable: true,
  29616. configurable: true
  29617. });
  29618. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29619. get: function () {
  29620. return VertexBuffer._MatricesIndicesKind;
  29621. },
  29622. enumerable: true,
  29623. configurable: true
  29624. });
  29625. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29626. get: function () {
  29627. return VertexBuffer._MatricesWeightsKind;
  29628. },
  29629. enumerable: true,
  29630. configurable: true
  29631. });
  29632. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29633. get: function () {
  29634. return VertexBuffer._MatricesIndicesExtraKind;
  29635. },
  29636. enumerable: true,
  29637. configurable: true
  29638. });
  29639. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29640. get: function () {
  29641. return VertexBuffer._MatricesWeightsExtraKind;
  29642. },
  29643. enumerable: true,
  29644. configurable: true
  29645. });
  29646. /**
  29647. * Deduces the stride given a kind.
  29648. * @param kind The kind string to deduce
  29649. * @returns The deduced stride
  29650. */
  29651. VertexBuffer.DeduceStride = function (kind) {
  29652. switch (kind) {
  29653. case VertexBuffer.UVKind:
  29654. case VertexBuffer.UV2Kind:
  29655. case VertexBuffer.UV3Kind:
  29656. case VertexBuffer.UV4Kind:
  29657. case VertexBuffer.UV5Kind:
  29658. case VertexBuffer.UV6Kind:
  29659. return 2;
  29660. case VertexBuffer.NormalKind:
  29661. case VertexBuffer.PositionKind:
  29662. return 3;
  29663. case VertexBuffer.ColorKind:
  29664. case VertexBuffer.MatricesIndicesKind:
  29665. case VertexBuffer.MatricesIndicesExtraKind:
  29666. case VertexBuffer.MatricesWeightsKind:
  29667. case VertexBuffer.MatricesWeightsExtraKind:
  29668. case VertexBuffer.TangentKind:
  29669. return 4;
  29670. default:
  29671. throw new Error("Invalid kind '" + kind + "'");
  29672. }
  29673. };
  29674. /**
  29675. * Gets the byte length of the given type.
  29676. * @param type the type
  29677. * @returns the number of bytes
  29678. */
  29679. VertexBuffer.GetTypeByteLength = function (type) {
  29680. switch (type) {
  29681. case VertexBuffer.BYTE:
  29682. case VertexBuffer.UNSIGNED_BYTE:
  29683. return 1;
  29684. case VertexBuffer.SHORT:
  29685. case VertexBuffer.UNSIGNED_SHORT:
  29686. return 2;
  29687. case VertexBuffer.INT:
  29688. case VertexBuffer.FLOAT:
  29689. return 4;
  29690. default:
  29691. throw new Error("Invalid type '" + type + "'");
  29692. }
  29693. };
  29694. /**
  29695. * Enumerates each value of the given parameters as numbers.
  29696. * @param data the data to enumerate
  29697. * @param byteOffset the byte offset of the data
  29698. * @param byteStride the byte stride of the data
  29699. * @param componentCount the number of components per element
  29700. * @param componentType the type of the component
  29701. * @param count the total number of components
  29702. * @param normalized whether the data is normalized
  29703. * @param callback the callback function called for each value
  29704. */
  29705. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29706. if (data instanceof Array) {
  29707. var offset = byteOffset / 4;
  29708. var stride = byteStride / 4;
  29709. for (var index = 0; index < count; index += componentCount) {
  29710. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29711. callback(data[offset + componentIndex], index + componentIndex);
  29712. }
  29713. offset += stride;
  29714. }
  29715. }
  29716. else {
  29717. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29718. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29719. for (var index = 0; index < count; index += componentCount) {
  29720. var componentByteOffset = byteOffset;
  29721. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29722. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29723. callback(value, index + componentIndex);
  29724. componentByteOffset += componentByteLength;
  29725. }
  29726. byteOffset += byteStride;
  29727. }
  29728. }
  29729. };
  29730. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29731. switch (type) {
  29732. case VertexBuffer.BYTE: {
  29733. var value = dataView.getInt8(byteOffset);
  29734. if (normalized) {
  29735. value = Math.max(value / 127, -1);
  29736. }
  29737. return value;
  29738. }
  29739. case VertexBuffer.UNSIGNED_BYTE: {
  29740. var value = dataView.getUint8(byteOffset);
  29741. if (normalized) {
  29742. value = value / 255;
  29743. }
  29744. return value;
  29745. }
  29746. case VertexBuffer.SHORT: {
  29747. var value = dataView.getInt16(byteOffset, true);
  29748. if (normalized) {
  29749. value = Math.max(value / 16383, -1);
  29750. }
  29751. return value;
  29752. }
  29753. case VertexBuffer.UNSIGNED_SHORT: {
  29754. var value = dataView.getUint16(byteOffset, true);
  29755. if (normalized) {
  29756. value = value / 65535;
  29757. }
  29758. return value;
  29759. }
  29760. case VertexBuffer.FLOAT: {
  29761. return dataView.getFloat32(byteOffset, true);
  29762. }
  29763. default: {
  29764. throw new Error("Invalid component type " + type);
  29765. }
  29766. }
  29767. };
  29768. /**
  29769. * The byte type.
  29770. */
  29771. VertexBuffer.BYTE = 5120;
  29772. /**
  29773. * The unsigned byte type.
  29774. */
  29775. VertexBuffer.UNSIGNED_BYTE = 5121;
  29776. /**
  29777. * The short type.
  29778. */
  29779. VertexBuffer.SHORT = 5122;
  29780. /**
  29781. * The unsigned short type.
  29782. */
  29783. VertexBuffer.UNSIGNED_SHORT = 5123;
  29784. /**
  29785. * The integer type.
  29786. */
  29787. VertexBuffer.INT = 5124;
  29788. /**
  29789. * The unsigned integer type.
  29790. */
  29791. VertexBuffer.UNSIGNED_INT = 5125;
  29792. /**
  29793. * The float type.
  29794. */
  29795. VertexBuffer.FLOAT = 5126;
  29796. // Enums
  29797. VertexBuffer._PositionKind = "position";
  29798. VertexBuffer._NormalKind = "normal";
  29799. VertexBuffer._TangentKind = "tangent";
  29800. VertexBuffer._UVKind = "uv";
  29801. VertexBuffer._UV2Kind = "uv2";
  29802. VertexBuffer._UV3Kind = "uv3";
  29803. VertexBuffer._UV4Kind = "uv4";
  29804. VertexBuffer._UV5Kind = "uv5";
  29805. VertexBuffer._UV6Kind = "uv6";
  29806. VertexBuffer._ColorKind = "color";
  29807. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29808. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29809. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29810. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29811. return VertexBuffer;
  29812. }());
  29813. BABYLON.VertexBuffer = VertexBuffer;
  29814. })(BABYLON || (BABYLON = {}));
  29815. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29816. var BABYLON;
  29817. (function (BABYLON) {
  29818. /**
  29819. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29820. */
  29821. var DummyInternalTextureTracker = /** @class */ (function () {
  29822. function DummyInternalTextureTracker() {
  29823. /**
  29824. * Gets or set the previous tracker in the list
  29825. */
  29826. this.previous = null;
  29827. /**
  29828. * Gets or set the next tracker in the list
  29829. */
  29830. this.next = null;
  29831. }
  29832. return DummyInternalTextureTracker;
  29833. }());
  29834. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29835. })(BABYLON || (BABYLON = {}));
  29836. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29837. var BABYLON;
  29838. (function (BABYLON) {
  29839. /**
  29840. * Class used to store data associated with WebGL texture data for the engine
  29841. * This class should not be used directly
  29842. */
  29843. var InternalTexture = /** @class */ (function () {
  29844. /**
  29845. * Creates a new InternalTexture
  29846. * @param engine defines the engine to use
  29847. * @param dataSource defines the type of data that will be used
  29848. */
  29849. function InternalTexture(engine, dataSource) {
  29850. /**
  29851. * Observable called when the texture is loaded
  29852. */
  29853. this.onLoadedObservable = new BABYLON.Observable();
  29854. /**
  29855. * Gets or set the previous tracker in the list
  29856. */
  29857. this.previous = null;
  29858. /**
  29859. * Gets or set the next tracker in the list
  29860. */
  29861. this.next = null;
  29862. // Private
  29863. /** @hidden */
  29864. this._initialSlot = -1;
  29865. /** @hidden */
  29866. this._designatedSlot = -1;
  29867. /** @hidden */
  29868. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29869. /** @hidden */
  29870. this._comparisonFunction = 0;
  29871. /** @hidden */
  29872. this._references = 1;
  29873. this._engine = engine;
  29874. this._dataSource = dataSource;
  29875. this._webGLTexture = engine._createTexture();
  29876. }
  29877. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29878. /**
  29879. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29880. */
  29881. get: function () {
  29882. return this._dataSource;
  29883. },
  29884. enumerable: true,
  29885. configurable: true
  29886. });
  29887. /**
  29888. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29889. */
  29890. InternalTexture.prototype.incrementReferences = function () {
  29891. this._references++;
  29892. };
  29893. /**
  29894. * Change the size of the texture (not the size of the content)
  29895. * @param width defines the new width
  29896. * @param height defines the new height
  29897. * @param depth defines the new depth (1 by default)
  29898. */
  29899. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29900. if (depth === void 0) { depth = 1; }
  29901. this.width = width;
  29902. this.height = height;
  29903. this.depth = depth;
  29904. this.baseWidth = width;
  29905. this.baseHeight = height;
  29906. this.baseDepth = depth;
  29907. this._size = width * height * depth;
  29908. };
  29909. /** @hidden */
  29910. InternalTexture.prototype._rebuild = function () {
  29911. var _this = this;
  29912. var proxy;
  29913. this.isReady = false;
  29914. this._cachedCoordinatesMode = null;
  29915. this._cachedWrapU = null;
  29916. this._cachedWrapV = null;
  29917. this._cachedAnisotropicFilteringLevel = null;
  29918. switch (this._dataSource) {
  29919. case InternalTexture.DATASOURCE_TEMP:
  29920. return;
  29921. case InternalTexture.DATASOURCE_URL:
  29922. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29923. _this.isReady = true;
  29924. }, null, this._buffer, undefined, this.format);
  29925. proxy._swapAndDie(this);
  29926. return;
  29927. case InternalTexture.DATASOURCE_RAW:
  29928. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29929. proxy._swapAndDie(this);
  29930. this.isReady = true;
  29931. return;
  29932. case InternalTexture.DATASOURCE_RAW3D:
  29933. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29934. proxy._swapAndDie(this);
  29935. this.isReady = true;
  29936. return;
  29937. case InternalTexture.DATASOURCE_DYNAMIC:
  29938. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29939. proxy._swapAndDie(this);
  29940. // The engine will make sure to update content so no need to flag it as isReady = true
  29941. return;
  29942. case InternalTexture.DATASOURCE_RENDERTARGET:
  29943. var options = new BABYLON.RenderTargetCreationOptions();
  29944. options.generateDepthBuffer = this._generateDepthBuffer;
  29945. options.generateMipMaps = this.generateMipMaps;
  29946. options.generateStencilBuffer = this._generateStencilBuffer;
  29947. options.samplingMode = this.samplingMode;
  29948. options.type = this.type;
  29949. if (this.isCube) {
  29950. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29951. }
  29952. else {
  29953. var size = {
  29954. width: this.width,
  29955. height: this.height
  29956. };
  29957. proxy = this._engine.createRenderTargetTexture(size, options);
  29958. }
  29959. proxy._swapAndDie(this);
  29960. this.isReady = true;
  29961. return;
  29962. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29963. var depthTextureOptions = {
  29964. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29965. comparisonFunction: this._comparisonFunction,
  29966. generateStencil: this._generateStencilBuffer,
  29967. isCube: this.isCube
  29968. };
  29969. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29970. proxy._swapAndDie(this);
  29971. this.isReady = true;
  29972. return;
  29973. case InternalTexture.DATASOURCE_CUBE:
  29974. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29975. _this.isReady = true;
  29976. }, null, this.format, this._extension);
  29977. proxy._swapAndDie(this);
  29978. return;
  29979. case InternalTexture.DATASOURCE_CUBERAW:
  29980. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29981. proxy._swapAndDie(this);
  29982. this.isReady = true;
  29983. return;
  29984. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29985. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29986. if (proxy) {
  29987. proxy._swapAndDie(_this);
  29988. }
  29989. _this.isReady = true;
  29990. }, null, this.format, this._extension);
  29991. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29992. return;
  29993. }
  29994. };
  29995. InternalTexture.prototype._swapAndDie = function (target) {
  29996. target._webGLTexture = this._webGLTexture;
  29997. if (this._framebuffer) {
  29998. target._framebuffer = this._framebuffer;
  29999. }
  30000. if (this._depthStencilBuffer) {
  30001. target._depthStencilBuffer = this._depthStencilBuffer;
  30002. }
  30003. if (this._lodTextureHigh) {
  30004. if (target._lodTextureHigh) {
  30005. target._lodTextureHigh.dispose();
  30006. }
  30007. target._lodTextureHigh = this._lodTextureHigh;
  30008. }
  30009. if (this._lodTextureMid) {
  30010. if (target._lodTextureMid) {
  30011. target._lodTextureMid.dispose();
  30012. }
  30013. target._lodTextureMid = this._lodTextureMid;
  30014. }
  30015. if (this._lodTextureLow) {
  30016. if (target._lodTextureLow) {
  30017. target._lodTextureLow.dispose();
  30018. }
  30019. target._lodTextureLow = this._lodTextureLow;
  30020. }
  30021. var cache = this._engine.getLoadedTexturesCache();
  30022. var index = cache.indexOf(this);
  30023. if (index !== -1) {
  30024. cache.splice(index, 1);
  30025. }
  30026. };
  30027. /**
  30028. * Dispose the current allocated resources
  30029. */
  30030. InternalTexture.prototype.dispose = function () {
  30031. if (!this._webGLTexture) {
  30032. return;
  30033. }
  30034. this._references--;
  30035. if (this._references === 0) {
  30036. this._engine._releaseTexture(this);
  30037. this._webGLTexture = null;
  30038. this.previous = null;
  30039. this.next = null;
  30040. }
  30041. };
  30042. /**
  30043. * The source of the texture data is unknown
  30044. */
  30045. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30046. /**
  30047. * Texture data comes from an URL
  30048. */
  30049. InternalTexture.DATASOURCE_URL = 1;
  30050. /**
  30051. * Texture data is only used for temporary storage
  30052. */
  30053. InternalTexture.DATASOURCE_TEMP = 2;
  30054. /**
  30055. * Texture data comes from raw data (ArrayBuffer)
  30056. */
  30057. InternalTexture.DATASOURCE_RAW = 3;
  30058. /**
  30059. * Texture content is dynamic (video or dynamic texture)
  30060. */
  30061. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30062. /**
  30063. * Texture content is generated by rendering to it
  30064. */
  30065. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30066. /**
  30067. * Texture content is part of a multi render target process
  30068. */
  30069. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30070. /**
  30071. * Texture data comes from a cube data file
  30072. */
  30073. InternalTexture.DATASOURCE_CUBE = 7;
  30074. /**
  30075. * Texture data comes from a raw cube data
  30076. */
  30077. InternalTexture.DATASOURCE_CUBERAW = 8;
  30078. /**
  30079. * Texture data come from a prefiltered cube data file
  30080. */
  30081. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30082. /**
  30083. * Texture content is raw 3D data
  30084. */
  30085. InternalTexture.DATASOURCE_RAW3D = 10;
  30086. /**
  30087. * Texture content is a depth texture
  30088. */
  30089. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30090. return InternalTexture;
  30091. }());
  30092. BABYLON.InternalTexture = InternalTexture;
  30093. })(BABYLON || (BABYLON = {}));
  30094. //# sourceMappingURL=babylon.internalTexture.js.map
  30095. var BABYLON;
  30096. (function (BABYLON) {
  30097. var BaseTexture = /** @class */ (function () {
  30098. function BaseTexture(scene) {
  30099. this._hasAlpha = false;
  30100. this.getAlphaFromRGB = false;
  30101. this.level = 1;
  30102. this.coordinatesIndex = 0;
  30103. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30104. /**
  30105. * | Value | Type | Description |
  30106. * | ----- | ------------------ | ----------- |
  30107. * | 0 | CLAMP_ADDRESSMODE | |
  30108. * | 1 | WRAP_ADDRESSMODE | |
  30109. * | 2 | MIRROR_ADDRESSMODE | |
  30110. */
  30111. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30112. /**
  30113. * | Value | Type | Description |
  30114. * | ----- | ------------------ | ----------- |
  30115. * | 0 | CLAMP_ADDRESSMODE | |
  30116. * | 1 | WRAP_ADDRESSMODE | |
  30117. * | 2 | MIRROR_ADDRESSMODE | |
  30118. */
  30119. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30120. /**
  30121. * | Value | Type | Description |
  30122. * | ----- | ------------------ | ----------- |
  30123. * | 0 | CLAMP_ADDRESSMODE | |
  30124. * | 1 | WRAP_ADDRESSMODE | |
  30125. * | 2 | MIRROR_ADDRESSMODE | |
  30126. */
  30127. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30128. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30129. this.isCube = false;
  30130. this.is3D = false;
  30131. this.gammaSpace = true;
  30132. this.invertZ = false;
  30133. this.lodLevelInAlpha = false;
  30134. this.lodGenerationOffset = 0.0;
  30135. this.lodGenerationScale = 0.8;
  30136. this.isRenderTarget = false;
  30137. this.animations = new Array();
  30138. /**
  30139. * An event triggered when the texture is disposed.
  30140. */
  30141. this.onDisposeObservable = new BABYLON.Observable();
  30142. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30143. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30144. if (this._scene) {
  30145. this._scene.textures.push(this);
  30146. }
  30147. this._uid = null;
  30148. }
  30149. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30150. get: function () {
  30151. return this._hasAlpha;
  30152. },
  30153. set: function (value) {
  30154. if (this._hasAlpha === value) {
  30155. return;
  30156. }
  30157. this._hasAlpha = value;
  30158. if (this._scene) {
  30159. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30160. }
  30161. },
  30162. enumerable: true,
  30163. configurable: true
  30164. });
  30165. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30166. get: function () {
  30167. return this._coordinatesMode;
  30168. },
  30169. /**
  30170. * How a texture is mapped.
  30171. *
  30172. * | Value | Type | Description |
  30173. * | ----- | ----------------------------------- | ----------- |
  30174. * | 0 | EXPLICIT_MODE | |
  30175. * | 1 | SPHERICAL_MODE | |
  30176. * | 2 | PLANAR_MODE | |
  30177. * | 3 | CUBIC_MODE | |
  30178. * | 4 | PROJECTION_MODE | |
  30179. * | 5 | SKYBOX_MODE | |
  30180. * | 6 | INVCUBIC_MODE | |
  30181. * | 7 | EQUIRECTANGULAR_MODE | |
  30182. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30183. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30184. */
  30185. set: function (value) {
  30186. if (this._coordinatesMode === value) {
  30187. return;
  30188. }
  30189. this._coordinatesMode = value;
  30190. if (this._scene) {
  30191. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30192. }
  30193. },
  30194. enumerable: true,
  30195. configurable: true
  30196. });
  30197. Object.defineProperty(BaseTexture.prototype, "uid", {
  30198. get: function () {
  30199. if (!this._uid) {
  30200. this._uid = BABYLON.Tools.RandomId();
  30201. }
  30202. return this._uid;
  30203. },
  30204. enumerable: true,
  30205. configurable: true
  30206. });
  30207. BaseTexture.prototype.toString = function () {
  30208. return this.name;
  30209. };
  30210. BaseTexture.prototype.getClassName = function () {
  30211. return "BaseTexture";
  30212. };
  30213. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30214. set: function (callback) {
  30215. if (this._onDisposeObserver) {
  30216. this.onDisposeObservable.remove(this._onDisposeObserver);
  30217. }
  30218. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30219. },
  30220. enumerable: true,
  30221. configurable: true
  30222. });
  30223. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30224. get: function () {
  30225. return true;
  30226. },
  30227. enumerable: true,
  30228. configurable: true
  30229. });
  30230. BaseTexture.prototype.getScene = function () {
  30231. return this._scene;
  30232. };
  30233. BaseTexture.prototype.getTextureMatrix = function () {
  30234. return BABYLON.Matrix.IdentityReadOnly;
  30235. };
  30236. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30237. return BABYLON.Matrix.IdentityReadOnly;
  30238. };
  30239. BaseTexture.prototype.getInternalTexture = function () {
  30240. return this._texture;
  30241. };
  30242. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30243. return !this.isBlocking || this.isReady();
  30244. };
  30245. BaseTexture.prototype.isReady = function () {
  30246. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30247. this.delayLoad();
  30248. return false;
  30249. }
  30250. if (this._texture) {
  30251. return this._texture.isReady;
  30252. }
  30253. return false;
  30254. };
  30255. BaseTexture.prototype.getSize = function () {
  30256. if (this._texture && this._texture.width) {
  30257. return new BABYLON.Size(this._texture.width, this._texture.height);
  30258. }
  30259. if (this._texture && this._texture._size) {
  30260. return new BABYLON.Size(this._texture._size, this._texture._size);
  30261. }
  30262. return BABYLON.Size.Zero();
  30263. };
  30264. BaseTexture.prototype.getBaseSize = function () {
  30265. if (!this.isReady() || !this._texture)
  30266. return BABYLON.Size.Zero();
  30267. if (this._texture._size) {
  30268. return new BABYLON.Size(this._texture._size, this._texture._size);
  30269. }
  30270. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30271. };
  30272. BaseTexture.prototype.scale = function (ratio) {
  30273. };
  30274. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30275. get: function () {
  30276. return false;
  30277. },
  30278. enumerable: true,
  30279. configurable: true
  30280. });
  30281. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30282. if (!this._scene) {
  30283. return null;
  30284. }
  30285. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30286. for (var index = 0; index < texturesCache.length; index++) {
  30287. var texturesCacheEntry = texturesCache[index];
  30288. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30289. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30290. texturesCacheEntry.incrementReferences();
  30291. return texturesCacheEntry;
  30292. }
  30293. }
  30294. }
  30295. return null;
  30296. };
  30297. BaseTexture.prototype._rebuild = function () {
  30298. };
  30299. BaseTexture.prototype.delayLoad = function () {
  30300. };
  30301. BaseTexture.prototype.clone = function () {
  30302. return null;
  30303. };
  30304. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30305. get: function () {
  30306. if (!this._texture) {
  30307. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30308. }
  30309. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30310. },
  30311. enumerable: true,
  30312. configurable: true
  30313. });
  30314. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30315. get: function () {
  30316. if (!this._texture) {
  30317. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30318. }
  30319. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30320. },
  30321. enumerable: true,
  30322. configurable: true
  30323. });
  30324. BaseTexture.prototype.readPixels = function (faceIndex) {
  30325. if (faceIndex === void 0) { faceIndex = 0; }
  30326. if (!this._texture) {
  30327. return null;
  30328. }
  30329. var size = this.getSize();
  30330. var scene = this.getScene();
  30331. if (!scene) {
  30332. return null;
  30333. }
  30334. var engine = scene.getEngine();
  30335. if (this._texture.isCube) {
  30336. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30337. }
  30338. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30339. };
  30340. BaseTexture.prototype.releaseInternalTexture = function () {
  30341. if (this._texture) {
  30342. this._texture.dispose();
  30343. this._texture = null;
  30344. }
  30345. };
  30346. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30347. get: function () {
  30348. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30349. return null;
  30350. }
  30351. if (!this._texture._sphericalPolynomial) {
  30352. this._texture._sphericalPolynomial =
  30353. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30354. }
  30355. return this._texture._sphericalPolynomial;
  30356. },
  30357. set: function (value) {
  30358. if (this._texture) {
  30359. this._texture._sphericalPolynomial = value;
  30360. }
  30361. },
  30362. enumerable: true,
  30363. configurable: true
  30364. });
  30365. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30366. get: function () {
  30367. if (this._texture) {
  30368. return this._texture._lodTextureHigh;
  30369. }
  30370. return null;
  30371. },
  30372. enumerable: true,
  30373. configurable: true
  30374. });
  30375. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30376. get: function () {
  30377. if (this._texture) {
  30378. return this._texture._lodTextureMid;
  30379. }
  30380. return null;
  30381. },
  30382. enumerable: true,
  30383. configurable: true
  30384. });
  30385. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30386. get: function () {
  30387. if (this._texture) {
  30388. return this._texture._lodTextureLow;
  30389. }
  30390. return null;
  30391. },
  30392. enumerable: true,
  30393. configurable: true
  30394. });
  30395. BaseTexture.prototype.dispose = function () {
  30396. if (!this._scene) {
  30397. return;
  30398. }
  30399. // Animations
  30400. this._scene.stopAnimation(this);
  30401. // Remove from scene
  30402. this._scene._removePendingData(this);
  30403. var index = this._scene.textures.indexOf(this);
  30404. if (index >= 0) {
  30405. this._scene.textures.splice(index, 1);
  30406. }
  30407. if (this._texture === undefined) {
  30408. return;
  30409. }
  30410. // Release
  30411. this.releaseInternalTexture();
  30412. // Callback
  30413. this.onDisposeObservable.notifyObservers(this);
  30414. this.onDisposeObservable.clear();
  30415. };
  30416. BaseTexture.prototype.serialize = function () {
  30417. if (!this.name) {
  30418. return null;
  30419. }
  30420. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30421. // Animations
  30422. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30423. return serializationObject;
  30424. };
  30425. BaseTexture.WhenAllReady = function (textures, callback) {
  30426. var numRemaining = textures.length;
  30427. if (numRemaining === 0) {
  30428. callback();
  30429. return;
  30430. }
  30431. var _loop_1 = function () {
  30432. texture = textures[i];
  30433. if (texture.isReady()) {
  30434. if (--numRemaining === 0) {
  30435. callback();
  30436. }
  30437. }
  30438. else {
  30439. onLoadObservable = texture.onLoadObservable;
  30440. var onLoadCallback_1 = function () {
  30441. onLoadObservable.removeCallback(onLoadCallback_1);
  30442. if (--numRemaining === 0) {
  30443. callback();
  30444. }
  30445. };
  30446. onLoadObservable.add(onLoadCallback_1);
  30447. }
  30448. };
  30449. var texture, onLoadObservable;
  30450. for (var i = 0; i < textures.length; i++) {
  30451. _loop_1();
  30452. }
  30453. };
  30454. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30455. __decorate([
  30456. BABYLON.serialize()
  30457. ], BaseTexture.prototype, "name", void 0);
  30458. __decorate([
  30459. BABYLON.serialize("hasAlpha")
  30460. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30461. __decorate([
  30462. BABYLON.serialize()
  30463. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30464. __decorate([
  30465. BABYLON.serialize()
  30466. ], BaseTexture.prototype, "level", void 0);
  30467. __decorate([
  30468. BABYLON.serialize()
  30469. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30470. __decorate([
  30471. BABYLON.serialize("coordinatesMode")
  30472. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30473. __decorate([
  30474. BABYLON.serialize()
  30475. ], BaseTexture.prototype, "wrapU", void 0);
  30476. __decorate([
  30477. BABYLON.serialize()
  30478. ], BaseTexture.prototype, "wrapV", void 0);
  30479. __decorate([
  30480. BABYLON.serialize()
  30481. ], BaseTexture.prototype, "wrapR", void 0);
  30482. __decorate([
  30483. BABYLON.serialize()
  30484. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30485. __decorate([
  30486. BABYLON.serialize()
  30487. ], BaseTexture.prototype, "isCube", void 0);
  30488. __decorate([
  30489. BABYLON.serialize()
  30490. ], BaseTexture.prototype, "is3D", void 0);
  30491. __decorate([
  30492. BABYLON.serialize()
  30493. ], BaseTexture.prototype, "gammaSpace", void 0);
  30494. __decorate([
  30495. BABYLON.serialize()
  30496. ], BaseTexture.prototype, "invertZ", void 0);
  30497. __decorate([
  30498. BABYLON.serialize()
  30499. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30500. __decorate([
  30501. BABYLON.serialize()
  30502. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30503. __decorate([
  30504. BABYLON.serialize()
  30505. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30506. __decorate([
  30507. BABYLON.serialize()
  30508. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30509. return BaseTexture;
  30510. }());
  30511. BABYLON.BaseTexture = BaseTexture;
  30512. })(BABYLON || (BABYLON = {}));
  30513. //# sourceMappingURL=babylon.baseTexture.js.map
  30514. var BABYLON;
  30515. (function (BABYLON) {
  30516. var Texture = /** @class */ (function (_super) {
  30517. __extends(Texture, _super);
  30518. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30519. if (noMipmap === void 0) { noMipmap = false; }
  30520. if (invertY === void 0) { invertY = true; }
  30521. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30522. if (onLoad === void 0) { onLoad = null; }
  30523. if (onError === void 0) { onError = null; }
  30524. if (buffer === void 0) { buffer = null; }
  30525. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30526. var _this = _super.call(this, scene) || this;
  30527. _this.uOffset = 0;
  30528. _this.vOffset = 0;
  30529. _this.uScale = 1.0;
  30530. _this.vScale = 1.0;
  30531. _this.uAng = 0;
  30532. _this.vAng = 0;
  30533. _this.wAng = 0;
  30534. /**
  30535. * Defines the center of rotation (U)
  30536. */
  30537. _this.uRotationCenter = 0.5;
  30538. /**
  30539. * Defines the center of rotation (V)
  30540. */
  30541. _this.vRotationCenter = 0.5;
  30542. /**
  30543. * Defines the center of rotation (W)
  30544. */
  30545. _this.wRotationCenter = 0.5;
  30546. _this._isBlocking = true;
  30547. _this.name = url || "";
  30548. _this.url = url;
  30549. _this._noMipmap = noMipmap;
  30550. _this._invertY = invertY;
  30551. _this._samplingMode = samplingMode;
  30552. _this._buffer = buffer;
  30553. _this._deleteBuffer = deleteBuffer;
  30554. if (format) {
  30555. _this._format = format;
  30556. }
  30557. scene = _this.getScene();
  30558. if (!scene) {
  30559. return _this;
  30560. }
  30561. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30562. var load = function () {
  30563. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30564. _this.onLoadObservable.notifyObservers(_this);
  30565. }
  30566. if (onLoad) {
  30567. onLoad();
  30568. }
  30569. if (!_this.isBlocking && scene) {
  30570. scene.resetCachedMaterial();
  30571. }
  30572. };
  30573. if (!_this.url) {
  30574. _this._delayedOnLoad = load;
  30575. _this._delayedOnError = onError;
  30576. return _this;
  30577. }
  30578. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30579. if (!_this._texture) {
  30580. if (!scene.useDelayedTextureLoading) {
  30581. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30582. if (deleteBuffer) {
  30583. delete _this._buffer;
  30584. }
  30585. }
  30586. else {
  30587. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30588. _this._delayedOnLoad = load;
  30589. _this._delayedOnError = onError;
  30590. }
  30591. }
  30592. else {
  30593. if (_this._texture.isReady) {
  30594. BABYLON.Tools.SetImmediate(function () { return load(); });
  30595. }
  30596. else {
  30597. _this._texture.onLoadedObservable.add(load);
  30598. }
  30599. }
  30600. return _this;
  30601. }
  30602. Object.defineProperty(Texture.prototype, "noMipmap", {
  30603. get: function () {
  30604. return this._noMipmap;
  30605. },
  30606. enumerable: true,
  30607. configurable: true
  30608. });
  30609. Object.defineProperty(Texture.prototype, "isBlocking", {
  30610. get: function () {
  30611. return this._isBlocking;
  30612. },
  30613. set: function (value) {
  30614. this._isBlocking = value;
  30615. },
  30616. enumerable: true,
  30617. configurable: true
  30618. });
  30619. Object.defineProperty(Texture.prototype, "samplingMode", {
  30620. get: function () {
  30621. return this._samplingMode;
  30622. },
  30623. enumerable: true,
  30624. configurable: true
  30625. });
  30626. /**
  30627. * Update the url (and optional buffer) of this texture if url was null during construction.
  30628. * @param url the url of the texture
  30629. * @param buffer the buffer of the texture (defaults to null)
  30630. */
  30631. Texture.prototype.updateURL = function (url, buffer) {
  30632. if (buffer === void 0) { buffer = null; }
  30633. if (this.url) {
  30634. throw new Error("URL is already set");
  30635. }
  30636. this.url = url;
  30637. this._buffer = buffer;
  30638. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30639. this.delayLoad();
  30640. };
  30641. Texture.prototype.delayLoad = function () {
  30642. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30643. return;
  30644. }
  30645. var scene = this.getScene();
  30646. if (!scene) {
  30647. return;
  30648. }
  30649. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30650. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30651. if (!this._texture) {
  30652. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30653. if (this._deleteBuffer) {
  30654. delete this._buffer;
  30655. }
  30656. }
  30657. else {
  30658. if (this._delayedOnLoad) {
  30659. if (this._texture.isReady) {
  30660. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30661. }
  30662. else {
  30663. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30664. }
  30665. }
  30666. }
  30667. this._delayedOnLoad = null;
  30668. this._delayedOnError = null;
  30669. };
  30670. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30671. if (!this._texture) {
  30672. return;
  30673. }
  30674. var scene = this.getScene();
  30675. if (!scene) {
  30676. return;
  30677. }
  30678. this._samplingMode = samplingMode;
  30679. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30680. };
  30681. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30682. x *= this.uScale;
  30683. y *= this.vScale;
  30684. x -= this.uRotationCenter * this.uScale;
  30685. y -= this.vRotationCenter * this.vScale;
  30686. z -= this.wRotationCenter;
  30687. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30688. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30689. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30690. t.z += this.wRotationCenter;
  30691. };
  30692. Texture.prototype.getTextureMatrix = function () {
  30693. var _this = this;
  30694. if (this.uOffset === this._cachedUOffset &&
  30695. this.vOffset === this._cachedVOffset &&
  30696. this.uScale === this._cachedUScale &&
  30697. this.vScale === this._cachedVScale &&
  30698. this.uAng === this._cachedUAng &&
  30699. this.vAng === this._cachedVAng &&
  30700. this.wAng === this._cachedWAng) {
  30701. return this._cachedTextureMatrix;
  30702. }
  30703. this._cachedUOffset = this.uOffset;
  30704. this._cachedVOffset = this.vOffset;
  30705. this._cachedUScale = this.uScale;
  30706. this._cachedVScale = this.vScale;
  30707. this._cachedUAng = this.uAng;
  30708. this._cachedVAng = this.vAng;
  30709. this._cachedWAng = this.wAng;
  30710. if (!this._cachedTextureMatrix) {
  30711. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30712. this._rowGenerationMatrix = new BABYLON.Matrix();
  30713. this._t0 = BABYLON.Vector3.Zero();
  30714. this._t1 = BABYLON.Vector3.Zero();
  30715. this._t2 = BABYLON.Vector3.Zero();
  30716. }
  30717. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30718. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30719. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30720. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30721. this._t1.subtractInPlace(this._t0);
  30722. this._t2.subtractInPlace(this._t0);
  30723. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30724. this._cachedTextureMatrix.m[0] = this._t1.x;
  30725. this._cachedTextureMatrix.m[1] = this._t1.y;
  30726. this._cachedTextureMatrix.m[2] = this._t1.z;
  30727. this._cachedTextureMatrix.m[4] = this._t2.x;
  30728. this._cachedTextureMatrix.m[5] = this._t2.y;
  30729. this._cachedTextureMatrix.m[6] = this._t2.z;
  30730. this._cachedTextureMatrix.m[8] = this._t0.x;
  30731. this._cachedTextureMatrix.m[9] = this._t0.y;
  30732. this._cachedTextureMatrix.m[10] = this._t0.z;
  30733. var scene = this.getScene();
  30734. if (!scene) {
  30735. return this._cachedTextureMatrix;
  30736. }
  30737. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30738. return mat.hasTexture(_this);
  30739. });
  30740. return this._cachedTextureMatrix;
  30741. };
  30742. Texture.prototype.getReflectionTextureMatrix = function () {
  30743. var _this = this;
  30744. var scene = this.getScene();
  30745. if (!scene) {
  30746. return this._cachedTextureMatrix;
  30747. }
  30748. if (this.uOffset === this._cachedUOffset &&
  30749. this.vOffset === this._cachedVOffset &&
  30750. this.uScale === this._cachedUScale &&
  30751. this.vScale === this._cachedVScale &&
  30752. this.coordinatesMode === this._cachedCoordinatesMode) {
  30753. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30754. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30755. return this._cachedTextureMatrix;
  30756. }
  30757. }
  30758. else {
  30759. return this._cachedTextureMatrix;
  30760. }
  30761. }
  30762. if (!this._cachedTextureMatrix) {
  30763. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30764. }
  30765. if (!this._projectionModeMatrix) {
  30766. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30767. }
  30768. this._cachedUOffset = this.uOffset;
  30769. this._cachedVOffset = this.vOffset;
  30770. this._cachedUScale = this.uScale;
  30771. this._cachedVScale = this.vScale;
  30772. this._cachedCoordinatesMode = this.coordinatesMode;
  30773. switch (this.coordinatesMode) {
  30774. case Texture.PLANAR_MODE:
  30775. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30776. this._cachedTextureMatrix[0] = this.uScale;
  30777. this._cachedTextureMatrix[5] = this.vScale;
  30778. this._cachedTextureMatrix[12] = this.uOffset;
  30779. this._cachedTextureMatrix[13] = this.vOffset;
  30780. break;
  30781. case Texture.PROJECTION_MODE:
  30782. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30783. this._projectionModeMatrix.m[0] = 0.5;
  30784. this._projectionModeMatrix.m[5] = -0.5;
  30785. this._projectionModeMatrix.m[10] = 0.0;
  30786. this._projectionModeMatrix.m[12] = 0.5;
  30787. this._projectionModeMatrix.m[13] = 0.5;
  30788. this._projectionModeMatrix.m[14] = 1.0;
  30789. this._projectionModeMatrix.m[15] = 1.0;
  30790. var projectionMatrix = scene.getProjectionMatrix();
  30791. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30792. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30793. break;
  30794. default:
  30795. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30796. break;
  30797. }
  30798. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30799. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30800. });
  30801. return this._cachedTextureMatrix;
  30802. };
  30803. Texture.prototype.clone = function () {
  30804. var _this = this;
  30805. return BABYLON.SerializationHelper.Clone(function () {
  30806. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30807. }, this);
  30808. };
  30809. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30810. get: function () {
  30811. if (!this._onLoadObservable) {
  30812. this._onLoadObservable = new BABYLON.Observable();
  30813. }
  30814. return this._onLoadObservable;
  30815. },
  30816. enumerable: true,
  30817. configurable: true
  30818. });
  30819. Texture.prototype.serialize = function () {
  30820. var serializationObject = _super.prototype.serialize.call(this);
  30821. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30822. serializationObject.base64String = this._buffer;
  30823. serializationObject.name = serializationObject.name.replace("data:", "");
  30824. }
  30825. serializationObject.invertY = this._invertY;
  30826. serializationObject.samplingMode = this.samplingMode;
  30827. return serializationObject;
  30828. };
  30829. Texture.prototype.getClassName = function () {
  30830. return "Texture";
  30831. };
  30832. Texture.prototype.dispose = function () {
  30833. _super.prototype.dispose.call(this);
  30834. if (this.onLoadObservable) {
  30835. this.onLoadObservable.clear();
  30836. this._onLoadObservable = null;
  30837. }
  30838. this._delayedOnLoad = null;
  30839. this._delayedOnError = null;
  30840. };
  30841. // Statics
  30842. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30843. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30844. if (onLoad === void 0) { onLoad = null; }
  30845. if (onError === void 0) { onError = null; }
  30846. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30847. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30848. };
  30849. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30850. if (parsedTexture.customType) {
  30851. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30852. // Update Sampling Mode
  30853. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30854. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30855. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30856. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30857. }
  30858. }
  30859. return parsedCustomTexture;
  30860. }
  30861. if (parsedTexture.isCube) {
  30862. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30863. }
  30864. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30865. return null;
  30866. }
  30867. var texture = BABYLON.SerializationHelper.Parse(function () {
  30868. var generateMipMaps = true;
  30869. if (parsedTexture.noMipmap) {
  30870. generateMipMaps = false;
  30871. }
  30872. if (parsedTexture.mirrorPlane) {
  30873. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30874. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30875. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30876. return mirrorTexture;
  30877. }
  30878. else if (parsedTexture.isRenderTarget) {
  30879. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30880. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30881. return renderTargetTexture;
  30882. }
  30883. else {
  30884. var texture;
  30885. if (parsedTexture.base64String) {
  30886. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30887. }
  30888. else {
  30889. var url = rootUrl + parsedTexture.name;
  30890. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30891. url = parsedTexture.url;
  30892. }
  30893. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30894. }
  30895. return texture;
  30896. }
  30897. }, parsedTexture, scene);
  30898. // Update Sampling Mode
  30899. if (parsedTexture.samplingMode) {
  30900. var sampling = parsedTexture.samplingMode;
  30901. if (texture._samplingMode !== sampling) {
  30902. texture.updateSamplingMode(sampling);
  30903. }
  30904. }
  30905. // Animations
  30906. if (parsedTexture.animations) {
  30907. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30908. var parsedAnimation = parsedTexture.animations[animationIndex];
  30909. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30910. }
  30911. }
  30912. return texture;
  30913. };
  30914. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30915. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30916. if (noMipmap === void 0) { noMipmap = false; }
  30917. if (invertY === void 0) { invertY = true; }
  30918. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30919. if (onLoad === void 0) { onLoad = null; }
  30920. if (onError === void 0) { onError = null; }
  30921. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30922. if (name.substr(0, 5) !== "data:") {
  30923. name = "data:" + name;
  30924. }
  30925. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30926. };
  30927. // Constants
  30928. Texture.NEAREST_SAMPLINGMODE = 1;
  30929. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30930. Texture.BILINEAR_SAMPLINGMODE = 2;
  30931. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30932. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30933. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30934. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30935. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30936. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30937. Texture.NEAREST_LINEAR = 7;
  30938. Texture.NEAREST_NEAREST = 8;
  30939. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30940. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30941. Texture.LINEAR_LINEAR = 11;
  30942. Texture.LINEAR_NEAREST = 12;
  30943. Texture.EXPLICIT_MODE = 0;
  30944. Texture.SPHERICAL_MODE = 1;
  30945. Texture.PLANAR_MODE = 2;
  30946. Texture.CUBIC_MODE = 3;
  30947. Texture.PROJECTION_MODE = 4;
  30948. Texture.SKYBOX_MODE = 5;
  30949. Texture.INVCUBIC_MODE = 6;
  30950. Texture.EQUIRECTANGULAR_MODE = 7;
  30951. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30952. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30953. Texture.CLAMP_ADDRESSMODE = 0;
  30954. Texture.WRAP_ADDRESSMODE = 1;
  30955. Texture.MIRROR_ADDRESSMODE = 2;
  30956. /**
  30957. * 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
  30958. */
  30959. Texture.UseSerializedUrlIfAny = false;
  30960. __decorate([
  30961. BABYLON.serialize()
  30962. ], Texture.prototype, "url", void 0);
  30963. __decorate([
  30964. BABYLON.serialize()
  30965. ], Texture.prototype, "uOffset", void 0);
  30966. __decorate([
  30967. BABYLON.serialize()
  30968. ], Texture.prototype, "vOffset", void 0);
  30969. __decorate([
  30970. BABYLON.serialize()
  30971. ], Texture.prototype, "uScale", void 0);
  30972. __decorate([
  30973. BABYLON.serialize()
  30974. ], Texture.prototype, "vScale", void 0);
  30975. __decorate([
  30976. BABYLON.serialize()
  30977. ], Texture.prototype, "uAng", void 0);
  30978. __decorate([
  30979. BABYLON.serialize()
  30980. ], Texture.prototype, "vAng", void 0);
  30981. __decorate([
  30982. BABYLON.serialize()
  30983. ], Texture.prototype, "wAng", void 0);
  30984. __decorate([
  30985. BABYLON.serialize()
  30986. ], Texture.prototype, "uRotationCenter", void 0);
  30987. __decorate([
  30988. BABYLON.serialize()
  30989. ], Texture.prototype, "vRotationCenter", void 0);
  30990. __decorate([
  30991. BABYLON.serialize()
  30992. ], Texture.prototype, "wRotationCenter", void 0);
  30993. __decorate([
  30994. BABYLON.serialize()
  30995. ], Texture.prototype, "isBlocking", null);
  30996. return Texture;
  30997. }(BABYLON.BaseTexture));
  30998. BABYLON.Texture = Texture;
  30999. })(BABYLON || (BABYLON = {}));
  31000. //# sourceMappingURL=babylon.texture.js.map
  31001. var BABYLON;
  31002. (function (BABYLON) {
  31003. /**
  31004. * @hidden
  31005. **/
  31006. var _InstancesBatch = /** @class */ (function () {
  31007. function _InstancesBatch() {
  31008. this.mustReturn = false;
  31009. this.visibleInstances = new Array();
  31010. this.renderSelf = new Array();
  31011. }
  31012. return _InstancesBatch;
  31013. }());
  31014. BABYLON._InstancesBatch = _InstancesBatch;
  31015. var Mesh = /** @class */ (function (_super) {
  31016. __extends(Mesh, _super);
  31017. /**
  31018. * @constructor
  31019. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31020. * @param {Scene} scene The scene to add this mesh to.
  31021. * @param {Node} parent The parent of this mesh, if it has one
  31022. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31023. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31024. * When false, achieved by calling a clone(), also passing False.
  31025. * This will make creation of children, recursive.
  31026. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31027. */
  31028. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31029. if (scene === void 0) { scene = null; }
  31030. if (parent === void 0) { parent = null; }
  31031. if (source === void 0) { source = null; }
  31032. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31033. var _this = _super.call(this, name, scene) || this;
  31034. // Events
  31035. /**
  31036. * An event triggered before rendering the mesh
  31037. */
  31038. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31039. /**
  31040. * An event triggered after rendering the mesh
  31041. */
  31042. _this.onAfterRenderObservable = new BABYLON.Observable();
  31043. /**
  31044. * An event triggered before drawing the mesh
  31045. */
  31046. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31047. // Members
  31048. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31049. _this.instances = new Array();
  31050. _this._LODLevels = new Array();
  31051. _this._visibleInstances = {};
  31052. _this._renderIdForInstances = new Array();
  31053. _this._batchCache = new _InstancesBatch();
  31054. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31055. // Use by builder only to know what orientation were the mesh build in.
  31056. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31057. _this.overrideMaterialSideOrientation = null;
  31058. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31059. // Will be used to save a source mesh reference, If any
  31060. _this._source = null;
  31061. scene = _this.getScene();
  31062. if (source) {
  31063. // Geometry
  31064. if (source._geometry) {
  31065. source._geometry.applyToMesh(_this);
  31066. }
  31067. // Deep copy
  31068. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31069. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31070. // Source mesh
  31071. _this._source = source;
  31072. // Metadata
  31073. if (source.metadata && source.metadata.clone) {
  31074. _this.metadata = source.metadata.clone();
  31075. }
  31076. else {
  31077. _this.metadata = source.metadata;
  31078. }
  31079. // Tags
  31080. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31081. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31082. }
  31083. // Parent
  31084. _this.parent = source.parent;
  31085. // Pivot
  31086. _this.setPivotMatrix(source.getPivotMatrix());
  31087. _this.id = name + "." + source.id;
  31088. // Material
  31089. _this.material = source.material;
  31090. var index;
  31091. if (!doNotCloneChildren) {
  31092. // Children
  31093. var directDescendants = source.getDescendants(true);
  31094. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31095. var child = directDescendants[index_1];
  31096. if (child.clone) {
  31097. child.clone(name + "." + child.name, _this);
  31098. }
  31099. }
  31100. }
  31101. // Physics clone
  31102. var physicsEngine = _this.getScene().getPhysicsEngine();
  31103. if (clonePhysicsImpostor && physicsEngine) {
  31104. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31105. if (impostor) {
  31106. _this.physicsImpostor = impostor.clone(_this);
  31107. }
  31108. }
  31109. // Particles
  31110. for (index = 0; index < scene.particleSystems.length; index++) {
  31111. var system = scene.particleSystems[index];
  31112. if (system.emitter === source) {
  31113. system.clone(system.name, _this);
  31114. }
  31115. }
  31116. _this.computeWorldMatrix(true);
  31117. }
  31118. // Parent
  31119. if (parent !== null) {
  31120. _this.parent = parent;
  31121. }
  31122. return _this;
  31123. }
  31124. Object.defineProperty(Mesh, "FRONTSIDE", {
  31125. /**
  31126. * Mesh side orientation : usually the external or front surface
  31127. */
  31128. get: function () {
  31129. return Mesh._FRONTSIDE;
  31130. },
  31131. enumerable: true,
  31132. configurable: true
  31133. });
  31134. Object.defineProperty(Mesh, "BACKSIDE", {
  31135. /**
  31136. * Mesh side orientation : usually the internal or back surface
  31137. */
  31138. get: function () {
  31139. return Mesh._BACKSIDE;
  31140. },
  31141. enumerable: true,
  31142. configurable: true
  31143. });
  31144. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31145. /**
  31146. * Mesh side orientation : both internal and external or front and back surfaces
  31147. */
  31148. get: function () {
  31149. return Mesh._DOUBLESIDE;
  31150. },
  31151. enumerable: true,
  31152. configurable: true
  31153. });
  31154. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31155. /**
  31156. * Mesh side orientation : by default, `FRONTSIDE`
  31157. */
  31158. get: function () {
  31159. return Mesh._DEFAULTSIDE;
  31160. },
  31161. enumerable: true,
  31162. configurable: true
  31163. });
  31164. Object.defineProperty(Mesh, "NO_CAP", {
  31165. /**
  31166. * Mesh cap setting : no cap
  31167. */
  31168. get: function () {
  31169. return Mesh._NO_CAP;
  31170. },
  31171. enumerable: true,
  31172. configurable: true
  31173. });
  31174. Object.defineProperty(Mesh, "CAP_START", {
  31175. /**
  31176. * Mesh cap setting : one cap at the beginning of the mesh
  31177. */
  31178. get: function () {
  31179. return Mesh._CAP_START;
  31180. },
  31181. enumerable: true,
  31182. configurable: true
  31183. });
  31184. Object.defineProperty(Mesh, "CAP_END", {
  31185. /**
  31186. * Mesh cap setting : one cap at the end of the mesh
  31187. */
  31188. get: function () {
  31189. return Mesh._CAP_END;
  31190. },
  31191. enumerable: true,
  31192. configurable: true
  31193. });
  31194. Object.defineProperty(Mesh, "CAP_ALL", {
  31195. /**
  31196. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31197. */
  31198. get: function () {
  31199. return Mesh._CAP_ALL;
  31200. },
  31201. enumerable: true,
  31202. configurable: true
  31203. });
  31204. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31205. set: function (callback) {
  31206. if (this._onBeforeDrawObserver) {
  31207. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31208. }
  31209. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31210. },
  31211. enumerable: true,
  31212. configurable: true
  31213. });
  31214. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31215. get: function () {
  31216. return this._morphTargetManager;
  31217. },
  31218. set: function (value) {
  31219. if (this._morphTargetManager === value) {
  31220. return;
  31221. }
  31222. this._morphTargetManager = value;
  31223. this._syncGeometryWithMorphTargetManager();
  31224. },
  31225. enumerable: true,
  31226. configurable: true
  31227. });
  31228. Object.defineProperty(Mesh.prototype, "source", {
  31229. get: function () {
  31230. return this._source;
  31231. },
  31232. enumerable: true,
  31233. configurable: true
  31234. });
  31235. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31236. get: function () {
  31237. return this._unIndexed;
  31238. },
  31239. set: function (value) {
  31240. if (this._unIndexed !== value) {
  31241. this._unIndexed = value;
  31242. this._markSubMeshesAsAttributesDirty();
  31243. }
  31244. },
  31245. enumerable: true,
  31246. configurable: true
  31247. });
  31248. // Methods
  31249. /**
  31250. * Returns the string "Mesh".
  31251. */
  31252. Mesh.prototype.getClassName = function () {
  31253. return "Mesh";
  31254. };
  31255. /**
  31256. * Returns a string.
  31257. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31258. */
  31259. Mesh.prototype.toString = function (fullDetails) {
  31260. var ret = _super.prototype.toString.call(this, fullDetails);
  31261. ret += ", n vertices: " + this.getTotalVertices();
  31262. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31263. if (this.animations) {
  31264. for (var i = 0; i < this.animations.length; i++) {
  31265. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31266. }
  31267. }
  31268. if (fullDetails) {
  31269. if (this._geometry) {
  31270. var ib = this.getIndices();
  31271. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31272. if (vb && ib) {
  31273. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31274. }
  31275. }
  31276. else {
  31277. ret += ", flat shading: UNKNOWN";
  31278. }
  31279. }
  31280. return ret;
  31281. };
  31282. Mesh.prototype._unBindEffect = function () {
  31283. _super.prototype._unBindEffect.call(this);
  31284. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31285. var instance = _a[_i];
  31286. instance._unBindEffect();
  31287. }
  31288. };
  31289. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31290. /**
  31291. * True if the mesh has some Levels Of Details (LOD).
  31292. * Returns a boolean.
  31293. */
  31294. get: function () {
  31295. return this._LODLevels.length > 0;
  31296. },
  31297. enumerable: true,
  31298. configurable: true
  31299. });
  31300. /**
  31301. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31302. * @returns an array of {BABYLON.MeshLODLevel}
  31303. */
  31304. Mesh.prototype.getLODLevels = function () {
  31305. return this._LODLevels;
  31306. };
  31307. Mesh.prototype._sortLODLevels = function () {
  31308. this._LODLevels.sort(function (a, b) {
  31309. if (a.distance < b.distance) {
  31310. return 1;
  31311. }
  31312. if (a.distance > b.distance) {
  31313. return -1;
  31314. }
  31315. return 0;
  31316. });
  31317. };
  31318. /**
  31319. * Add a mesh as LOD level triggered at the given distance.
  31320. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31321. * @param {number} distance The distance from the center of the object to show this level
  31322. * @param {Mesh} mesh The mesh to be added as LOD level
  31323. * @return {Mesh} This mesh (for chaining)
  31324. */
  31325. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31326. if (mesh && mesh._masterMesh) {
  31327. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31328. return this;
  31329. }
  31330. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31331. this._LODLevels.push(level);
  31332. if (mesh) {
  31333. mesh._masterMesh = this;
  31334. }
  31335. this._sortLODLevels();
  31336. return this;
  31337. };
  31338. /**
  31339. * Returns the LOD level mesh at the passed distance or null if not found.
  31340. * It is related to the method `addLODLevel(distance, mesh)`.
  31341. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31342. * Returns an object Mesh or `null`.
  31343. */
  31344. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31345. for (var index = 0; index < this._LODLevels.length; index++) {
  31346. var level = this._LODLevels[index];
  31347. if (level.distance === distance) {
  31348. return level.mesh;
  31349. }
  31350. }
  31351. return null;
  31352. };
  31353. /**
  31354. * Remove a mesh from the LOD array
  31355. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31356. * @param {Mesh} mesh The mesh to be removed.
  31357. * @return {Mesh} This mesh (for chaining)
  31358. */
  31359. Mesh.prototype.removeLODLevel = function (mesh) {
  31360. for (var index = 0; index < this._LODLevels.length; index++) {
  31361. if (this._LODLevels[index].mesh === mesh) {
  31362. this._LODLevels.splice(index, 1);
  31363. if (mesh) {
  31364. mesh._masterMesh = null;
  31365. }
  31366. }
  31367. }
  31368. this._sortLODLevels();
  31369. return this;
  31370. };
  31371. /**
  31372. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31373. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31374. */
  31375. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31376. if (!this._LODLevels || this._LODLevels.length === 0) {
  31377. return this;
  31378. }
  31379. var bSphere;
  31380. if (boundingSphere) {
  31381. bSphere = boundingSphere;
  31382. }
  31383. else {
  31384. var boundingInfo = this.getBoundingInfo();
  31385. bSphere = boundingInfo.boundingSphere;
  31386. }
  31387. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31388. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31389. if (this.onLODLevelSelection) {
  31390. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31391. }
  31392. return this;
  31393. }
  31394. for (var index = 0; index < this._LODLevels.length; index++) {
  31395. var level = this._LODLevels[index];
  31396. if (level.distance < distanceToCamera) {
  31397. if (level.mesh) {
  31398. level.mesh._preActivate();
  31399. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31400. }
  31401. if (this.onLODLevelSelection) {
  31402. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31403. }
  31404. return level.mesh;
  31405. }
  31406. }
  31407. if (this.onLODLevelSelection) {
  31408. this.onLODLevelSelection(distanceToCamera, this, this);
  31409. }
  31410. return this;
  31411. };
  31412. Object.defineProperty(Mesh.prototype, "geometry", {
  31413. /**
  31414. * Returns the mesh internal Geometry object.
  31415. */
  31416. get: function () {
  31417. return this._geometry;
  31418. },
  31419. enumerable: true,
  31420. configurable: true
  31421. });
  31422. /**
  31423. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31424. */
  31425. Mesh.prototype.getTotalVertices = function () {
  31426. if (this._geometry === null || this._geometry === undefined) {
  31427. return 0;
  31428. }
  31429. return this._geometry.getTotalVertices();
  31430. };
  31431. /**
  31432. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31433. * 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.
  31434. * You can force the copy with forceCopy === true
  31435. * Returns null if the mesh has no geometry or no vertex buffer.
  31436. * Possible `kind` values :
  31437. * - BABYLON.VertexBuffer.PositionKind
  31438. * - BABYLON.VertexBuffer.UVKind
  31439. * - BABYLON.VertexBuffer.UV2Kind
  31440. * - BABYLON.VertexBuffer.UV3Kind
  31441. * - BABYLON.VertexBuffer.UV4Kind
  31442. * - BABYLON.VertexBuffer.UV5Kind
  31443. * - BABYLON.VertexBuffer.UV6Kind
  31444. * - BABYLON.VertexBuffer.ColorKind
  31445. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31446. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31447. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31448. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31449. */
  31450. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31451. if (!this._geometry) {
  31452. return null;
  31453. }
  31454. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31455. };
  31456. /**
  31457. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31458. * Returns `null` if the mesh has no geometry.
  31459. * Possible `kind` values :
  31460. * - BABYLON.VertexBuffer.PositionKind
  31461. * - BABYLON.VertexBuffer.UVKind
  31462. * - BABYLON.VertexBuffer.UV2Kind
  31463. * - BABYLON.VertexBuffer.UV3Kind
  31464. * - BABYLON.VertexBuffer.UV4Kind
  31465. * - BABYLON.VertexBuffer.UV5Kind
  31466. * - BABYLON.VertexBuffer.UV6Kind
  31467. * - BABYLON.VertexBuffer.ColorKind
  31468. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31469. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31470. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31471. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31472. */
  31473. Mesh.prototype.getVertexBuffer = function (kind) {
  31474. if (!this._geometry) {
  31475. return null;
  31476. }
  31477. return this._geometry.getVertexBuffer(kind);
  31478. };
  31479. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31480. if (!this._geometry) {
  31481. if (this._delayInfo) {
  31482. return this._delayInfo.indexOf(kind) !== -1;
  31483. }
  31484. return false;
  31485. }
  31486. return this._geometry.isVerticesDataPresent(kind);
  31487. };
  31488. /**
  31489. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31490. * Possible `kind` values :
  31491. * - BABYLON.VertexBuffer.PositionKind
  31492. * - BABYLON.VertexBuffer.UVKind
  31493. * - BABYLON.VertexBuffer.UV2Kind
  31494. * - BABYLON.VertexBuffer.UV3Kind
  31495. * - BABYLON.VertexBuffer.UV4Kind
  31496. * - BABYLON.VertexBuffer.UV5Kind
  31497. * - BABYLON.VertexBuffer.UV6Kind
  31498. * - BABYLON.VertexBuffer.ColorKind
  31499. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31500. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31501. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31502. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31503. */
  31504. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31505. if (!this._geometry) {
  31506. if (this._delayInfo) {
  31507. return this._delayInfo.indexOf(kind) !== -1;
  31508. }
  31509. return false;
  31510. }
  31511. return this._geometry.isVertexBufferUpdatable(kind);
  31512. };
  31513. /**
  31514. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31515. * Possible `kind` values :
  31516. * - BABYLON.VertexBuffer.PositionKind
  31517. * - BABYLON.VertexBuffer.UVKind
  31518. * - BABYLON.VertexBuffer.UV2Kind
  31519. * - BABYLON.VertexBuffer.UV3Kind
  31520. * - BABYLON.VertexBuffer.UV4Kind
  31521. * - BABYLON.VertexBuffer.UV5Kind
  31522. * - BABYLON.VertexBuffer.UV6Kind
  31523. * - BABYLON.VertexBuffer.ColorKind
  31524. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31525. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31526. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31527. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31528. */
  31529. Mesh.prototype.getVerticesDataKinds = function () {
  31530. if (!this._geometry) {
  31531. var result = new Array();
  31532. if (this._delayInfo) {
  31533. this._delayInfo.forEach(function (kind, index, array) {
  31534. result.push(kind);
  31535. });
  31536. }
  31537. return result;
  31538. }
  31539. return this._geometry.getVerticesDataKinds();
  31540. };
  31541. /**
  31542. * Returns a positive integer : the total number of indices in this mesh geometry.
  31543. * Returns zero if the mesh has no geometry.
  31544. */
  31545. Mesh.prototype.getTotalIndices = function () {
  31546. if (!this._geometry) {
  31547. return 0;
  31548. }
  31549. return this._geometry.getTotalIndices();
  31550. };
  31551. /**
  31552. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31553. * 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.
  31554. * Returns an empty array if the mesh has no geometry.
  31555. */
  31556. Mesh.prototype.getIndices = function (copyWhenShared) {
  31557. if (!this._geometry) {
  31558. return [];
  31559. }
  31560. return this._geometry.getIndices(copyWhenShared);
  31561. };
  31562. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31563. get: function () {
  31564. return this._masterMesh !== null && this._masterMesh !== undefined;
  31565. },
  31566. enumerable: true,
  31567. configurable: true
  31568. });
  31569. /**
  31570. * Determine if the current mesh is ready to be rendered
  31571. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31572. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31573. * @returns true if all associated assets are ready (material, textures, shaders)
  31574. */
  31575. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31576. if (completeCheck === void 0) { completeCheck = false; }
  31577. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31578. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31579. return false;
  31580. }
  31581. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31582. return false;
  31583. }
  31584. if (!this.subMeshes || this.subMeshes.length === 0) {
  31585. return true;
  31586. }
  31587. if (!completeCheck) {
  31588. return true;
  31589. }
  31590. var engine = this.getEngine();
  31591. var scene = this.getScene();
  31592. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31593. this.computeWorldMatrix();
  31594. var mat = this.material || scene.defaultMaterial;
  31595. if (mat) {
  31596. if (mat.storeEffectOnSubMeshes) {
  31597. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31598. var subMesh = _a[_i];
  31599. var effectiveMaterial = subMesh.getMaterial();
  31600. if (effectiveMaterial) {
  31601. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31602. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31603. return false;
  31604. }
  31605. }
  31606. else {
  31607. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31608. return false;
  31609. }
  31610. }
  31611. }
  31612. }
  31613. }
  31614. else {
  31615. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31616. return false;
  31617. }
  31618. }
  31619. }
  31620. // Shadows
  31621. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31622. var light = _c[_b];
  31623. var generator = light.getShadowGenerator();
  31624. if (generator) {
  31625. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31626. var subMesh = _e[_d];
  31627. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31628. return false;
  31629. }
  31630. }
  31631. }
  31632. }
  31633. // LOD
  31634. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31635. var lod = _g[_f];
  31636. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31637. return false;
  31638. }
  31639. }
  31640. return true;
  31641. };
  31642. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31643. /**
  31644. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31645. * This property is pertinent only for updatable parametric shapes.
  31646. */
  31647. get: function () {
  31648. return this._areNormalsFrozen;
  31649. },
  31650. enumerable: true,
  31651. configurable: true
  31652. });
  31653. /**
  31654. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31655. * It has no effect at all on other shapes.
  31656. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31657. * Returns the Mesh.
  31658. */
  31659. Mesh.prototype.freezeNormals = function () {
  31660. this._areNormalsFrozen = true;
  31661. return this;
  31662. };
  31663. /**
  31664. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31665. * It has no effect at all on other shapes.
  31666. * It reactivates the mesh normals computation if it was previously frozen.
  31667. * Returns the Mesh.
  31668. */
  31669. Mesh.prototype.unfreezeNormals = function () {
  31670. this._areNormalsFrozen = false;
  31671. return this;
  31672. };
  31673. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31674. /**
  31675. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31676. */
  31677. set: function (count) {
  31678. this._overridenInstanceCount = count;
  31679. },
  31680. enumerable: true,
  31681. configurable: true
  31682. });
  31683. // Methods
  31684. Mesh.prototype._preActivate = function () {
  31685. var sceneRenderId = this.getScene().getRenderId();
  31686. if (this._preActivateId === sceneRenderId) {
  31687. return this;
  31688. }
  31689. this._preActivateId = sceneRenderId;
  31690. this._visibleInstances = null;
  31691. return this;
  31692. };
  31693. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31694. if (this._visibleInstances) {
  31695. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31696. }
  31697. return this;
  31698. };
  31699. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31700. if (!this._visibleInstances) {
  31701. this._visibleInstances = {};
  31702. this._visibleInstances.defaultRenderId = renderId;
  31703. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31704. }
  31705. if (!this._visibleInstances[renderId]) {
  31706. this._visibleInstances[renderId] = new Array();
  31707. }
  31708. this._visibleInstances[renderId].push(instance);
  31709. return this;
  31710. };
  31711. /**
  31712. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31713. * This means the mesh underlying bounding box and sphere are recomputed.
  31714. * Returns the Mesh.
  31715. */
  31716. Mesh.prototype.refreshBoundingInfo = function () {
  31717. return this._refreshBoundingInfo(false);
  31718. };
  31719. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31720. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31721. return this;
  31722. }
  31723. var data = this._getPositionData(applySkeleton);
  31724. if (data) {
  31725. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31726. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31727. }
  31728. if (this.subMeshes) {
  31729. for (var index = 0; index < this.subMeshes.length; index++) {
  31730. this.subMeshes[index].refreshBoundingInfo();
  31731. }
  31732. }
  31733. this._updateBoundingInfo();
  31734. return this;
  31735. };
  31736. Mesh.prototype._getPositionData = function (applySkeleton) {
  31737. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31738. if (data && applySkeleton && this.skeleton) {
  31739. data = BABYLON.Tools.Slice(data);
  31740. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31741. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31742. if (matricesWeightsData && matricesIndicesData) {
  31743. var needExtras = this.numBoneInfluencers > 4;
  31744. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31745. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31746. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31747. var tempVector = BABYLON.Tmp.Vector3[0];
  31748. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31749. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31750. var matWeightIdx = 0;
  31751. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31752. finalMatrix.reset();
  31753. var inf;
  31754. var weight;
  31755. for (inf = 0; inf < 4; inf++) {
  31756. weight = matricesWeightsData[matWeightIdx + inf];
  31757. if (weight <= 0)
  31758. break;
  31759. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31760. finalMatrix.addToSelf(tempMatrix);
  31761. }
  31762. if (needExtras) {
  31763. for (inf = 0; inf < 4; inf++) {
  31764. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31765. if (weight <= 0)
  31766. break;
  31767. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31768. finalMatrix.addToSelf(tempMatrix);
  31769. }
  31770. }
  31771. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31772. tempVector.toArray(data, index);
  31773. }
  31774. }
  31775. }
  31776. return data;
  31777. };
  31778. Mesh.prototype._createGlobalSubMesh = function (force) {
  31779. var totalVertices = this.getTotalVertices();
  31780. if (!totalVertices || !this.getIndices()) {
  31781. return null;
  31782. }
  31783. // Check if we need to recreate the submeshes
  31784. if (this.subMeshes && this.subMeshes.length > 0) {
  31785. var ib = this.getIndices();
  31786. if (!ib) {
  31787. return null;
  31788. }
  31789. var totalIndices = ib.length;
  31790. var needToRecreate = false;
  31791. if (force) {
  31792. needToRecreate = true;
  31793. }
  31794. else {
  31795. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31796. var submesh = _a[_i];
  31797. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31798. needToRecreate = true;
  31799. break;
  31800. }
  31801. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31802. needToRecreate = true;
  31803. break;
  31804. }
  31805. }
  31806. }
  31807. if (!needToRecreate) {
  31808. return this.subMeshes[0];
  31809. }
  31810. }
  31811. this.releaseSubMeshes();
  31812. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31813. };
  31814. Mesh.prototype.subdivide = function (count) {
  31815. if (count < 1) {
  31816. return;
  31817. }
  31818. var totalIndices = this.getTotalIndices();
  31819. var subdivisionSize = (totalIndices / count) | 0;
  31820. var offset = 0;
  31821. // Ensure that subdivisionSize is a multiple of 3
  31822. while (subdivisionSize % 3 !== 0) {
  31823. subdivisionSize++;
  31824. }
  31825. this.releaseSubMeshes();
  31826. for (var index = 0; index < count; index++) {
  31827. if (offset >= totalIndices) {
  31828. break;
  31829. }
  31830. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31831. offset += subdivisionSize;
  31832. }
  31833. this.synchronizeInstances();
  31834. };
  31835. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31836. if (updatable === void 0) { updatable = false; }
  31837. if (!this._geometry) {
  31838. var vertexData = new BABYLON.VertexData();
  31839. vertexData.set(data, kind);
  31840. var scene = this.getScene();
  31841. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31842. }
  31843. else {
  31844. this._geometry.setVerticesData(kind, data, updatable, stride);
  31845. }
  31846. return this;
  31847. };
  31848. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31849. if (updatable === void 0) { updatable = true; }
  31850. var vb = this.getVertexBuffer(kind);
  31851. if (!vb || vb.isUpdatable() === updatable) {
  31852. return;
  31853. }
  31854. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31855. };
  31856. /**
  31857. * Sets the mesh VertexBuffer.
  31858. * Returns the Mesh.
  31859. */
  31860. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31861. if (!this._geometry) {
  31862. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31863. }
  31864. this._geometry.setVerticesBuffer(buffer);
  31865. return this;
  31866. };
  31867. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31868. if (!this._geometry) {
  31869. return this;
  31870. }
  31871. if (!makeItUnique) {
  31872. this._geometry.updateVerticesData(kind, data, updateExtends);
  31873. }
  31874. else {
  31875. this.makeGeometryUnique();
  31876. this.updateVerticesData(kind, data, updateExtends, false);
  31877. }
  31878. return this;
  31879. };
  31880. /**
  31881. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31882. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31883. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31884. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31885. * Returns the Mesh.
  31886. */
  31887. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31888. if (computeNormals === void 0) { computeNormals = true; }
  31889. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31890. if (!positions) {
  31891. return this;
  31892. }
  31893. positionFunction(positions);
  31894. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31895. if (computeNormals) {
  31896. var indices = this.getIndices();
  31897. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31898. if (!normals) {
  31899. return this;
  31900. }
  31901. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31902. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31903. }
  31904. return this;
  31905. };
  31906. /**
  31907. * Creates a un-shared specific occurence of the geometry for the mesh.
  31908. * Returns the Mesh.
  31909. */
  31910. Mesh.prototype.makeGeometryUnique = function () {
  31911. if (!this._geometry) {
  31912. return this;
  31913. }
  31914. var oldGeometry = this._geometry;
  31915. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31916. oldGeometry.releaseForMesh(this, true);
  31917. geometry.applyToMesh(this);
  31918. return this;
  31919. };
  31920. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31921. if (totalVertices === void 0) { totalVertices = null; }
  31922. if (updatable === void 0) { updatable = false; }
  31923. if (!this._geometry) {
  31924. var vertexData = new BABYLON.VertexData();
  31925. vertexData.indices = indices;
  31926. var scene = this.getScene();
  31927. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31928. }
  31929. else {
  31930. this._geometry.setIndices(indices, totalVertices, updatable);
  31931. }
  31932. return this;
  31933. };
  31934. /**
  31935. * Update the current index buffer
  31936. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31937. * Returns the Mesh.
  31938. */
  31939. Mesh.prototype.updateIndices = function (indices, offset) {
  31940. if (!this._geometry) {
  31941. return this;
  31942. }
  31943. this._geometry.updateIndices(indices, offset);
  31944. return this;
  31945. };
  31946. /**
  31947. * Invert the geometry to move from a right handed system to a left handed one.
  31948. * Returns the Mesh.
  31949. */
  31950. Mesh.prototype.toLeftHanded = function () {
  31951. if (!this._geometry) {
  31952. return this;
  31953. }
  31954. this._geometry.toLeftHanded();
  31955. return this;
  31956. };
  31957. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31958. if (!this._geometry) {
  31959. return this;
  31960. }
  31961. var engine = this.getScene().getEngine();
  31962. // Wireframe
  31963. var indexToBind;
  31964. if (this._unIndexed) {
  31965. indexToBind = null;
  31966. }
  31967. else {
  31968. switch (fillMode) {
  31969. case BABYLON.Material.PointFillMode:
  31970. indexToBind = null;
  31971. break;
  31972. case BABYLON.Material.WireFrameFillMode:
  31973. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31974. break;
  31975. default:
  31976. case BABYLON.Material.TriangleFillMode:
  31977. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31978. break;
  31979. }
  31980. }
  31981. // VBOs
  31982. this._geometry._bind(effect, indexToBind);
  31983. return this;
  31984. };
  31985. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31986. if (alternate === void 0) { alternate = false; }
  31987. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31988. return this;
  31989. }
  31990. this.onBeforeDrawObservable.notifyObservers(this);
  31991. var scene = this.getScene();
  31992. var engine = scene.getEngine();
  31993. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31994. // or triangles as points
  31995. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31996. }
  31997. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31998. // Triangles as wireframe
  31999. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32000. }
  32001. else {
  32002. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32003. }
  32004. if (scene._isAlternateRenderingEnabled && !alternate) {
  32005. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32006. if (!effect || !scene.activeCamera) {
  32007. return this;
  32008. }
  32009. scene._switchToAlternateCameraConfiguration(true);
  32010. this._effectiveMaterial.bindView(effect);
  32011. this._effectiveMaterial.bindViewProjection(effect);
  32012. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32013. this._draw(subMesh, fillMode, instancesCount, true);
  32014. engine.setViewport(scene.activeCamera.viewport);
  32015. scene._switchToAlternateCameraConfiguration(false);
  32016. this._effectiveMaterial.bindView(effect);
  32017. this._effectiveMaterial.bindViewProjection(effect);
  32018. }
  32019. return this;
  32020. };
  32021. /**
  32022. * Registers for this mesh a javascript function called just before the rendering process.
  32023. * This function is passed the current mesh.
  32024. * Return the Mesh.
  32025. */
  32026. Mesh.prototype.registerBeforeRender = function (func) {
  32027. this.onBeforeRenderObservable.add(func);
  32028. return this;
  32029. };
  32030. /**
  32031. * Disposes a previously registered javascript function called before the rendering.
  32032. * This function is passed the current mesh.
  32033. * Returns the Mesh.
  32034. */
  32035. Mesh.prototype.unregisterBeforeRender = function (func) {
  32036. this.onBeforeRenderObservable.removeCallback(func);
  32037. return this;
  32038. };
  32039. /**
  32040. * Registers for this mesh a javascript function called just after the rendering is complete.
  32041. * This function is passed the current mesh.
  32042. * Returns the Mesh.
  32043. */
  32044. Mesh.prototype.registerAfterRender = function (func) {
  32045. this.onAfterRenderObservable.add(func);
  32046. return this;
  32047. };
  32048. /**
  32049. * Disposes a previously registered javascript function called after the rendering.
  32050. * This function is passed the current mesh.
  32051. * Return the Mesh.
  32052. */
  32053. Mesh.prototype.unregisterAfterRender = function (func) {
  32054. this.onAfterRenderObservable.removeCallback(func);
  32055. return this;
  32056. };
  32057. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32058. var scene = this.getScene();
  32059. this._batchCache.mustReturn = false;
  32060. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32061. this._batchCache.visibleInstances[subMeshId] = null;
  32062. if (this._visibleInstances) {
  32063. var currentRenderId = scene.getRenderId();
  32064. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32065. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32066. var selfRenderId = this._renderId;
  32067. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32068. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32069. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32070. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32071. }
  32072. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32073. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32074. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32075. this._batchCache.mustReturn = true;
  32076. return this._batchCache;
  32077. }
  32078. if (currentRenderId !== selfRenderId) {
  32079. this._batchCache.renderSelf[subMeshId] = false;
  32080. }
  32081. }
  32082. this._renderIdForInstances[subMeshId] = currentRenderId;
  32083. }
  32084. return this._batchCache;
  32085. };
  32086. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32087. var visibleInstances = batch.visibleInstances[subMesh._id];
  32088. if (!visibleInstances) {
  32089. return this;
  32090. }
  32091. var matricesCount = visibleInstances.length + 1;
  32092. var bufferSize = matricesCount * 16 * 4;
  32093. var currentInstancesBufferSize = this._instancesBufferSize;
  32094. var instancesBuffer = this._instancesBuffer;
  32095. while (this._instancesBufferSize < bufferSize) {
  32096. this._instancesBufferSize *= 2;
  32097. }
  32098. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32099. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32100. }
  32101. var offset = 0;
  32102. var instancesCount = 0;
  32103. var world = this.getWorldMatrix();
  32104. if (batch.renderSelf[subMesh._id]) {
  32105. world.copyToArray(this._instancesData, offset);
  32106. offset += 16;
  32107. instancesCount++;
  32108. }
  32109. if (visibleInstances) {
  32110. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32111. var instance = visibleInstances[instanceIndex];
  32112. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32113. offset += 16;
  32114. instancesCount++;
  32115. }
  32116. }
  32117. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32118. if (instancesBuffer) {
  32119. instancesBuffer.dispose();
  32120. }
  32121. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32122. this._instancesBuffer = instancesBuffer;
  32123. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32124. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32125. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32126. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32127. }
  32128. else {
  32129. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32130. }
  32131. this._bind(subMesh, effect, fillMode);
  32132. this._draw(subMesh, fillMode, instancesCount);
  32133. engine.unbindInstanceAttributes();
  32134. return this;
  32135. };
  32136. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32137. var scene = this.getScene();
  32138. var engine = scene.getEngine();
  32139. if (hardwareInstancedRendering) {
  32140. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32141. }
  32142. else {
  32143. if (batch.renderSelf[subMesh._id]) {
  32144. // Draw
  32145. if (onBeforeDraw) {
  32146. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32147. }
  32148. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32149. }
  32150. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32151. if (visibleInstancesForSubMesh) {
  32152. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32153. var instance = visibleInstancesForSubMesh[instanceIndex];
  32154. // World
  32155. var world = instance.getWorldMatrix();
  32156. if (onBeforeDraw) {
  32157. onBeforeDraw(true, world, effectiveMaterial);
  32158. }
  32159. // Draw
  32160. this._draw(subMesh, fillMode);
  32161. }
  32162. }
  32163. }
  32164. return this;
  32165. };
  32166. /**
  32167. * Triggers the draw call for the mesh.
  32168. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32169. * Returns the Mesh.
  32170. */
  32171. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32172. this._checkOcclusionQuery();
  32173. if (this._isOccluded) {
  32174. return this;
  32175. }
  32176. var scene = this.getScene();
  32177. // Managing instances
  32178. var batch = this._getInstancesRenderList(subMesh._id);
  32179. if (batch.mustReturn) {
  32180. return this;
  32181. }
  32182. // Checking geometry state
  32183. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32184. return this;
  32185. }
  32186. this.onBeforeRenderObservable.notifyObservers(this);
  32187. var engine = scene.getEngine();
  32188. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32189. // Material
  32190. var material = subMesh.getMaterial();
  32191. if (!material) {
  32192. return this;
  32193. }
  32194. this._effectiveMaterial = material;
  32195. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32196. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32197. return this;
  32198. }
  32199. }
  32200. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32201. return this;
  32202. }
  32203. // Alpha mode
  32204. if (enableAlphaMode) {
  32205. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32206. }
  32207. // Outline - step 1
  32208. var savedDepthWrite = engine.getDepthWrite();
  32209. if (this.renderOutline) {
  32210. engine.setDepthWrite(false);
  32211. scene.getOutlineRenderer().render(subMesh, batch);
  32212. engine.setDepthWrite(savedDepthWrite);
  32213. }
  32214. var effect;
  32215. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32216. effect = subMesh.effect;
  32217. }
  32218. else {
  32219. effect = this._effectiveMaterial.getEffect();
  32220. }
  32221. if (!effect) {
  32222. return this;
  32223. }
  32224. var sideOrientation = this.overrideMaterialSideOrientation;
  32225. if (sideOrientation == null) {
  32226. sideOrientation = this._effectiveMaterial.sideOrientation;
  32227. if (this._getWorldMatrixDeterminant() < 0) {
  32228. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32229. }
  32230. }
  32231. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32232. if (this._effectiveMaterial.forceDepthWrite) {
  32233. engine.setDepthWrite(true);
  32234. }
  32235. // Bind
  32236. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32237. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32238. this._bind(subMesh, effect, fillMode);
  32239. }
  32240. var world = this.getWorldMatrix();
  32241. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32242. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32243. }
  32244. else {
  32245. this._effectiveMaterial.bind(world, this);
  32246. }
  32247. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32248. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32249. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32250. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32251. }
  32252. // Draw
  32253. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32254. // Unbind
  32255. this._effectiveMaterial.unbind();
  32256. // Outline - step 2
  32257. if (this.renderOutline && savedDepthWrite) {
  32258. engine.setDepthWrite(true);
  32259. engine.setColorWrite(false);
  32260. scene.getOutlineRenderer().render(subMesh, batch);
  32261. engine.setColorWrite(true);
  32262. }
  32263. // Overlay
  32264. if (this.renderOverlay) {
  32265. var currentMode = engine.getAlphaMode();
  32266. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32267. scene.getOutlineRenderer().render(subMesh, batch, true);
  32268. engine.setAlphaMode(currentMode);
  32269. }
  32270. this.onAfterRenderObservable.notifyObservers(this);
  32271. return this;
  32272. };
  32273. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32274. if (isInstance && effectiveMaterial) {
  32275. effectiveMaterial.bindOnlyWorldMatrix(world);
  32276. }
  32277. };
  32278. /**
  32279. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32280. */
  32281. Mesh.prototype.getEmittedParticleSystems = function () {
  32282. var results = new Array();
  32283. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32284. var particleSystem = this.getScene().particleSystems[index];
  32285. if (particleSystem.emitter === this) {
  32286. results.push(particleSystem);
  32287. }
  32288. }
  32289. return results;
  32290. };
  32291. /**
  32292. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32293. */
  32294. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32295. var results = new Array();
  32296. var descendants = this.getDescendants();
  32297. descendants.push(this);
  32298. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32299. var particleSystem = this.getScene().particleSystems[index];
  32300. var emitter = particleSystem.emitter;
  32301. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32302. results.push(particleSystem);
  32303. }
  32304. }
  32305. return results;
  32306. };
  32307. /**
  32308. * Normalize matrix weights so that all vertices have a total weight set to 1
  32309. */
  32310. Mesh.prototype.cleanMatrixWeights = function () {
  32311. var epsilon = 1e-3;
  32312. var noInfluenceBoneIndex = 0.0;
  32313. if (this.skeleton) {
  32314. noInfluenceBoneIndex = this.skeleton.bones.length;
  32315. }
  32316. else {
  32317. return;
  32318. }
  32319. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32320. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32321. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32322. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32323. var influencers = this.numBoneInfluencers;
  32324. var size = matricesWeights.length;
  32325. for (var i = 0; i < size; i += 4) {
  32326. var weight = 0.0;
  32327. var firstZeroWeight = -1;
  32328. for (var j = 0; j < 4; j++) {
  32329. var w = matricesWeights[i + j];
  32330. weight += w;
  32331. if (w < epsilon && firstZeroWeight < 0) {
  32332. firstZeroWeight = j;
  32333. }
  32334. }
  32335. if (matricesWeightsExtra) {
  32336. for (var j = 0; j < 4; j++) {
  32337. var w = matricesWeightsExtra[i + j];
  32338. weight += w;
  32339. if (w < epsilon && firstZeroWeight < 0) {
  32340. firstZeroWeight = j + 4;
  32341. }
  32342. }
  32343. }
  32344. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32345. firstZeroWeight = influencers - 1;
  32346. }
  32347. if (weight > epsilon) {
  32348. var mweight = 1.0 / weight;
  32349. for (var j = 0; j < 4; j++) {
  32350. matricesWeights[i + j] *= mweight;
  32351. }
  32352. if (matricesWeightsExtra) {
  32353. for (var j = 0; j < 4; j++) {
  32354. matricesWeightsExtra[i + j] *= mweight;
  32355. }
  32356. }
  32357. }
  32358. else {
  32359. if (firstZeroWeight >= 4) {
  32360. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32361. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32362. }
  32363. else {
  32364. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32365. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32366. }
  32367. }
  32368. }
  32369. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32370. if (matricesIndicesExtra) {
  32371. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32372. }
  32373. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32374. if (matricesWeightsExtra) {
  32375. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32376. }
  32377. };
  32378. Mesh.prototype._checkDelayState = function () {
  32379. var scene = this.getScene();
  32380. if (this._geometry) {
  32381. this._geometry.load(scene);
  32382. }
  32383. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32384. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32385. this._queueLoad(scene);
  32386. }
  32387. return this;
  32388. };
  32389. Mesh.prototype._queueLoad = function (scene) {
  32390. var _this = this;
  32391. scene._addPendingData(this);
  32392. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32393. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32394. if (data instanceof ArrayBuffer) {
  32395. _this._delayLoadingFunction(data, _this);
  32396. }
  32397. else {
  32398. _this._delayLoadingFunction(JSON.parse(data), _this);
  32399. }
  32400. _this.instances.forEach(function (instance) {
  32401. instance._syncSubMeshes();
  32402. });
  32403. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32404. scene._removePendingData(_this);
  32405. }, function () { }, scene.database, getBinaryData);
  32406. return this;
  32407. };
  32408. /**
  32409. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32410. */
  32411. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32412. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32413. return false;
  32414. }
  32415. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32416. return false;
  32417. }
  32418. this._checkDelayState();
  32419. return true;
  32420. };
  32421. /**
  32422. * Sets the mesh material by the material or multiMaterial `id` property.
  32423. * The material `id` is a string identifying the material or the multiMaterial.
  32424. * This method returns the Mesh.
  32425. */
  32426. Mesh.prototype.setMaterialByID = function (id) {
  32427. var materials = this.getScene().materials;
  32428. var index;
  32429. for (index = materials.length - 1; index > -1; index--) {
  32430. if (materials[index].id === id) {
  32431. this.material = materials[index];
  32432. return this;
  32433. }
  32434. }
  32435. // Multi
  32436. var multiMaterials = this.getScene().multiMaterials;
  32437. for (index = multiMaterials.length - 1; index > -1; index--) {
  32438. if (multiMaterials[index].id === id) {
  32439. this.material = multiMaterials[index];
  32440. return this;
  32441. }
  32442. }
  32443. return this;
  32444. };
  32445. /**
  32446. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32447. */
  32448. Mesh.prototype.getAnimatables = function () {
  32449. var results = new Array();
  32450. if (this.material) {
  32451. results.push(this.material);
  32452. }
  32453. if (this.skeleton) {
  32454. results.push(this.skeleton);
  32455. }
  32456. return results;
  32457. };
  32458. /**
  32459. * Modifies the mesh geometry according to the passed transformation matrix.
  32460. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32461. * The mesh normals are modified accordingly the same transformation.
  32462. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32463. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32464. * Returns the Mesh.
  32465. */
  32466. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32467. // Position
  32468. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32469. return this;
  32470. }
  32471. var submeshes = this.subMeshes.splice(0);
  32472. this._resetPointsArrayCache();
  32473. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32474. var temp = new Array();
  32475. var index;
  32476. for (index = 0; index < data.length; index += 3) {
  32477. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32478. }
  32479. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32480. // Normals
  32481. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32482. return this;
  32483. }
  32484. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32485. temp = [];
  32486. for (index = 0; index < data.length; index += 3) {
  32487. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32488. }
  32489. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32490. // flip faces?
  32491. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32492. this.flipFaces();
  32493. }
  32494. // Restore submeshes
  32495. this.releaseSubMeshes();
  32496. this.subMeshes = submeshes;
  32497. return this;
  32498. };
  32499. /**
  32500. * Modifies the mesh geometry according to its own current World Matrix.
  32501. * The mesh World Matrix is then reset.
  32502. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32503. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32504. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32505. * Returns the Mesh.
  32506. */
  32507. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32508. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32509. this.scaling.copyFromFloats(1, 1, 1);
  32510. this.position.copyFromFloats(0, 0, 0);
  32511. this.rotation.copyFromFloats(0, 0, 0);
  32512. //only if quaternion is already set
  32513. if (this.rotationQuaternion) {
  32514. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32515. }
  32516. this._worldMatrix = BABYLON.Matrix.Identity();
  32517. return this;
  32518. };
  32519. Object.defineProperty(Mesh.prototype, "_positions", {
  32520. // Cache
  32521. get: function () {
  32522. if (this._geometry) {
  32523. return this._geometry._positions;
  32524. }
  32525. return null;
  32526. },
  32527. enumerable: true,
  32528. configurable: true
  32529. });
  32530. Mesh.prototype._resetPointsArrayCache = function () {
  32531. if (this._geometry) {
  32532. this._geometry._resetPointsArrayCache();
  32533. }
  32534. return this;
  32535. };
  32536. Mesh.prototype._generatePointsArray = function () {
  32537. if (this._geometry) {
  32538. return this._geometry._generatePointsArray();
  32539. }
  32540. return false;
  32541. };
  32542. /**
  32543. * Returns a new Mesh object generated from the current mesh properties.
  32544. * This method must not get confused with createInstance().
  32545. * The parameter `name` is a string, the name given to the new mesh.
  32546. * The optional parameter `newParent` can be any Node object (default `null`).
  32547. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32548. * 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.
  32549. */
  32550. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32551. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32552. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32553. };
  32554. /**
  32555. * Releases resources associated with this mesh.
  32556. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32557. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32558. */
  32559. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32560. var _this = this;
  32561. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32562. this.morphTargetManager = null;
  32563. if (this._geometry) {
  32564. this._geometry.releaseForMesh(this, true);
  32565. }
  32566. // Sources
  32567. var meshes = this.getScene().meshes;
  32568. meshes.forEach(function (abstractMesh) {
  32569. var mesh = abstractMesh;
  32570. if (mesh._source && mesh._source === _this) {
  32571. mesh._source = null;
  32572. }
  32573. });
  32574. this._source = null;
  32575. // Instances
  32576. if (this._instancesBuffer) {
  32577. this._instancesBuffer.dispose();
  32578. this._instancesBuffer = null;
  32579. }
  32580. while (this.instances.length) {
  32581. this.instances[0].dispose();
  32582. }
  32583. // Effect layers.
  32584. var effectLayers = this.getScene().effectLayers;
  32585. for (var i = 0; i < effectLayers.length; i++) {
  32586. var effectLayer = effectLayers[i];
  32587. if (effectLayer) {
  32588. effectLayer._disposeMesh(this);
  32589. }
  32590. }
  32591. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32592. };
  32593. /**
  32594. * Modifies the mesh geometry according to a displacement map.
  32595. * 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.
  32596. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32597. * This method returns nothing.
  32598. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32599. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32600. * 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.
  32601. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32602. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32603. *
  32604. * Returns the Mesh.
  32605. */
  32606. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32607. var _this = this;
  32608. var scene = this.getScene();
  32609. var onload = function (img) {
  32610. // Getting height map data
  32611. var canvas = document.createElement("canvas");
  32612. var context = canvas.getContext("2d");
  32613. var heightMapWidth = img.width;
  32614. var heightMapHeight = img.height;
  32615. canvas.width = heightMapWidth;
  32616. canvas.height = heightMapHeight;
  32617. context.drawImage(img, 0, 0);
  32618. // Create VertexData from map data
  32619. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32620. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32621. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32622. //execute success callback, if set
  32623. if (onSuccess) {
  32624. onSuccess(_this);
  32625. }
  32626. };
  32627. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32628. return this;
  32629. };
  32630. /**
  32631. * Modifies the mesh geometry according to a displacementMap buffer.
  32632. * 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.
  32633. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32634. * This method returns nothing.
  32635. * 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.
  32636. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32637. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32638. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32639. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32640. *
  32641. * Returns the Mesh.
  32642. */
  32643. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32644. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32645. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32646. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32647. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32648. return this;
  32649. }
  32650. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32651. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32652. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32653. var position = BABYLON.Vector3.Zero();
  32654. var normal = BABYLON.Vector3.Zero();
  32655. var uv = BABYLON.Vector2.Zero();
  32656. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32657. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32658. for (var index = 0; index < positions.length; index += 3) {
  32659. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32660. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32661. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32662. // Compute height
  32663. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32664. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32665. var pos = (u + v * heightMapWidth) * 4;
  32666. var r = buffer[pos] / 255.0;
  32667. var g = buffer[pos + 1] / 255.0;
  32668. var b = buffer[pos + 2] / 255.0;
  32669. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32670. normal.normalize();
  32671. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32672. position = position.add(normal);
  32673. position.toArray(positions, index);
  32674. }
  32675. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32676. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32677. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32678. return this;
  32679. };
  32680. /**
  32681. * Modify the mesh to get a flat shading rendering.
  32682. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32683. * This method returns the Mesh.
  32684. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32685. */
  32686. Mesh.prototype.convertToFlatShadedMesh = function () {
  32687. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32688. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32689. var kinds = this.getVerticesDataKinds();
  32690. var vbs = {};
  32691. var data = {};
  32692. var newdata = {};
  32693. var updatableNormals = false;
  32694. var kindIndex;
  32695. var kind;
  32696. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32697. kind = kinds[kindIndex];
  32698. var vertexBuffer = this.getVertexBuffer(kind);
  32699. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32700. updatableNormals = vertexBuffer.isUpdatable();
  32701. kinds.splice(kindIndex, 1);
  32702. kindIndex--;
  32703. continue;
  32704. }
  32705. vbs[kind] = vertexBuffer;
  32706. data[kind] = vbs[kind].getData();
  32707. newdata[kind] = [];
  32708. }
  32709. // Save previous submeshes
  32710. var previousSubmeshes = this.subMeshes.slice(0);
  32711. var indices = this.getIndices();
  32712. var totalIndices = this.getTotalIndices();
  32713. // Generating unique vertices per face
  32714. var index;
  32715. for (index = 0; index < totalIndices; index++) {
  32716. var vertexIndex = indices[index];
  32717. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32718. kind = kinds[kindIndex];
  32719. var stride = vbs[kind].getStrideSize();
  32720. for (var offset = 0; offset < stride; offset++) {
  32721. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32722. }
  32723. }
  32724. }
  32725. // Updating faces & normal
  32726. var normals = [];
  32727. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32728. for (index = 0; index < totalIndices; index += 3) {
  32729. indices[index] = index;
  32730. indices[index + 1] = index + 1;
  32731. indices[index + 2] = index + 2;
  32732. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32733. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32734. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32735. var p1p2 = p1.subtract(p2);
  32736. var p3p2 = p3.subtract(p2);
  32737. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32738. // Store same normals for every vertex
  32739. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32740. normals.push(normal.x);
  32741. normals.push(normal.y);
  32742. normals.push(normal.z);
  32743. }
  32744. }
  32745. this.setIndices(indices);
  32746. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32747. // Updating vertex buffers
  32748. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32749. kind = kinds[kindIndex];
  32750. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32751. }
  32752. // Updating submeshes
  32753. this.releaseSubMeshes();
  32754. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32755. var previousOne = previousSubmeshes[submeshIndex];
  32756. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32757. }
  32758. this.synchronizeInstances();
  32759. return this;
  32760. };
  32761. /**
  32762. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32763. * In other words, more vertices, no more indices and a single bigger VBO.
  32764. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32765. * Returns the Mesh.
  32766. */
  32767. Mesh.prototype.convertToUnIndexedMesh = function () {
  32768. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32769. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32770. var kinds = this.getVerticesDataKinds();
  32771. var vbs = {};
  32772. var data = {};
  32773. var newdata = {};
  32774. var kindIndex;
  32775. var kind;
  32776. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32777. kind = kinds[kindIndex];
  32778. var vertexBuffer = this.getVertexBuffer(kind);
  32779. vbs[kind] = vertexBuffer;
  32780. data[kind] = vbs[kind].getData();
  32781. newdata[kind] = [];
  32782. }
  32783. // Save previous submeshes
  32784. var previousSubmeshes = this.subMeshes.slice(0);
  32785. var indices = this.getIndices();
  32786. var totalIndices = this.getTotalIndices();
  32787. // Generating unique vertices per face
  32788. var index;
  32789. for (index = 0; index < totalIndices; index++) {
  32790. var vertexIndex = indices[index];
  32791. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32792. kind = kinds[kindIndex];
  32793. var stride = vbs[kind].getStrideSize();
  32794. for (var offset = 0; offset < stride; offset++) {
  32795. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32796. }
  32797. }
  32798. }
  32799. // Updating indices
  32800. for (index = 0; index < totalIndices; index += 3) {
  32801. indices[index] = index;
  32802. indices[index + 1] = index + 1;
  32803. indices[index + 2] = index + 2;
  32804. }
  32805. this.setIndices(indices);
  32806. // Updating vertex buffers
  32807. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32808. kind = kinds[kindIndex];
  32809. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32810. }
  32811. // Updating submeshes
  32812. this.releaseSubMeshes();
  32813. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32814. var previousOne = previousSubmeshes[submeshIndex];
  32815. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32816. }
  32817. this._unIndexed = true;
  32818. this.synchronizeInstances();
  32819. return this;
  32820. };
  32821. /**
  32822. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32823. * This method returns the Mesh.
  32824. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32825. */
  32826. Mesh.prototype.flipFaces = function (flipNormals) {
  32827. if (flipNormals === void 0) { flipNormals = false; }
  32828. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32829. var i;
  32830. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32831. for (i = 0; i < vertex_data.normals.length; i++) {
  32832. vertex_data.normals[i] *= -1;
  32833. }
  32834. }
  32835. if (vertex_data.indices) {
  32836. var temp;
  32837. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32838. // reassign indices
  32839. temp = vertex_data.indices[i + 1];
  32840. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32841. vertex_data.indices[i + 2] = temp;
  32842. }
  32843. }
  32844. vertex_data.applyToMesh(this);
  32845. return this;
  32846. };
  32847. // Instances
  32848. /**
  32849. * Creates a new InstancedMesh object from the mesh model.
  32850. * An instance shares the same properties and the same material than its model.
  32851. * Only these properties of each instance can then be set individually :
  32852. * - position
  32853. * - rotation
  32854. * - rotationQuaternion
  32855. * - setPivotMatrix
  32856. * - scaling
  32857. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32858. * Warning : this method is not supported for Line mesh and LineSystem
  32859. */
  32860. Mesh.prototype.createInstance = function (name) {
  32861. return new BABYLON.InstancedMesh(name, this);
  32862. };
  32863. /**
  32864. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32865. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32866. * This method returns the Mesh.
  32867. */
  32868. Mesh.prototype.synchronizeInstances = function () {
  32869. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32870. var instance = this.instances[instanceIndex];
  32871. instance._syncSubMeshes();
  32872. }
  32873. return this;
  32874. };
  32875. /**
  32876. * Simplify the mesh according to the given array of settings.
  32877. * Function will return immediately and will simplify async. It returns the Mesh.
  32878. * @param settings a collection of simplification settings.
  32879. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32880. * @param type the type of simplification to run.
  32881. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32882. */
  32883. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32884. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32885. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32886. this.getScene().simplificationQueue.addTask({
  32887. settings: settings,
  32888. parallelProcessing: parallelProcessing,
  32889. mesh: this,
  32890. simplificationType: simplificationType,
  32891. successCallback: successCallback
  32892. });
  32893. return this;
  32894. };
  32895. /**
  32896. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32897. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32898. * This should be used together with the simplification to avoid disappearing triangles.
  32899. * Returns the Mesh.
  32900. * @param successCallback an optional success callback to be called after the optimization finished.
  32901. */
  32902. Mesh.prototype.optimizeIndices = function (successCallback) {
  32903. var _this = this;
  32904. var indices = this.getIndices();
  32905. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32906. if (!positions || !indices) {
  32907. return this;
  32908. }
  32909. var vectorPositions = new Array();
  32910. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32911. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32912. }
  32913. var dupes = new Array();
  32914. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32915. var realPos = vectorPositions.length - 1 - iteration;
  32916. var testedPosition = vectorPositions[realPos];
  32917. for (var j = 0; j < realPos; ++j) {
  32918. var againstPosition = vectorPositions[j];
  32919. if (testedPosition.equals(againstPosition)) {
  32920. dupes[realPos] = j;
  32921. break;
  32922. }
  32923. }
  32924. }, function () {
  32925. for (var i = 0; i < indices.length; ++i) {
  32926. indices[i] = dupes[indices[i]] || indices[i];
  32927. }
  32928. //indices are now reordered
  32929. var originalSubMeshes = _this.subMeshes.slice(0);
  32930. _this.setIndices(indices);
  32931. _this.subMeshes = originalSubMeshes;
  32932. if (successCallback) {
  32933. successCallback(_this);
  32934. }
  32935. });
  32936. return this;
  32937. };
  32938. Mesh.prototype.serialize = function (serializationObject) {
  32939. serializationObject.name = this.name;
  32940. serializationObject.id = this.id;
  32941. serializationObject.type = this.getClassName();
  32942. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32943. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32944. }
  32945. serializationObject.position = this.position.asArray();
  32946. if (this.rotationQuaternion) {
  32947. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32948. }
  32949. else if (this.rotation) {
  32950. serializationObject.rotation = this.rotation.asArray();
  32951. }
  32952. serializationObject.scaling = this.scaling.asArray();
  32953. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32954. serializationObject.isEnabled = this.isEnabled(false);
  32955. serializationObject.isVisible = this.isVisible;
  32956. serializationObject.infiniteDistance = this.infiniteDistance;
  32957. serializationObject.pickable = this.isPickable;
  32958. serializationObject.receiveShadows = this.receiveShadows;
  32959. serializationObject.billboardMode = this.billboardMode;
  32960. serializationObject.visibility = this.visibility;
  32961. serializationObject.checkCollisions = this.checkCollisions;
  32962. serializationObject.isBlocker = this.isBlocker;
  32963. // Parent
  32964. if (this.parent) {
  32965. serializationObject.parentId = this.parent.id;
  32966. }
  32967. // Geometry
  32968. serializationObject.isUnIndexed = this.isUnIndexed;
  32969. var geometry = this._geometry;
  32970. if (geometry) {
  32971. var geometryId = geometry.id;
  32972. serializationObject.geometryId = geometryId;
  32973. // SubMeshes
  32974. serializationObject.subMeshes = [];
  32975. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32976. var subMesh = this.subMeshes[subIndex];
  32977. serializationObject.subMeshes.push({
  32978. materialIndex: subMesh.materialIndex,
  32979. verticesStart: subMesh.verticesStart,
  32980. verticesCount: subMesh.verticesCount,
  32981. indexStart: subMesh.indexStart,
  32982. indexCount: subMesh.indexCount
  32983. });
  32984. }
  32985. }
  32986. // Material
  32987. if (this.material) {
  32988. serializationObject.materialId = this.material.id;
  32989. }
  32990. else {
  32991. this.material = null;
  32992. }
  32993. // Morph targets
  32994. if (this.morphTargetManager) {
  32995. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32996. }
  32997. // Skeleton
  32998. if (this.skeleton) {
  32999. serializationObject.skeletonId = this.skeleton.id;
  33000. }
  33001. // Physics
  33002. //TODO implement correct serialization for physics impostors.
  33003. var impostor = this.getPhysicsImpostor();
  33004. if (impostor) {
  33005. serializationObject.physicsMass = impostor.getParam("mass");
  33006. serializationObject.physicsFriction = impostor.getParam("friction");
  33007. serializationObject.physicsRestitution = impostor.getParam("mass");
  33008. serializationObject.physicsImpostor = impostor.type;
  33009. }
  33010. // Metadata
  33011. if (this.metadata) {
  33012. serializationObject.metadata = this.metadata;
  33013. }
  33014. // Instances
  33015. serializationObject.instances = [];
  33016. for (var index = 0; index < this.instances.length; index++) {
  33017. var instance = this.instances[index];
  33018. var serializationInstance = {
  33019. name: instance.name,
  33020. id: instance.id,
  33021. position: instance.position.asArray(),
  33022. scaling: instance.scaling.asArray()
  33023. };
  33024. if (instance.rotationQuaternion) {
  33025. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33026. }
  33027. else if (instance.rotation) {
  33028. serializationInstance.rotation = instance.rotation.asArray();
  33029. }
  33030. serializationObject.instances.push(serializationInstance);
  33031. // Animations
  33032. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33033. serializationInstance.ranges = instance.serializeAnimationRanges();
  33034. }
  33035. //
  33036. // Animations
  33037. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33038. serializationObject.ranges = this.serializeAnimationRanges();
  33039. // Layer mask
  33040. serializationObject.layerMask = this.layerMask;
  33041. // Alpha
  33042. serializationObject.alphaIndex = this.alphaIndex;
  33043. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33044. // Overlay
  33045. serializationObject.overlayAlpha = this.overlayAlpha;
  33046. serializationObject.overlayColor = this.overlayColor.asArray();
  33047. serializationObject.renderOverlay = this.renderOverlay;
  33048. // Fog
  33049. serializationObject.applyFog = this.applyFog;
  33050. // Action Manager
  33051. if (this.actionManager) {
  33052. serializationObject.actions = this.actionManager.serialize(this.name);
  33053. }
  33054. };
  33055. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33056. if (!this.geometry) {
  33057. return;
  33058. }
  33059. this._markSubMeshesAsAttributesDirty();
  33060. var morphTargetManager = this._morphTargetManager;
  33061. if (morphTargetManager && morphTargetManager.vertexCount) {
  33062. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33063. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33064. this.morphTargetManager = null;
  33065. return;
  33066. }
  33067. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33068. var morphTarget = morphTargetManager.getActiveTarget(index);
  33069. var positions = morphTarget.getPositions();
  33070. if (!positions) {
  33071. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33072. return;
  33073. }
  33074. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33075. var normals = morphTarget.getNormals();
  33076. if (normals) {
  33077. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33078. }
  33079. var tangents = morphTarget.getTangents();
  33080. if (tangents) {
  33081. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33082. }
  33083. }
  33084. }
  33085. else {
  33086. var index = 0;
  33087. // Positions
  33088. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33089. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33090. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33091. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33092. }
  33093. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33094. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33095. }
  33096. index++;
  33097. }
  33098. }
  33099. };
  33100. // Statics
  33101. /**
  33102. * Returns a new Mesh object parsed from the source provided.
  33103. * The parameter `parsedMesh` is the source.
  33104. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33105. */
  33106. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33107. var mesh;
  33108. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33109. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33110. }
  33111. else {
  33112. mesh = new Mesh(parsedMesh.name, scene);
  33113. }
  33114. mesh.id = parsedMesh.id;
  33115. if (BABYLON.Tags) {
  33116. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33117. }
  33118. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33119. if (parsedMesh.metadata !== undefined) {
  33120. mesh.metadata = parsedMesh.metadata;
  33121. }
  33122. if (parsedMesh.rotationQuaternion) {
  33123. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33124. }
  33125. else if (parsedMesh.rotation) {
  33126. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33127. }
  33128. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33129. if (parsedMesh.localMatrix) {
  33130. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33131. }
  33132. else if (parsedMesh.pivotMatrix) {
  33133. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33134. }
  33135. mesh.setEnabled(parsedMesh.isEnabled);
  33136. mesh.isVisible = parsedMesh.isVisible;
  33137. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33138. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33139. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33140. if (parsedMesh.applyFog !== undefined) {
  33141. mesh.applyFog = parsedMesh.applyFog;
  33142. }
  33143. if (parsedMesh.pickable !== undefined) {
  33144. mesh.isPickable = parsedMesh.pickable;
  33145. }
  33146. if (parsedMesh.alphaIndex !== undefined) {
  33147. mesh.alphaIndex = parsedMesh.alphaIndex;
  33148. }
  33149. mesh.receiveShadows = parsedMesh.receiveShadows;
  33150. mesh.billboardMode = parsedMesh.billboardMode;
  33151. if (parsedMesh.visibility !== undefined) {
  33152. mesh.visibility = parsedMesh.visibility;
  33153. }
  33154. mesh.checkCollisions = parsedMesh.checkCollisions;
  33155. if (parsedMesh.isBlocker !== undefined) {
  33156. mesh.isBlocker = parsedMesh.isBlocker;
  33157. }
  33158. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33159. // freezeWorldMatrix
  33160. if (parsedMesh.freezeWorldMatrix) {
  33161. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33162. }
  33163. // Parent
  33164. if (parsedMesh.parentId) {
  33165. mesh._waitingParentId = parsedMesh.parentId;
  33166. }
  33167. // Actions
  33168. if (parsedMesh.actions !== undefined) {
  33169. mesh._waitingActions = parsedMesh.actions;
  33170. }
  33171. // Overlay
  33172. if (parsedMesh.overlayAlpha !== undefined) {
  33173. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33174. }
  33175. if (parsedMesh.overlayColor !== undefined) {
  33176. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33177. }
  33178. if (parsedMesh.renderOverlay !== undefined) {
  33179. mesh.renderOverlay = parsedMesh.renderOverlay;
  33180. }
  33181. // Geometry
  33182. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33183. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33184. if (parsedMesh.delayLoadingFile) {
  33185. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33186. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33187. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33188. if (parsedMesh._binaryInfo) {
  33189. mesh._binaryInfo = parsedMesh._binaryInfo;
  33190. }
  33191. mesh._delayInfo = [];
  33192. if (parsedMesh.hasUVs) {
  33193. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33194. }
  33195. if (parsedMesh.hasUVs2) {
  33196. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33197. }
  33198. if (parsedMesh.hasUVs3) {
  33199. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33200. }
  33201. if (parsedMesh.hasUVs4) {
  33202. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33203. }
  33204. if (parsedMesh.hasUVs5) {
  33205. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33206. }
  33207. if (parsedMesh.hasUVs6) {
  33208. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33209. }
  33210. if (parsedMesh.hasColors) {
  33211. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33212. }
  33213. if (parsedMesh.hasMatricesIndices) {
  33214. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33215. }
  33216. if (parsedMesh.hasMatricesWeights) {
  33217. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33218. }
  33219. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33220. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33221. mesh._checkDelayState();
  33222. }
  33223. }
  33224. else {
  33225. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33226. }
  33227. // Material
  33228. if (parsedMesh.materialId) {
  33229. mesh.setMaterialByID(parsedMesh.materialId);
  33230. }
  33231. else {
  33232. mesh.material = null;
  33233. }
  33234. // Morph targets
  33235. if (parsedMesh.morphTargetManagerId > -1) {
  33236. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33237. }
  33238. // Skeleton
  33239. if (parsedMesh.skeletonId > -1) {
  33240. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33241. if (parsedMesh.numBoneInfluencers) {
  33242. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33243. }
  33244. }
  33245. // Animations
  33246. if (parsedMesh.animations) {
  33247. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33248. var parsedAnimation = parsedMesh.animations[animationIndex];
  33249. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33250. }
  33251. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33252. }
  33253. if (parsedMesh.autoAnimate) {
  33254. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33255. }
  33256. // Layer Mask
  33257. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33258. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33259. }
  33260. else {
  33261. mesh.layerMask = 0x0FFFFFFF;
  33262. }
  33263. // Physics
  33264. if (parsedMesh.physicsImpostor) {
  33265. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33266. mass: parsedMesh.physicsMass,
  33267. friction: parsedMesh.physicsFriction,
  33268. restitution: parsedMesh.physicsRestitution
  33269. }, scene);
  33270. }
  33271. // Instances
  33272. if (parsedMesh.instances) {
  33273. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33274. var parsedInstance = parsedMesh.instances[index];
  33275. var instance = mesh.createInstance(parsedInstance.name);
  33276. if (parsedInstance.id) {
  33277. instance.id = parsedInstance.id;
  33278. }
  33279. if (BABYLON.Tags) {
  33280. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33281. }
  33282. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33283. if (parsedInstance.parentId) {
  33284. instance._waitingParentId = parsedInstance.parentId;
  33285. }
  33286. if (parsedInstance.rotationQuaternion) {
  33287. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33288. }
  33289. else if (parsedInstance.rotation) {
  33290. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33291. }
  33292. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33293. instance.checkCollisions = mesh.checkCollisions;
  33294. if (parsedMesh.animations) {
  33295. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33296. parsedAnimation = parsedMesh.animations[animationIndex];
  33297. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33298. }
  33299. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33300. }
  33301. }
  33302. }
  33303. return mesh;
  33304. };
  33305. /**
  33306. * Creates a ribbon mesh.
  33307. * Please consider using the same method from the MeshBuilder class instead.
  33308. * 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.
  33309. *
  33310. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33311. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33312. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33313. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33314. * 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.
  33315. * 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.
  33316. * 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
  33317. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33318. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33319. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33320. */
  33321. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33322. if (closeArray === void 0) { closeArray = false; }
  33323. if (updatable === void 0) { updatable = false; }
  33324. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33325. pathArray: pathArray,
  33326. closeArray: closeArray,
  33327. closePath: closePath,
  33328. offset: offset,
  33329. updatable: updatable,
  33330. sideOrientation: sideOrientation,
  33331. instance: instance
  33332. }, scene);
  33333. };
  33334. /**
  33335. * Creates a plane polygonal mesh. By default, this is a disc.
  33336. * Please consider using the same method from the MeshBuilder class instead.
  33337. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33338. * 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.
  33339. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33340. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33341. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33342. */
  33343. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33344. if (scene === void 0) { scene = null; }
  33345. var options = {
  33346. radius: radius,
  33347. tessellation: tessellation,
  33348. sideOrientation: sideOrientation,
  33349. updatable: updatable
  33350. };
  33351. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33352. };
  33353. /**
  33354. * Creates a box mesh.
  33355. * Please consider using the same method from the MeshBuilder class instead.
  33356. * The parameter `size` sets the size (float) of each box side (default 1).
  33357. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33358. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33359. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33360. */
  33361. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33362. if (scene === void 0) { scene = null; }
  33363. var options = {
  33364. size: size,
  33365. sideOrientation: sideOrientation,
  33366. updatable: updatable
  33367. };
  33368. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33369. };
  33370. /**
  33371. * Creates a sphere mesh.
  33372. * Please consider using the same method from the MeshBuilder class instead.
  33373. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33374. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33375. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33376. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33377. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33378. */
  33379. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33380. var options = {
  33381. segments: segments,
  33382. diameterX: diameter,
  33383. diameterY: diameter,
  33384. diameterZ: diameter,
  33385. sideOrientation: sideOrientation,
  33386. updatable: updatable
  33387. };
  33388. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33389. };
  33390. /**
  33391. * Creates a cylinder or a cone mesh.
  33392. * Please consider using the same method from the MeshBuilder class instead.
  33393. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33394. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33395. * 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.
  33396. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33397. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33398. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33399. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33400. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33401. */
  33402. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33403. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33404. if (scene !== undefined) {
  33405. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33406. updatable = scene;
  33407. }
  33408. scene = subdivisions;
  33409. subdivisions = 1;
  33410. }
  33411. var options = {
  33412. height: height,
  33413. diameterTop: diameterTop,
  33414. diameterBottom: diameterBottom,
  33415. tessellation: tessellation,
  33416. subdivisions: subdivisions,
  33417. sideOrientation: sideOrientation,
  33418. updatable: updatable
  33419. };
  33420. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33421. };
  33422. // Torus (Code from SharpDX.org)
  33423. /**
  33424. * Creates a torus mesh.
  33425. * Please consider using the same method from the MeshBuilder class instead.
  33426. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33427. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33428. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33429. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33430. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33432. */
  33433. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33434. var options = {
  33435. diameter: diameter,
  33436. thickness: thickness,
  33437. tessellation: tessellation,
  33438. sideOrientation: sideOrientation,
  33439. updatable: updatable
  33440. };
  33441. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33442. };
  33443. /**
  33444. * Creates a torus knot mesh.
  33445. * Please consider using the same method from the MeshBuilder class instead.
  33446. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33447. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33448. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33449. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33450. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33451. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33452. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33453. */
  33454. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33455. var options = {
  33456. radius: radius,
  33457. tube: tube,
  33458. radialSegments: radialSegments,
  33459. tubularSegments: tubularSegments,
  33460. p: p,
  33461. q: q,
  33462. sideOrientation: sideOrientation,
  33463. updatable: updatable
  33464. };
  33465. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33466. };
  33467. /**
  33468. * Creates a line mesh.
  33469. * Please consider using the same method from the MeshBuilder class instead.
  33470. * 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.
  33471. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33472. * The parameter `points` is an array successive Vector3.
  33473. * 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
  33474. * When updating an instance, remember that only point positions can change, not the number of points.
  33475. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33476. */
  33477. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33478. if (scene === void 0) { scene = null; }
  33479. if (updatable === void 0) { updatable = false; }
  33480. if (instance === void 0) { instance = null; }
  33481. var options = {
  33482. points: points,
  33483. updatable: updatable,
  33484. instance: instance
  33485. };
  33486. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33487. };
  33488. /**
  33489. * Creates a dashed line mesh.
  33490. * Please consider using the same method from the MeshBuilder class instead.
  33491. * 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.
  33492. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33493. * The parameter `points` is an array successive Vector3.
  33494. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33495. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33496. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33497. * 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
  33498. * When updating an instance, remember that only point positions can change, not the number of points.
  33499. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33500. */
  33501. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33502. if (scene === void 0) { scene = null; }
  33503. var options = {
  33504. points: points,
  33505. dashSize: dashSize,
  33506. gapSize: gapSize,
  33507. dashNb: dashNb,
  33508. updatable: updatable,
  33509. instance: instance
  33510. };
  33511. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33512. };
  33513. /**
  33514. * Creates a polygon mesh.
  33515. * Please consider using the same method from the MeshBuilder class instead.
  33516. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33517. * 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.
  33518. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33519. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33520. * Remember you can only change the shape positions, not their number when updating a polygon.
  33521. */
  33522. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33523. var options = {
  33524. shape: shape,
  33525. holes: holes,
  33526. updatable: updatable,
  33527. sideOrientation: sideOrientation
  33528. };
  33529. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33530. };
  33531. /**
  33532. * Creates an extruded polygon mesh, with depth in the Y direction.
  33533. * Please consider using the same method from the MeshBuilder class instead.
  33534. */
  33535. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33536. var options = {
  33537. shape: shape,
  33538. holes: holes,
  33539. depth: depth,
  33540. updatable: updatable,
  33541. sideOrientation: sideOrientation
  33542. };
  33543. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33544. };
  33545. /**
  33546. * Creates an extruded shape mesh.
  33547. * 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.
  33548. * Please consider using the same method from the MeshBuilder class instead.
  33549. *
  33550. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33551. * 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
  33552. * extruded along the Z axis.
  33553. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33554. * 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.
  33555. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33556. * 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
  33557. * 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
  33558. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33559. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33560. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33562. */
  33563. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33564. if (scene === void 0) { scene = null; }
  33565. var options = {
  33566. shape: shape,
  33567. path: path,
  33568. scale: scale,
  33569. rotation: rotation,
  33570. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33571. sideOrientation: sideOrientation,
  33572. instance: instance,
  33573. updatable: updatable
  33574. };
  33575. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33576. };
  33577. /**
  33578. * Creates an custom extruded shape mesh.
  33579. * 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.
  33580. * Please consider using the same method from the MeshBuilder class instead.
  33581. *
  33582. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33583. * 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
  33584. * extruded along the Z axis.
  33585. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33586. * 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
  33587. * and the distance of this point from the begining of the path :
  33588. * ```javascript
  33589. * var rotationFunction = function(i, distance) {
  33590. * // do things
  33591. * return rotationValue; }
  33592. * ```
  33593. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33594. * 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
  33595. * and the distance of this point from the begining of the path :
  33596. * ```javascript
  33597. * var scaleFunction = function(i, distance) {
  33598. * // do things
  33599. * return scaleValue;}
  33600. * ```
  33601. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33602. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33603. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33604. * 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
  33605. * 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
  33606. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33607. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33608. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33609. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33610. */
  33611. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33612. var options = {
  33613. shape: shape,
  33614. path: path,
  33615. scaleFunction: scaleFunction,
  33616. rotationFunction: rotationFunction,
  33617. ribbonCloseArray: ribbonCloseArray,
  33618. ribbonClosePath: ribbonClosePath,
  33619. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33620. sideOrientation: sideOrientation,
  33621. instance: instance,
  33622. updatable: updatable
  33623. };
  33624. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33625. };
  33626. /**
  33627. * Creates lathe mesh.
  33628. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33629. * Please consider using the same method from the MeshBuilder class instead.
  33630. * 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
  33631. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33632. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33633. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33634. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33635. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33636. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33637. */
  33638. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33639. var options = {
  33640. shape: shape,
  33641. radius: radius,
  33642. tessellation: tessellation,
  33643. sideOrientation: sideOrientation,
  33644. updatable: updatable
  33645. };
  33646. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33647. };
  33648. /**
  33649. * Creates a plane mesh.
  33650. * Please consider using the same method from the MeshBuilder class instead.
  33651. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33652. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33653. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33654. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33655. */
  33656. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33657. var options = {
  33658. size: size,
  33659. width: size,
  33660. height: size,
  33661. sideOrientation: sideOrientation,
  33662. updatable: updatable
  33663. };
  33664. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33665. };
  33666. /**
  33667. * Creates a ground mesh.
  33668. * Please consider using the same method from the MeshBuilder class instead.
  33669. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33670. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33671. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33672. */
  33673. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33674. var options = {
  33675. width: width,
  33676. height: height,
  33677. subdivisions: subdivisions,
  33678. updatable: updatable
  33679. };
  33680. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33681. };
  33682. /**
  33683. * Creates a tiled ground mesh.
  33684. * Please consider using the same method from the MeshBuilder class instead.
  33685. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33686. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33687. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33688. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33689. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33690. * numbers of subdivisions on the ground width and height of each tile.
  33691. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33692. */
  33693. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33694. var options = {
  33695. xmin: xmin,
  33696. zmin: zmin,
  33697. xmax: xmax,
  33698. zmax: zmax,
  33699. subdivisions: subdivisions,
  33700. precision: precision,
  33701. updatable: updatable
  33702. };
  33703. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33704. };
  33705. /**
  33706. * Creates a ground mesh from a height map.
  33707. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33708. * Please consider using the same method from the MeshBuilder class instead.
  33709. * The parameter `url` sets the URL of the height map image resource.
  33710. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33711. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33712. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33713. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33714. * 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).
  33715. * This function is passed the newly built mesh :
  33716. * ```javascript
  33717. * function(mesh) { // do things
  33718. * return; }
  33719. * ```
  33720. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33721. */
  33722. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33723. var options = {
  33724. width: width,
  33725. height: height,
  33726. subdivisions: subdivisions,
  33727. minHeight: minHeight,
  33728. maxHeight: maxHeight,
  33729. updatable: updatable,
  33730. onReady: onReady
  33731. };
  33732. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33733. };
  33734. /**
  33735. * Creates a tube mesh.
  33736. * 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.
  33737. * Please consider using the same method from the MeshBuilder class instead.
  33738. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33739. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33740. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33741. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33742. * 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.
  33743. * It must return a radius value (positive float) :
  33744. * ```javascript
  33745. * var radiusFunction = function(i, distance) {
  33746. * // do things
  33747. * return radius; }
  33748. * ```
  33749. * 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
  33750. * 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
  33751. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33752. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33753. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33754. */
  33755. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33756. var options = {
  33757. path: path,
  33758. radius: radius,
  33759. tessellation: tessellation,
  33760. radiusFunction: radiusFunction,
  33761. arc: 1,
  33762. cap: cap,
  33763. updatable: updatable,
  33764. sideOrientation: sideOrientation,
  33765. instance: instance
  33766. };
  33767. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33768. };
  33769. /**
  33770. * Creates a polyhedron mesh.
  33771. * Please consider using the same method from the MeshBuilder class instead.
  33772. * 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
  33773. * to choose the wanted type.
  33774. * The parameter `size` (positive float, default 1) sets the polygon size.
  33775. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33776. * 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`.
  33777. * 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
  33778. * 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)`).
  33779. * 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
  33780. * 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.
  33781. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33782. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33783. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33784. */
  33785. Mesh.CreatePolyhedron = function (name, options, scene) {
  33786. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33787. };
  33788. /**
  33789. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33790. * Please consider using the same method from the MeshBuilder class instead.
  33791. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33792. * 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`).
  33793. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33794. * 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.
  33795. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33796. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33797. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33798. */
  33799. Mesh.CreateIcoSphere = function (name, options, scene) {
  33800. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33801. };
  33802. /**
  33803. * Creates a decal mesh.
  33804. * Please consider using the same method from the MeshBuilder class instead.
  33805. * 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.
  33806. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33807. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33808. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33809. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33810. */
  33811. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33812. var options = {
  33813. position: position,
  33814. normal: normal,
  33815. size: size,
  33816. angle: angle
  33817. };
  33818. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33819. };
  33820. // Skeletons
  33821. /**
  33822. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33823. */
  33824. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33825. if (!this._sourcePositions) {
  33826. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33827. if (!source) {
  33828. return this._sourcePositions;
  33829. }
  33830. this._sourcePositions = new Float32Array(source);
  33831. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33832. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33833. }
  33834. }
  33835. return this._sourcePositions;
  33836. };
  33837. /**
  33838. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33839. */
  33840. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33841. if (!this._sourceNormals) {
  33842. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33843. if (!source) {
  33844. return this._sourceNormals;
  33845. }
  33846. this._sourceNormals = new Float32Array(source);
  33847. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33848. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33849. }
  33850. }
  33851. return this._sourceNormals;
  33852. };
  33853. /**
  33854. * Updates the vertex buffer by applying transformation from the bones.
  33855. * Returns the Mesh.
  33856. *
  33857. * @param {skeleton} skeleton to apply
  33858. */
  33859. Mesh.prototype.applySkeleton = function (skeleton) {
  33860. if (!this.geometry) {
  33861. return this;
  33862. }
  33863. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33864. return this;
  33865. }
  33866. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33867. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33868. return this;
  33869. }
  33870. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33871. return this;
  33872. }
  33873. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33874. return this;
  33875. }
  33876. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33877. return this;
  33878. }
  33879. if (!this._sourcePositions) {
  33880. var submeshes = this.subMeshes.slice();
  33881. this.setPositionsForCPUSkinning();
  33882. this.subMeshes = submeshes;
  33883. }
  33884. if (!this._sourceNormals) {
  33885. this.setNormalsForCPUSkinning();
  33886. }
  33887. // positionsData checks for not being Float32Array will only pass at most once
  33888. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33889. if (!positionsData) {
  33890. return this;
  33891. }
  33892. if (!(positionsData instanceof Float32Array)) {
  33893. positionsData = new Float32Array(positionsData);
  33894. }
  33895. // normalsData checks for not being Float32Array will only pass at most once
  33896. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33897. if (!normalsData) {
  33898. return this;
  33899. }
  33900. if (!(normalsData instanceof Float32Array)) {
  33901. normalsData = new Float32Array(normalsData);
  33902. }
  33903. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33904. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33905. if (!matricesWeightsData || !matricesIndicesData) {
  33906. return this;
  33907. }
  33908. var needExtras = this.numBoneInfluencers > 4;
  33909. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33910. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33911. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33912. var tempVector3 = BABYLON.Vector3.Zero();
  33913. var finalMatrix = new BABYLON.Matrix();
  33914. var tempMatrix = new BABYLON.Matrix();
  33915. var matWeightIdx = 0;
  33916. var inf;
  33917. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33918. var weight;
  33919. for (inf = 0; inf < 4; inf++) {
  33920. weight = matricesWeightsData[matWeightIdx + inf];
  33921. if (weight > 0) {
  33922. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33923. finalMatrix.addToSelf(tempMatrix);
  33924. }
  33925. else
  33926. break;
  33927. }
  33928. if (needExtras) {
  33929. for (inf = 0; inf < 4; inf++) {
  33930. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33931. if (weight > 0) {
  33932. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33933. finalMatrix.addToSelf(tempMatrix);
  33934. }
  33935. else
  33936. break;
  33937. }
  33938. }
  33939. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33940. tempVector3.toArray(positionsData, index);
  33941. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33942. tempVector3.toArray(normalsData, index);
  33943. finalMatrix.reset();
  33944. }
  33945. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33946. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33947. return this;
  33948. };
  33949. // Tools
  33950. /**
  33951. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33952. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33953. */
  33954. Mesh.MinMax = function (meshes) {
  33955. var minVector = null;
  33956. var maxVector = null;
  33957. meshes.forEach(function (mesh, index, array) {
  33958. var boundingInfo = mesh.getBoundingInfo();
  33959. var boundingBox = boundingInfo.boundingBox;
  33960. if (!minVector || !maxVector) {
  33961. minVector = boundingBox.minimumWorld;
  33962. maxVector = boundingBox.maximumWorld;
  33963. }
  33964. else {
  33965. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33966. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33967. }
  33968. });
  33969. if (!minVector || !maxVector) {
  33970. return {
  33971. min: BABYLON.Vector3.Zero(),
  33972. max: BABYLON.Vector3.Zero()
  33973. };
  33974. }
  33975. return {
  33976. min: minVector,
  33977. max: maxVector
  33978. };
  33979. };
  33980. /**
  33981. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33982. */
  33983. Mesh.Center = function (meshesOrMinMaxVector) {
  33984. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33985. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33986. };
  33987. /**
  33988. * Merge the array of meshes into a single mesh for performance reasons.
  33989. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33990. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33991. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33992. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33993. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33994. */
  33995. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33996. if (disposeSource === void 0) { disposeSource = true; }
  33997. var index;
  33998. if (!allow32BitsIndices) {
  33999. var totalVertices = 0;
  34000. // Counting vertices
  34001. for (index = 0; index < meshes.length; index++) {
  34002. if (meshes[index]) {
  34003. totalVertices += meshes[index].getTotalVertices();
  34004. if (totalVertices > 65536) {
  34005. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34006. return null;
  34007. }
  34008. }
  34009. }
  34010. }
  34011. // Merge
  34012. var vertexData = null;
  34013. var otherVertexData;
  34014. var indiceArray = new Array();
  34015. var source = null;
  34016. for (index = 0; index < meshes.length; index++) {
  34017. if (meshes[index]) {
  34018. meshes[index].computeWorldMatrix(true);
  34019. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  34020. otherVertexData.transform(meshes[index].getWorldMatrix());
  34021. if (vertexData) {
  34022. vertexData.merge(otherVertexData);
  34023. }
  34024. else {
  34025. vertexData = otherVertexData;
  34026. source = meshes[index];
  34027. }
  34028. if (subdivideWithSubMeshes) {
  34029. indiceArray.push(meshes[index].getTotalIndices());
  34030. }
  34031. }
  34032. }
  34033. source = source;
  34034. if (!meshSubclass) {
  34035. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34036. }
  34037. vertexData.applyToMesh(meshSubclass);
  34038. // Setting properties
  34039. meshSubclass.material = source.material;
  34040. meshSubclass.checkCollisions = source.checkCollisions;
  34041. // Cleaning
  34042. if (disposeSource) {
  34043. for (index = 0; index < meshes.length; index++) {
  34044. if (meshes[index]) {
  34045. meshes[index].dispose();
  34046. }
  34047. }
  34048. }
  34049. // Subdivide
  34050. if (subdivideWithSubMeshes) {
  34051. //-- Suppresions du submesh global
  34052. meshSubclass.releaseSubMeshes();
  34053. index = 0;
  34054. var offset = 0;
  34055. //-- aplique la subdivision en fonction du tableau d'indices
  34056. while (index < indiceArray.length) {
  34057. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34058. offset += indiceArray[index];
  34059. index++;
  34060. }
  34061. }
  34062. return meshSubclass;
  34063. };
  34064. // Consts
  34065. Mesh._FRONTSIDE = 0;
  34066. Mesh._BACKSIDE = 1;
  34067. Mesh._DOUBLESIDE = 2;
  34068. Mesh._DEFAULTSIDE = 0;
  34069. Mesh._NO_CAP = 0;
  34070. Mesh._CAP_START = 1;
  34071. Mesh._CAP_END = 2;
  34072. Mesh._CAP_ALL = 3;
  34073. return Mesh;
  34074. }(BABYLON.AbstractMesh));
  34075. BABYLON.Mesh = Mesh;
  34076. })(BABYLON || (BABYLON = {}));
  34077. //# sourceMappingURL=babylon.mesh.js.map
  34078. var BABYLON;
  34079. (function (BABYLON) {
  34080. var BaseSubMesh = /** @class */ (function () {
  34081. function BaseSubMesh() {
  34082. }
  34083. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34084. get: function () {
  34085. return this._materialEffect;
  34086. },
  34087. enumerable: true,
  34088. configurable: true
  34089. });
  34090. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34091. if (defines === void 0) { defines = null; }
  34092. if (this._materialEffect === effect) {
  34093. if (!effect) {
  34094. this._materialDefines = null;
  34095. }
  34096. return;
  34097. }
  34098. this._materialDefines = defines;
  34099. this._materialEffect = effect;
  34100. };
  34101. return BaseSubMesh;
  34102. }());
  34103. BABYLON.BaseSubMesh = BaseSubMesh;
  34104. var SubMesh = /** @class */ (function (_super) {
  34105. __extends(SubMesh, _super);
  34106. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34107. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34108. var _this = _super.call(this) || this;
  34109. _this.materialIndex = materialIndex;
  34110. _this.verticesStart = verticesStart;
  34111. _this.verticesCount = verticesCount;
  34112. _this.indexStart = indexStart;
  34113. _this.indexCount = indexCount;
  34114. _this._renderId = 0;
  34115. _this._mesh = mesh;
  34116. _this._renderingMesh = renderingMesh || mesh;
  34117. mesh.subMeshes.push(_this);
  34118. _this._trianglePlanes = [];
  34119. _this._id = mesh.subMeshes.length - 1;
  34120. if (createBoundingBox) {
  34121. _this.refreshBoundingInfo();
  34122. mesh.computeWorldMatrix(true);
  34123. }
  34124. return _this;
  34125. }
  34126. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34127. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34128. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34129. };
  34130. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34131. get: function () {
  34132. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34133. },
  34134. enumerable: true,
  34135. configurable: true
  34136. });
  34137. /**
  34138. * Returns the submesh BoudingInfo object.
  34139. */
  34140. SubMesh.prototype.getBoundingInfo = function () {
  34141. if (this.IsGlobal) {
  34142. return this._mesh.getBoundingInfo();
  34143. }
  34144. return this._boundingInfo;
  34145. };
  34146. /**
  34147. * Sets the submesh BoundingInfo.
  34148. * Return the SubMesh.
  34149. */
  34150. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34151. this._boundingInfo = boundingInfo;
  34152. return this;
  34153. };
  34154. /**
  34155. * Returns the mesh of the current submesh.
  34156. */
  34157. SubMesh.prototype.getMesh = function () {
  34158. return this._mesh;
  34159. };
  34160. /**
  34161. * Returns the rendering mesh of the submesh.
  34162. */
  34163. SubMesh.prototype.getRenderingMesh = function () {
  34164. return this._renderingMesh;
  34165. };
  34166. /**
  34167. * Returns the submesh material.
  34168. */
  34169. SubMesh.prototype.getMaterial = function () {
  34170. var rootMaterial = this._renderingMesh.material;
  34171. if (rootMaterial === null || rootMaterial === undefined) {
  34172. return this._mesh.getScene().defaultMaterial;
  34173. }
  34174. else if (rootMaterial.getSubMaterial) {
  34175. var multiMaterial = rootMaterial;
  34176. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34177. if (this._currentMaterial !== effectiveMaterial) {
  34178. this._currentMaterial = effectiveMaterial;
  34179. this._materialDefines = null;
  34180. }
  34181. return effectiveMaterial;
  34182. }
  34183. return rootMaterial;
  34184. };
  34185. // Methods
  34186. /**
  34187. * Sets a new updated BoundingInfo object to the submesh.
  34188. * Returns the SubMesh.
  34189. */
  34190. SubMesh.prototype.refreshBoundingInfo = function () {
  34191. this._lastColliderWorldVertices = null;
  34192. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34193. return this;
  34194. }
  34195. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34196. if (!data) {
  34197. this._boundingInfo = this._mesh.getBoundingInfo();
  34198. return this;
  34199. }
  34200. var indices = this._renderingMesh.getIndices();
  34201. var extend;
  34202. //is this the only submesh?
  34203. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34204. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34205. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34206. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34207. }
  34208. else {
  34209. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34210. }
  34211. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34212. return this;
  34213. };
  34214. SubMesh.prototype._checkCollision = function (collider) {
  34215. var boundingInfo = this.getBoundingInfo();
  34216. return boundingInfo._checkCollision(collider);
  34217. };
  34218. /**
  34219. * Updates the submesh BoundingInfo.
  34220. * Returns the Submesh.
  34221. */
  34222. SubMesh.prototype.updateBoundingInfo = function (world) {
  34223. var boundingInfo = this.getBoundingInfo();
  34224. if (!boundingInfo) {
  34225. this.refreshBoundingInfo();
  34226. boundingInfo = this.getBoundingInfo();
  34227. }
  34228. boundingInfo.update(world);
  34229. return this;
  34230. };
  34231. /**
  34232. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34233. * Boolean returned.
  34234. */
  34235. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34236. var boundingInfo = this.getBoundingInfo();
  34237. if (!boundingInfo) {
  34238. return false;
  34239. }
  34240. return boundingInfo.isInFrustum(frustumPlanes);
  34241. };
  34242. /**
  34243. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34244. * Boolean returned.
  34245. */
  34246. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34247. var boundingInfo = this.getBoundingInfo();
  34248. if (!boundingInfo) {
  34249. return false;
  34250. }
  34251. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34252. };
  34253. /**
  34254. * Renders the submesh.
  34255. * Returns it.
  34256. */
  34257. SubMesh.prototype.render = function (enableAlphaMode) {
  34258. this._renderingMesh.render(this, enableAlphaMode);
  34259. return this;
  34260. };
  34261. /**
  34262. * Returns a new Index Buffer.
  34263. * Type returned : WebGLBuffer.
  34264. */
  34265. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34266. if (!this._linesIndexBuffer) {
  34267. var linesIndices = [];
  34268. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34269. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34270. }
  34271. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34272. this.linesIndexCount = linesIndices.length;
  34273. }
  34274. return this._linesIndexBuffer;
  34275. };
  34276. /**
  34277. * True is the passed Ray intersects the submesh bounding box.
  34278. * Boolean returned.
  34279. */
  34280. SubMesh.prototype.canIntersects = function (ray) {
  34281. var boundingInfo = this.getBoundingInfo();
  34282. if (!boundingInfo) {
  34283. return false;
  34284. }
  34285. return ray.intersectsBox(boundingInfo.boundingBox);
  34286. };
  34287. /**
  34288. * Returns an object IntersectionInfo.
  34289. */
  34290. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34291. var intersectInfo = null;
  34292. var material = this.getMaterial();
  34293. if (!material) {
  34294. return null;
  34295. }
  34296. switch (material.fillMode) {
  34297. case BABYLON.Material.PointListDrawMode:
  34298. case BABYLON.Material.LineListDrawMode:
  34299. case BABYLON.Material.LineLoopDrawMode:
  34300. case BABYLON.Material.LineStripDrawMode:
  34301. case BABYLON.Material.TriangleFanDrawMode:
  34302. case BABYLON.Material.TriangleStripDrawMode:
  34303. return null;
  34304. }
  34305. // LineMesh first as it's also a Mesh...
  34306. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34307. var lineMesh = this._mesh;
  34308. // Line test
  34309. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34310. var p0 = positions[indices[index]];
  34311. var p1 = positions[indices[index + 1]];
  34312. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34313. if (length < 0) {
  34314. continue;
  34315. }
  34316. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34317. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34318. if (fastCheck) {
  34319. break;
  34320. }
  34321. }
  34322. }
  34323. }
  34324. else {
  34325. // Triangles test
  34326. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34327. var p0 = positions[indices[index]];
  34328. var p1 = positions[indices[index + 1]];
  34329. var p2 = positions[indices[index + 2]];
  34330. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34331. if (currentIntersectInfo) {
  34332. if (currentIntersectInfo.distance < 0) {
  34333. continue;
  34334. }
  34335. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34336. intersectInfo = currentIntersectInfo;
  34337. intersectInfo.faceId = index / 3;
  34338. if (fastCheck) {
  34339. break;
  34340. }
  34341. }
  34342. }
  34343. }
  34344. }
  34345. return intersectInfo;
  34346. };
  34347. SubMesh.prototype._rebuild = function () {
  34348. if (this._linesIndexBuffer) {
  34349. this._linesIndexBuffer = null;
  34350. }
  34351. };
  34352. // Clone
  34353. /**
  34354. * Creates a new Submesh from the passed Mesh.
  34355. */
  34356. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34357. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34358. if (!this.IsGlobal) {
  34359. var boundingInfo = this.getBoundingInfo();
  34360. if (!boundingInfo) {
  34361. return result;
  34362. }
  34363. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34364. }
  34365. return result;
  34366. };
  34367. // Dispose
  34368. /**
  34369. * Disposes the Submesh.
  34370. * Returns nothing.
  34371. */
  34372. SubMesh.prototype.dispose = function () {
  34373. if (this._linesIndexBuffer) {
  34374. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34375. this._linesIndexBuffer = null;
  34376. }
  34377. // Remove from mesh
  34378. var index = this._mesh.subMeshes.indexOf(this);
  34379. this._mesh.subMeshes.splice(index, 1);
  34380. };
  34381. // Statics
  34382. /**
  34383. * Creates a new Submesh from the passed parameters :
  34384. * - materialIndex (integer) : the index of the main mesh material.
  34385. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34386. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34387. * - mesh (Mesh) : the main mesh to create the submesh from.
  34388. * - renderingMesh (optional Mesh) : rendering mesh.
  34389. */
  34390. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34391. var minVertexIndex = Number.MAX_VALUE;
  34392. var maxVertexIndex = -Number.MAX_VALUE;
  34393. renderingMesh = (renderingMesh || mesh);
  34394. var indices = renderingMesh.getIndices();
  34395. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34396. var vertexIndex = indices[index];
  34397. if (vertexIndex < minVertexIndex)
  34398. minVertexIndex = vertexIndex;
  34399. if (vertexIndex > maxVertexIndex)
  34400. maxVertexIndex = vertexIndex;
  34401. }
  34402. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34403. };
  34404. return SubMesh;
  34405. }(BaseSubMesh));
  34406. BABYLON.SubMesh = SubMesh;
  34407. })(BABYLON || (BABYLON = {}));
  34408. //# sourceMappingURL=babylon.subMesh.js.map
  34409. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34410. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34411. s = arguments[i];
  34412. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34413. t[p] = s[p];
  34414. }
  34415. return t;
  34416. };
  34417. var BABYLON;
  34418. (function (BABYLON) {
  34419. /**
  34420. * Manages the defines for the Material
  34421. */
  34422. var MaterialDefines = /** @class */ (function () {
  34423. function MaterialDefines() {
  34424. this._isDirty = true;
  34425. /** @hidden */
  34426. this._areLightsDirty = true;
  34427. /** @hidden */
  34428. this._areAttributesDirty = true;
  34429. /** @hidden */
  34430. this._areTexturesDirty = true;
  34431. /** @hidden */
  34432. this._areFresnelDirty = true;
  34433. /** @hidden */
  34434. this._areMiscDirty = true;
  34435. /** @hidden */
  34436. this._areImageProcessingDirty = true;
  34437. /** @hidden */
  34438. this._normals = false;
  34439. /** @hidden */
  34440. this._uvs = false;
  34441. /** @hidden */
  34442. this._needNormals = false;
  34443. /** @hidden */
  34444. this._needUVs = false;
  34445. }
  34446. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34447. /**
  34448. * Specifies if the material needs to be re-calculated
  34449. */
  34450. get: function () {
  34451. return this._isDirty;
  34452. },
  34453. enumerable: true,
  34454. configurable: true
  34455. });
  34456. /**
  34457. * Marks the material to indicate that it has been re-calculated
  34458. */
  34459. MaterialDefines.prototype.markAsProcessed = function () {
  34460. this._isDirty = false;
  34461. this._areAttributesDirty = false;
  34462. this._areTexturesDirty = false;
  34463. this._areFresnelDirty = false;
  34464. this._areLightsDirty = false;
  34465. this._areMiscDirty = false;
  34466. this._areImageProcessingDirty = false;
  34467. };
  34468. /**
  34469. * Marks the material to indicate that it needs to be re-calculated
  34470. */
  34471. MaterialDefines.prototype.markAsUnprocessed = function () {
  34472. this._isDirty = true;
  34473. };
  34474. /**
  34475. * Marks the material to indicate all of its defines need to be re-calculated
  34476. */
  34477. MaterialDefines.prototype.markAllAsDirty = function () {
  34478. this._areTexturesDirty = true;
  34479. this._areAttributesDirty = true;
  34480. this._areLightsDirty = true;
  34481. this._areFresnelDirty = true;
  34482. this._areMiscDirty = true;
  34483. this._areImageProcessingDirty = true;
  34484. this._isDirty = true;
  34485. };
  34486. /**
  34487. * Marks the material to indicate that image processing needs to be re-calculated
  34488. */
  34489. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34490. this._areImageProcessingDirty = true;
  34491. this._isDirty = true;
  34492. };
  34493. /**
  34494. * Marks the material to indicate the lights need to be re-calculated
  34495. */
  34496. MaterialDefines.prototype.markAsLightDirty = function () {
  34497. this._areLightsDirty = true;
  34498. this._isDirty = true;
  34499. };
  34500. /**
  34501. * Marks the attribute state as changed
  34502. */
  34503. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34504. this._areAttributesDirty = true;
  34505. this._isDirty = true;
  34506. };
  34507. /**
  34508. * Marks the texture state as changed
  34509. */
  34510. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34511. this._areTexturesDirty = true;
  34512. this._isDirty = true;
  34513. };
  34514. /**
  34515. * Marks the fresnel state as changed
  34516. */
  34517. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34518. this._areFresnelDirty = true;
  34519. this._isDirty = true;
  34520. };
  34521. /**
  34522. * Marks the misc state as changed
  34523. */
  34524. MaterialDefines.prototype.markAsMiscDirty = function () {
  34525. this._areMiscDirty = true;
  34526. this._isDirty = true;
  34527. };
  34528. /**
  34529. * Rebuilds the material defines
  34530. */
  34531. MaterialDefines.prototype.rebuild = function () {
  34532. if (this._keys) {
  34533. delete this._keys;
  34534. }
  34535. this._keys = [];
  34536. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34537. var key = _a[_i];
  34538. if (key[0] === "_") {
  34539. continue;
  34540. }
  34541. this._keys.push(key);
  34542. }
  34543. };
  34544. /**
  34545. * Specifies if two material defines are equal
  34546. * @param other - A material define instance to compare to
  34547. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34548. */
  34549. MaterialDefines.prototype.isEqual = function (other) {
  34550. if (this._keys.length !== other._keys.length) {
  34551. return false;
  34552. }
  34553. for (var index = 0; index < this._keys.length; index++) {
  34554. var prop = this._keys[index];
  34555. if (this[prop] !== other[prop]) {
  34556. return false;
  34557. }
  34558. }
  34559. return true;
  34560. };
  34561. /**
  34562. * Clones this instance's defines to another instance
  34563. * @param other - material defines to clone values to
  34564. */
  34565. MaterialDefines.prototype.cloneTo = function (other) {
  34566. if (this._keys.length !== other._keys.length) {
  34567. other._keys = this._keys.slice(0);
  34568. }
  34569. for (var index = 0; index < this._keys.length; index++) {
  34570. var prop = this._keys[index];
  34571. other[prop] = this[prop];
  34572. }
  34573. };
  34574. /**
  34575. * Resets the material define values
  34576. */
  34577. MaterialDefines.prototype.reset = function () {
  34578. for (var index = 0; index < this._keys.length; index++) {
  34579. var prop = this._keys[index];
  34580. var type = typeof this[prop];
  34581. switch (type) {
  34582. case "number":
  34583. this[prop] = 0;
  34584. break;
  34585. case "string":
  34586. this[prop] = "";
  34587. break;
  34588. default:
  34589. this[prop] = false;
  34590. break;
  34591. }
  34592. }
  34593. };
  34594. /**
  34595. * Converts the material define values to a string
  34596. * @returns - String of material define information
  34597. */
  34598. MaterialDefines.prototype.toString = function () {
  34599. var result = "";
  34600. for (var index = 0; index < this._keys.length; index++) {
  34601. var prop = this._keys[index];
  34602. var value = this[prop];
  34603. var type = typeof value;
  34604. switch (type) {
  34605. case "number":
  34606. case "string":
  34607. result += "#define " + prop + " " + value + "\n";
  34608. break;
  34609. default:
  34610. if (value) {
  34611. result += "#define " + prop + "\n";
  34612. }
  34613. break;
  34614. }
  34615. }
  34616. return result;
  34617. };
  34618. return MaterialDefines;
  34619. }());
  34620. BABYLON.MaterialDefines = MaterialDefines;
  34621. /**
  34622. * Base class for the main features of a material in Babylon.js
  34623. */
  34624. var Material = /** @class */ (function () {
  34625. /**
  34626. * Creates a material instance
  34627. * @param name defines the name of the material
  34628. * @param scene defines the scene to reference
  34629. * @param doNotAdd specifies if the material should be added to the scene
  34630. */
  34631. function Material(name, scene, doNotAdd) {
  34632. /**
  34633. * Specifies if the ready state should be checked on each call
  34634. */
  34635. this.checkReadyOnEveryCall = false;
  34636. /**
  34637. * Specifies if the ready state should be checked once
  34638. */
  34639. this.checkReadyOnlyOnce = false;
  34640. /**
  34641. * The state of the material
  34642. */
  34643. this.state = "";
  34644. /**
  34645. * The alpha value of the material
  34646. */
  34647. this._alpha = 1.0;
  34648. /**
  34649. * Specifies if back face culling is enabled
  34650. */
  34651. this._backFaceCulling = true;
  34652. /**
  34653. * Specifies if the material should be serialized
  34654. */
  34655. this.doNotSerialize = false;
  34656. /**
  34657. * Specifies if the effect should be stored on sub meshes
  34658. */
  34659. this.storeEffectOnSubMeshes = false;
  34660. /**
  34661. * An event triggered when the material is disposed
  34662. */
  34663. this.onDisposeObservable = new BABYLON.Observable();
  34664. /**
  34665. * An event triggered when the material is bound
  34666. */
  34667. this.onBindObservable = new BABYLON.Observable();
  34668. /**
  34669. * An event triggered when the material is unbound
  34670. */
  34671. this.onUnBindObservable = new BABYLON.Observable();
  34672. /**
  34673. * Stores the value of the alpha mode
  34674. */
  34675. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34676. /**
  34677. * Stores the state of the need depth pre-pass value
  34678. */
  34679. this._needDepthPrePass = false;
  34680. /**
  34681. * Specifies if depth writing should be disabled
  34682. */
  34683. this.disableDepthWrite = false;
  34684. /**
  34685. * Specifies if depth writing should be forced
  34686. */
  34687. this.forceDepthWrite = false;
  34688. /**
  34689. * Specifies if there should be a separate pass for culling
  34690. */
  34691. this.separateCullingPass = false;
  34692. /**
  34693. * Stores the state specifing if fog should be enabled
  34694. */
  34695. this._fogEnabled = true;
  34696. /**
  34697. * Stores the size of points
  34698. */
  34699. this.pointSize = 1.0;
  34700. /**
  34701. * Stores the z offset value
  34702. */
  34703. this.zOffset = 0;
  34704. /**
  34705. * Specifies if the material was previously ready
  34706. */
  34707. this._wasPreviouslyReady = false;
  34708. /**
  34709. * Stores the fill mode state
  34710. */
  34711. this._fillMode = Material.TriangleFillMode;
  34712. this.name = name;
  34713. this.id = name || BABYLON.Tools.RandomId();
  34714. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34715. if (this._scene.useRightHandedSystem) {
  34716. this.sideOrientation = Material.ClockWiseSideOrientation;
  34717. }
  34718. else {
  34719. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34720. }
  34721. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34722. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34723. if (!doNotAdd) {
  34724. this._scene.materials.push(this);
  34725. }
  34726. }
  34727. Object.defineProperty(Material, "TriangleFillMode", {
  34728. /**
  34729. * Returns the triangle fill mode
  34730. */
  34731. get: function () {
  34732. return Material._TriangleFillMode;
  34733. },
  34734. enumerable: true,
  34735. configurable: true
  34736. });
  34737. Object.defineProperty(Material, "WireFrameFillMode", {
  34738. /**
  34739. * Returns the wireframe mode
  34740. */
  34741. get: function () {
  34742. return Material._WireFrameFillMode;
  34743. },
  34744. enumerable: true,
  34745. configurable: true
  34746. });
  34747. Object.defineProperty(Material, "PointFillMode", {
  34748. /**
  34749. * Returns the point fill mode
  34750. */
  34751. get: function () {
  34752. return Material._PointFillMode;
  34753. },
  34754. enumerable: true,
  34755. configurable: true
  34756. });
  34757. Object.defineProperty(Material, "PointListDrawMode", {
  34758. /**
  34759. * Returns the point list draw mode
  34760. */
  34761. get: function () {
  34762. return Material._PointListDrawMode;
  34763. },
  34764. enumerable: true,
  34765. configurable: true
  34766. });
  34767. Object.defineProperty(Material, "LineListDrawMode", {
  34768. /**
  34769. * Returns the line list draw mode
  34770. */
  34771. get: function () {
  34772. return Material._LineListDrawMode;
  34773. },
  34774. enumerable: true,
  34775. configurable: true
  34776. });
  34777. Object.defineProperty(Material, "LineLoopDrawMode", {
  34778. /**
  34779. * Returns the line loop draw mode
  34780. */
  34781. get: function () {
  34782. return Material._LineLoopDrawMode;
  34783. },
  34784. enumerable: true,
  34785. configurable: true
  34786. });
  34787. Object.defineProperty(Material, "LineStripDrawMode", {
  34788. /**
  34789. * Returns the line strip draw mode
  34790. */
  34791. get: function () {
  34792. return Material._LineStripDrawMode;
  34793. },
  34794. enumerable: true,
  34795. configurable: true
  34796. });
  34797. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34798. /**
  34799. * Returns the triangle strip draw mode
  34800. */
  34801. get: function () {
  34802. return Material._TriangleStripDrawMode;
  34803. },
  34804. enumerable: true,
  34805. configurable: true
  34806. });
  34807. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34808. /**
  34809. * Returns the triangle fan draw mode
  34810. */
  34811. get: function () {
  34812. return Material._TriangleFanDrawMode;
  34813. },
  34814. enumerable: true,
  34815. configurable: true
  34816. });
  34817. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34818. /**
  34819. * Returns the clock-wise side orientation
  34820. */
  34821. get: function () {
  34822. return Material._ClockWiseSideOrientation;
  34823. },
  34824. enumerable: true,
  34825. configurable: true
  34826. });
  34827. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34828. /**
  34829. * Returns the counter clock-wise side orientation
  34830. */
  34831. get: function () {
  34832. return Material._CounterClockWiseSideOrientation;
  34833. },
  34834. enumerable: true,
  34835. configurable: true
  34836. });
  34837. Object.defineProperty(Material, "TextureDirtyFlag", {
  34838. /**
  34839. * Returns the dirty texture flag value
  34840. */
  34841. get: function () {
  34842. return Material._TextureDirtyFlag;
  34843. },
  34844. enumerable: true,
  34845. configurable: true
  34846. });
  34847. Object.defineProperty(Material, "LightDirtyFlag", {
  34848. /**
  34849. * Returns the dirty light flag value
  34850. */
  34851. get: function () {
  34852. return Material._LightDirtyFlag;
  34853. },
  34854. enumerable: true,
  34855. configurable: true
  34856. });
  34857. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34858. /**
  34859. * Returns the dirty fresnel flag value
  34860. */
  34861. get: function () {
  34862. return Material._FresnelDirtyFlag;
  34863. },
  34864. enumerable: true,
  34865. configurable: true
  34866. });
  34867. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34868. /**
  34869. * Returns the dirty attributes flag value
  34870. */
  34871. get: function () {
  34872. return Material._AttributesDirtyFlag;
  34873. },
  34874. enumerable: true,
  34875. configurable: true
  34876. });
  34877. Object.defineProperty(Material, "MiscDirtyFlag", {
  34878. /**
  34879. * Returns the dirty misc flag value
  34880. */
  34881. get: function () {
  34882. return Material._MiscDirtyFlag;
  34883. },
  34884. enumerable: true,
  34885. configurable: true
  34886. });
  34887. Object.defineProperty(Material.prototype, "alpha", {
  34888. /**
  34889. * Gets the alpha value of the material
  34890. */
  34891. get: function () {
  34892. return this._alpha;
  34893. },
  34894. /**
  34895. * Sets the alpha value of the material
  34896. */
  34897. set: function (value) {
  34898. if (this._alpha === value) {
  34899. return;
  34900. }
  34901. this._alpha = value;
  34902. this.markAsDirty(Material.MiscDirtyFlag);
  34903. },
  34904. enumerable: true,
  34905. configurable: true
  34906. });
  34907. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34908. /**
  34909. * Gets the back-face culling state
  34910. */
  34911. get: function () {
  34912. return this._backFaceCulling;
  34913. },
  34914. /**
  34915. * Sets the back-face culling state
  34916. */
  34917. set: function (value) {
  34918. if (this._backFaceCulling === value) {
  34919. return;
  34920. }
  34921. this._backFaceCulling = value;
  34922. this.markAsDirty(Material.TextureDirtyFlag);
  34923. },
  34924. enumerable: true,
  34925. configurable: true
  34926. });
  34927. Object.defineProperty(Material.prototype, "onDispose", {
  34928. /**
  34929. * Called during a dispose event
  34930. */
  34931. set: function (callback) {
  34932. if (this._onDisposeObserver) {
  34933. this.onDisposeObservable.remove(this._onDisposeObserver);
  34934. }
  34935. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34936. },
  34937. enumerable: true,
  34938. configurable: true
  34939. });
  34940. Object.defineProperty(Material.prototype, "onBind", {
  34941. /**
  34942. * Called during a bind event
  34943. */
  34944. set: function (callback) {
  34945. if (this._onBindObserver) {
  34946. this.onBindObservable.remove(this._onBindObserver);
  34947. }
  34948. this._onBindObserver = this.onBindObservable.add(callback);
  34949. },
  34950. enumerable: true,
  34951. configurable: true
  34952. });
  34953. Object.defineProperty(Material.prototype, "alphaMode", {
  34954. /**
  34955. * Gets the value of the alpha mode
  34956. */
  34957. get: function () {
  34958. return this._alphaMode;
  34959. },
  34960. /**
  34961. * Sets the value of the alpha mode.
  34962. *
  34963. * | Value | Type | Description |
  34964. * | --- | --- | --- |
  34965. * | 0 | ALPHA_DISABLE | |
  34966. * | 1 | ALPHA_ADD | |
  34967. * | 2 | ALPHA_COMBINE | |
  34968. * | 3 | ALPHA_SUBTRACT | |
  34969. * | 4 | ALPHA_MULTIPLY | |
  34970. * | 5 | ALPHA_MAXIMIZED | |
  34971. * | 6 | ALPHA_ONEONE | |
  34972. * | 7 | ALPHA_PREMULTIPLIED | |
  34973. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34974. * | 9 | ALPHA_INTERPOLATE | |
  34975. * | 10 | ALPHA_SCREENMODE | |
  34976. *
  34977. */
  34978. set: function (value) {
  34979. if (this._alphaMode === value) {
  34980. return;
  34981. }
  34982. this._alphaMode = value;
  34983. this.markAsDirty(Material.TextureDirtyFlag);
  34984. },
  34985. enumerable: true,
  34986. configurable: true
  34987. });
  34988. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34989. /**
  34990. * Gets the depth pre-pass value
  34991. */
  34992. get: function () {
  34993. return this._needDepthPrePass;
  34994. },
  34995. /**
  34996. * Sets the need depth pre-pass value
  34997. */
  34998. set: function (value) {
  34999. if (this._needDepthPrePass === value) {
  35000. return;
  35001. }
  35002. this._needDepthPrePass = value;
  35003. if (this._needDepthPrePass) {
  35004. this.checkReadyOnEveryCall = true;
  35005. }
  35006. },
  35007. enumerable: true,
  35008. configurable: true
  35009. });
  35010. Object.defineProperty(Material.prototype, "fogEnabled", {
  35011. /**
  35012. * Gets the value of the fog enabled state
  35013. */
  35014. get: function () {
  35015. return this._fogEnabled;
  35016. },
  35017. /**
  35018. * Sets the state for enabling fog
  35019. */
  35020. set: function (value) {
  35021. if (this._fogEnabled === value) {
  35022. return;
  35023. }
  35024. this._fogEnabled = value;
  35025. this.markAsDirty(Material.MiscDirtyFlag);
  35026. },
  35027. enumerable: true,
  35028. configurable: true
  35029. });
  35030. Object.defineProperty(Material.prototype, "wireframe", {
  35031. /**
  35032. * Gets a value specifying if wireframe mode is enabled
  35033. */
  35034. get: function () {
  35035. switch (this._fillMode) {
  35036. case Material.WireFrameFillMode:
  35037. case Material.LineListDrawMode:
  35038. case Material.LineLoopDrawMode:
  35039. case Material.LineStripDrawMode:
  35040. return true;
  35041. }
  35042. return this._scene.forceWireframe;
  35043. },
  35044. /**
  35045. * Sets the state of wireframe mode
  35046. */
  35047. set: function (value) {
  35048. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35049. },
  35050. enumerable: true,
  35051. configurable: true
  35052. });
  35053. Object.defineProperty(Material.prototype, "pointsCloud", {
  35054. /**
  35055. * Gets the value specifying if point clouds are enabled
  35056. */
  35057. get: function () {
  35058. switch (this._fillMode) {
  35059. case Material.PointFillMode:
  35060. case Material.PointListDrawMode:
  35061. return true;
  35062. }
  35063. return this._scene.forcePointsCloud;
  35064. },
  35065. /**
  35066. * Sets the state of point cloud mode
  35067. */
  35068. set: function (value) {
  35069. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35070. },
  35071. enumerable: true,
  35072. configurable: true
  35073. });
  35074. Object.defineProperty(Material.prototype, "fillMode", {
  35075. /**
  35076. * Gets the material fill mode
  35077. */
  35078. get: function () {
  35079. return this._fillMode;
  35080. },
  35081. /**
  35082. * Sets the material fill mode
  35083. */
  35084. set: function (value) {
  35085. if (this._fillMode === value) {
  35086. return;
  35087. }
  35088. this._fillMode = value;
  35089. this.markAsDirty(Material.MiscDirtyFlag);
  35090. },
  35091. enumerable: true,
  35092. configurable: true
  35093. });
  35094. /**
  35095. * Returns a string representation of the current material
  35096. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35097. * @returns a string with material information
  35098. */
  35099. Material.prototype.toString = function (fullDetails) {
  35100. var ret = "Name: " + this.name;
  35101. if (fullDetails) {
  35102. }
  35103. return ret;
  35104. };
  35105. /**
  35106. * Gets the class name of the material
  35107. * @returns a string with the class name of the material
  35108. */
  35109. Material.prototype.getClassName = function () {
  35110. return "Material";
  35111. };
  35112. Object.defineProperty(Material.prototype, "isFrozen", {
  35113. /**
  35114. * Specifies if updates for the material been locked
  35115. */
  35116. get: function () {
  35117. return this.checkReadyOnlyOnce;
  35118. },
  35119. enumerable: true,
  35120. configurable: true
  35121. });
  35122. /**
  35123. * Locks updates for the material
  35124. */
  35125. Material.prototype.freeze = function () {
  35126. this.checkReadyOnlyOnce = true;
  35127. };
  35128. /**
  35129. * Unlocks updates for the material
  35130. */
  35131. Material.prototype.unfreeze = function () {
  35132. this.checkReadyOnlyOnce = false;
  35133. };
  35134. /**
  35135. * Specifies if the material is ready to be used
  35136. * @param mesh defines the mesh to check
  35137. * @param useInstances specifies if instances should be used
  35138. * @returns a boolean indicating if the material is ready to be used
  35139. */
  35140. Material.prototype.isReady = function (mesh, useInstances) {
  35141. return true;
  35142. };
  35143. /**
  35144. * Specifies that the submesh is ready to be used
  35145. * @param mesh defines the mesh to check
  35146. * @param subMesh defines which submesh to check
  35147. * @param useInstances specifies that instances should be used
  35148. * @returns a boolean indicating that the submesh is ready or not
  35149. */
  35150. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35151. return false;
  35152. };
  35153. /**
  35154. * Returns the material effect
  35155. * @returns the effect associated with the material
  35156. */
  35157. Material.prototype.getEffect = function () {
  35158. return this._effect;
  35159. };
  35160. /**
  35161. * Returns the current scene
  35162. * @returns a Scene
  35163. */
  35164. Material.prototype.getScene = function () {
  35165. return this._scene;
  35166. };
  35167. /**
  35168. * Specifies if the material will require alpha blending
  35169. * @returns a boolean specifying if alpha blending is needed
  35170. */
  35171. Material.prototype.needAlphaBlending = function () {
  35172. return (this.alpha < 1.0);
  35173. };
  35174. /**
  35175. * Specifies if the mesh will require alpha blending
  35176. * @param mesh defines the mesh to check
  35177. * @returns a boolean specifying if alpha blending is needed for the mesh
  35178. */
  35179. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35180. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35181. };
  35182. /**
  35183. * Specifies if this material should be rendered in alpha test mode
  35184. * @returns a boolean specifying if an alpha test is needed.
  35185. */
  35186. Material.prototype.needAlphaTesting = function () {
  35187. return false;
  35188. };
  35189. /**
  35190. * Gets the texture used for the alpha test
  35191. * @returns the texture to use for alpha testing
  35192. */
  35193. Material.prototype.getAlphaTestTexture = function () {
  35194. return null;
  35195. };
  35196. /**
  35197. * Marks the material to indicate that it needs to be re-calculated
  35198. */
  35199. Material.prototype.markDirty = function () {
  35200. this._wasPreviouslyReady = false;
  35201. };
  35202. /** @hidden */
  35203. Material.prototype._preBind = function (effect, overrideOrientation) {
  35204. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35205. var engine = this._scene.getEngine();
  35206. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35207. var reverse = orientation === Material.ClockWiseSideOrientation;
  35208. engine.enableEffect(effect ? effect : this._effect);
  35209. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35210. return reverse;
  35211. };
  35212. /**
  35213. * Binds the material to the mesh
  35214. * @param world defines the world transformation matrix
  35215. * @param mesh defines the mesh to bind the material to
  35216. */
  35217. Material.prototype.bind = function (world, mesh) {
  35218. };
  35219. /**
  35220. * Binds the submesh to the material
  35221. * @param world defines the world transformation matrix
  35222. * @param mesh defines the mesh containing the submesh
  35223. * @param subMesh defines the submesh to bind the material to
  35224. */
  35225. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35226. };
  35227. /**
  35228. * Binds the world matrix to the material
  35229. * @param world defines the world transformation matrix
  35230. */
  35231. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35232. };
  35233. /**
  35234. * Binds the scene's uniform buffer to the effect.
  35235. * @param effect defines the effect to bind to the scene uniform buffer
  35236. * @param sceneUbo defines the uniform buffer storing scene data
  35237. */
  35238. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35239. sceneUbo.bindToEffect(effect, "Scene");
  35240. };
  35241. /**
  35242. * Binds the view matrix to the effect
  35243. * @param effect defines the effect to bind the view matrix to
  35244. */
  35245. Material.prototype.bindView = function (effect) {
  35246. if (!this._useUBO) {
  35247. effect.setMatrix("view", this.getScene().getViewMatrix());
  35248. }
  35249. else {
  35250. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35251. }
  35252. };
  35253. /**
  35254. * Binds the view projection matrix to the effect
  35255. * @param effect defines the effect to bind the view projection matrix to
  35256. */
  35257. Material.prototype.bindViewProjection = function (effect) {
  35258. if (!this._useUBO) {
  35259. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35260. }
  35261. else {
  35262. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35263. }
  35264. };
  35265. /**
  35266. * Specifies if material alpha testing should be turned on for the mesh
  35267. * @param mesh defines the mesh to check
  35268. */
  35269. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35270. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35271. };
  35272. /**
  35273. * Processes to execute after binding the material to a mesh
  35274. * @param mesh defines the rendered mesh
  35275. */
  35276. Material.prototype._afterBind = function (mesh) {
  35277. this._scene._cachedMaterial = this;
  35278. if (mesh) {
  35279. this._scene._cachedVisibility = mesh.visibility;
  35280. }
  35281. else {
  35282. this._scene._cachedVisibility = 1;
  35283. }
  35284. if (mesh) {
  35285. this.onBindObservable.notifyObservers(mesh);
  35286. }
  35287. if (this.disableDepthWrite) {
  35288. var engine = this._scene.getEngine();
  35289. this._cachedDepthWriteState = engine.getDepthWrite();
  35290. engine.setDepthWrite(false);
  35291. }
  35292. };
  35293. /**
  35294. * Unbinds the material from the mesh
  35295. */
  35296. Material.prototype.unbind = function () {
  35297. this.onUnBindObservable.notifyObservers(this);
  35298. if (this.disableDepthWrite) {
  35299. var engine = this._scene.getEngine();
  35300. engine.setDepthWrite(this._cachedDepthWriteState);
  35301. }
  35302. };
  35303. /**
  35304. * Gets the active textures from the material
  35305. * @returns an array of textures
  35306. */
  35307. Material.prototype.getActiveTextures = function () {
  35308. return [];
  35309. };
  35310. /**
  35311. * Specifies if the material uses a texture
  35312. * @param texture defines the texture to check against the material
  35313. * @returns a boolean specifying if the material uses the texture
  35314. */
  35315. Material.prototype.hasTexture = function (texture) {
  35316. return false;
  35317. };
  35318. /**
  35319. * Makes a duplicate of the material, and gives it a new name
  35320. * @param name defines the new name for the duplicated material
  35321. * @returns the cloned material
  35322. */
  35323. Material.prototype.clone = function (name) {
  35324. return null;
  35325. };
  35326. /**
  35327. * Gets the meshes bound to the material
  35328. * @returns an array of meshes bound to the material
  35329. */
  35330. Material.prototype.getBindedMeshes = function () {
  35331. var result = new Array();
  35332. for (var index = 0; index < this._scene.meshes.length; index++) {
  35333. var mesh = this._scene.meshes[index];
  35334. if (mesh.material === this) {
  35335. result.push(mesh);
  35336. }
  35337. }
  35338. return result;
  35339. };
  35340. /**
  35341. * Force shader compilation
  35342. * @param mesh defines the mesh associated with this material
  35343. * @param onCompiled defines a function to execute once the material is compiled
  35344. * @param options defines the options to configure the compilation
  35345. */
  35346. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35347. var _this = this;
  35348. var localOptions = __assign({ clipPlane: false }, options);
  35349. var subMesh = new BABYLON.BaseSubMesh();
  35350. var scene = this.getScene();
  35351. var checkReady = function () {
  35352. if (!_this._scene || !_this._scene.getEngine()) {
  35353. return;
  35354. }
  35355. if (subMesh._materialDefines) {
  35356. subMesh._materialDefines._renderId = -1;
  35357. }
  35358. var clipPlaneState = scene.clipPlane;
  35359. if (localOptions.clipPlane) {
  35360. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35361. }
  35362. if (_this.storeEffectOnSubMeshes) {
  35363. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35364. if (onCompiled) {
  35365. onCompiled(_this);
  35366. }
  35367. }
  35368. else {
  35369. setTimeout(checkReady, 16);
  35370. }
  35371. }
  35372. else {
  35373. if (_this.isReady(mesh)) {
  35374. if (onCompiled) {
  35375. onCompiled(_this);
  35376. }
  35377. }
  35378. else {
  35379. setTimeout(checkReady, 16);
  35380. }
  35381. }
  35382. if (localOptions.clipPlane) {
  35383. scene.clipPlane = clipPlaneState;
  35384. }
  35385. };
  35386. checkReady();
  35387. };
  35388. /**
  35389. * Force shader compilation
  35390. * @param mesh defines the mesh that will use this material
  35391. * @param options defines additional options for compiling the shaders
  35392. * @returns a promise that resolves when the compilation completes
  35393. */
  35394. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35395. var _this = this;
  35396. return new Promise(function (resolve) {
  35397. _this.forceCompilation(mesh, function () {
  35398. resolve();
  35399. }, options);
  35400. });
  35401. };
  35402. /**
  35403. * Marks a define in the material to indicate that it needs to be re-computed
  35404. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35405. */
  35406. Material.prototype.markAsDirty = function (flag) {
  35407. if (flag & Material.TextureDirtyFlag) {
  35408. this._markAllSubMeshesAsTexturesDirty();
  35409. }
  35410. if (flag & Material.LightDirtyFlag) {
  35411. this._markAllSubMeshesAsLightsDirty();
  35412. }
  35413. if (flag & Material.FresnelDirtyFlag) {
  35414. this._markAllSubMeshesAsFresnelDirty();
  35415. }
  35416. if (flag & Material.AttributesDirtyFlag) {
  35417. this._markAllSubMeshesAsAttributesDirty();
  35418. }
  35419. if (flag & Material.MiscDirtyFlag) {
  35420. this._markAllSubMeshesAsMiscDirty();
  35421. }
  35422. this.getScene().resetCachedMaterial();
  35423. };
  35424. /**
  35425. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35426. * @param func defines a function which checks material defines against the submeshes
  35427. */
  35428. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35429. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35430. var mesh = _a[_i];
  35431. if (!mesh.subMeshes) {
  35432. continue;
  35433. }
  35434. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35435. var subMesh = _c[_b];
  35436. if (subMesh.getMaterial() !== this) {
  35437. continue;
  35438. }
  35439. if (!subMesh._materialDefines) {
  35440. continue;
  35441. }
  35442. func(subMesh._materialDefines);
  35443. }
  35444. }
  35445. };
  35446. /**
  35447. * Indicates that image processing needs to be re-calculated for all submeshes
  35448. */
  35449. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35450. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35451. };
  35452. /**
  35453. * Indicates that textures need to be re-calculated for all submeshes
  35454. */
  35455. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35456. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35457. };
  35458. /**
  35459. * Indicates that fresnel needs to be re-calculated for all submeshes
  35460. */
  35461. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35462. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35463. };
  35464. /**
  35465. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35466. */
  35467. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35468. this._markAllSubMeshesAsDirty(function (defines) {
  35469. defines.markAsFresnelDirty();
  35470. defines.markAsMiscDirty();
  35471. });
  35472. };
  35473. /**
  35474. * Indicates that lights need to be re-calculated for all submeshes
  35475. */
  35476. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35477. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35478. };
  35479. /**
  35480. * Indicates that attributes need to be re-calculated for all submeshes
  35481. */
  35482. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35483. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35484. };
  35485. /**
  35486. * Indicates that misc needs to be re-calculated for all submeshes
  35487. */
  35488. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35489. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35490. };
  35491. /**
  35492. * Indicates that textures and misc need to be re-calculated for all submeshes
  35493. */
  35494. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35495. this._markAllSubMeshesAsDirty(function (defines) {
  35496. defines.markAsTexturesDirty();
  35497. defines.markAsMiscDirty();
  35498. });
  35499. };
  35500. /**
  35501. * Disposes the material
  35502. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35503. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35504. */
  35505. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35506. // Animations
  35507. this.getScene().stopAnimation(this);
  35508. this.getScene().freeProcessedMaterials();
  35509. // Remove from scene
  35510. var index = this._scene.materials.indexOf(this);
  35511. if (index >= 0) {
  35512. this._scene.materials.splice(index, 1);
  35513. }
  35514. // Remove from meshes
  35515. for (index = 0; index < this._scene.meshes.length; index++) {
  35516. var mesh = this._scene.meshes[index];
  35517. if (mesh.material === this) {
  35518. mesh.material = null;
  35519. if (mesh.geometry) {
  35520. var geometry = (mesh.geometry);
  35521. if (this.storeEffectOnSubMeshes) {
  35522. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35523. var subMesh = _a[_i];
  35524. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35525. if (forceDisposeEffect && subMesh._materialEffect) {
  35526. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35527. }
  35528. }
  35529. }
  35530. else {
  35531. geometry._releaseVertexArrayObject(this._effect);
  35532. }
  35533. }
  35534. }
  35535. }
  35536. this._uniformBuffer.dispose();
  35537. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35538. if (forceDisposeEffect && this._effect) {
  35539. if (!this.storeEffectOnSubMeshes) {
  35540. this._scene.getEngine()._releaseEffect(this._effect);
  35541. }
  35542. this._effect = null;
  35543. }
  35544. // Callback
  35545. this.onDisposeObservable.notifyObservers(this);
  35546. this.onDisposeObservable.clear();
  35547. this.onBindObservable.clear();
  35548. this.onUnBindObservable.clear();
  35549. };
  35550. /**
  35551. * Serializes this material
  35552. * @returns the serialized material object
  35553. */
  35554. Material.prototype.serialize = function () {
  35555. return BABYLON.SerializationHelper.Serialize(this);
  35556. };
  35557. /**
  35558. * Creates a MultiMaterial from parsed MultiMaterial data.
  35559. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35560. * @param scene defines the hosting scene
  35561. * @returns a new MultiMaterial
  35562. */
  35563. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35564. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35565. multiMaterial.id = parsedMultiMaterial.id;
  35566. if (BABYLON.Tags) {
  35567. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35568. }
  35569. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35570. var subMatId = parsedMultiMaterial.materials[matIndex];
  35571. if (subMatId) {
  35572. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35573. }
  35574. else {
  35575. multiMaterial.subMaterials.push(null);
  35576. }
  35577. }
  35578. return multiMaterial;
  35579. };
  35580. /**
  35581. * Creates a material from parsed material data
  35582. * @param parsedMaterial defines parsed material data
  35583. * @param scene defines the hosting scene
  35584. * @param rootUrl defines the root URL to use to load textures
  35585. * @returns a new material
  35586. */
  35587. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35588. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35589. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35590. }
  35591. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35592. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35593. if (!BABYLON.LegacyPBRMaterial) {
  35594. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35595. return;
  35596. }
  35597. }
  35598. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35599. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35600. };
  35601. // Triangle views
  35602. Material._TriangleFillMode = 0;
  35603. Material._WireFrameFillMode = 1;
  35604. Material._PointFillMode = 2;
  35605. // Draw modes
  35606. Material._PointListDrawMode = 3;
  35607. Material._LineListDrawMode = 4;
  35608. Material._LineLoopDrawMode = 5;
  35609. Material._LineStripDrawMode = 6;
  35610. Material._TriangleStripDrawMode = 7;
  35611. Material._TriangleFanDrawMode = 8;
  35612. /**
  35613. * Stores the clock-wise side orientation
  35614. */
  35615. Material._ClockWiseSideOrientation = 0;
  35616. /**
  35617. * Stores the counter clock-wise side orientation
  35618. */
  35619. Material._CounterClockWiseSideOrientation = 1;
  35620. /**
  35621. * The dirty texture flag value
  35622. */
  35623. Material._TextureDirtyFlag = 1;
  35624. /**
  35625. * The dirty light flag value
  35626. */
  35627. Material._LightDirtyFlag = 2;
  35628. /**
  35629. * The dirty fresnel flag value
  35630. */
  35631. Material._FresnelDirtyFlag = 4;
  35632. /**
  35633. * The dirty attribute flag value
  35634. */
  35635. Material._AttributesDirtyFlag = 8;
  35636. /**
  35637. * The dirty misc flag value
  35638. */
  35639. Material._MiscDirtyFlag = 16;
  35640. __decorate([
  35641. BABYLON.serialize()
  35642. ], Material.prototype, "id", void 0);
  35643. __decorate([
  35644. BABYLON.serialize()
  35645. ], Material.prototype, "name", void 0);
  35646. __decorate([
  35647. BABYLON.serialize()
  35648. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35649. __decorate([
  35650. BABYLON.serialize()
  35651. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35652. __decorate([
  35653. BABYLON.serialize()
  35654. ], Material.prototype, "state", void 0);
  35655. __decorate([
  35656. BABYLON.serialize("alpha")
  35657. ], Material.prototype, "_alpha", void 0);
  35658. __decorate([
  35659. BABYLON.serialize("backFaceCulling")
  35660. ], Material.prototype, "_backFaceCulling", void 0);
  35661. __decorate([
  35662. BABYLON.serialize()
  35663. ], Material.prototype, "sideOrientation", void 0);
  35664. __decorate([
  35665. BABYLON.serialize("alphaMode")
  35666. ], Material.prototype, "_alphaMode", void 0);
  35667. __decorate([
  35668. BABYLON.serialize()
  35669. ], Material.prototype, "_needDepthPrePass", void 0);
  35670. __decorate([
  35671. BABYLON.serialize()
  35672. ], Material.prototype, "disableDepthWrite", void 0);
  35673. __decorate([
  35674. BABYLON.serialize()
  35675. ], Material.prototype, "forceDepthWrite", void 0);
  35676. __decorate([
  35677. BABYLON.serialize()
  35678. ], Material.prototype, "separateCullingPass", void 0);
  35679. __decorate([
  35680. BABYLON.serialize("fogEnabled")
  35681. ], Material.prototype, "_fogEnabled", void 0);
  35682. __decorate([
  35683. BABYLON.serialize()
  35684. ], Material.prototype, "pointSize", void 0);
  35685. __decorate([
  35686. BABYLON.serialize()
  35687. ], Material.prototype, "zOffset", void 0);
  35688. __decorate([
  35689. BABYLON.serialize()
  35690. ], Material.prototype, "wireframe", null);
  35691. __decorate([
  35692. BABYLON.serialize()
  35693. ], Material.prototype, "pointsCloud", null);
  35694. __decorate([
  35695. BABYLON.serialize()
  35696. ], Material.prototype, "fillMode", null);
  35697. return Material;
  35698. }());
  35699. BABYLON.Material = Material;
  35700. })(BABYLON || (BABYLON = {}));
  35701. //# sourceMappingURL=babylon.material.js.map
  35702. var BABYLON;
  35703. (function (BABYLON) {
  35704. var UniformBuffer = /** @class */ (function () {
  35705. /**
  35706. * Uniform buffer objects.
  35707. *
  35708. * Handles blocks of uniform on the GPU.
  35709. *
  35710. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35711. *
  35712. * For more information, please refer to :
  35713. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35714. */
  35715. function UniformBuffer(engine, data, dynamic) {
  35716. this._engine = engine;
  35717. this._noUBO = !engine.supportsUniformBuffers;
  35718. this._dynamic = dynamic;
  35719. this._data = data || [];
  35720. this._uniformLocations = {};
  35721. this._uniformSizes = {};
  35722. this._uniformLocationPointer = 0;
  35723. this._needSync = false;
  35724. if (this._noUBO) {
  35725. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35726. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35727. this.updateFloat = this._updateFloatForEffect;
  35728. this.updateFloat2 = this._updateFloat2ForEffect;
  35729. this.updateFloat3 = this._updateFloat3ForEffect;
  35730. this.updateFloat4 = this._updateFloat4ForEffect;
  35731. this.updateMatrix = this._updateMatrixForEffect;
  35732. this.updateVector3 = this._updateVector3ForEffect;
  35733. this.updateVector4 = this._updateVector4ForEffect;
  35734. this.updateColor3 = this._updateColor3ForEffect;
  35735. this.updateColor4 = this._updateColor4ForEffect;
  35736. }
  35737. else {
  35738. this._engine._uniformBuffers.push(this);
  35739. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35740. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35741. this.updateFloat = this._updateFloatForUniform;
  35742. this.updateFloat2 = this._updateFloat2ForUniform;
  35743. this.updateFloat3 = this._updateFloat3ForUniform;
  35744. this.updateFloat4 = this._updateFloat4ForUniform;
  35745. this.updateMatrix = this._updateMatrixForUniform;
  35746. this.updateVector3 = this._updateVector3ForUniform;
  35747. this.updateVector4 = this._updateVector4ForUniform;
  35748. this.updateColor3 = this._updateColor3ForUniform;
  35749. this.updateColor4 = this._updateColor4ForUniform;
  35750. }
  35751. }
  35752. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35753. // Properties
  35754. /**
  35755. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35756. * or just falling back on setUniformXXX calls.
  35757. */
  35758. get: function () {
  35759. return !this._noUBO;
  35760. },
  35761. enumerable: true,
  35762. configurable: true
  35763. });
  35764. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35765. /**
  35766. * Indicates if the WebGL underlying uniform buffer is in sync
  35767. * with the javascript cache data.
  35768. */
  35769. get: function () {
  35770. return !this._needSync;
  35771. },
  35772. enumerable: true,
  35773. configurable: true
  35774. });
  35775. /**
  35776. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35777. * Also, a dynamic UniformBuffer will disable cache verification and always
  35778. * update the underlying WebGL uniform buffer to the GPU.
  35779. */
  35780. UniformBuffer.prototype.isDynamic = function () {
  35781. return this._dynamic !== undefined;
  35782. };
  35783. /**
  35784. * The data cache on JS side.
  35785. */
  35786. UniformBuffer.prototype.getData = function () {
  35787. return this._bufferData;
  35788. };
  35789. /**
  35790. * The underlying WebGL Uniform buffer.
  35791. */
  35792. UniformBuffer.prototype.getBuffer = function () {
  35793. return this._buffer;
  35794. };
  35795. /**
  35796. * std140 layout specifies how to align data within an UBO structure.
  35797. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35798. * for specs.
  35799. */
  35800. UniformBuffer.prototype._fillAlignment = function (size) {
  35801. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35802. // and 4x4 matrices
  35803. // TODO : change if other types are used
  35804. var alignment;
  35805. if (size <= 2) {
  35806. alignment = size;
  35807. }
  35808. else {
  35809. alignment = 4;
  35810. }
  35811. if ((this._uniformLocationPointer % alignment) !== 0) {
  35812. var oldPointer = this._uniformLocationPointer;
  35813. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35814. var diff = this._uniformLocationPointer - oldPointer;
  35815. for (var i = 0; i < diff; i++) {
  35816. this._data.push(0);
  35817. }
  35818. }
  35819. };
  35820. /**
  35821. * Adds an uniform in the buffer.
  35822. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35823. * for the layout to be correct !
  35824. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35825. * @param {number|number[]} size Data size, or data directly.
  35826. */
  35827. UniformBuffer.prototype.addUniform = function (name, size) {
  35828. if (this._noUBO) {
  35829. return;
  35830. }
  35831. if (this._uniformLocations[name] !== undefined) {
  35832. // Already existing uniform
  35833. return;
  35834. }
  35835. // This function must be called in the order of the shader layout !
  35836. // size can be the size of the uniform, or data directly
  35837. var data;
  35838. if (size instanceof Array) {
  35839. data = size;
  35840. size = data.length;
  35841. }
  35842. else {
  35843. size = size;
  35844. data = [];
  35845. // Fill with zeros
  35846. for (var i = 0; i < size; i++) {
  35847. data.push(0);
  35848. }
  35849. }
  35850. this._fillAlignment(size);
  35851. this._uniformSizes[name] = size;
  35852. this._uniformLocations[name] = this._uniformLocationPointer;
  35853. this._uniformLocationPointer += size;
  35854. for (var i = 0; i < size; i++) {
  35855. this._data.push(data[i]);
  35856. }
  35857. this._needSync = true;
  35858. };
  35859. /**
  35860. * Wrapper for addUniform.
  35861. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35862. * @param {Matrix} mat A 4x4 matrix.
  35863. */
  35864. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35865. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35866. };
  35867. /**
  35868. * Wrapper for addUniform.
  35869. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35870. * @param {number} x
  35871. * @param {number} y
  35872. */
  35873. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35874. var temp = [x, y];
  35875. this.addUniform(name, temp);
  35876. };
  35877. /**
  35878. * Wrapper for addUniform.
  35879. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35880. * @param {number} x
  35881. * @param {number} y
  35882. * @param {number} z
  35883. */
  35884. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35885. var temp = [x, y, z];
  35886. this.addUniform(name, temp);
  35887. };
  35888. /**
  35889. * Wrapper for addUniform.
  35890. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35891. * @param {Color3} color
  35892. */
  35893. UniformBuffer.prototype.addColor3 = function (name, color) {
  35894. var temp = new Array();
  35895. color.toArray(temp);
  35896. this.addUniform(name, temp);
  35897. };
  35898. /**
  35899. * Wrapper for addUniform.
  35900. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35901. * @param {Color3} color
  35902. * @param {number} alpha
  35903. */
  35904. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35905. var temp = new Array();
  35906. color.toArray(temp);
  35907. temp.push(alpha);
  35908. this.addUniform(name, temp);
  35909. };
  35910. /**
  35911. * Wrapper for addUniform.
  35912. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35913. * @param {Vector3} vector
  35914. */
  35915. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35916. var temp = new Array();
  35917. vector.toArray(temp);
  35918. this.addUniform(name, temp);
  35919. };
  35920. /**
  35921. * Wrapper for addUniform.
  35922. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35923. */
  35924. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35925. this.addUniform(name, 12);
  35926. };
  35927. /**
  35928. * Wrapper for addUniform.
  35929. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35930. */
  35931. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35932. this.addUniform(name, 8);
  35933. };
  35934. /**
  35935. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35936. */
  35937. UniformBuffer.prototype.create = function () {
  35938. if (this._noUBO) {
  35939. return;
  35940. }
  35941. if (this._buffer) {
  35942. return; // nothing to do
  35943. }
  35944. // See spec, alignment must be filled as a vec4
  35945. this._fillAlignment(4);
  35946. this._bufferData = new Float32Array(this._data);
  35947. this._rebuild();
  35948. this._needSync = true;
  35949. };
  35950. UniformBuffer.prototype._rebuild = function () {
  35951. if (this._noUBO) {
  35952. return;
  35953. }
  35954. if (this._dynamic) {
  35955. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35956. }
  35957. else {
  35958. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35959. }
  35960. };
  35961. /**
  35962. * Updates the WebGL Uniform Buffer on the GPU.
  35963. * If the `dynamic` flag is set to true, no cache comparison is done.
  35964. * Otherwise, the buffer will be updated only if the cache differs.
  35965. */
  35966. UniformBuffer.prototype.update = function () {
  35967. if (!this._buffer) {
  35968. this.create();
  35969. return;
  35970. }
  35971. if (!this._dynamic && !this._needSync) {
  35972. return;
  35973. }
  35974. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35975. this._needSync = false;
  35976. };
  35977. /**
  35978. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35979. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35980. * @param {number[]|Float32Array} data Flattened data
  35981. * @param {number} size Size of the data.
  35982. */
  35983. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35984. var location = this._uniformLocations[uniformName];
  35985. if (location === undefined) {
  35986. if (this._buffer) {
  35987. // Cannot add an uniform if the buffer is already created
  35988. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35989. return;
  35990. }
  35991. this.addUniform(uniformName, size);
  35992. location = this._uniformLocations[uniformName];
  35993. }
  35994. if (!this._buffer) {
  35995. this.create();
  35996. }
  35997. if (!this._dynamic) {
  35998. // Cache for static uniform buffers
  35999. var changed = false;
  36000. for (var i = 0; i < size; i++) {
  36001. if (this._bufferData[location + i] !== data[i]) {
  36002. changed = true;
  36003. this._bufferData[location + i] = data[i];
  36004. }
  36005. }
  36006. this._needSync = this._needSync || changed;
  36007. }
  36008. else {
  36009. // No cache for dynamic
  36010. for (var i = 0; i < size; i++) {
  36011. this._bufferData[location + i] = data[i];
  36012. }
  36013. }
  36014. };
  36015. // Update methods
  36016. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36017. // To match std140, matrix must be realigned
  36018. for (var i = 0; i < 3; i++) {
  36019. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36020. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36021. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36022. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36023. }
  36024. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36025. };
  36026. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36027. this._currentEffect.setMatrix3x3(name, matrix);
  36028. };
  36029. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36030. this._currentEffect.setMatrix2x2(name, matrix);
  36031. };
  36032. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36033. // To match std140, matrix must be realigned
  36034. for (var i = 0; i < 2; i++) {
  36035. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36036. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36037. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36038. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36039. }
  36040. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36041. };
  36042. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36043. this._currentEffect.setFloat(name, x);
  36044. };
  36045. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36046. UniformBuffer._tempBuffer[0] = x;
  36047. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36048. };
  36049. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36050. if (suffix === void 0) { suffix = ""; }
  36051. this._currentEffect.setFloat2(name + suffix, x, y);
  36052. };
  36053. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36054. if (suffix === void 0) { suffix = ""; }
  36055. UniformBuffer._tempBuffer[0] = x;
  36056. UniformBuffer._tempBuffer[1] = y;
  36057. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36058. };
  36059. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36060. if (suffix === void 0) { suffix = ""; }
  36061. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36062. };
  36063. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36064. if (suffix === void 0) { suffix = ""; }
  36065. UniformBuffer._tempBuffer[0] = x;
  36066. UniformBuffer._tempBuffer[1] = y;
  36067. UniformBuffer._tempBuffer[2] = z;
  36068. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36069. };
  36070. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36071. if (suffix === void 0) { suffix = ""; }
  36072. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36073. };
  36074. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36075. if (suffix === void 0) { suffix = ""; }
  36076. UniformBuffer._tempBuffer[0] = x;
  36077. UniformBuffer._tempBuffer[1] = y;
  36078. UniformBuffer._tempBuffer[2] = z;
  36079. UniformBuffer._tempBuffer[3] = w;
  36080. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36081. };
  36082. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36083. this._currentEffect.setMatrix(name, mat);
  36084. };
  36085. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36086. this.updateUniform(name, mat.toArray(), 16);
  36087. };
  36088. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36089. this._currentEffect.setVector3(name, vector);
  36090. };
  36091. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36092. vector.toArray(UniformBuffer._tempBuffer);
  36093. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36094. };
  36095. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36096. this._currentEffect.setVector4(name, vector);
  36097. };
  36098. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36099. vector.toArray(UniformBuffer._tempBuffer);
  36100. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36101. };
  36102. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36103. if (suffix === void 0) { suffix = ""; }
  36104. this._currentEffect.setColor3(name + suffix, color);
  36105. };
  36106. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36107. if (suffix === void 0) { suffix = ""; }
  36108. color.toArray(UniformBuffer._tempBuffer);
  36109. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36110. };
  36111. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36112. if (suffix === void 0) { suffix = ""; }
  36113. this._currentEffect.setColor4(name + suffix, color, alpha);
  36114. };
  36115. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36116. if (suffix === void 0) { suffix = ""; }
  36117. color.toArray(UniformBuffer._tempBuffer);
  36118. UniformBuffer._tempBuffer[3] = alpha;
  36119. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36120. };
  36121. /**
  36122. * Sets a sampler uniform on the effect.
  36123. * @param {string} name Name of the sampler.
  36124. * @param {Texture} texture
  36125. */
  36126. UniformBuffer.prototype.setTexture = function (name, texture) {
  36127. this._currentEffect.setTexture(name, texture);
  36128. };
  36129. /**
  36130. * Directly updates the value of the uniform in the cache AND on the GPU.
  36131. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36132. * @param {number[]|Float32Array} data Flattened data
  36133. */
  36134. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36135. this.updateUniform(uniformName, data, data.length);
  36136. this.update();
  36137. };
  36138. /**
  36139. * Binds this uniform buffer to an effect.
  36140. * @param {Effect} effect
  36141. * @param {string} name Name of the uniform block in the shader.
  36142. */
  36143. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36144. this._currentEffect = effect;
  36145. if (this._noUBO || !this._buffer) {
  36146. return;
  36147. }
  36148. effect.bindUniformBuffer(this._buffer, name);
  36149. };
  36150. /**
  36151. * Disposes the uniform buffer.
  36152. */
  36153. UniformBuffer.prototype.dispose = function () {
  36154. if (this._noUBO) {
  36155. return;
  36156. }
  36157. var index = this._engine._uniformBuffers.indexOf(this);
  36158. if (index !== -1) {
  36159. this._engine._uniformBuffers.splice(index, 1);
  36160. }
  36161. if (!this._buffer) {
  36162. return;
  36163. }
  36164. if (this._engine._releaseBuffer(this._buffer)) {
  36165. this._buffer = null;
  36166. }
  36167. };
  36168. // Pool for avoiding memory leaks
  36169. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36170. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36171. return UniformBuffer;
  36172. }());
  36173. BABYLON.UniformBuffer = UniformBuffer;
  36174. })(BABYLON || (BABYLON = {}));
  36175. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36176. var BABYLON;
  36177. (function (BABYLON) {
  36178. /**
  36179. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36180. */
  36181. var VertexData = /** @class */ (function () {
  36182. function VertexData() {
  36183. }
  36184. /**
  36185. * Uses the passed data array to set the set the values for the specified kind of data
  36186. * @param data a linear array of floating numbers
  36187. * @param kind the type of data that is being set, eg positions, colors etc
  36188. */
  36189. VertexData.prototype.set = function (data, kind) {
  36190. switch (kind) {
  36191. case BABYLON.VertexBuffer.PositionKind:
  36192. this.positions = data;
  36193. break;
  36194. case BABYLON.VertexBuffer.NormalKind:
  36195. this.normals = data;
  36196. break;
  36197. case BABYLON.VertexBuffer.TangentKind:
  36198. this.tangents = data;
  36199. break;
  36200. case BABYLON.VertexBuffer.UVKind:
  36201. this.uvs = data;
  36202. break;
  36203. case BABYLON.VertexBuffer.UV2Kind:
  36204. this.uvs2 = data;
  36205. break;
  36206. case BABYLON.VertexBuffer.UV3Kind:
  36207. this.uvs3 = data;
  36208. break;
  36209. case BABYLON.VertexBuffer.UV4Kind:
  36210. this.uvs4 = data;
  36211. break;
  36212. case BABYLON.VertexBuffer.UV5Kind:
  36213. this.uvs5 = data;
  36214. break;
  36215. case BABYLON.VertexBuffer.UV6Kind:
  36216. this.uvs6 = data;
  36217. break;
  36218. case BABYLON.VertexBuffer.ColorKind:
  36219. this.colors = data;
  36220. break;
  36221. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36222. this.matricesIndices = data;
  36223. break;
  36224. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36225. this.matricesWeights = data;
  36226. break;
  36227. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36228. this.matricesIndicesExtra = data;
  36229. break;
  36230. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36231. this.matricesWeightsExtra = data;
  36232. break;
  36233. }
  36234. };
  36235. /**
  36236. * Associates the vertexData to the passed Mesh.
  36237. * Sets it as updatable or not (default `false`)
  36238. * @param mesh the mesh the vertexData is applied to
  36239. * @param updatable when used and having the value true allows new data to update the vertexData
  36240. * @returns the VertexData
  36241. */
  36242. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36243. this._applyTo(mesh, updatable);
  36244. return this;
  36245. };
  36246. /**
  36247. * Associates the vertexData to the passed Geometry.
  36248. * Sets it as updatable or not (default `false`)
  36249. * @param geometry the geometry the vertexData is applied to
  36250. * @param updatable when used and having the value true allows new data to update the vertexData
  36251. * @returns VertexData
  36252. */
  36253. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36254. this._applyTo(geometry, updatable);
  36255. return this;
  36256. };
  36257. /**
  36258. * Updates the associated mesh
  36259. * @param mesh the mesh to be updated
  36260. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36261. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36262. * @returns VertexData
  36263. */
  36264. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36265. this._update(mesh);
  36266. return this;
  36267. };
  36268. /**
  36269. * Updates the associated geometry
  36270. * @param geometry the geometry to be updated
  36271. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36272. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36273. * @returns VertexData.
  36274. */
  36275. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36276. this._update(geometry);
  36277. return this;
  36278. };
  36279. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36280. if (updatable === void 0) { updatable = false; }
  36281. if (this.positions) {
  36282. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36283. }
  36284. if (this.normals) {
  36285. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36286. }
  36287. if (this.tangents) {
  36288. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36289. }
  36290. if (this.uvs) {
  36291. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36292. }
  36293. if (this.uvs2) {
  36294. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36295. }
  36296. if (this.uvs3) {
  36297. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36298. }
  36299. if (this.uvs4) {
  36300. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36301. }
  36302. if (this.uvs5) {
  36303. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36304. }
  36305. if (this.uvs6) {
  36306. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36307. }
  36308. if (this.colors) {
  36309. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36310. }
  36311. if (this.matricesIndices) {
  36312. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36313. }
  36314. if (this.matricesWeights) {
  36315. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36316. }
  36317. if (this.matricesIndicesExtra) {
  36318. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36319. }
  36320. if (this.matricesWeightsExtra) {
  36321. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36322. }
  36323. if (this.indices) {
  36324. meshOrGeometry.setIndices(this.indices, null, updatable);
  36325. }
  36326. return this;
  36327. };
  36328. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36329. if (this.positions) {
  36330. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36331. }
  36332. if (this.normals) {
  36333. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36334. }
  36335. if (this.tangents) {
  36336. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36337. }
  36338. if (this.uvs) {
  36339. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36340. }
  36341. if (this.uvs2) {
  36342. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36343. }
  36344. if (this.uvs3) {
  36345. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36346. }
  36347. if (this.uvs4) {
  36348. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36349. }
  36350. if (this.uvs5) {
  36351. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36352. }
  36353. if (this.uvs6) {
  36354. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36355. }
  36356. if (this.colors) {
  36357. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36358. }
  36359. if (this.matricesIndices) {
  36360. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36361. }
  36362. if (this.matricesWeights) {
  36363. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36364. }
  36365. if (this.matricesIndicesExtra) {
  36366. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36367. }
  36368. if (this.matricesWeightsExtra) {
  36369. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36370. }
  36371. if (this.indices) {
  36372. meshOrGeometry.setIndices(this.indices, null);
  36373. }
  36374. return this;
  36375. };
  36376. /**
  36377. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36378. * @param matrix the transforming matrix
  36379. * @returns the VertexData
  36380. */
  36381. VertexData.prototype.transform = function (matrix) {
  36382. var transformed = BABYLON.Vector3.Zero();
  36383. var index;
  36384. if (this.positions) {
  36385. var position = BABYLON.Vector3.Zero();
  36386. for (index = 0; index < this.positions.length; index += 3) {
  36387. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36388. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36389. this.positions[index] = transformed.x;
  36390. this.positions[index + 1] = transformed.y;
  36391. this.positions[index + 2] = transformed.z;
  36392. }
  36393. }
  36394. if (this.normals) {
  36395. var normal = BABYLON.Vector3.Zero();
  36396. for (index = 0; index < this.normals.length; index += 3) {
  36397. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36398. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36399. this.normals[index] = transformed.x;
  36400. this.normals[index + 1] = transformed.y;
  36401. this.normals[index + 2] = transformed.z;
  36402. }
  36403. }
  36404. if (this.tangents) {
  36405. var tangent = BABYLON.Vector4.Zero();
  36406. var tangentTransformed = BABYLON.Vector4.Zero();
  36407. for (index = 0; index < this.tangents.length; index += 4) {
  36408. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36409. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36410. this.tangents[index] = tangentTransformed.x;
  36411. this.tangents[index + 1] = tangentTransformed.y;
  36412. this.tangents[index + 2] = tangentTransformed.z;
  36413. this.tangents[index + 3] = tangentTransformed.w;
  36414. }
  36415. }
  36416. return this;
  36417. };
  36418. /**
  36419. * Merges the passed VertexData into the current one
  36420. * @param other the VertexData to be merged into the current one
  36421. * @returns the modified VertexData
  36422. */
  36423. VertexData.prototype.merge = function (other) {
  36424. this._validate();
  36425. other._validate();
  36426. if (!this.normals !== !other.normals ||
  36427. !this.tangents !== !other.tangents ||
  36428. !this.uvs !== !other.uvs ||
  36429. !this.uvs2 !== !other.uvs2 ||
  36430. !this.uvs3 !== !other.uvs3 ||
  36431. !this.uvs4 !== !other.uvs4 ||
  36432. !this.uvs5 !== !other.uvs5 ||
  36433. !this.uvs6 !== !other.uvs6 ||
  36434. !this.colors !== !other.colors ||
  36435. !this.matricesIndices !== !other.matricesIndices ||
  36436. !this.matricesWeights !== !other.matricesWeights ||
  36437. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36438. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36439. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36440. }
  36441. if (other.indices) {
  36442. if (!this.indices) {
  36443. this.indices = [];
  36444. }
  36445. var offset = this.positions ? this.positions.length / 3 : 0;
  36446. for (var index = 0; index < other.indices.length; index++) {
  36447. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36448. this.indices.push(other.indices[index] + offset);
  36449. }
  36450. }
  36451. this.positions = this._mergeElement(this.positions, other.positions);
  36452. this.normals = this._mergeElement(this.normals, other.normals);
  36453. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36454. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36455. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36456. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36457. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36458. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36459. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36460. this.colors = this._mergeElement(this.colors, other.colors);
  36461. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36462. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36463. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36464. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36465. return this;
  36466. };
  36467. VertexData.prototype._mergeElement = function (source, other) {
  36468. if (!source) {
  36469. return other;
  36470. }
  36471. if (!other) {
  36472. return source;
  36473. }
  36474. var len = other.length + source.length;
  36475. var isSrcTypedArray = source instanceof Float32Array;
  36476. var isOthTypedArray = other instanceof Float32Array;
  36477. // use non-loop method when the source is Float32Array
  36478. if (isSrcTypedArray) {
  36479. var ret32 = new Float32Array(len);
  36480. ret32.set(source);
  36481. ret32.set(other, source.length);
  36482. return ret32;
  36483. // source is number[], when other is also use concat
  36484. }
  36485. else if (!isOthTypedArray) {
  36486. return source.concat(other);
  36487. // source is a number[], but other is a Float32Array, loop required
  36488. }
  36489. else {
  36490. var ret = source.slice(0); // copy source to a separate array
  36491. for (var i = 0, len = other.length; i < len; i++) {
  36492. ret.push(other[i]);
  36493. }
  36494. return ret;
  36495. }
  36496. };
  36497. VertexData.prototype._validate = function () {
  36498. if (!this.positions) {
  36499. throw new Error("Positions are required");
  36500. }
  36501. var getElementCount = function (kind, values) {
  36502. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36503. if ((values.length % stride) !== 0) {
  36504. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36505. }
  36506. return values.length / stride;
  36507. };
  36508. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36509. var validateElementCount = function (kind, values) {
  36510. var elementCount = getElementCount(kind, values);
  36511. if (elementCount !== positionsElementCount) {
  36512. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36513. }
  36514. };
  36515. if (this.normals)
  36516. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36517. if (this.tangents)
  36518. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36519. if (this.uvs)
  36520. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36521. if (this.uvs2)
  36522. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36523. if (this.uvs3)
  36524. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36525. if (this.uvs4)
  36526. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36527. if (this.uvs5)
  36528. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36529. if (this.uvs6)
  36530. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36531. if (this.colors)
  36532. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36533. if (this.matricesIndices)
  36534. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36535. if (this.matricesWeights)
  36536. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36537. if (this.matricesIndicesExtra)
  36538. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36539. if (this.matricesWeightsExtra)
  36540. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36541. };
  36542. /**
  36543. * Serializes the VertexData
  36544. * @returns a serialized object
  36545. */
  36546. VertexData.prototype.serialize = function () {
  36547. var serializationObject = this.serialize();
  36548. if (this.positions) {
  36549. serializationObject.positions = this.positions;
  36550. }
  36551. if (this.normals) {
  36552. serializationObject.normals = this.normals;
  36553. }
  36554. if (this.tangents) {
  36555. serializationObject.tangents = this.tangents;
  36556. }
  36557. if (this.uvs) {
  36558. serializationObject.uvs = this.uvs;
  36559. }
  36560. if (this.uvs2) {
  36561. serializationObject.uvs2 = this.uvs2;
  36562. }
  36563. if (this.uvs3) {
  36564. serializationObject.uvs3 = this.uvs3;
  36565. }
  36566. if (this.uvs4) {
  36567. serializationObject.uvs4 = this.uvs4;
  36568. }
  36569. if (this.uvs5) {
  36570. serializationObject.uvs5 = this.uvs5;
  36571. }
  36572. if (this.uvs6) {
  36573. serializationObject.uvs6 = this.uvs6;
  36574. }
  36575. if (this.colors) {
  36576. serializationObject.colors = this.colors;
  36577. }
  36578. if (this.matricesIndices) {
  36579. serializationObject.matricesIndices = this.matricesIndices;
  36580. serializationObject.matricesIndices._isExpanded = true;
  36581. }
  36582. if (this.matricesWeights) {
  36583. serializationObject.matricesWeights = this.matricesWeights;
  36584. }
  36585. if (this.matricesIndicesExtra) {
  36586. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36587. serializationObject.matricesIndicesExtra._isExpanded = true;
  36588. }
  36589. if (this.matricesWeightsExtra) {
  36590. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36591. }
  36592. serializationObject.indices = this.indices;
  36593. return serializationObject;
  36594. };
  36595. // Statics
  36596. /**
  36597. * Extracts the vertexData from a mesh
  36598. * @param mesh the mesh from which to extract the VertexData
  36599. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36600. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36601. * @returns the object VertexData associated to the passed mesh
  36602. */
  36603. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36604. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36605. };
  36606. /**
  36607. * Extracts the vertexData from the geometry
  36608. * @param geometry the geometry from which to extract the VertexData
  36609. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36610. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36611. * @returns the object VertexData associated to the passed mesh
  36612. */
  36613. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36614. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36615. };
  36616. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36617. var result = new VertexData();
  36618. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36619. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36620. }
  36621. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36622. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36623. }
  36624. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36625. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36626. }
  36627. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36628. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36629. }
  36630. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36631. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36632. }
  36633. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36634. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36635. }
  36636. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36637. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36638. }
  36639. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36640. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36641. }
  36642. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36643. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36644. }
  36645. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36646. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36647. }
  36648. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36649. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36650. }
  36651. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36652. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36653. }
  36654. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36655. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36656. }
  36657. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36658. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36659. }
  36660. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36661. return result;
  36662. };
  36663. /**
  36664. * Creates the VertexData for a Ribbon
  36665. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36666. * * pathArray array of paths, each of which an array of successive Vector3
  36667. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36668. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36669. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  36670. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36671. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36672. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36673. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36674. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36675. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36676. * @returns the VertexData of the ribbon
  36677. */
  36678. VertexData.CreateRibbon = function (options) {
  36679. var pathArray = options.pathArray;
  36680. var closeArray = options.closeArray || false;
  36681. var closePath = options.closePath || false;
  36682. var invertUV = options.invertUV || false;
  36683. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36684. var offset = options.offset || defaultOffset;
  36685. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36686. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36687. var customUV = options.uvs;
  36688. var customColors = options.colors;
  36689. var positions = [];
  36690. var indices = [];
  36691. var normals = [];
  36692. var uvs = [];
  36693. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36694. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36695. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36696. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36697. var minlg; // minimal length among all paths from pathArray
  36698. var lg = []; // array of path lengths : nb of vertex per path
  36699. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36700. var p; // path iterator
  36701. var i; // point iterator
  36702. var j; // point iterator
  36703. // if single path in pathArray
  36704. if (pathArray.length < 2) {
  36705. var ar1 = [];
  36706. var ar2 = [];
  36707. for (i = 0; i < pathArray[0].length - offset; i++) {
  36708. ar1.push(pathArray[0][i]);
  36709. ar2.push(pathArray[0][i + offset]);
  36710. }
  36711. pathArray = [ar1, ar2];
  36712. }
  36713. // positions and horizontal distances (u)
  36714. var idc = 0;
  36715. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36716. var path;
  36717. var l;
  36718. minlg = pathArray[0].length;
  36719. var vectlg;
  36720. var dist;
  36721. for (p = 0; p < pathArray.length; p++) {
  36722. uTotalDistance[p] = 0;
  36723. us[p] = [0];
  36724. path = pathArray[p];
  36725. l = path.length;
  36726. minlg = (minlg < l) ? minlg : l;
  36727. j = 0;
  36728. while (j < l) {
  36729. positions.push(path[j].x, path[j].y, path[j].z);
  36730. if (j > 0) {
  36731. vectlg = path[j].subtract(path[j - 1]).length();
  36732. dist = vectlg + uTotalDistance[p];
  36733. us[p].push(dist);
  36734. uTotalDistance[p] = dist;
  36735. }
  36736. j++;
  36737. }
  36738. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36739. j--;
  36740. positions.push(path[0].x, path[0].y, path[0].z);
  36741. vectlg = path[j].subtract(path[0]).length();
  36742. dist = vectlg + uTotalDistance[p];
  36743. us[p].push(dist);
  36744. uTotalDistance[p] = dist;
  36745. }
  36746. lg[p] = l + closePathCorr;
  36747. idx[p] = idc;
  36748. idc += (l + closePathCorr);
  36749. }
  36750. // vertical distances (v)
  36751. var path1;
  36752. var path2;
  36753. var vertex1 = null;
  36754. var vertex2 = null;
  36755. for (i = 0; i < minlg + closePathCorr; i++) {
  36756. vTotalDistance[i] = 0;
  36757. vs[i] = [0];
  36758. for (p = 0; p < pathArray.length - 1; p++) {
  36759. path1 = pathArray[p];
  36760. path2 = pathArray[p + 1];
  36761. if (i === minlg) { // closePath
  36762. vertex1 = path1[0];
  36763. vertex2 = path2[0];
  36764. }
  36765. else {
  36766. vertex1 = path1[i];
  36767. vertex2 = path2[i];
  36768. }
  36769. vectlg = vertex2.subtract(vertex1).length();
  36770. dist = vectlg + vTotalDistance[i];
  36771. vs[i].push(dist);
  36772. vTotalDistance[i] = dist;
  36773. }
  36774. if (closeArray && vertex2 && vertex1) {
  36775. path1 = pathArray[p];
  36776. path2 = pathArray[0];
  36777. if (i === minlg) { // closePath
  36778. vertex2 = path2[0];
  36779. }
  36780. vectlg = vertex2.subtract(vertex1).length();
  36781. dist = vectlg + vTotalDistance[i];
  36782. vTotalDistance[i] = dist;
  36783. }
  36784. }
  36785. // uvs
  36786. var u;
  36787. var v;
  36788. if (customUV) {
  36789. for (p = 0; p < customUV.length; p++) {
  36790. uvs.push(customUV[p].x, customUV[p].y);
  36791. }
  36792. }
  36793. else {
  36794. for (p = 0; p < pathArray.length; p++) {
  36795. for (i = 0; i < minlg + closePathCorr; i++) {
  36796. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36797. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36798. if (invertUV) {
  36799. uvs.push(v, u);
  36800. }
  36801. else {
  36802. uvs.push(u, v);
  36803. }
  36804. }
  36805. }
  36806. }
  36807. // indices
  36808. p = 0; // path index
  36809. var pi = 0; // positions array index
  36810. var l1 = lg[p] - 1; // path1 length
  36811. var l2 = lg[p + 1] - 1; // path2 length
  36812. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36813. var shft = idx[1] - idx[0]; // shift
  36814. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36815. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36816. // 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
  36817. indices.push(pi, pi + shft, pi + 1);
  36818. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36819. pi += 1;
  36820. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36821. p++;
  36822. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36823. shft = idx[0] - idx[p];
  36824. l1 = lg[p] - 1;
  36825. l2 = lg[0] - 1;
  36826. }
  36827. else {
  36828. shft = idx[p + 1] - idx[p];
  36829. l1 = lg[p] - 1;
  36830. l2 = lg[p + 1] - 1;
  36831. }
  36832. pi = idx[p];
  36833. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36834. }
  36835. }
  36836. // normals
  36837. VertexData.ComputeNormals(positions, indices, normals);
  36838. if (closePath) { // update both the first and last vertex normals to their average value
  36839. var indexFirst = 0;
  36840. var indexLast = 0;
  36841. for (p = 0; p < pathArray.length; p++) {
  36842. indexFirst = idx[p] * 3;
  36843. if (p + 1 < pathArray.length) {
  36844. indexLast = (idx[p + 1] - 1) * 3;
  36845. }
  36846. else {
  36847. indexLast = normals.length - 3;
  36848. }
  36849. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36850. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36851. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36852. normals[indexLast] = normals[indexFirst];
  36853. normals[indexLast + 1] = normals[indexFirst + 1];
  36854. normals[indexLast + 2] = normals[indexFirst + 2];
  36855. }
  36856. }
  36857. // sides
  36858. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36859. // Colors
  36860. var colors = null;
  36861. if (customColors) {
  36862. colors = new Float32Array(customColors.length * 4);
  36863. for (var c = 0; c < customColors.length; c++) {
  36864. colors[c * 4] = customColors[c].r;
  36865. colors[c * 4 + 1] = customColors[c].g;
  36866. colors[c * 4 + 2] = customColors[c].b;
  36867. colors[c * 4 + 3] = customColors[c].a;
  36868. }
  36869. }
  36870. // Result
  36871. var vertexData = new VertexData();
  36872. var positions32 = new Float32Array(positions);
  36873. var normals32 = new Float32Array(normals);
  36874. var uvs32 = new Float32Array(uvs);
  36875. vertexData.indices = indices;
  36876. vertexData.positions = positions32;
  36877. vertexData.normals = normals32;
  36878. vertexData.uvs = uvs32;
  36879. if (colors) {
  36880. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36881. }
  36882. if (closePath) {
  36883. vertexData._idx = idx;
  36884. }
  36885. return vertexData;
  36886. };
  36887. /**
  36888. * Creates the VertexData for a box
  36889. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36890. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36891. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36892. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36893. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36894. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36895. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36896. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36897. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36898. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36899. * @returns the VertexData of the box
  36900. */
  36901. VertexData.CreateBox = function (options) {
  36902. var normalsSource = [
  36903. new BABYLON.Vector3(0, 0, 1),
  36904. new BABYLON.Vector3(0, 0, -1),
  36905. new BABYLON.Vector3(1, 0, 0),
  36906. new BABYLON.Vector3(-1, 0, 0),
  36907. new BABYLON.Vector3(0, 1, 0),
  36908. new BABYLON.Vector3(0, -1, 0)
  36909. ];
  36910. var indices = [];
  36911. var positions = [];
  36912. var normals = [];
  36913. var uvs = [];
  36914. var width = options.width || options.size || 1;
  36915. var height = options.height || options.size || 1;
  36916. var depth = options.depth || options.size || 1;
  36917. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36918. var faceUV = options.faceUV || new Array(6);
  36919. var faceColors = options.faceColors;
  36920. var colors = [];
  36921. // default face colors and UV if undefined
  36922. for (var f = 0; f < 6; f++) {
  36923. if (faceUV[f] === undefined) {
  36924. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36925. }
  36926. if (faceColors && faceColors[f] === undefined) {
  36927. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36928. }
  36929. }
  36930. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36931. // Create each face in turn.
  36932. for (var index = 0; index < normalsSource.length; index++) {
  36933. var normal = normalsSource[index];
  36934. // Get two vectors perpendicular to the face normal and to each other.
  36935. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36936. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36937. // Six indices (two triangles) per face.
  36938. var verticesLength = positions.length / 3;
  36939. indices.push(verticesLength);
  36940. indices.push(verticesLength + 1);
  36941. indices.push(verticesLength + 2);
  36942. indices.push(verticesLength);
  36943. indices.push(verticesLength + 2);
  36944. indices.push(verticesLength + 3);
  36945. // Four vertices per face.
  36946. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36947. positions.push(vertex.x, vertex.y, vertex.z);
  36948. normals.push(normal.x, normal.y, normal.z);
  36949. uvs.push(faceUV[index].z, faceUV[index].w);
  36950. if (faceColors) {
  36951. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36952. }
  36953. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36954. positions.push(vertex.x, vertex.y, vertex.z);
  36955. normals.push(normal.x, normal.y, normal.z);
  36956. uvs.push(faceUV[index].x, faceUV[index].w);
  36957. if (faceColors) {
  36958. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36959. }
  36960. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36961. positions.push(vertex.x, vertex.y, vertex.z);
  36962. normals.push(normal.x, normal.y, normal.z);
  36963. uvs.push(faceUV[index].x, faceUV[index].y);
  36964. if (faceColors) {
  36965. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36966. }
  36967. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36968. positions.push(vertex.x, vertex.y, vertex.z);
  36969. normals.push(normal.x, normal.y, normal.z);
  36970. uvs.push(faceUV[index].z, faceUV[index].y);
  36971. if (faceColors) {
  36972. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36973. }
  36974. }
  36975. // sides
  36976. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36977. // Result
  36978. var vertexData = new VertexData();
  36979. vertexData.indices = indices;
  36980. vertexData.positions = positions;
  36981. vertexData.normals = normals;
  36982. vertexData.uvs = uvs;
  36983. if (faceColors) {
  36984. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36985. vertexData.colors = totalColors;
  36986. }
  36987. return vertexData;
  36988. };
  36989. /**
  36990. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36991. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36992. * * segments sets the number of horizontal strips optional, default 32
  36993. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36994. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36995. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36996. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36997. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  36998. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  36999. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37000. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37001. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37002. * @returns the VertexData of the ellipsoid
  37003. */
  37004. VertexData.CreateSphere = function (options) {
  37005. var segments = options.segments || 32;
  37006. var diameterX = options.diameterX || options.diameter || 1;
  37007. var diameterY = options.diameterY || options.diameter || 1;
  37008. var diameterZ = options.diameterZ || options.diameter || 1;
  37009. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37010. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37011. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37012. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37013. var totalZRotationSteps = 2 + segments;
  37014. var totalYRotationSteps = 2 * totalZRotationSteps;
  37015. var indices = [];
  37016. var positions = [];
  37017. var normals = [];
  37018. var uvs = [];
  37019. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37020. var normalizedZ = zRotationStep / totalZRotationSteps;
  37021. var angleZ = normalizedZ * Math.PI * slice;
  37022. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37023. var normalizedY = yRotationStep / totalYRotationSteps;
  37024. var angleY = normalizedY * Math.PI * 2 * arc;
  37025. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37026. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37027. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37028. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37029. var vertex = complete.multiply(radius);
  37030. var normal = complete.divide(radius).normalize();
  37031. positions.push(vertex.x, vertex.y, vertex.z);
  37032. normals.push(normal.x, normal.y, normal.z);
  37033. uvs.push(normalizedY, normalizedZ);
  37034. }
  37035. if (zRotationStep > 0) {
  37036. var verticesCount = positions.length / 3;
  37037. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37038. indices.push((firstIndex));
  37039. indices.push((firstIndex + 1));
  37040. indices.push(firstIndex + totalYRotationSteps + 1);
  37041. indices.push((firstIndex + totalYRotationSteps + 1));
  37042. indices.push((firstIndex + 1));
  37043. indices.push((firstIndex + totalYRotationSteps + 2));
  37044. }
  37045. }
  37046. }
  37047. // Sides
  37048. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37049. // Result
  37050. var vertexData = new VertexData();
  37051. vertexData.indices = indices;
  37052. vertexData.positions = positions;
  37053. vertexData.normals = normals;
  37054. vertexData.uvs = uvs;
  37055. return vertexData;
  37056. };
  37057. /**
  37058. * Creates the VertexData for a cylinder, cone or prism
  37059. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37060. * * height sets the height (y direction) of the cylinder, optional, default 2
  37061. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37062. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37063. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37064. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37065. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37066. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  37067. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37068. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37069. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37070. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37071. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37072. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37073. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37074. * @returns the VertexData of the cylinder, cone or prism
  37075. */
  37076. VertexData.CreateCylinder = function (options) {
  37077. var height = options.height || 2;
  37078. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37079. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37080. var tessellation = options.tessellation || 24;
  37081. var subdivisions = options.subdivisions || 1;
  37082. var hasRings = options.hasRings ? true : false;
  37083. var enclose = options.enclose ? true : false;
  37084. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37085. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37086. var faceUV = options.faceUV || new Array(3);
  37087. var faceColors = options.faceColors;
  37088. // default face colors and UV if undefined
  37089. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37090. var ringNb = (hasRings) ? subdivisions : 1;
  37091. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37092. var f;
  37093. for (f = 0; f < surfaceNb; f++) {
  37094. if (faceColors && faceColors[f] === undefined) {
  37095. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37096. }
  37097. }
  37098. for (f = 0; f < surfaceNb; f++) {
  37099. if (faceUV && faceUV[f] === undefined) {
  37100. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37101. }
  37102. }
  37103. var indices = new Array();
  37104. var positions = new Array();
  37105. var normals = new Array();
  37106. var uvs = new Array();
  37107. var colors = new Array();
  37108. var angle_step = Math.PI * 2 * arc / tessellation;
  37109. var angle;
  37110. var h;
  37111. var radius;
  37112. var tan = (diameterBottom - diameterTop) / 2 / height;
  37113. var ringVertex = BABYLON.Vector3.Zero();
  37114. var ringNormal = BABYLON.Vector3.Zero();
  37115. var ringFirstVertex = BABYLON.Vector3.Zero();
  37116. var ringFirstNormal = BABYLON.Vector3.Zero();
  37117. var quadNormal = BABYLON.Vector3.Zero();
  37118. var Y = BABYLON.Axis.Y;
  37119. // positions, normals, uvs
  37120. var i;
  37121. var j;
  37122. var r;
  37123. var ringIdx = 1;
  37124. var s = 1; // surface index
  37125. var cs = 0;
  37126. var v = 0;
  37127. for (i = 0; i <= subdivisions; i++) {
  37128. h = i / subdivisions;
  37129. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37130. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37131. for (r = 0; r < ringIdx; r++) {
  37132. if (hasRings) {
  37133. s += r;
  37134. }
  37135. if (enclose) {
  37136. s += 2 * r;
  37137. }
  37138. for (j = 0; j <= tessellation; j++) {
  37139. angle = j * angle_step;
  37140. // position
  37141. ringVertex.x = Math.cos(-angle) * radius;
  37142. ringVertex.y = -height / 2 + h * height;
  37143. ringVertex.z = Math.sin(-angle) * radius;
  37144. // normal
  37145. if (diameterTop === 0 && i === subdivisions) {
  37146. // if no top cap, reuse former normals
  37147. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37148. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37149. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37150. }
  37151. else {
  37152. ringNormal.x = ringVertex.x;
  37153. ringNormal.z = ringVertex.z;
  37154. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37155. ringNormal.normalize();
  37156. }
  37157. // keep first ring vertex values for enclose
  37158. if (j === 0) {
  37159. ringFirstVertex.copyFrom(ringVertex);
  37160. ringFirstNormal.copyFrom(ringNormal);
  37161. }
  37162. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37163. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37164. if (hasRings) {
  37165. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37166. }
  37167. else {
  37168. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37169. }
  37170. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37171. if (faceColors) {
  37172. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37173. }
  37174. }
  37175. // if enclose, add four vertices and their dedicated normals
  37176. if (arc !== 1 && enclose) {
  37177. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37178. positions.push(0, ringVertex.y, 0);
  37179. positions.push(0, ringVertex.y, 0);
  37180. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37181. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37182. quadNormal.normalize();
  37183. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37184. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37185. quadNormal.normalize();
  37186. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37187. if (hasRings) {
  37188. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37189. }
  37190. else {
  37191. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37192. }
  37193. uvs.push(faceUV[s + 1].x, v);
  37194. uvs.push(faceUV[s + 1].z, v);
  37195. if (hasRings) {
  37196. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37197. }
  37198. else {
  37199. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37200. }
  37201. uvs.push(faceUV[s + 2].x, v);
  37202. uvs.push(faceUV[s + 2].z, v);
  37203. if (faceColors) {
  37204. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37205. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37206. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37207. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37208. }
  37209. }
  37210. if (cs !== s) {
  37211. cs = s;
  37212. }
  37213. }
  37214. }
  37215. // indices
  37216. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37217. var s;
  37218. i = 0;
  37219. for (s = 0; s < subdivisions; s++) {
  37220. var i0 = 0;
  37221. var i1 = 0;
  37222. var i2 = 0;
  37223. var i3 = 0;
  37224. for (j = 0; j < tessellation; j++) {
  37225. i0 = i * (e + 1) + j;
  37226. i1 = (i + 1) * (e + 1) + j;
  37227. i2 = i * (e + 1) + (j + 1);
  37228. i3 = (i + 1) * (e + 1) + (j + 1);
  37229. indices.push(i0, i1, i2);
  37230. indices.push(i3, i2, i1);
  37231. }
  37232. if (arc !== 1 && enclose) { // if enclose, add two quads
  37233. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37234. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37235. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37236. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37237. }
  37238. i = (hasRings) ? (i + 2) : (i + 1);
  37239. }
  37240. // Caps
  37241. var createCylinderCap = function (isTop) {
  37242. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37243. if (radius === 0) {
  37244. return;
  37245. }
  37246. // Cap positions, normals & uvs
  37247. var angle;
  37248. var circleVector;
  37249. var i;
  37250. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37251. var c = null;
  37252. if (faceColors) {
  37253. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37254. }
  37255. // cap center
  37256. var vbase = positions.length / 3;
  37257. var offset = isTop ? height / 2 : -height / 2;
  37258. var center = new BABYLON.Vector3(0, offset, 0);
  37259. positions.push(center.x, center.y, center.z);
  37260. normals.push(0, isTop ? 1 : -1, 0);
  37261. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37262. if (c) {
  37263. colors.push(c.r, c.g, c.b, c.a);
  37264. }
  37265. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37266. for (i = 0; i <= tessellation; i++) {
  37267. angle = Math.PI * 2 * i * arc / tessellation;
  37268. var cos = Math.cos(-angle);
  37269. var sin = Math.sin(-angle);
  37270. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37271. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37272. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37273. normals.push(0, isTop ? 1 : -1, 0);
  37274. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37275. if (c) {
  37276. colors.push(c.r, c.g, c.b, c.a);
  37277. }
  37278. }
  37279. // Cap indices
  37280. for (i = 0; i < tessellation; i++) {
  37281. if (!isTop) {
  37282. indices.push(vbase);
  37283. indices.push(vbase + (i + 1));
  37284. indices.push(vbase + (i + 2));
  37285. }
  37286. else {
  37287. indices.push(vbase);
  37288. indices.push(vbase + (i + 2));
  37289. indices.push(vbase + (i + 1));
  37290. }
  37291. }
  37292. };
  37293. // add caps to geometry
  37294. createCylinderCap(false);
  37295. createCylinderCap(true);
  37296. // Sides
  37297. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37298. var vertexData = new VertexData();
  37299. vertexData.indices = indices;
  37300. vertexData.positions = positions;
  37301. vertexData.normals = normals;
  37302. vertexData.uvs = uvs;
  37303. if (faceColors) {
  37304. vertexData.colors = colors;
  37305. }
  37306. return vertexData;
  37307. };
  37308. /**
  37309. * Creates the VertexData for a torus
  37310. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37311. * * diameter the diameter of the torus, optional default 1
  37312. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37313. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37314. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37315. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37316. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37317. * @returns the VertexData of the torus
  37318. */
  37319. VertexData.CreateTorus = function (options) {
  37320. var indices = [];
  37321. var positions = [];
  37322. var normals = [];
  37323. var uvs = [];
  37324. var diameter = options.diameter || 1;
  37325. var thickness = options.thickness || 0.5;
  37326. var tessellation = options.tessellation || 16;
  37327. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37328. var stride = tessellation + 1;
  37329. for (var i = 0; i <= tessellation; i++) {
  37330. var u = i / tessellation;
  37331. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37332. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37333. for (var j = 0; j <= tessellation; j++) {
  37334. var v = 1 - j / tessellation;
  37335. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37336. var dx = Math.cos(innerAngle);
  37337. var dy = Math.sin(innerAngle);
  37338. // Create a vertex.
  37339. var normal = new BABYLON.Vector3(dx, dy, 0);
  37340. var position = normal.scale(thickness / 2);
  37341. var textureCoordinate = new BABYLON.Vector2(u, v);
  37342. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37343. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37344. positions.push(position.x, position.y, position.z);
  37345. normals.push(normal.x, normal.y, normal.z);
  37346. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37347. // And create indices for two triangles.
  37348. var nextI = (i + 1) % stride;
  37349. var nextJ = (j + 1) % stride;
  37350. indices.push(i * stride + j);
  37351. indices.push(i * stride + nextJ);
  37352. indices.push(nextI * stride + j);
  37353. indices.push(i * stride + nextJ);
  37354. indices.push(nextI * stride + nextJ);
  37355. indices.push(nextI * stride + j);
  37356. }
  37357. }
  37358. // Sides
  37359. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37360. // Result
  37361. var vertexData = new VertexData();
  37362. vertexData.indices = indices;
  37363. vertexData.positions = positions;
  37364. vertexData.normals = normals;
  37365. vertexData.uvs = uvs;
  37366. return vertexData;
  37367. };
  37368. /**
  37369. * Creates the VertexData of the LineSystem
  37370. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37371. * - lines an array of lines, each line being an array of successive Vector3
  37372. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37373. * @returns the VertexData of the LineSystem
  37374. */
  37375. VertexData.CreateLineSystem = function (options) {
  37376. var indices = [];
  37377. var positions = [];
  37378. var lines = options.lines;
  37379. var colors = options.colors;
  37380. var vertexColors = [];
  37381. var idx = 0;
  37382. for (var l = 0; l < lines.length; l++) {
  37383. var points = lines[l];
  37384. for (var index = 0; index < points.length; index++) {
  37385. positions.push(points[index].x, points[index].y, points[index].z);
  37386. if (colors) {
  37387. var color = colors[l];
  37388. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37389. }
  37390. if (index > 0) {
  37391. indices.push(idx - 1);
  37392. indices.push(idx);
  37393. }
  37394. idx++;
  37395. }
  37396. }
  37397. var vertexData = new VertexData();
  37398. vertexData.indices = indices;
  37399. vertexData.positions = positions;
  37400. if (colors) {
  37401. vertexData.colors = vertexColors;
  37402. }
  37403. return vertexData;
  37404. };
  37405. /**
  37406. * Create the VertexData for a DashedLines
  37407. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37408. * - points an array successive Vector3
  37409. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37410. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37411. * - dashNb the intended total number of dashes, optional, default 200
  37412. * @returns the VertexData for the DashedLines
  37413. */
  37414. VertexData.CreateDashedLines = function (options) {
  37415. var dashSize = options.dashSize || 3;
  37416. var gapSize = options.gapSize || 1;
  37417. var dashNb = options.dashNb || 200;
  37418. var points = options.points;
  37419. var positions = new Array();
  37420. var indices = new Array();
  37421. var curvect = BABYLON.Vector3.Zero();
  37422. var lg = 0;
  37423. var nb = 0;
  37424. var shft = 0;
  37425. var dashshft = 0;
  37426. var curshft = 0;
  37427. var idx = 0;
  37428. var i = 0;
  37429. for (i = 0; i < points.length - 1; i++) {
  37430. points[i + 1].subtractToRef(points[i], curvect);
  37431. lg += curvect.length();
  37432. }
  37433. shft = lg / dashNb;
  37434. dashshft = dashSize * shft / (dashSize + gapSize);
  37435. for (i = 0; i < points.length - 1; i++) {
  37436. points[i + 1].subtractToRef(points[i], curvect);
  37437. nb = Math.floor(curvect.length() / shft);
  37438. curvect.normalize();
  37439. for (var j = 0; j < nb; j++) {
  37440. curshft = shft * j;
  37441. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37442. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37443. indices.push(idx, idx + 1);
  37444. idx += 2;
  37445. }
  37446. }
  37447. // Result
  37448. var vertexData = new VertexData();
  37449. vertexData.positions = positions;
  37450. vertexData.indices = indices;
  37451. return vertexData;
  37452. };
  37453. /**
  37454. * Creates the VertexData for a Ground
  37455. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37456. * - width the width (x direction) of the ground, optional, default 1
  37457. * - height the height (z direction) of the ground, optional, default 1
  37458. * - subdivisions the number of subdivisions per side, optional, default 1
  37459. * @returns the VertexData of the Ground
  37460. */
  37461. VertexData.CreateGround = function (options) {
  37462. var indices = [];
  37463. var positions = [];
  37464. var normals = [];
  37465. var uvs = [];
  37466. var row, col;
  37467. var width = options.width || 1;
  37468. var height = options.height || 1;
  37469. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37470. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37471. for (row = 0; row <= subdivisionsY; row++) {
  37472. for (col = 0; col <= subdivisionsX; col++) {
  37473. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37474. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37475. positions.push(position.x, position.y, position.z);
  37476. normals.push(normal.x, normal.y, normal.z);
  37477. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37478. }
  37479. }
  37480. for (row = 0; row < subdivisionsY; row++) {
  37481. for (col = 0; col < subdivisionsX; col++) {
  37482. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37483. indices.push(col + 1 + row * (subdivisionsX + 1));
  37484. indices.push(col + row * (subdivisionsX + 1));
  37485. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37486. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37487. indices.push(col + row * (subdivisionsX + 1));
  37488. }
  37489. }
  37490. // Result
  37491. var vertexData = new VertexData();
  37492. vertexData.indices = indices;
  37493. vertexData.positions = positions;
  37494. vertexData.normals = normals;
  37495. vertexData.uvs = uvs;
  37496. return vertexData;
  37497. };
  37498. /**
  37499. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37500. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37501. * * xmin the ground minimum X coordinate, optional, default -1
  37502. * * zmin the ground minimum Z coordinate, optional, default -1
  37503. * * xmax the ground maximum X coordinate, optional, default 1
  37504. * * zmax the ground maximum Z coordinate, optional, default 1
  37505. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37506. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37507. * @returns the VertexData of the TiledGround
  37508. */
  37509. VertexData.CreateTiledGround = function (options) {
  37510. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37511. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37512. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37513. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37514. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37515. var precision = options.precision || { w: 1, h: 1 };
  37516. var indices = new Array();
  37517. var positions = new Array();
  37518. var normals = new Array();
  37519. var uvs = new Array();
  37520. var row, col, tileRow, tileCol;
  37521. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37522. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37523. precision.w = (precision.w < 1) ? 1 : precision.w;
  37524. precision.h = (precision.h < 1) ? 1 : precision.h;
  37525. var tileSize = {
  37526. 'w': (xmax - xmin) / subdivisions.w,
  37527. 'h': (zmax - zmin) / subdivisions.h
  37528. };
  37529. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37530. // Indices
  37531. var base = positions.length / 3;
  37532. var rowLength = precision.w + 1;
  37533. for (row = 0; row < precision.h; row++) {
  37534. for (col = 0; col < precision.w; col++) {
  37535. var square = [
  37536. base + col + row * rowLength,
  37537. base + (col + 1) + row * rowLength,
  37538. base + (col + 1) + (row + 1) * rowLength,
  37539. base + col + (row + 1) * rowLength
  37540. ];
  37541. indices.push(square[1]);
  37542. indices.push(square[2]);
  37543. indices.push(square[3]);
  37544. indices.push(square[0]);
  37545. indices.push(square[1]);
  37546. indices.push(square[3]);
  37547. }
  37548. }
  37549. // Position, normals and uvs
  37550. var position = BABYLON.Vector3.Zero();
  37551. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37552. for (row = 0; row <= precision.h; row++) {
  37553. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37554. for (col = 0; col <= precision.w; col++) {
  37555. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37556. position.y = 0;
  37557. positions.push(position.x, position.y, position.z);
  37558. normals.push(normal.x, normal.y, normal.z);
  37559. uvs.push(col / precision.w, row / precision.h);
  37560. }
  37561. }
  37562. }
  37563. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37564. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37565. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37566. }
  37567. }
  37568. // Result
  37569. var vertexData = new VertexData();
  37570. vertexData.indices = indices;
  37571. vertexData.positions = positions;
  37572. vertexData.normals = normals;
  37573. vertexData.uvs = uvs;
  37574. return vertexData;
  37575. };
  37576. /**
  37577. * Creates the VertexData of the Ground designed from a heightmap
  37578. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37579. * * width the width (x direction) of the ground
  37580. * * height the height (z direction) of the ground
  37581. * * subdivisions the number of subdivisions per side
  37582. * * minHeight the minimum altitude on the ground, optional, default 0
  37583. * * maxHeight the maximum altitude on the ground, optional default 1
  37584. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37585. * * buffer the array holding the image color data
  37586. * * bufferWidth the width of image
  37587. * * bufferHeight the height of image
  37588. * @returns the VertexData of the Ground designed from a heightmap
  37589. */
  37590. VertexData.CreateGroundFromHeightMap = function (options) {
  37591. var indices = [];
  37592. var positions = [];
  37593. var normals = [];
  37594. var uvs = [];
  37595. var row, col;
  37596. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37597. // Vertices
  37598. for (row = 0; row <= options.subdivisions; row++) {
  37599. for (col = 0; col <= options.subdivisions; col++) {
  37600. 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));
  37601. // Compute height
  37602. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37603. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37604. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37605. var r = options.buffer[pos] / 255.0;
  37606. var g = options.buffer[pos + 1] / 255.0;
  37607. var b = options.buffer[pos + 2] / 255.0;
  37608. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37609. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37610. // Add vertex
  37611. positions.push(position.x, position.y, position.z);
  37612. normals.push(0, 0, 0);
  37613. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37614. }
  37615. }
  37616. // Indices
  37617. for (row = 0; row < options.subdivisions; row++) {
  37618. for (col = 0; col < options.subdivisions; col++) {
  37619. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37620. indices.push(col + 1 + row * (options.subdivisions + 1));
  37621. indices.push(col + row * (options.subdivisions + 1));
  37622. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37623. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37624. indices.push(col + row * (options.subdivisions + 1));
  37625. }
  37626. }
  37627. // Normals
  37628. VertexData.ComputeNormals(positions, indices, normals);
  37629. // Result
  37630. var vertexData = new VertexData();
  37631. vertexData.indices = indices;
  37632. vertexData.positions = positions;
  37633. vertexData.normals = normals;
  37634. vertexData.uvs = uvs;
  37635. return vertexData;
  37636. };
  37637. /**
  37638. * Creates the VertexData for a Plane
  37639. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37640. * * size sets the width and height of the plane to the value of size, optional default 1
  37641. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37642. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37643. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37644. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37645. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37646. * @returns the VertexData of the box
  37647. */
  37648. VertexData.CreatePlane = function (options) {
  37649. var indices = [];
  37650. var positions = [];
  37651. var normals = [];
  37652. var uvs = [];
  37653. var width = options.width || options.size || 1;
  37654. var height = options.height || options.size || 1;
  37655. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37656. // Vertices
  37657. var halfWidth = width / 2.0;
  37658. var halfHeight = height / 2.0;
  37659. positions.push(-halfWidth, -halfHeight, 0);
  37660. normals.push(0, 0, -1.0);
  37661. uvs.push(0.0, 0.0);
  37662. positions.push(halfWidth, -halfHeight, 0);
  37663. normals.push(0, 0, -1.0);
  37664. uvs.push(1.0, 0.0);
  37665. positions.push(halfWidth, halfHeight, 0);
  37666. normals.push(0, 0, -1.0);
  37667. uvs.push(1.0, 1.0);
  37668. positions.push(-halfWidth, halfHeight, 0);
  37669. normals.push(0, 0, -1.0);
  37670. uvs.push(0.0, 1.0);
  37671. // Indices
  37672. indices.push(0);
  37673. indices.push(1);
  37674. indices.push(2);
  37675. indices.push(0);
  37676. indices.push(2);
  37677. indices.push(3);
  37678. // Sides
  37679. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37680. // Result
  37681. var vertexData = new VertexData();
  37682. vertexData.indices = indices;
  37683. vertexData.positions = positions;
  37684. vertexData.normals = normals;
  37685. vertexData.uvs = uvs;
  37686. return vertexData;
  37687. };
  37688. /**
  37689. * Creates the VertexData of the Disc or regular Polygon
  37690. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37691. * * radius the radius of the disc, optional default 0.5
  37692. * * tessellation the number of polygon sides, optional, default 64
  37693. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  37694. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37695. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37696. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37697. * @returns the VertexData of the box
  37698. */
  37699. VertexData.CreateDisc = function (options) {
  37700. var positions = new Array();
  37701. var indices = new Array();
  37702. var normals = new Array();
  37703. var uvs = new Array();
  37704. var radius = options.radius || 0.5;
  37705. var tessellation = options.tessellation || 64;
  37706. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37707. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37708. // positions and uvs
  37709. positions.push(0, 0, 0); // disc center first
  37710. uvs.push(0.5, 0.5);
  37711. var theta = Math.PI * 2 * arc;
  37712. var step = theta / tessellation;
  37713. for (var a = 0; a < theta; a += step) {
  37714. var x = Math.cos(a);
  37715. var y = Math.sin(a);
  37716. var u = (x + 1) / 2;
  37717. var v = (1 - y) / 2;
  37718. positions.push(radius * x, radius * y, 0);
  37719. uvs.push(u, v);
  37720. }
  37721. if (arc === 1) {
  37722. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37723. uvs.push(uvs[2], uvs[3]);
  37724. }
  37725. //indices
  37726. var vertexNb = positions.length / 3;
  37727. for (var i = 1; i < vertexNb - 1; i++) {
  37728. indices.push(i + 1, 0, i);
  37729. }
  37730. // result
  37731. VertexData.ComputeNormals(positions, indices, normals);
  37732. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37733. var vertexData = new VertexData();
  37734. vertexData.indices = indices;
  37735. vertexData.positions = positions;
  37736. vertexData.normals = normals;
  37737. vertexData.uvs = uvs;
  37738. return vertexData;
  37739. };
  37740. /**
  37741. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37742. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37743. * @param polygon a mesh built from polygonTriangulation.build()
  37744. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37745. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37746. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37747. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37748. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37749. * @returns the VertexData of the Polygon
  37750. */
  37751. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37752. var faceUV = fUV || new Array(3);
  37753. var faceColors = fColors;
  37754. var colors = [];
  37755. // default face colors and UV if undefined
  37756. for (var f = 0; f < 3; f++) {
  37757. if (faceUV[f] === undefined) {
  37758. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37759. }
  37760. if (faceColors && faceColors[f] === undefined) {
  37761. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37762. }
  37763. }
  37764. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37765. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37766. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37767. var indices = polygon.getIndices();
  37768. // set face colours and textures
  37769. var idx = 0;
  37770. var face = 0;
  37771. for (var index = 0; index < normals.length; index += 3) {
  37772. //Edge Face no. 1
  37773. if (Math.abs(normals[index + 1]) < 0.001) {
  37774. face = 1;
  37775. }
  37776. //Top Face no. 0
  37777. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37778. face = 0;
  37779. }
  37780. //Bottom Face no. 2
  37781. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37782. face = 2;
  37783. }
  37784. idx = index / 3;
  37785. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37786. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37787. if (faceColors) {
  37788. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37789. }
  37790. }
  37791. // sides
  37792. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37793. // Result
  37794. var vertexData = new VertexData();
  37795. vertexData.indices = indices;
  37796. vertexData.positions = positions;
  37797. vertexData.normals = normals;
  37798. vertexData.uvs = uvs;
  37799. if (faceColors) {
  37800. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37801. vertexData.colors = totalColors;
  37802. }
  37803. return vertexData;
  37804. };
  37805. /**
  37806. * Creates the VertexData of the IcoSphere
  37807. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37808. * * radius the radius of the IcoSphere, optional default 1
  37809. * * radiusX allows stretching in the x direction, optional, default radius
  37810. * * radiusY allows stretching in the y direction, optional, default radius
  37811. * * radiusZ allows stretching in the z direction, optional, default radius
  37812. * * flat when true creates a flat shaded mesh, optional, default true
  37813. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37814. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37815. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37816. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37817. * @returns the VertexData of the IcoSphere
  37818. */
  37819. VertexData.CreateIcoSphere = function (options) {
  37820. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37821. var radius = options.radius || 1;
  37822. var flat = (options.flat === undefined) ? true : options.flat;
  37823. var subdivisions = options.subdivisions || 4;
  37824. var radiusX = options.radiusX || radius;
  37825. var radiusY = options.radiusY || radius;
  37826. var radiusZ = options.radiusZ || radius;
  37827. var t = (1 + Math.sqrt(5)) / 2;
  37828. // 12 vertex x,y,z
  37829. var ico_vertices = [
  37830. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37831. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37832. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37833. ];
  37834. // index of 3 vertex makes a face of icopshere
  37835. var ico_indices = [
  37836. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37837. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37838. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37839. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37840. ];
  37841. // vertex for uv have aliased position, not for UV
  37842. var vertices_unalias_id = [
  37843. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37844. // vertex alias
  37845. 0,
  37846. 2,
  37847. 3,
  37848. 3,
  37849. 3,
  37850. 4,
  37851. 7,
  37852. 8,
  37853. 9,
  37854. 9,
  37855. 10,
  37856. 11 // 23: B + 12
  37857. ];
  37858. // uv as integer step (not pixels !)
  37859. var ico_vertexuv = [
  37860. 5, 1, 3, 1, 6, 4, 0, 0,
  37861. 5, 3, 4, 2, 2, 2, 4, 0,
  37862. 2, 0, 1, 1, 6, 0, 6, 2,
  37863. // vertex alias (for same vertex on different faces)
  37864. 0, 4,
  37865. 3, 3,
  37866. 4, 4,
  37867. 3, 1,
  37868. 4, 2,
  37869. 4, 4,
  37870. 0, 2,
  37871. 1, 1,
  37872. 2, 2,
  37873. 3, 3,
  37874. 1, 3,
  37875. 2, 4 // 23: B + 12
  37876. ];
  37877. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37878. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37879. // First island of uv mapping
  37880. // v = 4h 3+ 2
  37881. // v = 3h 9+ 4
  37882. // v = 2h 9+ 5 B
  37883. // v = 1h 9 1 0
  37884. // v = 0h 3 8 7 A
  37885. // u = 0 1 2 3 4 5 6 *a
  37886. // Second island of uv mapping
  37887. // v = 4h 0+ B+ 4+
  37888. // v = 3h A+ 2+
  37889. // v = 2h 7+ 6 3+
  37890. // v = 1h 8+ 3+
  37891. // v = 0h
  37892. // u = 0 1 2 3 4 5 6 *a
  37893. // Face layout on texture UV mapping
  37894. // ============
  37895. // \ 4 /\ 16 / ======
  37896. // \ / \ / /\ 11 /
  37897. // \/ 7 \/ / \ /
  37898. // ======= / 10 \/
  37899. // /\ 17 /\ =======
  37900. // / \ / \ \ 15 /\
  37901. // / 8 \/ 12 \ \ / \
  37902. // ============ \/ 6 \
  37903. // \ 18 /\ ============
  37904. // \ / \ \ 5 /\ 0 /
  37905. // \/ 13 \ \ / \ /
  37906. // ======= \/ 1 \/
  37907. // =============
  37908. // /\ 19 /\ 2 /\
  37909. // / \ / \ / \
  37910. // / 14 \/ 9 \/ 3 \
  37911. // ===================
  37912. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37913. var ustep = 138 / 1024;
  37914. var vstep = 239 / 1024;
  37915. var uoffset = 60 / 1024;
  37916. var voffset = 26 / 1024;
  37917. // Second island should have margin, not to touch the first island
  37918. // avoid any borderline artefact in pixel rounding
  37919. var island_u_offset = -40 / 1024;
  37920. var island_v_offset = +20 / 1024;
  37921. // face is either island 0 or 1 :
  37922. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37923. var island = [
  37924. 0, 0, 0, 0, 1,
  37925. 0, 0, 1, 1, 0,
  37926. 0, 0, 1, 1, 0,
  37927. 0, 1, 1, 1, 0 // 15 - 19
  37928. ];
  37929. var indices = new Array();
  37930. var positions = new Array();
  37931. var normals = new Array();
  37932. var uvs = new Array();
  37933. var current_indice = 0;
  37934. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37935. var face_vertex_pos = new Array(3);
  37936. var face_vertex_uv = new Array(3);
  37937. var v012;
  37938. for (v012 = 0; v012 < 3; v012++) {
  37939. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37940. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37941. }
  37942. // create all with normals
  37943. for (var face = 0; face < 20; face++) {
  37944. // 3 vertex per face
  37945. for (v012 = 0; v012 < 3; v012++) {
  37946. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37947. var v_id = ico_indices[3 * face + v012];
  37948. // vertex have 3D position (x,y,z)
  37949. 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]);
  37950. // Normalize to get normal, then scale to radius
  37951. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37952. // uv Coordinates from vertex ID
  37953. 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);
  37954. }
  37955. // Subdivide the face (interpolate pos, norm, uv)
  37956. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37957. // - norm is linear interpolation of vertex corner normal
  37958. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37959. // - uv is linear interpolation
  37960. //
  37961. // Topology is as below for sub-divide by 2
  37962. // vertex shown as v0,v1,v2
  37963. // interp index is i1 to progress in range [v0,v1[
  37964. // interp index is i2 to progress in range [v0,v2[
  37965. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37966. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37967. //
  37968. //
  37969. // i2 v2
  37970. // ^ ^
  37971. // / / \
  37972. // / / \
  37973. // / / \
  37974. // / / (0,1) \
  37975. // / #---------\
  37976. // / / \ (0,0)'/ \
  37977. // / / \ / \
  37978. // / / \ / \
  37979. // / / (0,0) \ / (1,0) \
  37980. // / #---------#---------\
  37981. // v0 v1
  37982. //
  37983. // --------------------> i1
  37984. //
  37985. // interp of (i1,i2):
  37986. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37987. // along i1 : lerp(x0,x1, i1/(S-i2))
  37988. //
  37989. // centroid of triangle is needed to get help normal computation
  37990. // (c1,c2) are used for centroid location
  37991. var interp_vertex = function (i1, i2, c1, c2) {
  37992. // vertex is interpolated from
  37993. // - face_vertex_pos[0..2]
  37994. // - face_vertex_uv[0..2]
  37995. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37996. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37997. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37998. pos_interp.normalize();
  37999. var vertex_normal;
  38000. if (flat) {
  38001. // in flat mode, recalculate normal as face centroid normal
  38002. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38003. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38004. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38005. }
  38006. else {
  38007. // in smooth mode, recalculate normal from each single vertex position
  38008. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38009. }
  38010. // Vertex normal need correction due to X,Y,Z radius scaling
  38011. vertex_normal.x /= radiusX;
  38012. vertex_normal.y /= radiusY;
  38013. vertex_normal.z /= radiusZ;
  38014. vertex_normal.normalize();
  38015. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38016. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38017. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38018. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38019. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38020. uvs.push(uv_interp.x, uv_interp.y);
  38021. // push each vertex has member of a face
  38022. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38023. indices.push(current_indice);
  38024. current_indice++;
  38025. };
  38026. for (var i2 = 0; i2 < subdivisions; i2++) {
  38027. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38028. // face : (i1,i2) for /\ :
  38029. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38030. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38031. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38032. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38033. if (i1 + i2 + 1 < subdivisions) {
  38034. // face : (i1,i2)' for \/ :
  38035. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38036. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38037. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38038. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38039. }
  38040. }
  38041. }
  38042. }
  38043. // Sides
  38044. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38045. // Result
  38046. var vertexData = new VertexData();
  38047. vertexData.indices = indices;
  38048. vertexData.positions = positions;
  38049. vertexData.normals = normals;
  38050. vertexData.uvs = uvs;
  38051. return vertexData;
  38052. };
  38053. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38054. /**
  38055. * Creates the VertexData for a Polyhedron
  38056. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38057. * * type provided types are:
  38058. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38059. * * 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)
  38060. * * size the size of the IcoSphere, optional default 1
  38061. * * sizeX allows stretching in the x direction, optional, default size
  38062. * * sizeY allows stretching in the y direction, optional, default size
  38063. * * sizeZ allows stretching in the z direction, optional, default size
  38064. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  38065. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38066. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38067. * * flat when true creates a flat shaded mesh, optional, default true
  38068. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38069. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38070. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38071. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38072. * @returns the VertexData of the Polyhedron
  38073. */
  38074. VertexData.CreatePolyhedron = function (options) {
  38075. // provided polyhedron types :
  38076. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38077. // 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)
  38078. var polyhedra = [];
  38079. 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]] };
  38080. 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]] };
  38081. polyhedra[2] = {
  38082. 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]],
  38083. 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]]
  38084. };
  38085. polyhedra[3] = {
  38086. 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]],
  38087. 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]]
  38088. };
  38089. polyhedra[4] = {
  38090. 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]],
  38091. 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]]
  38092. };
  38093. 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]] };
  38094. 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]] };
  38095. 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]] };
  38096. 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]] };
  38097. 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]] };
  38098. 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]] };
  38099. 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]] };
  38100. 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]] };
  38101. 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]] };
  38102. polyhedra[14] = {
  38103. 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]],
  38104. 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]]
  38105. };
  38106. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38107. var size = options.size;
  38108. var sizeX = options.sizeX || size || 1;
  38109. var sizeY = options.sizeY || size || 1;
  38110. var sizeZ = options.sizeZ || size || 1;
  38111. var data = options.custom || polyhedra[type];
  38112. var nbfaces = data.face.length;
  38113. var faceUV = options.faceUV || new Array(nbfaces);
  38114. var faceColors = options.faceColors;
  38115. var flat = (options.flat === undefined) ? true : options.flat;
  38116. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38117. var positions = new Array();
  38118. var indices = new Array();
  38119. var normals = new Array();
  38120. var uvs = new Array();
  38121. var colors = new Array();
  38122. var index = 0;
  38123. var faceIdx = 0; // face cursor in the array "indexes"
  38124. var indexes = new Array();
  38125. var i = 0;
  38126. var f = 0;
  38127. var u, v, ang, x, y, tmp;
  38128. // default face colors and UV if undefined
  38129. if (flat) {
  38130. for (f = 0; f < nbfaces; f++) {
  38131. if (faceColors && faceColors[f] === undefined) {
  38132. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38133. }
  38134. if (faceUV && faceUV[f] === undefined) {
  38135. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38136. }
  38137. }
  38138. }
  38139. if (!flat) {
  38140. for (i = 0; i < data.vertex.length; i++) {
  38141. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38142. uvs.push(0, 0);
  38143. }
  38144. for (f = 0; f < nbfaces; f++) {
  38145. for (i = 0; i < data.face[f].length - 2; i++) {
  38146. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38147. }
  38148. }
  38149. }
  38150. else {
  38151. for (f = 0; f < nbfaces; f++) {
  38152. var fl = data.face[f].length; // number of vertices of the current face
  38153. ang = 2 * Math.PI / fl;
  38154. x = 0.5 * Math.tan(ang / 2);
  38155. y = 0.5;
  38156. // positions, uvs, colors
  38157. for (i = 0; i < fl; i++) {
  38158. // positions
  38159. 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);
  38160. indexes.push(index);
  38161. index++;
  38162. // uvs
  38163. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38164. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38165. uvs.push(u, v);
  38166. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38167. y = x * Math.sin(ang) + y * Math.cos(ang);
  38168. x = tmp;
  38169. // colors
  38170. if (faceColors) {
  38171. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38172. }
  38173. }
  38174. // indices from indexes
  38175. for (i = 0; i < fl - 2; i++) {
  38176. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38177. }
  38178. faceIdx += fl;
  38179. }
  38180. }
  38181. VertexData.ComputeNormals(positions, indices, normals);
  38182. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38183. var vertexData = new VertexData();
  38184. vertexData.positions = positions;
  38185. vertexData.indices = indices;
  38186. vertexData.normals = normals;
  38187. vertexData.uvs = uvs;
  38188. if (faceColors && flat) {
  38189. vertexData.colors = colors;
  38190. }
  38191. return vertexData;
  38192. };
  38193. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38194. /**
  38195. * Creates the VertexData for a TorusKnot
  38196. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38197. * * radius the radius of the torus knot, optional, default 2
  38198. * * tube the thickness of the tube, optional, default 0.5
  38199. * * radialSegments the number of sides on each tube segments, optional, default 32
  38200. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38201. * * p the number of windings around the z axis, optional, default 2
  38202. * * q the number of windings around the x axis, optional, default 3
  38203. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38204. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38205. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38206. * @returns the VertexData of the Torus Knot
  38207. */
  38208. VertexData.CreateTorusKnot = function (options) {
  38209. var indices = new Array();
  38210. var positions = new Array();
  38211. var normals = new Array();
  38212. var uvs = new Array();
  38213. var radius = options.radius || 2;
  38214. var tube = options.tube || 0.5;
  38215. var radialSegments = options.radialSegments || 32;
  38216. var tubularSegments = options.tubularSegments || 32;
  38217. var p = options.p || 2;
  38218. var q = options.q || 3;
  38219. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38220. // Helper
  38221. var getPos = function (angle) {
  38222. var cu = Math.cos(angle);
  38223. var su = Math.sin(angle);
  38224. var quOverP = q / p * angle;
  38225. var cs = Math.cos(quOverP);
  38226. var tx = radius * (2 + cs) * 0.5 * cu;
  38227. var ty = radius * (2 + cs) * su * 0.5;
  38228. var tz = radius * Math.sin(quOverP) * 0.5;
  38229. return new BABYLON.Vector3(tx, ty, tz);
  38230. };
  38231. // Vertices
  38232. var i;
  38233. var j;
  38234. for (i = 0; i <= radialSegments; i++) {
  38235. var modI = i % radialSegments;
  38236. var u = modI / radialSegments * 2 * p * Math.PI;
  38237. var p1 = getPos(u);
  38238. var p2 = getPos(u + 0.01);
  38239. var tang = p2.subtract(p1);
  38240. var n = p2.add(p1);
  38241. var bitan = BABYLON.Vector3.Cross(tang, n);
  38242. n = BABYLON.Vector3.Cross(bitan, tang);
  38243. bitan.normalize();
  38244. n.normalize();
  38245. for (j = 0; j < tubularSegments; j++) {
  38246. var modJ = j % tubularSegments;
  38247. var v = modJ / tubularSegments * 2 * Math.PI;
  38248. var cx = -tube * Math.cos(v);
  38249. var cy = tube * Math.sin(v);
  38250. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38251. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38252. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38253. uvs.push(i / radialSegments);
  38254. uvs.push(j / tubularSegments);
  38255. }
  38256. }
  38257. for (i = 0; i < radialSegments; i++) {
  38258. for (j = 0; j < tubularSegments; j++) {
  38259. var jNext = (j + 1) % tubularSegments;
  38260. var a = i * tubularSegments + j;
  38261. var b = (i + 1) * tubularSegments + j;
  38262. var c = (i + 1) * tubularSegments + jNext;
  38263. var d = i * tubularSegments + jNext;
  38264. indices.push(d);
  38265. indices.push(b);
  38266. indices.push(a);
  38267. indices.push(d);
  38268. indices.push(c);
  38269. indices.push(b);
  38270. }
  38271. }
  38272. // Normals
  38273. VertexData.ComputeNormals(positions, indices, normals);
  38274. // Sides
  38275. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38276. // Result
  38277. var vertexData = new VertexData();
  38278. vertexData.indices = indices;
  38279. vertexData.positions = positions;
  38280. vertexData.normals = normals;
  38281. vertexData.uvs = uvs;
  38282. return vertexData;
  38283. };
  38284. // Tools
  38285. /**
  38286. * Compute normals for given positions and indices
  38287. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38288. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38289. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38290. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38291. * * facetNormals : optional array of facet normals (vector3)
  38292. * * facetPositions : optional array of facet positions (vector3)
  38293. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38294. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38295. * * bInfo : optional bounding info, required for facetPartitioning computation
  38296. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38297. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38298. * * useRightHandedSystem: optional boolean to for right handed system computation
  38299. * * depthSort : optional boolean to enable the facet depth sort computation
  38300. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38301. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38302. */
  38303. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38304. // temporary scalar variables
  38305. var index = 0; // facet index
  38306. var p1p2x = 0.0; // p1p2 vector x coordinate
  38307. var p1p2y = 0.0; // p1p2 vector y coordinate
  38308. var p1p2z = 0.0; // p1p2 vector z coordinate
  38309. var p3p2x = 0.0; // p3p2 vector x coordinate
  38310. var p3p2y = 0.0; // p3p2 vector y coordinate
  38311. var p3p2z = 0.0; // p3p2 vector z coordinate
  38312. var faceNormalx = 0.0; // facet normal x coordinate
  38313. var faceNormaly = 0.0; // facet normal y coordinate
  38314. var faceNormalz = 0.0; // facet normal z coordinate
  38315. var length = 0.0; // facet normal length before normalization
  38316. var v1x = 0; // vector1 x index in the positions array
  38317. var v1y = 0; // vector1 y index in the positions array
  38318. var v1z = 0; // vector1 z index in the positions array
  38319. var v2x = 0; // vector2 x index in the positions array
  38320. var v2y = 0; // vector2 y index in the positions array
  38321. var v2z = 0; // vector2 z index in the positions array
  38322. var v3x = 0; // vector3 x index in the positions array
  38323. var v3y = 0; // vector3 y index in the positions array
  38324. var v3z = 0; // vector3 z index in the positions array
  38325. var computeFacetNormals = false;
  38326. var computeFacetPositions = false;
  38327. var computeFacetPartitioning = false;
  38328. var computeDepthSort = false;
  38329. var faceNormalSign = 1;
  38330. var ratio = 0;
  38331. var distanceTo = null;
  38332. if (options) {
  38333. computeFacetNormals = (options.facetNormals) ? true : false;
  38334. computeFacetPositions = (options.facetPositions) ? true : false;
  38335. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38336. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38337. ratio = options.ratio || 0;
  38338. computeDepthSort = (options.depthSort) ? true : false;
  38339. distanceTo = (options.distanceTo);
  38340. if (computeDepthSort) {
  38341. if (distanceTo === undefined) {
  38342. distanceTo = BABYLON.Vector3.Zero();
  38343. }
  38344. var depthSortedFacets = options.depthSortedFacets;
  38345. }
  38346. }
  38347. // facetPartitioning reinit if needed
  38348. var xSubRatio = 0;
  38349. var ySubRatio = 0;
  38350. var zSubRatio = 0;
  38351. var subSq = 0;
  38352. if (computeFacetPartitioning && options && options.bbSize) {
  38353. var ox = 0; // X partitioning index for facet position
  38354. var oy = 0; // Y partinioning index for facet position
  38355. var oz = 0; // Z partinioning index for facet position
  38356. var b1x = 0; // X partitioning index for facet v1 vertex
  38357. var b1y = 0; // Y partitioning index for facet v1 vertex
  38358. var b1z = 0; // z partitioning index for facet v1 vertex
  38359. var b2x = 0; // X partitioning index for facet v2 vertex
  38360. var b2y = 0; // Y partitioning index for facet v2 vertex
  38361. var b2z = 0; // Z partitioning index for facet v2 vertex
  38362. var b3x = 0; // X partitioning index for facet v3 vertex
  38363. var b3y = 0; // Y partitioning index for facet v3 vertex
  38364. var b3z = 0; // Z partitioning index for facet v3 vertex
  38365. var block_idx_o = 0; // facet barycenter block index
  38366. var block_idx_v1 = 0; // v1 vertex block index
  38367. var block_idx_v2 = 0; // v2 vertex block index
  38368. var block_idx_v3 = 0; // v3 vertex block index
  38369. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38370. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38371. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38372. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38373. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38374. subSq = options.subDiv.max * options.subDiv.max;
  38375. options.facetPartitioning.length = 0;
  38376. }
  38377. // reset the normals
  38378. for (index = 0; index < positions.length; index++) {
  38379. normals[index] = 0.0;
  38380. }
  38381. // Loop : 1 indice triplet = 1 facet
  38382. var nbFaces = (indices.length / 3) | 0;
  38383. for (index = 0; index < nbFaces; index++) {
  38384. // get the indexes of the coordinates of each vertex of the facet
  38385. v1x = indices[index * 3] * 3;
  38386. v1y = v1x + 1;
  38387. v1z = v1x + 2;
  38388. v2x = indices[index * 3 + 1] * 3;
  38389. v2y = v2x + 1;
  38390. v2z = v2x + 2;
  38391. v3x = indices[index * 3 + 2] * 3;
  38392. v3y = v3x + 1;
  38393. v3z = v3x + 2;
  38394. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38395. p1p2y = positions[v1y] - positions[v2y];
  38396. p1p2z = positions[v1z] - positions[v2z];
  38397. p3p2x = positions[v3x] - positions[v2x];
  38398. p3p2y = positions[v3y] - positions[v2y];
  38399. p3p2z = positions[v3z] - positions[v2z];
  38400. // compute the face normal with the cross product
  38401. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38402. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38403. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38404. // normalize this normal and store it in the array facetData
  38405. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38406. length = (length === 0) ? 1.0 : length;
  38407. faceNormalx /= length;
  38408. faceNormaly /= length;
  38409. faceNormalz /= length;
  38410. if (computeFacetNormals && options) {
  38411. options.facetNormals[index].x = faceNormalx;
  38412. options.facetNormals[index].y = faceNormaly;
  38413. options.facetNormals[index].z = faceNormalz;
  38414. }
  38415. if (computeFacetPositions && options) {
  38416. // compute and the facet barycenter coordinates in the array facetPositions
  38417. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38418. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38419. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38420. }
  38421. if (computeFacetPartitioning && options) {
  38422. // store the facet indexes in arrays in the main facetPartitioning array :
  38423. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38424. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38425. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38426. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38427. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38428. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38429. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38430. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38431. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38432. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38433. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38434. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38435. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38436. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38437. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38438. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38439. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38440. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38441. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38442. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38443. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38444. // push each facet index in each block containing the vertex
  38445. options.facetPartitioning[block_idx_v1].push(index);
  38446. if (block_idx_v2 != block_idx_v1) {
  38447. options.facetPartitioning[block_idx_v2].push(index);
  38448. }
  38449. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38450. options.facetPartitioning[block_idx_v3].push(index);
  38451. }
  38452. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38453. options.facetPartitioning[block_idx_o].push(index);
  38454. }
  38455. }
  38456. if (computeDepthSort && options && options.facetPositions) {
  38457. var dsf = depthSortedFacets[index];
  38458. dsf.ind = index * 3;
  38459. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38460. }
  38461. // compute the normals anyway
  38462. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38463. normals[v1y] += faceNormaly;
  38464. normals[v1z] += faceNormalz;
  38465. normals[v2x] += faceNormalx;
  38466. normals[v2y] += faceNormaly;
  38467. normals[v2z] += faceNormalz;
  38468. normals[v3x] += faceNormalx;
  38469. normals[v3y] += faceNormaly;
  38470. normals[v3z] += faceNormalz;
  38471. }
  38472. // last normalization of each normal
  38473. for (index = 0; index < normals.length / 3; index++) {
  38474. faceNormalx = normals[index * 3];
  38475. faceNormaly = normals[index * 3 + 1];
  38476. faceNormalz = normals[index * 3 + 2];
  38477. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38478. length = (length === 0) ? 1.0 : length;
  38479. faceNormalx /= length;
  38480. faceNormaly /= length;
  38481. faceNormalz /= length;
  38482. normals[index * 3] = faceNormalx;
  38483. normals[index * 3 + 1] = faceNormaly;
  38484. normals[index * 3 + 2] = faceNormalz;
  38485. }
  38486. };
  38487. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38488. var li = indices.length;
  38489. var ln = normals.length;
  38490. var i;
  38491. var n;
  38492. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38493. switch (sideOrientation) {
  38494. case BABYLON.Mesh.FRONTSIDE:
  38495. // nothing changed
  38496. break;
  38497. case BABYLON.Mesh.BACKSIDE:
  38498. var tmp;
  38499. // indices
  38500. for (i = 0; i < li; i += 3) {
  38501. tmp = indices[i];
  38502. indices[i] = indices[i + 2];
  38503. indices[i + 2] = tmp;
  38504. }
  38505. // normals
  38506. for (n = 0; n < ln; n++) {
  38507. normals[n] = -normals[n];
  38508. }
  38509. break;
  38510. case BABYLON.Mesh.DOUBLESIDE:
  38511. // positions
  38512. var lp = positions.length;
  38513. var l = lp / 3;
  38514. for (var p = 0; p < lp; p++) {
  38515. positions[lp + p] = positions[p];
  38516. }
  38517. // indices
  38518. for (i = 0; i < li; i += 3) {
  38519. indices[i + li] = indices[i + 2] + l;
  38520. indices[i + 1 + li] = indices[i + 1] + l;
  38521. indices[i + 2 + li] = indices[i] + l;
  38522. }
  38523. // normals
  38524. for (n = 0; n < ln; n++) {
  38525. normals[ln + n] = -normals[n];
  38526. }
  38527. // uvs
  38528. var lu = uvs.length;
  38529. var u = 0;
  38530. for (u = 0; u < lu; u++) {
  38531. uvs[u + lu] = uvs[u];
  38532. }
  38533. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38534. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38535. u = 0;
  38536. for (i = 0; i < lu / 2; i++) {
  38537. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38538. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38539. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38540. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38541. u += 2;
  38542. }
  38543. break;
  38544. }
  38545. };
  38546. /**
  38547. * Applies VertexData created from the imported parameters to the geometry
  38548. * @param parsedVertexData the parsed data from an imported file
  38549. * @param geometry the geometry to apply the VertexData to
  38550. */
  38551. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38552. var vertexData = new VertexData();
  38553. // positions
  38554. var positions = parsedVertexData.positions;
  38555. if (positions) {
  38556. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38557. }
  38558. // normals
  38559. var normals = parsedVertexData.normals;
  38560. if (normals) {
  38561. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38562. }
  38563. // tangents
  38564. var tangents = parsedVertexData.tangents;
  38565. if (tangents) {
  38566. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38567. }
  38568. // uvs
  38569. var uvs = parsedVertexData.uvs;
  38570. if (uvs) {
  38571. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38572. }
  38573. // uv2s
  38574. var uv2s = parsedVertexData.uv2s;
  38575. if (uv2s) {
  38576. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38577. }
  38578. // uv3s
  38579. var uv3s = parsedVertexData.uv3s;
  38580. if (uv3s) {
  38581. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38582. }
  38583. // uv4s
  38584. var uv4s = parsedVertexData.uv4s;
  38585. if (uv4s) {
  38586. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38587. }
  38588. // uv5s
  38589. var uv5s = parsedVertexData.uv5s;
  38590. if (uv5s) {
  38591. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38592. }
  38593. // uv6s
  38594. var uv6s = parsedVertexData.uv6s;
  38595. if (uv6s) {
  38596. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38597. }
  38598. // colors
  38599. var colors = parsedVertexData.colors;
  38600. if (colors) {
  38601. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38602. }
  38603. // matricesIndices
  38604. var matricesIndices = parsedVertexData.matricesIndices;
  38605. if (matricesIndices) {
  38606. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38607. }
  38608. // matricesWeights
  38609. var matricesWeights = parsedVertexData.matricesWeights;
  38610. if (matricesWeights) {
  38611. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38612. }
  38613. // indices
  38614. var indices = parsedVertexData.indices;
  38615. if (indices) {
  38616. vertexData.indices = indices;
  38617. }
  38618. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38619. };
  38620. return VertexData;
  38621. }());
  38622. BABYLON.VertexData = VertexData;
  38623. })(BABYLON || (BABYLON = {}));
  38624. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38625. var BABYLON;
  38626. (function (BABYLON) {
  38627. /**
  38628. * Class used to store geometry data (vertex buffers + index buffer)
  38629. */
  38630. var Geometry = /** @class */ (function () {
  38631. /**
  38632. * Creates a new geometry
  38633. * @param id defines the unique ID
  38634. * @param scene defines the hosting scene
  38635. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38636. * @param updatable defines if geometry must be updatable (false by default)
  38637. * @param mesh defines the mesh that will be associated with the geometry
  38638. */
  38639. function Geometry(id, scene, vertexData, updatable, mesh) {
  38640. if (updatable === void 0) { updatable = false; }
  38641. if (mesh === void 0) { mesh = null; }
  38642. /**
  38643. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38644. */
  38645. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38646. this._totalVertices = 0;
  38647. this._isDisposed = false;
  38648. this._indexBufferIsUpdatable = false;
  38649. this.id = id;
  38650. this._engine = scene.getEngine();
  38651. this._meshes = [];
  38652. this._scene = scene;
  38653. //Init vertex buffer cache
  38654. this._vertexBuffers = {};
  38655. this._indices = [];
  38656. this._updatable = updatable;
  38657. // vertexData
  38658. if (vertexData) {
  38659. this.setAllVerticesData(vertexData, updatable);
  38660. }
  38661. else {
  38662. this._totalVertices = 0;
  38663. this._indices = [];
  38664. }
  38665. if (this._engine.getCaps().vertexArrayObject) {
  38666. this._vertexArrayObjects = {};
  38667. }
  38668. // applyToMesh
  38669. if (mesh) {
  38670. if (mesh.getClassName() === "LinesMesh") {
  38671. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38672. this._updateExtend();
  38673. }
  38674. this.applyToMesh(mesh);
  38675. mesh.computeWorldMatrix(true);
  38676. }
  38677. }
  38678. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38679. /**
  38680. * 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
  38681. */
  38682. get: function () {
  38683. return this._boundingBias;
  38684. },
  38685. /**
  38686. * 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
  38687. */
  38688. set: function (value) {
  38689. if (this._boundingBias && this._boundingBias.equals(value)) {
  38690. return;
  38691. }
  38692. this._boundingBias = value.clone();
  38693. this._updateBoundingInfo(true, null);
  38694. },
  38695. enumerable: true,
  38696. configurable: true
  38697. });
  38698. /**
  38699. * Static function used to attach a new empty geometry to a mesh
  38700. * @param mesh defines the mesh to attach the geometry to
  38701. * @returns the new {BABYLON.Geometry}
  38702. */
  38703. Geometry.CreateGeometryForMesh = function (mesh) {
  38704. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38705. geometry.applyToMesh(mesh);
  38706. return geometry;
  38707. };
  38708. Object.defineProperty(Geometry.prototype, "extend", {
  38709. /**
  38710. * Gets the current extend of the geometry
  38711. */
  38712. get: function () {
  38713. return this._extend;
  38714. },
  38715. enumerable: true,
  38716. configurable: true
  38717. });
  38718. /**
  38719. * Gets the hosting scene
  38720. * @returns the hosting {BABYLON.Scene}
  38721. */
  38722. Geometry.prototype.getScene = function () {
  38723. return this._scene;
  38724. };
  38725. /**
  38726. * Gets the hosting engine
  38727. * @returns the hosting {BABYLON.Engine}
  38728. */
  38729. Geometry.prototype.getEngine = function () {
  38730. return this._engine;
  38731. };
  38732. /**
  38733. * Defines if the geometry is ready to use
  38734. * @returns true if the geometry is ready to be used
  38735. */
  38736. Geometry.prototype.isReady = function () {
  38737. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38738. };
  38739. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38740. /**
  38741. * Gets a value indicating that the geometry should not be serialized
  38742. */
  38743. get: function () {
  38744. for (var index = 0; index < this._meshes.length; index++) {
  38745. if (!this._meshes[index].doNotSerialize) {
  38746. return false;
  38747. }
  38748. }
  38749. return true;
  38750. },
  38751. enumerable: true,
  38752. configurable: true
  38753. });
  38754. /** @hidden */
  38755. Geometry.prototype._rebuild = function () {
  38756. if (this._vertexArrayObjects) {
  38757. this._vertexArrayObjects = {};
  38758. }
  38759. // Index buffer
  38760. if (this._meshes.length !== 0 && this._indices) {
  38761. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38762. }
  38763. // Vertex buffers
  38764. for (var key in this._vertexBuffers) {
  38765. var vertexBuffer = this._vertexBuffers[key];
  38766. vertexBuffer._rebuild();
  38767. }
  38768. };
  38769. /**
  38770. * Affects all gemetry data in one call
  38771. * @param vertexData defines the geometry data
  38772. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38773. */
  38774. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38775. vertexData.applyToGeometry(this, updatable);
  38776. this.notifyUpdate();
  38777. };
  38778. /**
  38779. * Set specific vertex data
  38780. * @param kind defines the data kind (Position, normal, etc...)
  38781. * @param data defines the vertex data to use
  38782. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38783. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38784. */
  38785. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38786. if (updatable === void 0) { updatable = false; }
  38787. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38788. this.setVerticesBuffer(buffer);
  38789. };
  38790. /**
  38791. * Removes a specific vertex data
  38792. * @param kind defines the data kind (Position, normal, etc...)
  38793. */
  38794. Geometry.prototype.removeVerticesData = function (kind) {
  38795. if (this._vertexBuffers[kind]) {
  38796. this._vertexBuffers[kind].dispose();
  38797. delete this._vertexBuffers[kind];
  38798. }
  38799. };
  38800. /**
  38801. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38802. * @param buffer defines the vertex buffer to use
  38803. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38804. */
  38805. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38806. if (totalVertices === void 0) { totalVertices = null; }
  38807. var kind = buffer.getKind();
  38808. if (this._vertexBuffers[kind]) {
  38809. this._vertexBuffers[kind].dispose();
  38810. }
  38811. this._vertexBuffers[kind] = buffer;
  38812. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38813. var data = buffer.getData();
  38814. if (totalVertices != null) {
  38815. this._totalVertices = totalVertices;
  38816. }
  38817. else {
  38818. if (data != null) {
  38819. this._totalVertices = data.length / (buffer.byteStride / 4);
  38820. }
  38821. }
  38822. this._updateExtend(data);
  38823. this._resetPointsArrayCache();
  38824. var meshes = this._meshes;
  38825. var numOfMeshes = meshes.length;
  38826. for (var index = 0; index < numOfMeshes; index++) {
  38827. var mesh = meshes[index];
  38828. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38829. mesh._createGlobalSubMesh(false);
  38830. mesh.computeWorldMatrix(true);
  38831. }
  38832. }
  38833. this.notifyUpdate(kind);
  38834. if (this._vertexArrayObjects) {
  38835. this._disposeVertexArrayObjects();
  38836. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38837. }
  38838. };
  38839. /**
  38840. * Update a specific vertex buffer
  38841. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38842. * It will do nothing if the buffer is not updatable
  38843. * @param kind defines the data kind (Position, normal, etc...)
  38844. * @param data defines the data to use
  38845. * @param offset defines the offset in the target buffer where to store the data
  38846. * @param useBytes set to true if the offset is in bytes
  38847. */
  38848. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38849. if (useBytes === void 0) { useBytes = false; }
  38850. var vertexBuffer = this.getVertexBuffer(kind);
  38851. if (!vertexBuffer) {
  38852. return;
  38853. }
  38854. vertexBuffer.updateDirectly(data, offset, useBytes);
  38855. this.notifyUpdate(kind);
  38856. };
  38857. /**
  38858. * Update a specific vertex buffer
  38859. * This function will create a new buffer if the current one is not updatable
  38860. * @param kind defines the data kind (Position, normal, etc...)
  38861. * @param data defines the data to use
  38862. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38863. */
  38864. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38865. if (updateExtends === void 0) { updateExtends = false; }
  38866. var vertexBuffer = this.getVertexBuffer(kind);
  38867. if (!vertexBuffer) {
  38868. return;
  38869. }
  38870. vertexBuffer.update(data);
  38871. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38872. this._updateBoundingInfo(updateExtends, data);
  38873. }
  38874. this.notifyUpdate(kind);
  38875. };
  38876. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38877. if (updateExtends) {
  38878. this._updateExtend(data);
  38879. }
  38880. var meshes = this._meshes;
  38881. var numOfMeshes = meshes.length;
  38882. this._resetPointsArrayCache();
  38883. for (var index = 0; index < numOfMeshes; index++) {
  38884. var mesh = meshes[index];
  38885. if (updateExtends) {
  38886. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38887. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38888. var subMesh = mesh.subMeshes[subIndex];
  38889. subMesh.refreshBoundingInfo();
  38890. }
  38891. }
  38892. }
  38893. };
  38894. /** @hidden */
  38895. Geometry.prototype._bind = function (effect, indexToBind) {
  38896. if (!effect) {
  38897. return;
  38898. }
  38899. if (indexToBind === undefined) {
  38900. indexToBind = this._indexBuffer;
  38901. }
  38902. var vbs = this.getVertexBuffers();
  38903. if (!vbs) {
  38904. return;
  38905. }
  38906. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38907. this._engine.bindBuffers(vbs, indexToBind, effect);
  38908. return;
  38909. }
  38910. // Using VAO
  38911. if (!this._vertexArrayObjects[effect.key]) {
  38912. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38913. }
  38914. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38915. };
  38916. /**
  38917. * Gets total number of vertices
  38918. * @returns the total number of vertices
  38919. */
  38920. Geometry.prototype.getTotalVertices = function () {
  38921. if (!this.isReady()) {
  38922. return 0;
  38923. }
  38924. return this._totalVertices;
  38925. };
  38926. /**
  38927. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38928. * @param kind defines the data kind (Position, normal, etc...)
  38929. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38930. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38931. * @returns a float array containing vertex data
  38932. */
  38933. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38934. var vertexBuffer = this.getVertexBuffer(kind);
  38935. if (!vertexBuffer) {
  38936. return null;
  38937. }
  38938. var data = vertexBuffer.getData();
  38939. if (!data) {
  38940. return null;
  38941. }
  38942. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38943. var count = this._totalVertices * vertexBuffer.getSize();
  38944. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38945. var copy_1 = new Array(count);
  38946. vertexBuffer.forEach(count, function (value, index) {
  38947. copy_1[index] = value;
  38948. });
  38949. return copy_1;
  38950. }
  38951. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38952. if (data instanceof Array) {
  38953. var offset = vertexBuffer.byteOffset / 4;
  38954. return BABYLON.Tools.Slice(data, offset, offset + count);
  38955. }
  38956. else if (data instanceof ArrayBuffer) {
  38957. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38958. }
  38959. else {
  38960. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38961. }
  38962. }
  38963. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38964. return BABYLON.Tools.Slice(data);
  38965. }
  38966. return data;
  38967. };
  38968. /**
  38969. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38970. * @param kind defines the data kind (Position, normal, etc...)
  38971. * @returns true if the vertex buffer with the specified kind is updatable
  38972. */
  38973. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38974. var vb = this._vertexBuffers[kind];
  38975. if (!vb) {
  38976. return false;
  38977. }
  38978. return vb.isUpdatable();
  38979. };
  38980. /**
  38981. * Gets a specific vertex buffer
  38982. * @param kind defines the data kind (Position, normal, etc...)
  38983. * @returns a {BABYLON.VertexBuffer}
  38984. */
  38985. Geometry.prototype.getVertexBuffer = function (kind) {
  38986. if (!this.isReady()) {
  38987. return null;
  38988. }
  38989. return this._vertexBuffers[kind];
  38990. };
  38991. /**
  38992. * Returns all vertex buffers
  38993. * @return an object holding all vertex buffers indexed by kind
  38994. */
  38995. Geometry.prototype.getVertexBuffers = function () {
  38996. if (!this.isReady()) {
  38997. return null;
  38998. }
  38999. return this._vertexBuffers;
  39000. };
  39001. /**
  39002. * Gets a boolean indicating if specific vertex buffer is present
  39003. * @param kind defines the data kind (Position, normal, etc...)
  39004. * @returns true if data is present
  39005. */
  39006. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39007. if (!this._vertexBuffers) {
  39008. if (this._delayInfo) {
  39009. return this._delayInfo.indexOf(kind) !== -1;
  39010. }
  39011. return false;
  39012. }
  39013. return this._vertexBuffers[kind] !== undefined;
  39014. };
  39015. /**
  39016. * Gets a list of all attached data kinds (Position, normal, etc...)
  39017. * @returns a list of string containing all kinds
  39018. */
  39019. Geometry.prototype.getVerticesDataKinds = function () {
  39020. var result = [];
  39021. var kind;
  39022. if (!this._vertexBuffers && this._delayInfo) {
  39023. for (kind in this._delayInfo) {
  39024. result.push(kind);
  39025. }
  39026. }
  39027. else {
  39028. for (kind in this._vertexBuffers) {
  39029. result.push(kind);
  39030. }
  39031. }
  39032. return result;
  39033. };
  39034. /**
  39035. * Update index buffer
  39036. * @param indices defines the indices to store in the index buffer
  39037. * @param offset defines the offset in the target buffer where to store the data
  39038. */
  39039. Geometry.prototype.updateIndices = function (indices, offset) {
  39040. if (!this._indexBuffer) {
  39041. return;
  39042. }
  39043. if (!this._indexBufferIsUpdatable) {
  39044. this.setIndices(indices, null, true);
  39045. }
  39046. else {
  39047. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39048. }
  39049. };
  39050. /**
  39051. * Creates a new index buffer
  39052. * @param indices defines the indices to store in the index buffer
  39053. * @param totalVertices defines the total number of vertices (could be null)
  39054. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39055. */
  39056. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39057. if (totalVertices === void 0) { totalVertices = null; }
  39058. if (updatable === void 0) { updatable = false; }
  39059. if (this._indexBuffer) {
  39060. this._engine._releaseBuffer(this._indexBuffer);
  39061. }
  39062. this._disposeVertexArrayObjects();
  39063. this._indices = indices;
  39064. this._indexBufferIsUpdatable = updatable;
  39065. if (this._meshes.length !== 0 && this._indices) {
  39066. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39067. }
  39068. if (totalVertices != undefined) { // including null and undefined
  39069. this._totalVertices = totalVertices;
  39070. }
  39071. var meshes = this._meshes;
  39072. var numOfMeshes = meshes.length;
  39073. for (var index = 0; index < numOfMeshes; index++) {
  39074. meshes[index]._createGlobalSubMesh(true);
  39075. }
  39076. this.notifyUpdate();
  39077. };
  39078. /**
  39079. * Return the total number of indices
  39080. * @returns the total number of indices
  39081. */
  39082. Geometry.prototype.getTotalIndices = function () {
  39083. if (!this.isReady()) {
  39084. return 0;
  39085. }
  39086. return this._indices.length;
  39087. };
  39088. /**
  39089. * Gets the index buffer array
  39090. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39091. * @returns the index buffer array
  39092. */
  39093. Geometry.prototype.getIndices = function (copyWhenShared) {
  39094. if (!this.isReady()) {
  39095. return null;
  39096. }
  39097. var orig = this._indices;
  39098. if (!copyWhenShared || this._meshes.length === 1) {
  39099. return orig;
  39100. }
  39101. else {
  39102. var len = orig.length;
  39103. var copy = [];
  39104. for (var i = 0; i < len; i++) {
  39105. copy.push(orig[i]);
  39106. }
  39107. return copy;
  39108. }
  39109. };
  39110. /**
  39111. * Gets the index buffer
  39112. * @return the index buffer
  39113. */
  39114. Geometry.prototype.getIndexBuffer = function () {
  39115. if (!this.isReady()) {
  39116. return null;
  39117. }
  39118. return this._indexBuffer;
  39119. };
  39120. /** @hidden */
  39121. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39122. if (effect === void 0) { effect = null; }
  39123. if (!effect || !this._vertexArrayObjects) {
  39124. return;
  39125. }
  39126. if (this._vertexArrayObjects[effect.key]) {
  39127. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39128. delete this._vertexArrayObjects[effect.key];
  39129. }
  39130. };
  39131. /**
  39132. * Release the associated resources for a specific mesh
  39133. * @param mesh defines the source mesh
  39134. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39135. */
  39136. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39137. var meshes = this._meshes;
  39138. var index = meshes.indexOf(mesh);
  39139. if (index === -1) {
  39140. return;
  39141. }
  39142. meshes.splice(index, 1);
  39143. mesh._geometry = null;
  39144. if (meshes.length === 0 && shouldDispose) {
  39145. this.dispose();
  39146. }
  39147. };
  39148. /**
  39149. * Apply current geometry to a given mesh
  39150. * @param mesh defines the mesh to apply geometry to
  39151. */
  39152. Geometry.prototype.applyToMesh = function (mesh) {
  39153. if (mesh._geometry === this) {
  39154. return;
  39155. }
  39156. var previousGeometry = mesh._geometry;
  39157. if (previousGeometry) {
  39158. previousGeometry.releaseForMesh(mesh);
  39159. }
  39160. var meshes = this._meshes;
  39161. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39162. mesh._geometry = this;
  39163. this._scene.pushGeometry(this);
  39164. meshes.push(mesh);
  39165. if (this.isReady()) {
  39166. this._applyToMesh(mesh);
  39167. }
  39168. else {
  39169. mesh._boundingInfo = this._boundingInfo;
  39170. }
  39171. };
  39172. Geometry.prototype._updateExtend = function (data) {
  39173. if (data === void 0) { data = null; }
  39174. if (!data) {
  39175. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39176. }
  39177. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39178. };
  39179. Geometry.prototype._applyToMesh = function (mesh) {
  39180. var numOfMeshes = this._meshes.length;
  39181. // vertexBuffers
  39182. for (var kind in this._vertexBuffers) {
  39183. if (numOfMeshes === 1) {
  39184. this._vertexBuffers[kind].create();
  39185. }
  39186. var buffer = this._vertexBuffers[kind].getBuffer();
  39187. if (buffer)
  39188. buffer.references = numOfMeshes;
  39189. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39190. if (!this._extend) {
  39191. this._updateExtend();
  39192. }
  39193. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39194. mesh._createGlobalSubMesh(false);
  39195. //bounding info was just created again, world matrix should be applied again.
  39196. mesh._updateBoundingInfo();
  39197. }
  39198. }
  39199. // indexBuffer
  39200. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39201. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39202. }
  39203. if (this._indexBuffer) {
  39204. this._indexBuffer.references = numOfMeshes;
  39205. }
  39206. };
  39207. Geometry.prototype.notifyUpdate = function (kind) {
  39208. if (this.onGeometryUpdated) {
  39209. this.onGeometryUpdated(this, kind);
  39210. }
  39211. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39212. var mesh = _a[_i];
  39213. mesh._markSubMeshesAsAttributesDirty();
  39214. }
  39215. };
  39216. /**
  39217. * Load the geometry if it was flagged as delay loaded
  39218. * @param scene defines the hosting scene
  39219. * @param onLoaded defines a callback called when the geometry is loaded
  39220. */
  39221. Geometry.prototype.load = function (scene, onLoaded) {
  39222. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39223. return;
  39224. }
  39225. if (this.isReady()) {
  39226. if (onLoaded) {
  39227. onLoaded();
  39228. }
  39229. return;
  39230. }
  39231. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39232. this._queueLoad(scene, onLoaded);
  39233. };
  39234. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39235. var _this = this;
  39236. if (!this.delayLoadingFile) {
  39237. return;
  39238. }
  39239. scene._addPendingData(this);
  39240. scene._loadFile(this.delayLoadingFile, function (data) {
  39241. if (!_this._delayLoadingFunction) {
  39242. return;
  39243. }
  39244. _this._delayLoadingFunction(JSON.parse(data), _this);
  39245. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39246. _this._delayInfo = [];
  39247. scene._removePendingData(_this);
  39248. var meshes = _this._meshes;
  39249. var numOfMeshes = meshes.length;
  39250. for (var index = 0; index < numOfMeshes; index++) {
  39251. _this._applyToMesh(meshes[index]);
  39252. }
  39253. if (onLoaded) {
  39254. onLoaded();
  39255. }
  39256. }, undefined, true);
  39257. };
  39258. /**
  39259. * Invert the geometry to move from a right handed system to a left handed one.
  39260. */
  39261. Geometry.prototype.toLeftHanded = function () {
  39262. // Flip faces
  39263. var tIndices = this.getIndices(false);
  39264. if (tIndices != null && tIndices.length > 0) {
  39265. for (var i = 0; i < tIndices.length; i += 3) {
  39266. var tTemp = tIndices[i + 0];
  39267. tIndices[i + 0] = tIndices[i + 2];
  39268. tIndices[i + 2] = tTemp;
  39269. }
  39270. this.setIndices(tIndices);
  39271. }
  39272. // Negate position.z
  39273. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39274. if (tPositions != null && tPositions.length > 0) {
  39275. for (var i = 0; i < tPositions.length; i += 3) {
  39276. tPositions[i + 2] = -tPositions[i + 2];
  39277. }
  39278. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39279. }
  39280. // Negate normal.z
  39281. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39282. if (tNormals != null && tNormals.length > 0) {
  39283. for (var i = 0; i < tNormals.length; i += 3) {
  39284. tNormals[i + 2] = -tNormals[i + 2];
  39285. }
  39286. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39287. }
  39288. };
  39289. // Cache
  39290. /** @hidden */
  39291. Geometry.prototype._resetPointsArrayCache = function () {
  39292. this._positions = null;
  39293. };
  39294. /** @hidden */
  39295. Geometry.prototype._generatePointsArray = function () {
  39296. if (this._positions)
  39297. return true;
  39298. this._positions = [];
  39299. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39300. if (!data) {
  39301. return false;
  39302. }
  39303. for (var index = 0; index < data.length; index += 3) {
  39304. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39305. }
  39306. return true;
  39307. };
  39308. /**
  39309. * Gets a value indicating if the geometry is disposed
  39310. * @returns true if the geometry was disposed
  39311. */
  39312. Geometry.prototype.isDisposed = function () {
  39313. return this._isDisposed;
  39314. };
  39315. Geometry.prototype._disposeVertexArrayObjects = function () {
  39316. if (this._vertexArrayObjects) {
  39317. for (var kind in this._vertexArrayObjects) {
  39318. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39319. }
  39320. this._vertexArrayObjects = {};
  39321. }
  39322. };
  39323. /**
  39324. * Free all associated resources
  39325. */
  39326. Geometry.prototype.dispose = function () {
  39327. var meshes = this._meshes;
  39328. var numOfMeshes = meshes.length;
  39329. var index;
  39330. for (index = 0; index < numOfMeshes; index++) {
  39331. this.releaseForMesh(meshes[index]);
  39332. }
  39333. this._meshes = [];
  39334. this._disposeVertexArrayObjects();
  39335. for (var kind in this._vertexBuffers) {
  39336. this._vertexBuffers[kind].dispose();
  39337. }
  39338. this._vertexBuffers = {};
  39339. this._totalVertices = 0;
  39340. if (this._indexBuffer) {
  39341. this._engine._releaseBuffer(this._indexBuffer);
  39342. }
  39343. this._indexBuffer = null;
  39344. this._indices = [];
  39345. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39346. this.delayLoadingFile = null;
  39347. this._delayLoadingFunction = null;
  39348. this._delayInfo = [];
  39349. this._boundingInfo = null;
  39350. this._scene.removeGeometry(this);
  39351. this._isDisposed = true;
  39352. };
  39353. /**
  39354. * Clone the current geometry into a new geometry
  39355. * @param id defines the unique ID of the new geometry
  39356. * @returns a new geometry object
  39357. */
  39358. Geometry.prototype.copy = function (id) {
  39359. var vertexData = new BABYLON.VertexData();
  39360. vertexData.indices = [];
  39361. var indices = this.getIndices();
  39362. if (indices) {
  39363. for (var index = 0; index < indices.length; index++) {
  39364. vertexData.indices.push(indices[index]);
  39365. }
  39366. }
  39367. var updatable = false;
  39368. var stopChecking = false;
  39369. var kind;
  39370. for (kind in this._vertexBuffers) {
  39371. // using slice() to make a copy of the array and not just reference it
  39372. var data = this.getVerticesData(kind);
  39373. if (data instanceof Float32Array) {
  39374. vertexData.set(new Float32Array(data), kind);
  39375. }
  39376. else {
  39377. vertexData.set(data.slice(0), kind);
  39378. }
  39379. if (!stopChecking) {
  39380. var vb = this.getVertexBuffer(kind);
  39381. if (vb) {
  39382. updatable = vb.isUpdatable();
  39383. stopChecking = !updatable;
  39384. }
  39385. }
  39386. }
  39387. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39388. geometry.delayLoadState = this.delayLoadState;
  39389. geometry.delayLoadingFile = this.delayLoadingFile;
  39390. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39391. for (kind in this._delayInfo) {
  39392. geometry._delayInfo = geometry._delayInfo || [];
  39393. geometry._delayInfo.push(kind);
  39394. }
  39395. // Bounding info
  39396. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39397. return geometry;
  39398. };
  39399. /**
  39400. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39401. * @return a JSON representation of the current geometry data (without the vertices data)
  39402. */
  39403. Geometry.prototype.serialize = function () {
  39404. var serializationObject = {};
  39405. serializationObject.id = this.id;
  39406. serializationObject.updatable = this._updatable;
  39407. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39408. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39409. }
  39410. return serializationObject;
  39411. };
  39412. Geometry.prototype.toNumberArray = function (origin) {
  39413. if (Array.isArray(origin)) {
  39414. return origin;
  39415. }
  39416. else {
  39417. return Array.prototype.slice.call(origin);
  39418. }
  39419. };
  39420. /**
  39421. * Serialize all vertices data into a JSON oject
  39422. * @returns a JSON representation of the current geometry data
  39423. */
  39424. Geometry.prototype.serializeVerticeData = function () {
  39425. var serializationObject = this.serialize();
  39426. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39427. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39428. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39429. serializationObject.positions._updatable = true;
  39430. }
  39431. }
  39432. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39433. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39434. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39435. serializationObject.normals._updatable = true;
  39436. }
  39437. }
  39438. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39439. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39440. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39441. serializationObject.tangets._updatable = true;
  39442. }
  39443. }
  39444. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39445. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39446. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39447. serializationObject.uvs._updatable = true;
  39448. }
  39449. }
  39450. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39451. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39452. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39453. serializationObject.uv2s._updatable = true;
  39454. }
  39455. }
  39456. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39457. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39458. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39459. serializationObject.uv3s._updatable = true;
  39460. }
  39461. }
  39462. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39463. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39464. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39465. serializationObject.uv4s._updatable = true;
  39466. }
  39467. }
  39468. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39469. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39470. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39471. serializationObject.uv5s._updatable = true;
  39472. }
  39473. }
  39474. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39475. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39476. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39477. serializationObject.uv6s._updatable = true;
  39478. }
  39479. }
  39480. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39481. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39482. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39483. serializationObject.colors._updatable = true;
  39484. }
  39485. }
  39486. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39487. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39488. serializationObject.matricesIndices._isExpanded = true;
  39489. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39490. serializationObject.matricesIndices._updatable = true;
  39491. }
  39492. }
  39493. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39494. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39495. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39496. serializationObject.matricesWeights._updatable = true;
  39497. }
  39498. }
  39499. serializationObject.indices = this.toNumberArray(this.getIndices());
  39500. return serializationObject;
  39501. };
  39502. // Statics
  39503. /**
  39504. * Extracts a clone of a mesh geometry
  39505. * @param mesh defines the source mesh
  39506. * @param id defines the unique ID of the new geometry object
  39507. * @returns the new geometry object
  39508. */
  39509. Geometry.ExtractFromMesh = function (mesh, id) {
  39510. var geometry = mesh._geometry;
  39511. if (!geometry) {
  39512. return null;
  39513. }
  39514. return geometry.copy(id);
  39515. };
  39516. /**
  39517. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39518. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39519. * Be aware Math.random() could cause collisions, but:
  39520. * "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"
  39521. * @returns a string containing a new GUID
  39522. */
  39523. Geometry.RandomId = function () {
  39524. return BABYLON.Tools.RandomId();
  39525. };
  39526. /** @hidden */
  39527. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39528. var scene = mesh.getScene();
  39529. // Geometry
  39530. var geometryId = parsedGeometry.geometryId;
  39531. if (geometryId) {
  39532. var geometry = scene.getGeometryByID(geometryId);
  39533. if (geometry) {
  39534. geometry.applyToMesh(mesh);
  39535. }
  39536. }
  39537. else if (parsedGeometry instanceof ArrayBuffer) {
  39538. var binaryInfo = mesh._binaryInfo;
  39539. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39540. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39541. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39542. }
  39543. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39544. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39545. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39546. }
  39547. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39548. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39549. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39550. }
  39551. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39552. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39553. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39554. }
  39555. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39556. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39557. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39558. }
  39559. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39560. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39561. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39562. }
  39563. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39564. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39565. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39566. }
  39567. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39568. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39569. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39570. }
  39571. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39572. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39573. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39574. }
  39575. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39576. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39577. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39578. }
  39579. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39580. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39581. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39582. }
  39583. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39584. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39585. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39586. }
  39587. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39588. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39589. mesh.setIndices(indicesData, null);
  39590. }
  39591. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39592. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39593. mesh.subMeshes = [];
  39594. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39595. var materialIndex = subMeshesData[(i * 5) + 0];
  39596. var verticesStart = subMeshesData[(i * 5) + 1];
  39597. var verticesCount = subMeshesData[(i * 5) + 2];
  39598. var indexStart = subMeshesData[(i * 5) + 3];
  39599. var indexCount = subMeshesData[(i * 5) + 4];
  39600. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39601. }
  39602. }
  39603. }
  39604. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39605. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39606. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39607. if (parsedGeometry.tangents) {
  39608. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39609. }
  39610. if (parsedGeometry.uvs) {
  39611. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39612. }
  39613. if (parsedGeometry.uvs2) {
  39614. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39615. }
  39616. if (parsedGeometry.uvs3) {
  39617. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39618. }
  39619. if (parsedGeometry.uvs4) {
  39620. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39621. }
  39622. if (parsedGeometry.uvs5) {
  39623. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39624. }
  39625. if (parsedGeometry.uvs6) {
  39626. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39627. }
  39628. if (parsedGeometry.colors) {
  39629. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39630. }
  39631. if (parsedGeometry.matricesIndices) {
  39632. if (!parsedGeometry.matricesIndices._isExpanded) {
  39633. var floatIndices = [];
  39634. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39635. var matricesIndex = parsedGeometry.matricesIndices[i];
  39636. floatIndices.push(matricesIndex & 0x000000FF);
  39637. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39638. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39639. floatIndices.push(matricesIndex >> 24);
  39640. }
  39641. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39642. }
  39643. else {
  39644. delete parsedGeometry.matricesIndices._isExpanded;
  39645. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39646. }
  39647. }
  39648. if (parsedGeometry.matricesIndicesExtra) {
  39649. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39650. var floatIndices = [];
  39651. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39652. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39653. floatIndices.push(matricesIndex & 0x000000FF);
  39654. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39655. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39656. floatIndices.push(matricesIndex >> 24);
  39657. }
  39658. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39659. }
  39660. else {
  39661. delete parsedGeometry.matricesIndices._isExpanded;
  39662. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39663. }
  39664. }
  39665. if (parsedGeometry.matricesWeights) {
  39666. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39667. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39668. }
  39669. if (parsedGeometry.matricesWeightsExtra) {
  39670. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39671. }
  39672. mesh.setIndices(parsedGeometry.indices, null);
  39673. }
  39674. // SubMeshes
  39675. if (parsedGeometry.subMeshes) {
  39676. mesh.subMeshes = [];
  39677. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39678. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39679. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39680. }
  39681. }
  39682. // Flat shading
  39683. if (mesh._shouldGenerateFlatShading) {
  39684. mesh.convertToFlatShadedMesh();
  39685. delete mesh._shouldGenerateFlatShading;
  39686. }
  39687. // Update
  39688. mesh.computeWorldMatrix(true);
  39689. // Octree
  39690. var sceneOctree = scene.selectionOctree;
  39691. if (sceneOctree !== undefined && sceneOctree !== null) {
  39692. sceneOctree.addMesh(mesh);
  39693. }
  39694. };
  39695. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39696. var epsilon = 1e-3;
  39697. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39698. return;
  39699. }
  39700. var noInfluenceBoneIndex = 0.0;
  39701. if (parsedGeometry.skeletonId > -1) {
  39702. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39703. if (!skeleton) {
  39704. return;
  39705. }
  39706. noInfluenceBoneIndex = skeleton.bones.length;
  39707. }
  39708. else {
  39709. return;
  39710. }
  39711. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39712. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39713. var matricesWeights = parsedGeometry.matricesWeights;
  39714. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39715. var influencers = parsedGeometry.numBoneInfluencer;
  39716. var size = matricesWeights.length;
  39717. for (var i = 0; i < size; i += 4) {
  39718. var weight = 0.0;
  39719. var firstZeroWeight = -1;
  39720. for (var j = 0; j < 4; j++) {
  39721. var w = matricesWeights[i + j];
  39722. weight += w;
  39723. if (w < epsilon && firstZeroWeight < 0) {
  39724. firstZeroWeight = j;
  39725. }
  39726. }
  39727. if (matricesWeightsExtra) {
  39728. for (var j = 0; j < 4; j++) {
  39729. var w = matricesWeightsExtra[i + j];
  39730. weight += w;
  39731. if (w < epsilon && firstZeroWeight < 0) {
  39732. firstZeroWeight = j + 4;
  39733. }
  39734. }
  39735. }
  39736. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39737. firstZeroWeight = influencers - 1;
  39738. }
  39739. if (weight > epsilon) {
  39740. var mweight = 1.0 / weight;
  39741. for (var j = 0; j < 4; j++) {
  39742. matricesWeights[i + j] *= mweight;
  39743. }
  39744. if (matricesWeightsExtra) {
  39745. for (var j = 0; j < 4; j++) {
  39746. matricesWeightsExtra[i + j] *= mweight;
  39747. }
  39748. }
  39749. }
  39750. else {
  39751. if (firstZeroWeight >= 4) {
  39752. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39753. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39754. }
  39755. else {
  39756. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39757. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39758. }
  39759. }
  39760. }
  39761. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39762. if (parsedGeometry.matricesWeightsExtra) {
  39763. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39764. }
  39765. };
  39766. /**
  39767. * Create a new geometry from persisted data (Using .babylon file format)
  39768. * @param parsedVertexData defines the persisted data
  39769. * @param scene defines the hosting scene
  39770. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39771. * @returns the new geometry object
  39772. */
  39773. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39774. if (scene.getGeometryByID(parsedVertexData.id)) {
  39775. return null; // null since geometry could be something else than a box...
  39776. }
  39777. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39778. if (BABYLON.Tags) {
  39779. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39780. }
  39781. if (parsedVertexData.delayLoadingFile) {
  39782. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39783. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39784. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39785. geometry._delayInfo = [];
  39786. if (parsedVertexData.hasUVs) {
  39787. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39788. }
  39789. if (parsedVertexData.hasUVs2) {
  39790. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39791. }
  39792. if (parsedVertexData.hasUVs3) {
  39793. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39794. }
  39795. if (parsedVertexData.hasUVs4) {
  39796. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39797. }
  39798. if (parsedVertexData.hasUVs5) {
  39799. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39800. }
  39801. if (parsedVertexData.hasUVs6) {
  39802. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39803. }
  39804. if (parsedVertexData.hasColors) {
  39805. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39806. }
  39807. if (parsedVertexData.hasMatricesIndices) {
  39808. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39809. }
  39810. if (parsedVertexData.hasMatricesWeights) {
  39811. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39812. }
  39813. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39814. }
  39815. else {
  39816. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39817. }
  39818. scene.pushGeometry(geometry, true);
  39819. return geometry;
  39820. };
  39821. return Geometry;
  39822. }());
  39823. BABYLON.Geometry = Geometry;
  39824. // Primitives
  39825. /// Abstract class
  39826. /**
  39827. * Abstract class used to provide common services for all typed geometries
  39828. * @hidden
  39829. */
  39830. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39831. __extends(_PrimitiveGeometry, _super);
  39832. /**
  39833. * Creates a new typed geometry
  39834. * @param id defines the unique ID of the geometry
  39835. * @param scene defines the hosting scene
  39836. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39837. * @param mesh defines the hosting mesh (can be null)
  39838. */
  39839. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39840. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39841. if (mesh === void 0) { mesh = null; }
  39842. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39843. _this._canBeRegenerated = _canBeRegenerated;
  39844. _this._beingRegenerated = true;
  39845. _this.regenerate();
  39846. _this._beingRegenerated = false;
  39847. return _this;
  39848. }
  39849. /**
  39850. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39851. * @returns true if the geometry can be regenerated
  39852. */
  39853. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39854. return this._canBeRegenerated;
  39855. };
  39856. /**
  39857. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39858. */
  39859. _PrimitiveGeometry.prototype.regenerate = function () {
  39860. if (!this._canBeRegenerated) {
  39861. return;
  39862. }
  39863. this._beingRegenerated = true;
  39864. this.setAllVerticesData(this._regenerateVertexData(), false);
  39865. this._beingRegenerated = false;
  39866. };
  39867. /**
  39868. * Clone the geometry
  39869. * @param id defines the unique ID of the new geometry
  39870. * @returns the new geometry
  39871. */
  39872. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39873. return _super.prototype.copy.call(this, id);
  39874. };
  39875. // overrides
  39876. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39877. if (!this._beingRegenerated) {
  39878. return;
  39879. }
  39880. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39881. };
  39882. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39883. if (!this._beingRegenerated) {
  39884. return;
  39885. }
  39886. _super.prototype.setVerticesData.call(this, kind, data, false);
  39887. };
  39888. // to override
  39889. /** @hidden */
  39890. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39891. throw new Error("Abstract method");
  39892. };
  39893. _PrimitiveGeometry.prototype.copy = function (id) {
  39894. throw new Error("Must be overriden in sub-classes.");
  39895. };
  39896. _PrimitiveGeometry.prototype.serialize = function () {
  39897. var serializationObject = _super.prototype.serialize.call(this);
  39898. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39899. return serializationObject;
  39900. };
  39901. return _PrimitiveGeometry;
  39902. }(Geometry));
  39903. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39904. /**
  39905. * Creates a ribbon geometry
  39906. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39907. */
  39908. var RibbonGeometry = /** @class */ (function (_super) {
  39909. __extends(RibbonGeometry, _super);
  39910. /**
  39911. * Creates a ribbon geometry
  39912. * @param id defines the unique ID of the geometry
  39913. * @param scene defines the hosting scene
  39914. * @param pathArray defines the array of paths to use
  39915. * @param closeArray defines if the last path and the first path must be joined
  39916. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39917. * @param offset defines the offset between points
  39918. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39919. * @param mesh defines the hosting mesh (can be null)
  39920. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39921. */
  39922. function RibbonGeometry(id, scene,
  39923. /**
  39924. * Defines the array of paths to use
  39925. */
  39926. pathArray,
  39927. /**
  39928. * Defines if the last and first points of each path in your pathArray must be joined
  39929. */
  39930. closeArray,
  39931. /**
  39932. * Defines if the last and first points of each path in your pathArray must be joined
  39933. */
  39934. closePath,
  39935. /**
  39936. * Defines the offset between points
  39937. */
  39938. offset, canBeRegenerated, mesh,
  39939. /**
  39940. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39941. */
  39942. side) {
  39943. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39944. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39945. _this.pathArray = pathArray;
  39946. _this.closeArray = closeArray;
  39947. _this.closePath = closePath;
  39948. _this.offset = offset;
  39949. _this.side = side;
  39950. return _this;
  39951. }
  39952. /** @hidden */
  39953. RibbonGeometry.prototype._regenerateVertexData = function () {
  39954. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39955. };
  39956. RibbonGeometry.prototype.copy = function (id) {
  39957. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39958. };
  39959. return RibbonGeometry;
  39960. }(_PrimitiveGeometry));
  39961. BABYLON.RibbonGeometry = RibbonGeometry;
  39962. /**
  39963. * Creates a box geometry
  39964. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39965. */
  39966. var BoxGeometry = /** @class */ (function (_super) {
  39967. __extends(BoxGeometry, _super);
  39968. /**
  39969. * Creates a box geometry
  39970. * @param id defines the unique ID of the geometry
  39971. * @param scene defines the hosting scene
  39972. * @param size defines the zise of the box (width, height and depth are the same)
  39973. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39974. * @param mesh defines the hosting mesh (can be null)
  39975. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39976. */
  39977. function BoxGeometry(id, scene,
  39978. /**
  39979. * Defines the zise of the box (width, height and depth are the same)
  39980. */
  39981. size, canBeRegenerated, mesh,
  39982. /**
  39983. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39984. */
  39985. side) {
  39986. if (mesh === void 0) { mesh = null; }
  39987. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39988. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39989. _this.size = size;
  39990. _this.side = side;
  39991. return _this;
  39992. }
  39993. BoxGeometry.prototype._regenerateVertexData = function () {
  39994. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39995. };
  39996. BoxGeometry.prototype.copy = function (id) {
  39997. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39998. };
  39999. BoxGeometry.prototype.serialize = function () {
  40000. var serializationObject = _super.prototype.serialize.call(this);
  40001. serializationObject.size = this.size;
  40002. return serializationObject;
  40003. };
  40004. BoxGeometry.Parse = function (parsedBox, scene) {
  40005. if (scene.getGeometryByID(parsedBox.id)) {
  40006. return null; // null since geometry could be something else than a box...
  40007. }
  40008. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40009. if (BABYLON.Tags) {
  40010. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40011. }
  40012. scene.pushGeometry(box, true);
  40013. return box;
  40014. };
  40015. return BoxGeometry;
  40016. }(_PrimitiveGeometry));
  40017. BABYLON.BoxGeometry = BoxGeometry;
  40018. /**
  40019. * Creates a sphere geometry
  40020. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40021. */
  40022. var SphereGeometry = /** @class */ (function (_super) {
  40023. __extends(SphereGeometry, _super);
  40024. /**
  40025. * Create a new sphere geometry
  40026. * @param id defines the unique ID of the geometry
  40027. * @param scene defines the hosting scene
  40028. * @param segments defines the number of segments to use to create the sphere
  40029. * @param diameter defines the diameter of the sphere
  40030. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40031. * @param mesh defines the hosting mesh (can be null)
  40032. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40033. */
  40034. function SphereGeometry(id, scene,
  40035. /**
  40036. * Defines the number of segments to use to create the sphere
  40037. */
  40038. segments,
  40039. /**
  40040. * Defines the diameter of the sphere
  40041. */
  40042. diameter, canBeRegenerated, mesh,
  40043. /**
  40044. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40045. */
  40046. side) {
  40047. if (mesh === void 0) { mesh = null; }
  40048. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40049. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40050. _this.segments = segments;
  40051. _this.diameter = diameter;
  40052. _this.side = side;
  40053. return _this;
  40054. }
  40055. SphereGeometry.prototype._regenerateVertexData = function () {
  40056. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40057. };
  40058. SphereGeometry.prototype.copy = function (id) {
  40059. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40060. };
  40061. SphereGeometry.prototype.serialize = function () {
  40062. var serializationObject = _super.prototype.serialize.call(this);
  40063. serializationObject.segments = this.segments;
  40064. serializationObject.diameter = this.diameter;
  40065. return serializationObject;
  40066. };
  40067. SphereGeometry.Parse = function (parsedSphere, scene) {
  40068. if (scene.getGeometryByID(parsedSphere.id)) {
  40069. return null; // null since geometry could be something else than a sphere...
  40070. }
  40071. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40072. if (BABYLON.Tags) {
  40073. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40074. }
  40075. scene.pushGeometry(sphere, true);
  40076. return sphere;
  40077. };
  40078. return SphereGeometry;
  40079. }(_PrimitiveGeometry));
  40080. BABYLON.SphereGeometry = SphereGeometry;
  40081. /**
  40082. * Creates a disc geometry
  40083. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40084. */
  40085. var DiscGeometry = /** @class */ (function (_super) {
  40086. __extends(DiscGeometry, _super);
  40087. /**
  40088. * Creates a new disc geometry
  40089. * @param id defines the unique ID of the geometry
  40090. * @param scene defines the hosting scene
  40091. * @param radius defines the radius of the disc
  40092. * @param tessellation defines the tesselation factor to apply to the disc
  40093. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40094. * @param mesh defines the hosting mesh (can be null)
  40095. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40096. */
  40097. function DiscGeometry(id, scene,
  40098. /**
  40099. * Defines the radius of the disc
  40100. */
  40101. radius,
  40102. /**
  40103. * Defines the tesselation factor to apply to the disc
  40104. */
  40105. tessellation, canBeRegenerated, mesh,
  40106. /**
  40107. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40108. */
  40109. side) {
  40110. if (mesh === void 0) { mesh = null; }
  40111. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40112. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40113. _this.radius = radius;
  40114. _this.tessellation = tessellation;
  40115. _this.side = side;
  40116. return _this;
  40117. }
  40118. DiscGeometry.prototype._regenerateVertexData = function () {
  40119. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40120. };
  40121. DiscGeometry.prototype.copy = function (id) {
  40122. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40123. };
  40124. return DiscGeometry;
  40125. }(_PrimitiveGeometry));
  40126. BABYLON.DiscGeometry = DiscGeometry;
  40127. /**
  40128. * Creates a new cylinder geometry
  40129. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40130. */
  40131. var CylinderGeometry = /** @class */ (function (_super) {
  40132. __extends(CylinderGeometry, _super);
  40133. /**
  40134. * Creates a new cylinder geometry
  40135. * @param id defines the unique ID of the geometry
  40136. * @param scene defines the hosting scene
  40137. * @param height defines the height of the cylinder
  40138. * @param diameterTop defines the diameter of the cylinder's top cap
  40139. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40140. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40141. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40142. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40143. * @param mesh defines the hosting mesh (can be null)
  40144. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40145. */
  40146. function CylinderGeometry(id, scene,
  40147. /**
  40148. * Defines the height of the cylinder
  40149. */
  40150. height,
  40151. /**
  40152. * Defines the diameter of the cylinder's top cap
  40153. */
  40154. diameterTop,
  40155. /**
  40156. * Defines the diameter of the cylinder's bottom cap
  40157. */
  40158. diameterBottom,
  40159. /**
  40160. * Defines the tessellation factor to apply to the cylinder
  40161. */
  40162. tessellation,
  40163. /**
  40164. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40165. */
  40166. subdivisions, canBeRegenerated, mesh,
  40167. /**
  40168. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40169. */
  40170. side) {
  40171. if (subdivisions === void 0) { subdivisions = 1; }
  40172. if (mesh === void 0) { mesh = null; }
  40173. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40174. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40175. _this.height = height;
  40176. _this.diameterTop = diameterTop;
  40177. _this.diameterBottom = diameterBottom;
  40178. _this.tessellation = tessellation;
  40179. _this.subdivisions = subdivisions;
  40180. _this.side = side;
  40181. return _this;
  40182. }
  40183. CylinderGeometry.prototype._regenerateVertexData = function () {
  40184. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40185. };
  40186. CylinderGeometry.prototype.copy = function (id) {
  40187. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40188. };
  40189. CylinderGeometry.prototype.serialize = function () {
  40190. var serializationObject = _super.prototype.serialize.call(this);
  40191. serializationObject.height = this.height;
  40192. serializationObject.diameterTop = this.diameterTop;
  40193. serializationObject.diameterBottom = this.diameterBottom;
  40194. serializationObject.tessellation = this.tessellation;
  40195. return serializationObject;
  40196. };
  40197. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40198. if (scene.getGeometryByID(parsedCylinder.id)) {
  40199. return null; // null since geometry could be something else than a cylinder...
  40200. }
  40201. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40202. if (BABYLON.Tags) {
  40203. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40204. }
  40205. scene.pushGeometry(cylinder, true);
  40206. return cylinder;
  40207. };
  40208. return CylinderGeometry;
  40209. }(_PrimitiveGeometry));
  40210. BABYLON.CylinderGeometry = CylinderGeometry;
  40211. /**
  40212. * Creates a new torus geometry
  40213. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40214. */
  40215. var TorusGeometry = /** @class */ (function (_super) {
  40216. __extends(TorusGeometry, _super);
  40217. /**
  40218. * Creates a new torus geometry
  40219. * @param id defines the unique ID of the geometry
  40220. * @param scene defines the hosting scene
  40221. * @param diameter defines the diameter of the torus
  40222. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40223. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40224. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40225. * @param mesh defines the hosting mesh (can be null)
  40226. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40227. */
  40228. function TorusGeometry(id, scene,
  40229. /**
  40230. * Defines the diameter of the torus
  40231. */
  40232. diameter,
  40233. /**
  40234. * Defines the thickness of the torus (ie. internal diameter)
  40235. */
  40236. thickness,
  40237. /**
  40238. * Defines the tesselation factor to apply to the torus
  40239. */
  40240. tessellation, canBeRegenerated, mesh,
  40241. /**
  40242. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40243. */
  40244. side) {
  40245. if (mesh === void 0) { mesh = null; }
  40246. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40247. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40248. _this.diameter = diameter;
  40249. _this.thickness = thickness;
  40250. _this.tessellation = tessellation;
  40251. _this.side = side;
  40252. return _this;
  40253. }
  40254. TorusGeometry.prototype._regenerateVertexData = function () {
  40255. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40256. };
  40257. TorusGeometry.prototype.copy = function (id) {
  40258. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40259. };
  40260. TorusGeometry.prototype.serialize = function () {
  40261. var serializationObject = _super.prototype.serialize.call(this);
  40262. serializationObject.diameter = this.diameter;
  40263. serializationObject.thickness = this.thickness;
  40264. serializationObject.tessellation = this.tessellation;
  40265. return serializationObject;
  40266. };
  40267. TorusGeometry.Parse = function (parsedTorus, scene) {
  40268. if (scene.getGeometryByID(parsedTorus.id)) {
  40269. return null; // null since geometry could be something else than a torus...
  40270. }
  40271. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40272. if (BABYLON.Tags) {
  40273. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40274. }
  40275. scene.pushGeometry(torus, true);
  40276. return torus;
  40277. };
  40278. return TorusGeometry;
  40279. }(_PrimitiveGeometry));
  40280. BABYLON.TorusGeometry = TorusGeometry;
  40281. /**
  40282. * Creates a new ground geometry
  40283. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40284. */
  40285. var GroundGeometry = /** @class */ (function (_super) {
  40286. __extends(GroundGeometry, _super);
  40287. /**
  40288. * Creates a new ground geometry
  40289. * @param id defines the unique ID of the geometry
  40290. * @param scene defines the hosting scene
  40291. * @param width defines the width of the ground
  40292. * @param height defines the height of the ground
  40293. * @param subdivisions defines the subdivisions to apply to the ground
  40294. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40295. * @param mesh defines the hosting mesh (can be null)
  40296. */
  40297. function GroundGeometry(id, scene,
  40298. /**
  40299. * Defines the width of the ground
  40300. */
  40301. width,
  40302. /**
  40303. * Defines the height of the ground
  40304. */
  40305. height,
  40306. /**
  40307. * Defines the subdivisions to apply to the ground
  40308. */
  40309. subdivisions, canBeRegenerated, mesh) {
  40310. if (mesh === void 0) { mesh = null; }
  40311. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40312. _this.width = width;
  40313. _this.height = height;
  40314. _this.subdivisions = subdivisions;
  40315. return _this;
  40316. }
  40317. GroundGeometry.prototype._regenerateVertexData = function () {
  40318. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40319. };
  40320. GroundGeometry.prototype.copy = function (id) {
  40321. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40322. };
  40323. GroundGeometry.prototype.serialize = function () {
  40324. var serializationObject = _super.prototype.serialize.call(this);
  40325. serializationObject.width = this.width;
  40326. serializationObject.height = this.height;
  40327. serializationObject.subdivisions = this.subdivisions;
  40328. return serializationObject;
  40329. };
  40330. GroundGeometry.Parse = function (parsedGround, scene) {
  40331. if (scene.getGeometryByID(parsedGround.id)) {
  40332. return null; // null since geometry could be something else than a ground...
  40333. }
  40334. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40335. if (BABYLON.Tags) {
  40336. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40337. }
  40338. scene.pushGeometry(ground, true);
  40339. return ground;
  40340. };
  40341. return GroundGeometry;
  40342. }(_PrimitiveGeometry));
  40343. BABYLON.GroundGeometry = GroundGeometry;
  40344. /**
  40345. * Creates a tiled ground geometry
  40346. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40347. */
  40348. var TiledGroundGeometry = /** @class */ (function (_super) {
  40349. __extends(TiledGroundGeometry, _super);
  40350. /**
  40351. * Creates a tiled ground geometry
  40352. * @param id defines the unique ID of the geometry
  40353. * @param scene defines the hosting scene
  40354. * @param xmin defines the minimum value on X axis
  40355. * @param zmin defines the minimum value on Z axis
  40356. * @param xmax defines the maximum value on X axis
  40357. * @param zmax defines the maximum value on Z axis
  40358. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40359. * @param precision defines the precision to use when computing the tiles
  40360. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40361. * @param mesh defines the hosting mesh (can be null)
  40362. */
  40363. function TiledGroundGeometry(id, scene,
  40364. /**
  40365. * Defines the minimum value on X axis
  40366. */
  40367. xmin,
  40368. /**
  40369. * Defines the minimum value on Z axis
  40370. */
  40371. zmin,
  40372. /**
  40373. * Defines the maximum value on X axis
  40374. */
  40375. xmax,
  40376. /**
  40377. * Defines the maximum value on Z axis
  40378. */
  40379. zmax,
  40380. /**
  40381. * Defines the subdivisions to apply to the ground
  40382. */
  40383. subdivisions,
  40384. /**
  40385. * Defines the precision to use when computing the tiles
  40386. */
  40387. precision, canBeRegenerated, mesh) {
  40388. if (mesh === void 0) { mesh = null; }
  40389. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40390. _this.xmin = xmin;
  40391. _this.zmin = zmin;
  40392. _this.xmax = xmax;
  40393. _this.zmax = zmax;
  40394. _this.subdivisions = subdivisions;
  40395. _this.precision = precision;
  40396. return _this;
  40397. }
  40398. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40399. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40400. };
  40401. TiledGroundGeometry.prototype.copy = function (id) {
  40402. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40403. };
  40404. return TiledGroundGeometry;
  40405. }(_PrimitiveGeometry));
  40406. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40407. /**
  40408. * Creates a plane geometry
  40409. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40410. */
  40411. var PlaneGeometry = /** @class */ (function (_super) {
  40412. __extends(PlaneGeometry, _super);
  40413. /**
  40414. * Creates a plane geometry
  40415. * @param id defines the unique ID of the geometry
  40416. * @param scene defines the hosting scene
  40417. * @param size defines the size of the plane (width === height)
  40418. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40419. * @param mesh defines the hosting mesh (can be null)
  40420. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40421. */
  40422. function PlaneGeometry(id, scene,
  40423. /**
  40424. * Defines the size of the plane (width === height)
  40425. */
  40426. size, canBeRegenerated, mesh,
  40427. /**
  40428. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40429. */
  40430. side) {
  40431. if (mesh === void 0) { mesh = null; }
  40432. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40433. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40434. _this.size = size;
  40435. _this.side = side;
  40436. return _this;
  40437. }
  40438. PlaneGeometry.prototype._regenerateVertexData = function () {
  40439. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40440. };
  40441. PlaneGeometry.prototype.copy = function (id) {
  40442. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40443. };
  40444. PlaneGeometry.prototype.serialize = function () {
  40445. var serializationObject = _super.prototype.serialize.call(this);
  40446. serializationObject.size = this.size;
  40447. return serializationObject;
  40448. };
  40449. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40450. if (scene.getGeometryByID(parsedPlane.id)) {
  40451. return null; // null since geometry could be something else than a ground...
  40452. }
  40453. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40454. if (BABYLON.Tags) {
  40455. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40456. }
  40457. scene.pushGeometry(plane, true);
  40458. return plane;
  40459. };
  40460. return PlaneGeometry;
  40461. }(_PrimitiveGeometry));
  40462. BABYLON.PlaneGeometry = PlaneGeometry;
  40463. /**
  40464. * Creates a torus knot geometry
  40465. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40466. */
  40467. var TorusKnotGeometry = /** @class */ (function (_super) {
  40468. __extends(TorusKnotGeometry, _super);
  40469. /**
  40470. * Creates a torus knot geometry
  40471. * @param id defines the unique ID of the geometry
  40472. * @param scene defines the hosting scene
  40473. * @param radius defines the radius of the torus knot
  40474. * @param tube defines the thickness of the torus knot tube
  40475. * @param radialSegments defines the number of radial segments
  40476. * @param tubularSegments defines the number of tubular segments
  40477. * @param p defines the first number of windings
  40478. * @param q defines the second number of windings
  40479. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40480. * @param mesh defines the hosting mesh (can be null)
  40481. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40482. */
  40483. function TorusKnotGeometry(id, scene,
  40484. /**
  40485. * Defines the radius of the torus knot
  40486. */
  40487. radius,
  40488. /**
  40489. * Defines the thickness of the torus knot tube
  40490. */
  40491. tube,
  40492. /**
  40493. * Defines the number of radial segments
  40494. */
  40495. radialSegments,
  40496. /**
  40497. * Defines the number of tubular segments
  40498. */
  40499. tubularSegments,
  40500. /**
  40501. * Defines the first number of windings
  40502. */
  40503. p,
  40504. /**
  40505. * Defines the second number of windings
  40506. */
  40507. q, canBeRegenerated, mesh,
  40508. /**
  40509. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40510. */
  40511. side) {
  40512. if (mesh === void 0) { mesh = null; }
  40513. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40514. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40515. _this.radius = radius;
  40516. _this.tube = tube;
  40517. _this.radialSegments = radialSegments;
  40518. _this.tubularSegments = tubularSegments;
  40519. _this.p = p;
  40520. _this.q = q;
  40521. _this.side = side;
  40522. return _this;
  40523. }
  40524. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40525. 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 });
  40526. };
  40527. TorusKnotGeometry.prototype.copy = function (id) {
  40528. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40529. };
  40530. TorusKnotGeometry.prototype.serialize = function () {
  40531. var serializationObject = _super.prototype.serialize.call(this);
  40532. serializationObject.radius = this.radius;
  40533. serializationObject.tube = this.tube;
  40534. serializationObject.radialSegments = this.radialSegments;
  40535. serializationObject.tubularSegments = this.tubularSegments;
  40536. serializationObject.p = this.p;
  40537. serializationObject.q = this.q;
  40538. return serializationObject;
  40539. };
  40540. ;
  40541. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40542. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40543. return null; // null since geometry could be something else than a ground...
  40544. }
  40545. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40546. if (BABYLON.Tags) {
  40547. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40548. }
  40549. scene.pushGeometry(torusKnot, true);
  40550. return torusKnot;
  40551. };
  40552. return TorusKnotGeometry;
  40553. }(_PrimitiveGeometry));
  40554. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40555. //}
  40556. })(BABYLON || (BABYLON = {}));
  40557. //# sourceMappingURL=babylon.geometry.js.map
  40558. var BABYLON;
  40559. (function (BABYLON) {
  40560. /**
  40561. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40562. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40563. */
  40564. var PostProcessManager = /** @class */ (function () {
  40565. /**
  40566. * Creates a new instance PostProcess
  40567. * @param scene The scene that the post process is associated with.
  40568. */
  40569. function PostProcessManager(scene) {
  40570. this._vertexBuffers = {};
  40571. this._scene = scene;
  40572. }
  40573. PostProcessManager.prototype._prepareBuffers = function () {
  40574. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40575. return;
  40576. }
  40577. // VBO
  40578. var vertices = [];
  40579. vertices.push(1, 1);
  40580. vertices.push(-1, 1);
  40581. vertices.push(-1, -1);
  40582. vertices.push(1, -1);
  40583. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40584. this._buildIndexBuffer();
  40585. };
  40586. PostProcessManager.prototype._buildIndexBuffer = function () {
  40587. // Indices
  40588. var indices = [];
  40589. indices.push(0);
  40590. indices.push(1);
  40591. indices.push(2);
  40592. indices.push(0);
  40593. indices.push(2);
  40594. indices.push(3);
  40595. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40596. };
  40597. /**
  40598. * Rebuilds the vertex buffers of the manager.
  40599. */
  40600. PostProcessManager.prototype._rebuild = function () {
  40601. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40602. if (!vb) {
  40603. return;
  40604. }
  40605. vb._rebuild();
  40606. this._buildIndexBuffer();
  40607. };
  40608. // Methods
  40609. /**
  40610. * Prepares a frame to be run through a post process.
  40611. * @param sourceTexture The input texture to the post procesess. (default: null)
  40612. * @param postProcesses An array of post processes to be run. (default: null)
  40613. * @returns True if the post processes were able to be run.
  40614. */
  40615. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40616. if (sourceTexture === void 0) { sourceTexture = null; }
  40617. if (postProcesses === void 0) { postProcesses = null; }
  40618. var camera = this._scene.activeCamera;
  40619. if (!camera) {
  40620. return false;
  40621. }
  40622. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40623. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40624. return false;
  40625. }
  40626. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40627. return true;
  40628. };
  40629. /**
  40630. * Manually render a set of post processes to a texture.
  40631. * @param postProcesses An array of post processes to be run.
  40632. * @param targetTexture The target texture to render to.
  40633. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40634. */
  40635. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40636. if (targetTexture === void 0) { targetTexture = null; }
  40637. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40638. var engine = this._scene.getEngine();
  40639. for (var index = 0; index < postProcesses.length; index++) {
  40640. if (index < postProcesses.length - 1) {
  40641. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40642. }
  40643. else {
  40644. if (targetTexture) {
  40645. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40646. }
  40647. else {
  40648. engine.restoreDefaultFramebuffer();
  40649. }
  40650. }
  40651. var pp = postProcesses[index];
  40652. var effect = pp.apply();
  40653. if (effect) {
  40654. pp.onBeforeRenderObservable.notifyObservers(effect);
  40655. // VBOs
  40656. this._prepareBuffers();
  40657. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40658. // Draw order
  40659. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40660. pp.onAfterRenderObservable.notifyObservers(effect);
  40661. }
  40662. }
  40663. // Restore depth buffer
  40664. engine.setDepthBuffer(true);
  40665. engine.setDepthWrite(true);
  40666. };
  40667. /**
  40668. * Finalize the result of the output of the postprocesses.
  40669. * @param doNotPresent If true the result will not be displayed to the screen.
  40670. * @param targetTexture The target texture to render to.
  40671. * @param faceIndex The index of the face to bind the target texture to.
  40672. * @param postProcesses The array of post processes to render.
  40673. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40674. */
  40675. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40676. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40677. var camera = this._scene.activeCamera;
  40678. if (!camera) {
  40679. return;
  40680. }
  40681. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40682. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40683. return;
  40684. }
  40685. var engine = this._scene.getEngine();
  40686. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40687. var pp = postProcesses[index];
  40688. if (index < len - 1) {
  40689. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40690. }
  40691. else {
  40692. if (targetTexture) {
  40693. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40694. pp._outputTexture = targetTexture;
  40695. }
  40696. else {
  40697. engine.restoreDefaultFramebuffer();
  40698. pp._outputTexture = null;
  40699. }
  40700. }
  40701. if (doNotPresent) {
  40702. break;
  40703. }
  40704. var effect = pp.apply();
  40705. if (effect) {
  40706. pp.onBeforeRenderObservable.notifyObservers(effect);
  40707. // VBOs
  40708. this._prepareBuffers();
  40709. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40710. // Draw order
  40711. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40712. pp.onAfterRenderObservable.notifyObservers(effect);
  40713. }
  40714. }
  40715. // Restore states
  40716. engine.setDepthBuffer(true);
  40717. engine.setDepthWrite(true);
  40718. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40719. };
  40720. /**
  40721. * Disposes of the post process manager.
  40722. */
  40723. PostProcessManager.prototype.dispose = function () {
  40724. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40725. if (buffer) {
  40726. buffer.dispose();
  40727. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40728. }
  40729. if (this._indexBuffer) {
  40730. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40731. this._indexBuffer = null;
  40732. }
  40733. };
  40734. return PostProcessManager;
  40735. }());
  40736. BABYLON.PostProcessManager = PostProcessManager;
  40737. })(BABYLON || (BABYLON = {}));
  40738. //# sourceMappingURL=babylon.postProcessManager.js.map
  40739. var BABYLON;
  40740. (function (BABYLON) {
  40741. /**
  40742. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40743. */
  40744. var PerformanceMonitor = /** @class */ (function () {
  40745. /**
  40746. * constructor
  40747. * @param frameSampleSize The number of samples required to saturate the sliding window
  40748. */
  40749. function PerformanceMonitor(frameSampleSize) {
  40750. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40751. this._enabled = true;
  40752. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40753. }
  40754. /**
  40755. * Samples current frame
  40756. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40757. */
  40758. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40759. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40760. if (!this._enabled)
  40761. return;
  40762. if (this._lastFrameTimeMs != null) {
  40763. var dt = timeMs - this._lastFrameTimeMs;
  40764. this._rollingFrameTime.add(dt);
  40765. }
  40766. this._lastFrameTimeMs = timeMs;
  40767. };
  40768. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40769. /**
  40770. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40771. * @return Average frame time in milliseconds
  40772. */
  40773. get: function () {
  40774. return this._rollingFrameTime.average;
  40775. },
  40776. enumerable: true,
  40777. configurable: true
  40778. });
  40779. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40780. /**
  40781. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40782. * @return Frame time variance in milliseconds squared
  40783. */
  40784. get: function () {
  40785. return this._rollingFrameTime.variance;
  40786. },
  40787. enumerable: true,
  40788. configurable: true
  40789. });
  40790. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40791. /**
  40792. * Returns the frame time of the most recent frame
  40793. * @return Frame time in milliseconds
  40794. */
  40795. get: function () {
  40796. return this._rollingFrameTime.history(0);
  40797. },
  40798. enumerable: true,
  40799. configurable: true
  40800. });
  40801. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40802. /**
  40803. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40804. * @return Framerate in frames per second
  40805. */
  40806. get: function () {
  40807. return 1000.0 / this._rollingFrameTime.average;
  40808. },
  40809. enumerable: true,
  40810. configurable: true
  40811. });
  40812. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40813. /**
  40814. * Returns the average framerate in frames per second using the most recent frame time
  40815. * @return Framerate in frames per second
  40816. */
  40817. get: function () {
  40818. var history = this._rollingFrameTime.history(0);
  40819. if (history === 0) {
  40820. return 0;
  40821. }
  40822. return 1000.0 / history;
  40823. },
  40824. enumerable: true,
  40825. configurable: true
  40826. });
  40827. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40828. /**
  40829. * Returns true if enough samples have been taken to completely fill the sliding window
  40830. * @return true if saturated
  40831. */
  40832. get: function () {
  40833. return this._rollingFrameTime.isSaturated();
  40834. },
  40835. enumerable: true,
  40836. configurable: true
  40837. });
  40838. /**
  40839. * Enables contributions to the sliding window sample set
  40840. */
  40841. PerformanceMonitor.prototype.enable = function () {
  40842. this._enabled = true;
  40843. };
  40844. /**
  40845. * Disables contributions to the sliding window sample set
  40846. * Samples will not be interpolated over the disabled period
  40847. */
  40848. PerformanceMonitor.prototype.disable = function () {
  40849. this._enabled = false;
  40850. //clear last sample to avoid interpolating over the disabled period when next enabled
  40851. this._lastFrameTimeMs = null;
  40852. };
  40853. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40854. /**
  40855. * Returns true if sampling is enabled
  40856. * @return true if enabled
  40857. */
  40858. get: function () {
  40859. return this._enabled;
  40860. },
  40861. enumerable: true,
  40862. configurable: true
  40863. });
  40864. /**
  40865. * Resets performance monitor
  40866. */
  40867. PerformanceMonitor.prototype.reset = function () {
  40868. //clear last sample to avoid interpolating over the disabled period when next enabled
  40869. this._lastFrameTimeMs = null;
  40870. //wipe record
  40871. this._rollingFrameTime.reset();
  40872. };
  40873. return PerformanceMonitor;
  40874. }());
  40875. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40876. /**
  40877. * RollingAverage
  40878. *
  40879. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40880. */
  40881. var RollingAverage = /** @class */ (function () {
  40882. /**
  40883. * constructor
  40884. * @param length The number of samples required to saturate the sliding window
  40885. */
  40886. function RollingAverage(length) {
  40887. this._samples = new Array(length);
  40888. this.reset();
  40889. }
  40890. /**
  40891. * Adds a sample to the sample set
  40892. * @param v The sample value
  40893. */
  40894. RollingAverage.prototype.add = function (v) {
  40895. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40896. var delta;
  40897. //we need to check if we've already wrapped round
  40898. if (this.isSaturated()) {
  40899. //remove bottom of stack from mean
  40900. var bottomValue = this._samples[this._pos];
  40901. delta = bottomValue - this.average;
  40902. this.average -= delta / (this._sampleCount - 1);
  40903. this._m2 -= delta * (bottomValue - this.average);
  40904. }
  40905. else {
  40906. this._sampleCount++;
  40907. }
  40908. //add new value to mean
  40909. delta = v - this.average;
  40910. this.average += delta / (this._sampleCount);
  40911. this._m2 += delta * (v - this.average);
  40912. //set the new variance
  40913. this.variance = this._m2 / (this._sampleCount - 1);
  40914. this._samples[this._pos] = v;
  40915. this._pos++;
  40916. this._pos %= this._samples.length; //positive wrap around
  40917. };
  40918. /**
  40919. * Returns previously added values or null if outside of history or outside the sliding window domain
  40920. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40921. * @return Value previously recorded with add() or null if outside of range
  40922. */
  40923. RollingAverage.prototype.history = function (i) {
  40924. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40925. return 0;
  40926. }
  40927. var i0 = this._wrapPosition(this._pos - 1.0);
  40928. return this._samples[this._wrapPosition(i0 - i)];
  40929. };
  40930. /**
  40931. * Returns true if enough samples have been taken to completely fill the sliding window
  40932. * @return true if sample-set saturated
  40933. */
  40934. RollingAverage.prototype.isSaturated = function () {
  40935. return this._sampleCount >= this._samples.length;
  40936. };
  40937. /**
  40938. * Resets the rolling average (equivalent to 0 samples taken so far)
  40939. */
  40940. RollingAverage.prototype.reset = function () {
  40941. this.average = 0;
  40942. this.variance = 0;
  40943. this._sampleCount = 0;
  40944. this._pos = 0;
  40945. this._m2 = 0;
  40946. };
  40947. /**
  40948. * Wraps a value around the sample range boundaries
  40949. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40950. * @return Wrapped position in sample range
  40951. */
  40952. RollingAverage.prototype._wrapPosition = function (i) {
  40953. var max = this._samples.length;
  40954. return ((i % max) + max) % max;
  40955. };
  40956. return RollingAverage;
  40957. }());
  40958. BABYLON.RollingAverage = RollingAverage;
  40959. })(BABYLON || (BABYLON = {}));
  40960. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40961. var BABYLON;
  40962. (function (BABYLON) {
  40963. /**
  40964. * This groups together the common properties used for image processing either in direct forward pass
  40965. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40966. * or not.
  40967. */
  40968. var ImageProcessingConfiguration = /** @class */ (function () {
  40969. function ImageProcessingConfiguration() {
  40970. /**
  40971. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40972. */
  40973. this.colorCurves = new BABYLON.ColorCurves();
  40974. this._colorCurvesEnabled = false;
  40975. this._colorGradingEnabled = false;
  40976. this._colorGradingWithGreenDepth = true;
  40977. this._colorGradingBGR = true;
  40978. this._exposure = 1.0;
  40979. this._toneMappingEnabled = false;
  40980. this._contrast = 1.0;
  40981. /**
  40982. * Vignette stretch size.
  40983. */
  40984. this.vignetteStretch = 0;
  40985. /**
  40986. * Vignette centre X Offset.
  40987. */
  40988. this.vignetteCentreX = 0;
  40989. /**
  40990. * Vignette centre Y Offset.
  40991. */
  40992. this.vignetteCentreY = 0;
  40993. /**
  40994. * Vignette weight or intensity of the vignette effect.
  40995. */
  40996. this.vignetteWeight = 1.5;
  40997. /**
  40998. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40999. * if vignetteEnabled is set to true.
  41000. */
  41001. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41002. /**
  41003. * Camera field of view used by the Vignette effect.
  41004. */
  41005. this.vignetteCameraFov = 0.5;
  41006. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41007. this._vignetteEnabled = false;
  41008. this._applyByPostProcess = false;
  41009. this._isEnabled = true;
  41010. /**
  41011. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41012. */
  41013. this.onUpdateParameters = new BABYLON.Observable();
  41014. }
  41015. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41016. /**
  41017. * Gets wether the color curves effect is enabled.
  41018. */
  41019. get: function () {
  41020. return this._colorCurvesEnabled;
  41021. },
  41022. /**
  41023. * Sets wether the color curves effect is enabled.
  41024. */
  41025. set: function (value) {
  41026. if (this._colorCurvesEnabled === value) {
  41027. return;
  41028. }
  41029. this._colorCurvesEnabled = value;
  41030. this._updateParameters();
  41031. },
  41032. enumerable: true,
  41033. configurable: true
  41034. });
  41035. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41036. /**
  41037. * Gets wether the color grading effect is enabled.
  41038. */
  41039. get: function () {
  41040. return this._colorGradingEnabled;
  41041. },
  41042. /**
  41043. * Sets wether the color grading effect is enabled.
  41044. */
  41045. set: function (value) {
  41046. if (this._colorGradingEnabled === value) {
  41047. return;
  41048. }
  41049. this._colorGradingEnabled = value;
  41050. this._updateParameters();
  41051. },
  41052. enumerable: true,
  41053. configurable: true
  41054. });
  41055. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41056. /**
  41057. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41058. */
  41059. get: function () {
  41060. return this._colorGradingWithGreenDepth;
  41061. },
  41062. /**
  41063. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41064. */
  41065. set: function (value) {
  41066. if (this._colorGradingWithGreenDepth === value) {
  41067. return;
  41068. }
  41069. this._colorGradingWithGreenDepth = value;
  41070. this._updateParameters();
  41071. },
  41072. enumerable: true,
  41073. configurable: true
  41074. });
  41075. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41076. /**
  41077. * Gets wether the color grading texture contains BGR values.
  41078. */
  41079. get: function () {
  41080. return this._colorGradingBGR;
  41081. },
  41082. /**
  41083. * Sets wether the color grading texture contains BGR values.
  41084. */
  41085. set: function (value) {
  41086. if (this._colorGradingBGR === value) {
  41087. return;
  41088. }
  41089. this._colorGradingBGR = value;
  41090. this._updateParameters();
  41091. },
  41092. enumerable: true,
  41093. configurable: true
  41094. });
  41095. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41096. /**
  41097. * Gets the Exposure used in the effect.
  41098. */
  41099. get: function () {
  41100. return this._exposure;
  41101. },
  41102. /**
  41103. * Sets the Exposure used in the effect.
  41104. */
  41105. set: function (value) {
  41106. if (this._exposure === value) {
  41107. return;
  41108. }
  41109. this._exposure = value;
  41110. this._updateParameters();
  41111. },
  41112. enumerable: true,
  41113. configurable: true
  41114. });
  41115. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41116. /**
  41117. * Gets wether the tone mapping effect is enabled.
  41118. */
  41119. get: function () {
  41120. return this._toneMappingEnabled;
  41121. },
  41122. /**
  41123. * Sets wether the tone mapping effect is enabled.
  41124. */
  41125. set: function (value) {
  41126. if (this._toneMappingEnabled === value) {
  41127. return;
  41128. }
  41129. this._toneMappingEnabled = value;
  41130. this._updateParameters();
  41131. },
  41132. enumerable: true,
  41133. configurable: true
  41134. });
  41135. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41136. /**
  41137. * Gets the contrast used in the effect.
  41138. */
  41139. get: function () {
  41140. return this._contrast;
  41141. },
  41142. /**
  41143. * Sets the contrast used in the effect.
  41144. */
  41145. set: function (value) {
  41146. if (this._contrast === value) {
  41147. return;
  41148. }
  41149. this._contrast = value;
  41150. this._updateParameters();
  41151. },
  41152. enumerable: true,
  41153. configurable: true
  41154. });
  41155. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41156. /**
  41157. * Gets the vignette blend mode allowing different kind of effect.
  41158. */
  41159. get: function () {
  41160. return this._vignetteBlendMode;
  41161. },
  41162. /**
  41163. * Sets the vignette blend mode allowing different kind of effect.
  41164. */
  41165. set: function (value) {
  41166. if (this._vignetteBlendMode === value) {
  41167. return;
  41168. }
  41169. this._vignetteBlendMode = value;
  41170. this._updateParameters();
  41171. },
  41172. enumerable: true,
  41173. configurable: true
  41174. });
  41175. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41176. /**
  41177. * Gets wether the vignette effect is enabled.
  41178. */
  41179. get: function () {
  41180. return this._vignetteEnabled;
  41181. },
  41182. /**
  41183. * Sets wether the vignette effect is enabled.
  41184. */
  41185. set: function (value) {
  41186. if (this._vignetteEnabled === value) {
  41187. return;
  41188. }
  41189. this._vignetteEnabled = value;
  41190. this._updateParameters();
  41191. },
  41192. enumerable: true,
  41193. configurable: true
  41194. });
  41195. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41196. /**
  41197. * Gets wether the image processing is applied through a post process or not.
  41198. */
  41199. get: function () {
  41200. return this._applyByPostProcess;
  41201. },
  41202. /**
  41203. * Sets wether the image processing is applied through a post process or not.
  41204. */
  41205. set: function (value) {
  41206. if (this._applyByPostProcess === value) {
  41207. return;
  41208. }
  41209. this._applyByPostProcess = value;
  41210. this._updateParameters();
  41211. },
  41212. enumerable: true,
  41213. configurable: true
  41214. });
  41215. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41216. /**
  41217. * Gets wether the image processing is enabled or not.
  41218. */
  41219. get: function () {
  41220. return this._isEnabled;
  41221. },
  41222. /**
  41223. * Sets wether the image processing is enabled or not.
  41224. */
  41225. set: function (value) {
  41226. if (this._isEnabled === value) {
  41227. return;
  41228. }
  41229. this._isEnabled = value;
  41230. this._updateParameters();
  41231. },
  41232. enumerable: true,
  41233. configurable: true
  41234. });
  41235. /**
  41236. * Method called each time the image processing information changes requires to recompile the effect.
  41237. */
  41238. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41239. this.onUpdateParameters.notifyObservers(this);
  41240. };
  41241. ImageProcessingConfiguration.prototype.getClassName = function () {
  41242. return "ImageProcessingConfiguration";
  41243. };
  41244. /**
  41245. * Prepare the list of uniforms associated with the Image Processing effects.
  41246. * @param uniformsList The list of uniforms used in the effect
  41247. * @param defines the list of defines currently in use
  41248. */
  41249. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41250. if (defines.EXPOSURE) {
  41251. uniforms.push("exposureLinear");
  41252. }
  41253. if (defines.CONTRAST) {
  41254. uniforms.push("contrast");
  41255. }
  41256. if (defines.COLORGRADING) {
  41257. uniforms.push("colorTransformSettings");
  41258. }
  41259. if (defines.VIGNETTE) {
  41260. uniforms.push("vInverseScreenSize");
  41261. uniforms.push("vignetteSettings1");
  41262. uniforms.push("vignetteSettings2");
  41263. }
  41264. if (defines.COLORCURVES) {
  41265. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41266. }
  41267. };
  41268. /**
  41269. * Prepare the list of samplers associated with the Image Processing effects.
  41270. * @param uniformsList The list of uniforms used in the effect
  41271. * @param defines the list of defines currently in use
  41272. */
  41273. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41274. if (defines.COLORGRADING) {
  41275. samplersList.push("txColorTransform");
  41276. }
  41277. };
  41278. /**
  41279. * Prepare the list of defines associated to the shader.
  41280. * @param defines the list of defines to complete
  41281. */
  41282. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41283. if (forPostProcess === void 0) { forPostProcess = false; }
  41284. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41285. defines.VIGNETTE = false;
  41286. defines.TONEMAPPING = false;
  41287. defines.CONTRAST = false;
  41288. defines.EXPOSURE = false;
  41289. defines.COLORCURVES = false;
  41290. defines.COLORGRADING = false;
  41291. defines.COLORGRADING3D = false;
  41292. defines.IMAGEPROCESSING = false;
  41293. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41294. return;
  41295. }
  41296. defines.VIGNETTE = this.vignetteEnabled;
  41297. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41298. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41299. defines.TONEMAPPING = this.toneMappingEnabled;
  41300. defines.CONTRAST = (this.contrast !== 1.0);
  41301. defines.EXPOSURE = (this.exposure !== 1.0);
  41302. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41303. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41304. if (defines.COLORGRADING) {
  41305. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41306. }
  41307. else {
  41308. defines.COLORGRADING3D = false;
  41309. }
  41310. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41311. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41312. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41313. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41314. };
  41315. /**
  41316. * Returns true if all the image processing information are ready.
  41317. */
  41318. ImageProcessingConfiguration.prototype.isReady = function () {
  41319. // Color Grading texure can not be none blocking.
  41320. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41321. };
  41322. /**
  41323. * Binds the image processing to the shader.
  41324. * @param effect The effect to bind to
  41325. */
  41326. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41327. if (aspectRatio === void 0) { aspectRatio = 1; }
  41328. // Color Curves
  41329. if (this._colorCurvesEnabled && this.colorCurves) {
  41330. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41331. }
  41332. // Vignette
  41333. if (this._vignetteEnabled) {
  41334. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41335. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41336. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41337. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41338. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41339. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41340. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41341. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41342. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41343. var vignettePower = -2.0 * this.vignetteWeight;
  41344. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41345. }
  41346. // Exposure
  41347. effect.setFloat("exposureLinear", this.exposure);
  41348. // Contrast
  41349. effect.setFloat("contrast", this.contrast);
  41350. // Color transform settings
  41351. if (this.colorGradingTexture) {
  41352. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41353. var textureSize = this.colorGradingTexture.getSize().height;
  41354. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41355. 0.5 / textureSize, // textureOffset
  41356. textureSize, // textureSize
  41357. this.colorGradingTexture.level // weight
  41358. );
  41359. }
  41360. };
  41361. /**
  41362. * Clones the current image processing instance.
  41363. * @return The cloned image processing
  41364. */
  41365. ImageProcessingConfiguration.prototype.clone = function () {
  41366. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41367. };
  41368. /**
  41369. * Serializes the current image processing instance to a json representation.
  41370. * @return a JSON representation
  41371. */
  41372. ImageProcessingConfiguration.prototype.serialize = function () {
  41373. return BABYLON.SerializationHelper.Serialize(this);
  41374. };
  41375. /**
  41376. * Parses the image processing from a json representation.
  41377. * @param source the JSON source to parse
  41378. * @return The parsed image processing
  41379. */
  41380. ImageProcessingConfiguration.Parse = function (source) {
  41381. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41382. };
  41383. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41384. /**
  41385. * Used to apply the vignette as a mix with the pixel color.
  41386. */
  41387. get: function () {
  41388. return this._VIGNETTEMODE_MULTIPLY;
  41389. },
  41390. enumerable: true,
  41391. configurable: true
  41392. });
  41393. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41394. /**
  41395. * Used to apply the vignette as a replacement of the pixel color.
  41396. */
  41397. get: function () {
  41398. return this._VIGNETTEMODE_OPAQUE;
  41399. },
  41400. enumerable: true,
  41401. configurable: true
  41402. });
  41403. // Static constants associated to the image processing.
  41404. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41405. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41406. __decorate([
  41407. BABYLON.serializeAsColorCurves()
  41408. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41409. __decorate([
  41410. BABYLON.serialize()
  41411. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41412. __decorate([
  41413. BABYLON.serializeAsTexture()
  41414. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41415. __decorate([
  41416. BABYLON.serialize()
  41417. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41418. __decorate([
  41419. BABYLON.serialize()
  41420. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41421. __decorate([
  41422. BABYLON.serialize()
  41423. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41424. __decorate([
  41425. BABYLON.serialize()
  41426. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41427. __decorate([
  41428. BABYLON.serialize()
  41429. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41430. __decorate([
  41431. BABYLON.serialize()
  41432. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41433. __decorate([
  41434. BABYLON.serialize()
  41435. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41436. __decorate([
  41437. BABYLON.serialize()
  41438. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41439. __decorate([
  41440. BABYLON.serialize()
  41441. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41442. __decorate([
  41443. BABYLON.serialize()
  41444. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41445. __decorate([
  41446. BABYLON.serializeAsColor4()
  41447. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41448. __decorate([
  41449. BABYLON.serialize()
  41450. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41451. __decorate([
  41452. BABYLON.serialize()
  41453. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41454. __decorate([
  41455. BABYLON.serialize()
  41456. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41457. __decorate([
  41458. BABYLON.serialize()
  41459. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41460. __decorate([
  41461. BABYLON.serialize()
  41462. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41463. return ImageProcessingConfiguration;
  41464. }());
  41465. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41466. })(BABYLON || (BABYLON = {}));
  41467. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41468. var BABYLON;
  41469. (function (BABYLON) {
  41470. /**
  41471. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41472. * It can help converting any input color in a desired output one. This can then be used to create effects
  41473. * from sepia, black and white to sixties or futuristic rendering...
  41474. *
  41475. * The only supported format is currently 3dl.
  41476. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41477. */
  41478. var ColorGradingTexture = /** @class */ (function (_super) {
  41479. __extends(ColorGradingTexture, _super);
  41480. /**
  41481. * Instantiates a ColorGradingTexture from the following parameters.
  41482. *
  41483. * @param url The location of the color gradind data (currently only supporting 3dl)
  41484. * @param scene The scene the texture will be used in
  41485. */
  41486. function ColorGradingTexture(url, scene) {
  41487. var _this = _super.call(this, scene) || this;
  41488. if (!url) {
  41489. return _this;
  41490. }
  41491. _this._engine = scene.getEngine();
  41492. _this._textureMatrix = BABYLON.Matrix.Identity();
  41493. _this.name = url;
  41494. _this.url = url;
  41495. _this.hasAlpha = false;
  41496. _this.isCube = false;
  41497. _this.is3D = _this._engine.webGLVersion > 1;
  41498. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41499. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41500. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41501. _this.anisotropicFilteringLevel = 1;
  41502. _this._texture = _this._getFromCache(url, true);
  41503. if (!_this._texture) {
  41504. if (!scene.useDelayedTextureLoading) {
  41505. _this.loadTexture();
  41506. }
  41507. else {
  41508. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41509. }
  41510. }
  41511. return _this;
  41512. }
  41513. /**
  41514. * Returns the texture matrix used in most of the material.
  41515. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41516. */
  41517. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41518. return this._textureMatrix;
  41519. };
  41520. /**
  41521. * Occurs when the file being loaded is a .3dl LUT file.
  41522. */
  41523. ColorGradingTexture.prototype.load3dlTexture = function () {
  41524. var engine = this._engine;
  41525. var texture;
  41526. if (engine.webGLVersion === 1) {
  41527. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41528. }
  41529. else {
  41530. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41531. }
  41532. this._texture = texture;
  41533. var callback = function (text) {
  41534. if (typeof text !== "string") {
  41535. return;
  41536. }
  41537. var data = null;
  41538. var tempData = null;
  41539. var line;
  41540. var lines = text.split('\n');
  41541. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41542. var maxColor = 0;
  41543. for (var i = 0; i < lines.length; i++) {
  41544. line = lines[i];
  41545. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41546. continue;
  41547. if (line.indexOf('#') === 0)
  41548. continue;
  41549. var words = line.split(" ");
  41550. if (size === 0) {
  41551. // Number of space + one
  41552. size = words.length;
  41553. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41554. tempData = new Float32Array(size * size * size * 4);
  41555. continue;
  41556. }
  41557. if (size != 0) {
  41558. var r = Math.max(parseInt(words[0]), 0);
  41559. var g = Math.max(parseInt(words[1]), 0);
  41560. var b = Math.max(parseInt(words[2]), 0);
  41561. maxColor = Math.max(r, maxColor);
  41562. maxColor = Math.max(g, maxColor);
  41563. maxColor = Math.max(b, maxColor);
  41564. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41565. if (tempData) {
  41566. tempData[pixelStorageIndex + 0] = r;
  41567. tempData[pixelStorageIndex + 1] = g;
  41568. tempData[pixelStorageIndex + 2] = b;
  41569. }
  41570. pixelIndexSlice++;
  41571. if (pixelIndexSlice % size == 0) {
  41572. pixelIndexH++;
  41573. pixelIndexSlice = 0;
  41574. if (pixelIndexH % size == 0) {
  41575. pixelIndexW++;
  41576. pixelIndexH = 0;
  41577. }
  41578. }
  41579. }
  41580. }
  41581. if (tempData && data) {
  41582. for (var i = 0; i < tempData.length; i++) {
  41583. if (i > 0 && (i + 1) % 4 === 0) {
  41584. data[i] = 255;
  41585. }
  41586. else {
  41587. var value = tempData[i];
  41588. data[i] = (value / maxColor * 255);
  41589. }
  41590. }
  41591. }
  41592. if (texture.is3D) {
  41593. texture.updateSize(size, size, size);
  41594. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41595. }
  41596. else {
  41597. texture.updateSize(size * size, size);
  41598. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41599. }
  41600. };
  41601. var scene = this.getScene();
  41602. if (scene) {
  41603. scene._loadFile(this.url, callback);
  41604. }
  41605. else {
  41606. this._engine._loadFile(this.url, callback);
  41607. }
  41608. return this._texture;
  41609. };
  41610. /**
  41611. * Starts the loading process of the texture.
  41612. */
  41613. ColorGradingTexture.prototype.loadTexture = function () {
  41614. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41615. this.load3dlTexture();
  41616. }
  41617. };
  41618. /**
  41619. * Clones the color gradind texture.
  41620. */
  41621. ColorGradingTexture.prototype.clone = function () {
  41622. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41623. // Base texture
  41624. newTexture.level = this.level;
  41625. return newTexture;
  41626. };
  41627. /**
  41628. * Called during delayed load for textures.
  41629. */
  41630. ColorGradingTexture.prototype.delayLoad = function () {
  41631. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41632. return;
  41633. }
  41634. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41635. this._texture = this._getFromCache(this.url, true);
  41636. if (!this._texture) {
  41637. this.loadTexture();
  41638. }
  41639. };
  41640. /**
  41641. * Parses a color grading texture serialized by Babylon.
  41642. * @param parsedTexture The texture information being parsedTexture
  41643. * @param scene The scene to load the texture in
  41644. * @param rootUrl The root url of the data assets to load
  41645. * @return A color gradind texture
  41646. */
  41647. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41648. var texture = null;
  41649. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41650. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41651. texture.name = parsedTexture.name;
  41652. texture.level = parsedTexture.level;
  41653. }
  41654. return texture;
  41655. };
  41656. /**
  41657. * Serializes the LUT texture to json format.
  41658. */
  41659. ColorGradingTexture.prototype.serialize = function () {
  41660. if (!this.name) {
  41661. return null;
  41662. }
  41663. var serializationObject = {};
  41664. serializationObject.name = this.name;
  41665. serializationObject.level = this.level;
  41666. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41667. return serializationObject;
  41668. };
  41669. /**
  41670. * Empty line regex stored for GC.
  41671. */
  41672. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41673. return ColorGradingTexture;
  41674. }(BABYLON.BaseTexture));
  41675. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41676. })(BABYLON || (BABYLON = {}));
  41677. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41678. var BABYLON;
  41679. (function (BABYLON) {
  41680. /**
  41681. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41682. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41683. * 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;
  41684. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41685. */
  41686. var ColorCurves = /** @class */ (function () {
  41687. function ColorCurves() {
  41688. this._dirty = true;
  41689. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41690. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41691. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41692. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41693. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41694. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41695. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41696. this._globalHue = 30;
  41697. this._globalDensity = 0;
  41698. this._globalSaturation = 0;
  41699. this._globalExposure = 0;
  41700. this._highlightsHue = 30;
  41701. this._highlightsDensity = 0;
  41702. this._highlightsSaturation = 0;
  41703. this._highlightsExposure = 0;
  41704. this._midtonesHue = 30;
  41705. this._midtonesDensity = 0;
  41706. this._midtonesSaturation = 0;
  41707. this._midtonesExposure = 0;
  41708. this._shadowsHue = 30;
  41709. this._shadowsDensity = 0;
  41710. this._shadowsSaturation = 0;
  41711. this._shadowsExposure = 0;
  41712. }
  41713. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41714. /**
  41715. * Gets the global Hue value.
  41716. * 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).
  41717. */
  41718. get: function () {
  41719. return this._globalHue;
  41720. },
  41721. /**
  41722. * Sets the global Hue value.
  41723. * 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).
  41724. */
  41725. set: function (value) {
  41726. this._globalHue = value;
  41727. this._dirty = true;
  41728. },
  41729. enumerable: true,
  41730. configurable: true
  41731. });
  41732. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41733. /**
  41734. * Gets the global Density value.
  41735. * 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.
  41736. * Values less than zero provide a filter of opposite hue.
  41737. */
  41738. get: function () {
  41739. return this._globalDensity;
  41740. },
  41741. /**
  41742. * Sets the global Density value.
  41743. * 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.
  41744. * Values less than zero provide a filter of opposite hue.
  41745. */
  41746. set: function (value) {
  41747. this._globalDensity = value;
  41748. this._dirty = true;
  41749. },
  41750. enumerable: true,
  41751. configurable: true
  41752. });
  41753. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41754. /**
  41755. * Gets the global Saturation value.
  41756. * 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.
  41757. */
  41758. get: function () {
  41759. return this._globalSaturation;
  41760. },
  41761. /**
  41762. * Sets the global Saturation value.
  41763. * 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.
  41764. */
  41765. set: function (value) {
  41766. this._globalSaturation = value;
  41767. this._dirty = true;
  41768. },
  41769. enumerable: true,
  41770. configurable: true
  41771. });
  41772. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  41773. /**
  41774. * Gets the global Exposure value.
  41775. * 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.
  41776. */
  41777. get: function () {
  41778. return this._globalExposure;
  41779. },
  41780. /**
  41781. * Sets the global Exposure value.
  41782. * 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.
  41783. */
  41784. set: function (value) {
  41785. this._globalExposure = value;
  41786. this._dirty = true;
  41787. },
  41788. enumerable: true,
  41789. configurable: true
  41790. });
  41791. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41792. /**
  41793. * Gets the highlights Hue value.
  41794. * 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).
  41795. */
  41796. get: function () {
  41797. return this._highlightsHue;
  41798. },
  41799. /**
  41800. * Sets the highlights Hue value.
  41801. * 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).
  41802. */
  41803. set: function (value) {
  41804. this._highlightsHue = value;
  41805. this._dirty = true;
  41806. },
  41807. enumerable: true,
  41808. configurable: true
  41809. });
  41810. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41811. /**
  41812. * Gets the highlights Density value.
  41813. * 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.
  41814. * Values less than zero provide a filter of opposite hue.
  41815. */
  41816. get: function () {
  41817. return this._highlightsDensity;
  41818. },
  41819. /**
  41820. * Sets the highlights Density value.
  41821. * 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.
  41822. * Values less than zero provide a filter of opposite hue.
  41823. */
  41824. set: function (value) {
  41825. this._highlightsDensity = value;
  41826. this._dirty = true;
  41827. },
  41828. enumerable: true,
  41829. configurable: true
  41830. });
  41831. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41832. /**
  41833. * Gets the highlights Saturation value.
  41834. * 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.
  41835. */
  41836. get: function () {
  41837. return this._highlightsSaturation;
  41838. },
  41839. /**
  41840. * Sets the highlights Saturation value.
  41841. * 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.
  41842. */
  41843. set: function (value) {
  41844. this._highlightsSaturation = value;
  41845. this._dirty = true;
  41846. },
  41847. enumerable: true,
  41848. configurable: true
  41849. });
  41850. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41851. /**
  41852. * Gets the highlights Exposure value.
  41853. * 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.
  41854. */
  41855. get: function () {
  41856. return this._highlightsExposure;
  41857. },
  41858. /**
  41859. * Sets the highlights Exposure value.
  41860. * 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.
  41861. */
  41862. set: function (value) {
  41863. this._highlightsExposure = value;
  41864. this._dirty = true;
  41865. },
  41866. enumerable: true,
  41867. configurable: true
  41868. });
  41869. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41870. /**
  41871. * Gets the midtones Hue value.
  41872. * 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).
  41873. */
  41874. get: function () {
  41875. return this._midtonesHue;
  41876. },
  41877. /**
  41878. * Sets the midtones Hue value.
  41879. * 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).
  41880. */
  41881. set: function (value) {
  41882. this._midtonesHue = value;
  41883. this._dirty = true;
  41884. },
  41885. enumerable: true,
  41886. configurable: true
  41887. });
  41888. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41889. /**
  41890. * Gets the midtones Density value.
  41891. * 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.
  41892. * Values less than zero provide a filter of opposite hue.
  41893. */
  41894. get: function () {
  41895. return this._midtonesDensity;
  41896. },
  41897. /**
  41898. * Sets the midtones Density value.
  41899. * 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.
  41900. * Values less than zero provide a filter of opposite hue.
  41901. */
  41902. set: function (value) {
  41903. this._midtonesDensity = value;
  41904. this._dirty = true;
  41905. },
  41906. enumerable: true,
  41907. configurable: true
  41908. });
  41909. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41910. /**
  41911. * Gets the midtones Saturation value.
  41912. * 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.
  41913. */
  41914. get: function () {
  41915. return this._midtonesSaturation;
  41916. },
  41917. /**
  41918. * Sets the midtones Saturation value.
  41919. * 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.
  41920. */
  41921. set: function (value) {
  41922. this._midtonesSaturation = value;
  41923. this._dirty = true;
  41924. },
  41925. enumerable: true,
  41926. configurable: true
  41927. });
  41928. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41929. /**
  41930. * Gets the midtones Exposure value.
  41931. * 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.
  41932. */
  41933. get: function () {
  41934. return this._midtonesExposure;
  41935. },
  41936. /**
  41937. * Sets the midtones Exposure value.
  41938. * 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.
  41939. */
  41940. set: function (value) {
  41941. this._midtonesExposure = value;
  41942. this._dirty = true;
  41943. },
  41944. enumerable: true,
  41945. configurable: true
  41946. });
  41947. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41948. /**
  41949. * Gets the shadows Hue value.
  41950. * 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).
  41951. */
  41952. get: function () {
  41953. return this._shadowsHue;
  41954. },
  41955. /**
  41956. * Sets the shadows Hue value.
  41957. * 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).
  41958. */
  41959. set: function (value) {
  41960. this._shadowsHue = value;
  41961. this._dirty = true;
  41962. },
  41963. enumerable: true,
  41964. configurable: true
  41965. });
  41966. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41967. /**
  41968. * Gets the shadows Density value.
  41969. * 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.
  41970. * Values less than zero provide a filter of opposite hue.
  41971. */
  41972. get: function () {
  41973. return this._shadowsDensity;
  41974. },
  41975. /**
  41976. * Sets the shadows Density value.
  41977. * 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.
  41978. * Values less than zero provide a filter of opposite hue.
  41979. */
  41980. set: function (value) {
  41981. this._shadowsDensity = value;
  41982. this._dirty = true;
  41983. },
  41984. enumerable: true,
  41985. configurable: true
  41986. });
  41987. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41988. /**
  41989. * Gets the shadows Saturation value.
  41990. * 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.
  41991. */
  41992. get: function () {
  41993. return this._shadowsSaturation;
  41994. },
  41995. /**
  41996. * Sets the shadows Saturation value.
  41997. * 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.
  41998. */
  41999. set: function (value) {
  42000. this._shadowsSaturation = value;
  42001. this._dirty = true;
  42002. },
  42003. enumerable: true,
  42004. configurable: true
  42005. });
  42006. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42007. /**
  42008. * Gets the shadows Exposure value.
  42009. * 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.
  42010. */
  42011. get: function () {
  42012. return this._shadowsExposure;
  42013. },
  42014. /**
  42015. * Sets the shadows Exposure value.
  42016. * 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.
  42017. */
  42018. set: function (value) {
  42019. this._shadowsExposure = value;
  42020. this._dirty = true;
  42021. },
  42022. enumerable: true,
  42023. configurable: true
  42024. });
  42025. ColorCurves.prototype.getClassName = function () {
  42026. return "ColorCurves";
  42027. };
  42028. /**
  42029. * Binds the color curves to the shader.
  42030. * @param colorCurves The color curve to bind
  42031. * @param effect The effect to bind to
  42032. */
  42033. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42034. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42035. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42036. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42037. if (colorCurves._dirty) {
  42038. colorCurves._dirty = false;
  42039. // Fill in global info.
  42040. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42041. // Compute highlights info.
  42042. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42043. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42044. // Compute midtones info.
  42045. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42046. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42047. // Compute shadows info.
  42048. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42049. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42050. // Compute deltas (neutral is midtones).
  42051. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42052. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42053. }
  42054. if (effect) {
  42055. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42056. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42057. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42058. }
  42059. };
  42060. /**
  42061. * Prepare the list of uniforms associated with the ColorCurves effects.
  42062. * @param uniformsList The list of uniforms used in the effect
  42063. */
  42064. ColorCurves.PrepareUniforms = function (uniformsList) {
  42065. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42066. };
  42067. /**
  42068. * Returns color grading data based on a hue, density, saturation and exposure value.
  42069. * @param filterHue The hue of the color filter.
  42070. * @param filterDensity The density of the color filter.
  42071. * @param saturation The saturation.
  42072. * @param exposure The exposure.
  42073. * @param result The result data container.
  42074. */
  42075. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42076. if (hue == null) {
  42077. return;
  42078. }
  42079. hue = ColorCurves.clamp(hue, 0, 360);
  42080. density = ColorCurves.clamp(density, -100, 100);
  42081. saturation = ColorCurves.clamp(saturation, -100, 100);
  42082. exposure = ColorCurves.clamp(exposure, -100, 100);
  42083. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42084. // so that the maximum filter density is only 50% control. This provides fine control
  42085. // for small values and reasonable range.
  42086. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42087. density *= 0.5;
  42088. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42089. if (density < 0) {
  42090. density *= -1;
  42091. hue = (hue + 180) % 360;
  42092. }
  42093. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42094. result.scaleToRef(2, result);
  42095. result.a = 1 + 0.01 * saturation;
  42096. };
  42097. /**
  42098. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42099. * @param value The input slider value in range [-100,100].
  42100. * @returns Adjusted value.
  42101. */
  42102. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42103. value /= 100;
  42104. var x = Math.abs(value);
  42105. x = Math.pow(x, 2);
  42106. if (value < 0) {
  42107. x *= -1;
  42108. }
  42109. x *= 100;
  42110. return x;
  42111. };
  42112. /**
  42113. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42114. * @param hue The hue (H) input.
  42115. * @param saturation The saturation (S) input.
  42116. * @param brightness The brightness (B) input.
  42117. * @result An RGBA color represented as Vector4.
  42118. */
  42119. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42120. var h = ColorCurves.clamp(hue, 0, 360);
  42121. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42122. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42123. if (s === 0) {
  42124. result.r = v;
  42125. result.g = v;
  42126. result.b = v;
  42127. }
  42128. else {
  42129. // sector 0 to 5
  42130. h /= 60;
  42131. var i = Math.floor(h);
  42132. // fractional part of h
  42133. var f = h - i;
  42134. var p = v * (1 - s);
  42135. var q = v * (1 - s * f);
  42136. var t = v * (1 - s * (1 - f));
  42137. switch (i) {
  42138. case 0:
  42139. result.r = v;
  42140. result.g = t;
  42141. result.b = p;
  42142. break;
  42143. case 1:
  42144. result.r = q;
  42145. result.g = v;
  42146. result.b = p;
  42147. break;
  42148. case 2:
  42149. result.r = p;
  42150. result.g = v;
  42151. result.b = t;
  42152. break;
  42153. case 3:
  42154. result.r = p;
  42155. result.g = q;
  42156. result.b = v;
  42157. break;
  42158. case 4:
  42159. result.r = t;
  42160. result.g = p;
  42161. result.b = v;
  42162. break;
  42163. default: // case 5:
  42164. result.r = v;
  42165. result.g = p;
  42166. result.b = q;
  42167. break;
  42168. }
  42169. }
  42170. result.a = 1;
  42171. };
  42172. /**
  42173. * Returns a value clamped between min and max
  42174. * @param value The value to clamp
  42175. * @param min The minimum of value
  42176. * @param max The maximum of value
  42177. * @returns The clamped value.
  42178. */
  42179. ColorCurves.clamp = function (value, min, max) {
  42180. return Math.min(Math.max(value, min), max);
  42181. };
  42182. /**
  42183. * Clones the current color curve instance.
  42184. * @return The cloned curves
  42185. */
  42186. ColorCurves.prototype.clone = function () {
  42187. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42188. };
  42189. /**
  42190. * Serializes the current color curve instance to a json representation.
  42191. * @return a JSON representation
  42192. */
  42193. ColorCurves.prototype.serialize = function () {
  42194. return BABYLON.SerializationHelper.Serialize(this);
  42195. };
  42196. /**
  42197. * Parses the color curve from a json representation.
  42198. * @param source the JSON source to parse
  42199. * @return The parsed curves
  42200. */
  42201. ColorCurves.Parse = function (source) {
  42202. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42203. };
  42204. __decorate([
  42205. BABYLON.serialize()
  42206. ], ColorCurves.prototype, "_globalHue", void 0);
  42207. __decorate([
  42208. BABYLON.serialize()
  42209. ], ColorCurves.prototype, "_globalDensity", void 0);
  42210. __decorate([
  42211. BABYLON.serialize()
  42212. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42213. __decorate([
  42214. BABYLON.serialize()
  42215. ], ColorCurves.prototype, "_globalExposure", void 0);
  42216. __decorate([
  42217. BABYLON.serialize()
  42218. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42219. __decorate([
  42220. BABYLON.serialize()
  42221. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42222. __decorate([
  42223. BABYLON.serialize()
  42224. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42225. __decorate([
  42226. BABYLON.serialize()
  42227. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42228. __decorate([
  42229. BABYLON.serialize()
  42230. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42231. __decorate([
  42232. BABYLON.serialize()
  42233. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42234. __decorate([
  42235. BABYLON.serialize()
  42236. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42237. __decorate([
  42238. BABYLON.serialize()
  42239. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42240. return ColorCurves;
  42241. }());
  42242. BABYLON.ColorCurves = ColorCurves;
  42243. })(BABYLON || (BABYLON = {}));
  42244. //# sourceMappingURL=babylon.colorCurves.js.map
  42245. //# sourceMappingURL=babylon.behavior.js.map
  42246. var BABYLON;
  42247. (function (BABYLON) {
  42248. /**
  42249. * "Static Class" containing the most commonly used helper while dealing with material for
  42250. * rendering purpose.
  42251. *
  42252. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42253. *
  42254. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42255. */
  42256. var MaterialHelper = /** @class */ (function () {
  42257. function MaterialHelper() {
  42258. }
  42259. /**
  42260. * Bind the current view position to an effect.
  42261. * @param effect The effect to be bound
  42262. * @param scene The scene the eyes position is used from
  42263. */
  42264. MaterialHelper.BindEyePosition = function (effect, scene) {
  42265. if (scene._forcedViewPosition) {
  42266. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42267. return;
  42268. }
  42269. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42270. };
  42271. /**
  42272. * Helps preparing the defines values about the UVs in used in the effect.
  42273. * UVs are shared as much as we can accross chanels in the shaders.
  42274. * @param texture The texture we are preparing the UVs for
  42275. * @param defines The defines to update
  42276. * @param key The chanel key "diffuse", "specular"... used in the shader
  42277. */
  42278. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42279. defines._needUVs = true;
  42280. defines[key] = true;
  42281. if (texture.getTextureMatrix().isIdentity(true)) {
  42282. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42283. if (texture.coordinatesIndex === 0) {
  42284. defines["MAINUV1"] = true;
  42285. }
  42286. else {
  42287. defines["MAINUV2"] = true;
  42288. }
  42289. }
  42290. else {
  42291. defines[key + "DIRECTUV"] = 0;
  42292. }
  42293. };
  42294. /**
  42295. * Binds a texture matrix value to its corrsponding uniform
  42296. * @param texture The texture to bind the matrix for
  42297. * @param uniformBuffer The uniform buffer receivin the data
  42298. * @param key The chanel key "diffuse", "specular"... used in the shader
  42299. */
  42300. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42301. var matrix = texture.getTextureMatrix();
  42302. if (!matrix.isIdentity(true)) {
  42303. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42304. }
  42305. };
  42306. /**
  42307. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42308. * @param mesh defines the current mesh
  42309. * @param scene defines the current scene
  42310. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42311. * @param pointsCloud defines if point cloud rendering has to be turned on
  42312. * @param fogEnabled defines if fog has to be turned on
  42313. * @param alphaTest defines if alpha testing has to be turned on
  42314. * @param defines defines the current list of defines
  42315. */
  42316. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42317. if (defines._areMiscDirty) {
  42318. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42319. defines["POINTSIZE"] = pointsCloud;
  42320. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42321. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42322. defines["ALPHATEST"] = alphaTest;
  42323. }
  42324. };
  42325. /**
  42326. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42327. * @param scene defines the current scene
  42328. * @param engine defines the current engine
  42329. * @param defines specifies the list of active defines
  42330. * @param useInstances defines if instances have to be turned on
  42331. * @param useClipPlane defines if clip plane have to be turned on
  42332. */
  42333. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42334. if (useClipPlane === void 0) { useClipPlane = null; }
  42335. var changed = false;
  42336. if (useClipPlane == null) {
  42337. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42338. }
  42339. if (defines["CLIPPLANE"] !== useClipPlane) {
  42340. defines["CLIPPLANE"] = useClipPlane;
  42341. changed = true;
  42342. }
  42343. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42344. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42345. changed = true;
  42346. }
  42347. if (defines["INSTANCES"] !== useInstances) {
  42348. defines["INSTANCES"] = useInstances;
  42349. changed = true;
  42350. }
  42351. if (changed) {
  42352. defines.markAsUnprocessed();
  42353. }
  42354. };
  42355. /**
  42356. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42357. * @param mesh The mesh containing the geometry data we will draw
  42358. * @param defines The defines to update
  42359. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42360. * @param useBones Precise whether bones should be used or not (override mesh info)
  42361. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42362. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42363. * @returns false if defines are considered not dirty and have not been checked
  42364. */
  42365. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42366. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42367. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42368. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42369. return false;
  42370. }
  42371. defines._normals = defines._needNormals;
  42372. defines._uvs = defines._needUVs;
  42373. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42374. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42375. defines["TANGENT"] = true;
  42376. }
  42377. if (defines._needUVs) {
  42378. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42379. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42380. }
  42381. else {
  42382. defines["UV1"] = false;
  42383. defines["UV2"] = false;
  42384. }
  42385. if (useVertexColor) {
  42386. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42387. defines["VERTEXCOLOR"] = hasVertexColors;
  42388. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42389. }
  42390. if (useBones) {
  42391. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42392. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42393. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42394. }
  42395. else {
  42396. defines["NUM_BONE_INFLUENCERS"] = 0;
  42397. defines["BonesPerMesh"] = 0;
  42398. }
  42399. }
  42400. if (useMorphTargets) {
  42401. var manager = mesh.morphTargetManager;
  42402. if (manager) {
  42403. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42404. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42405. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42406. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42407. }
  42408. else {
  42409. defines["MORPHTARGETS_TANGENT"] = false;
  42410. defines["MORPHTARGETS_NORMAL"] = false;
  42411. defines["MORPHTARGETS"] = false;
  42412. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42413. }
  42414. }
  42415. return true;
  42416. };
  42417. /**
  42418. * Prepares the defines related to the light information passed in parameter
  42419. * @param scene The scene we are intending to draw
  42420. * @param mesh The mesh the effect is compiling for
  42421. * @param defines The defines to update
  42422. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42423. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42424. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42425. * @returns true if normals will be required for the rest of the effect
  42426. */
  42427. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42428. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42429. if (disableLighting === void 0) { disableLighting = false; }
  42430. if (!defines._areLightsDirty) {
  42431. return defines._needNormals;
  42432. }
  42433. var lightIndex = 0;
  42434. var needNormals = false;
  42435. var needRebuild = false;
  42436. var lightmapMode = false;
  42437. var shadowEnabled = false;
  42438. var specularEnabled = false;
  42439. if (scene.lightsEnabled && !disableLighting) {
  42440. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42441. var light = _a[_i];
  42442. needNormals = true;
  42443. if (defines["LIGHT" + lightIndex] === undefined) {
  42444. needRebuild = true;
  42445. }
  42446. defines["LIGHT" + lightIndex] = true;
  42447. defines["SPOTLIGHT" + lightIndex] = false;
  42448. defines["HEMILIGHT" + lightIndex] = false;
  42449. defines["POINTLIGHT" + lightIndex] = false;
  42450. defines["DIRLIGHT" + lightIndex] = false;
  42451. var type;
  42452. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42453. type = "SPOTLIGHT" + lightIndex;
  42454. var spotLight = light;
  42455. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42456. }
  42457. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42458. type = "HEMILIGHT" + lightIndex;
  42459. }
  42460. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42461. type = "POINTLIGHT" + lightIndex;
  42462. }
  42463. else {
  42464. type = "DIRLIGHT" + lightIndex;
  42465. }
  42466. defines[type] = true;
  42467. // Specular
  42468. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42469. specularEnabled = true;
  42470. }
  42471. // Shadows
  42472. defines["SHADOW" + lightIndex] = false;
  42473. defines["SHADOWPCF" + lightIndex] = false;
  42474. defines["SHADOWPCSS" + lightIndex] = false;
  42475. defines["SHADOWPOISSON" + lightIndex] = false;
  42476. defines["SHADOWESM" + lightIndex] = false;
  42477. defines["SHADOWCUBE" + lightIndex] = false;
  42478. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42479. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42480. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42481. var shadowGenerator = light.getShadowGenerator();
  42482. if (shadowGenerator) {
  42483. shadowEnabled = true;
  42484. shadowGenerator.prepareDefines(defines, lightIndex);
  42485. }
  42486. }
  42487. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42488. lightmapMode = true;
  42489. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42490. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42491. }
  42492. else {
  42493. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42494. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42495. }
  42496. lightIndex++;
  42497. if (lightIndex === maxSimultaneousLights)
  42498. break;
  42499. }
  42500. }
  42501. defines["SPECULARTERM"] = specularEnabled;
  42502. defines["SHADOWS"] = shadowEnabled;
  42503. // Resetting all other lights if any
  42504. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42505. if (defines["LIGHT" + index] !== undefined) {
  42506. defines["LIGHT" + index] = false;
  42507. defines["HEMILIGHT" + lightIndex] = false;
  42508. defines["POINTLIGHT" + lightIndex] = false;
  42509. defines["DIRLIGHT" + lightIndex] = false;
  42510. defines["SPOTLIGHT" + lightIndex] = false;
  42511. defines["SHADOW" + lightIndex] = false;
  42512. }
  42513. }
  42514. var caps = scene.getEngine().getCaps();
  42515. if (defines["SHADOWFLOAT"] === undefined) {
  42516. needRebuild = true;
  42517. }
  42518. defines["SHADOWFLOAT"] = shadowEnabled &&
  42519. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42520. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42521. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42522. if (needRebuild) {
  42523. defines.rebuild();
  42524. }
  42525. return needNormals;
  42526. };
  42527. /**
  42528. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42529. * that won t be acctive due to defines being turned off.
  42530. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42531. * @param samplersList The samplers list
  42532. * @param defines The defines helping in the list generation
  42533. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42534. */
  42535. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42536. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42537. var uniformsList;
  42538. var uniformBuffersList = null;
  42539. if (uniformsListOrOptions.uniformsNames) {
  42540. var options = uniformsListOrOptions;
  42541. uniformsList = options.uniformsNames;
  42542. uniformBuffersList = options.uniformBuffersNames;
  42543. samplersList = options.samplers;
  42544. defines = options.defines;
  42545. maxSimultaneousLights = options.maxSimultaneousLights;
  42546. }
  42547. else {
  42548. uniformsList = uniformsListOrOptions;
  42549. if (!samplersList) {
  42550. samplersList = [];
  42551. }
  42552. }
  42553. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42554. if (!defines["LIGHT" + lightIndex]) {
  42555. break;
  42556. }
  42557. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42558. if (uniformBuffersList) {
  42559. uniformBuffersList.push("Light" + lightIndex);
  42560. }
  42561. samplersList.push("shadowSampler" + lightIndex);
  42562. samplersList.push("depthSampler" + lightIndex);
  42563. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42564. samplersList.push("projectionLightSampler" + lightIndex);
  42565. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42566. }
  42567. }
  42568. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42569. uniformsList.push("morphTargetInfluences");
  42570. }
  42571. };
  42572. /**
  42573. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42574. * @param defines The defines to update while falling back
  42575. * @param fallbacks The authorized effect fallbacks
  42576. * @param maxSimultaneousLights The maximum number of lights allowed
  42577. * @param rank the current rank of the Effect
  42578. * @returns The newly affected rank
  42579. */
  42580. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42581. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42582. if (rank === void 0) { rank = 0; }
  42583. var lightFallbackRank = 0;
  42584. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42585. if (!defines["LIGHT" + lightIndex]) {
  42586. break;
  42587. }
  42588. if (lightIndex > 0) {
  42589. lightFallbackRank = rank + lightIndex;
  42590. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42591. }
  42592. if (!defines["SHADOWS"]) {
  42593. if (defines["SHADOW" + lightIndex]) {
  42594. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42595. }
  42596. if (defines["SHADOWPCF" + lightIndex]) {
  42597. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42598. }
  42599. if (defines["SHADOWPCSS" + lightIndex]) {
  42600. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42601. }
  42602. if (defines["SHADOWPOISSON" + lightIndex]) {
  42603. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42604. }
  42605. if (defines["SHADOWESM" + lightIndex]) {
  42606. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42607. }
  42608. }
  42609. }
  42610. return lightFallbackRank++;
  42611. };
  42612. /**
  42613. * Prepares the list of attributes required for morph targets according to the effect defines.
  42614. * @param attribs The current list of supported attribs
  42615. * @param mesh The mesh to prepare the morph targets attributes for
  42616. * @param defines The current Defines of the effect
  42617. */
  42618. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42619. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42620. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42621. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42622. var manager = mesh.morphTargetManager;
  42623. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42624. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42625. for (var index = 0; index < influencers; index++) {
  42626. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42627. if (normal) {
  42628. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42629. }
  42630. if (tangent) {
  42631. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42632. }
  42633. if (attribs.length > maxAttributesCount) {
  42634. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42635. }
  42636. }
  42637. }
  42638. };
  42639. /**
  42640. * Prepares the list of attributes required for bones according to the effect defines.
  42641. * @param attribs The current list of supported attribs
  42642. * @param mesh The mesh to prepare the bones attributes for
  42643. * @param defines The current Defines of the effect
  42644. * @param fallbacks The current efffect fallback strategy
  42645. */
  42646. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42647. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42648. fallbacks.addCPUSkinningFallback(0, mesh);
  42649. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42650. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42651. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42652. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42653. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42654. }
  42655. }
  42656. };
  42657. /**
  42658. * Prepares the list of attributes required for instances according to the effect defines.
  42659. * @param attribs The current list of supported attribs
  42660. * @param defines The current Defines of the effect
  42661. */
  42662. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42663. if (defines["INSTANCES"]) {
  42664. attribs.push("world0");
  42665. attribs.push("world1");
  42666. attribs.push("world2");
  42667. attribs.push("world3");
  42668. }
  42669. };
  42670. /**
  42671. * Binds the light shadow information to the effect for the given mesh.
  42672. * @param light The light containing the generator
  42673. * @param scene The scene the lights belongs to
  42674. * @param mesh The mesh we are binding the information to render
  42675. * @param lightIndex The light index in the effect used to render the mesh
  42676. * @param effect The effect we are binding the data to
  42677. */
  42678. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42679. if (light.shadowEnabled && mesh.receiveShadows) {
  42680. var shadowGenerator = light.getShadowGenerator();
  42681. if (shadowGenerator) {
  42682. shadowGenerator.bindShadowLight(lightIndex, effect);
  42683. }
  42684. }
  42685. };
  42686. /**
  42687. * Binds the light information to the effect.
  42688. * @param light The light containing the generator
  42689. * @param effect The effect we are binding the data to
  42690. * @param lightIndex The light index in the effect used to render
  42691. */
  42692. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42693. light.transferToEffect(effect, lightIndex + "");
  42694. };
  42695. /**
  42696. * Binds the lights information from the scene to the effect for the given mesh.
  42697. * @param scene The scene the lights belongs to
  42698. * @param mesh The mesh we are binding the information to render
  42699. * @param effect The effect we are binding the data to
  42700. * @param defines The generated defines for the effect
  42701. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42702. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42703. */
  42704. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42705. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42706. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42707. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42708. for (var i = 0; i < len; i++) {
  42709. var light = mesh._lightSources[i];
  42710. var iAsString = i.toString();
  42711. var scaledIntensity = light.getScaledIntensity();
  42712. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42713. MaterialHelper.BindLightProperties(light, effect, i);
  42714. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42715. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42716. if (defines["SPECULARTERM"]) {
  42717. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42718. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42719. }
  42720. // Shadows
  42721. if (scene.shadowsEnabled) {
  42722. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42723. }
  42724. light._uniformBuffer.update();
  42725. }
  42726. };
  42727. /**
  42728. * Binds the fog information from the scene to the effect for the given mesh.
  42729. * @param scene The scene the lights belongs to
  42730. * @param mesh The mesh we are binding the information to render
  42731. * @param effect The effect we are binding the data to
  42732. */
  42733. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42734. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42735. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42736. effect.setColor3("vFogColor", scene.fogColor);
  42737. }
  42738. };
  42739. /**
  42740. * Binds the bones information from the mesh to the effect.
  42741. * @param mesh The mesh we are binding the information to render
  42742. * @param effect The effect we are binding the data to
  42743. */
  42744. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42745. if (!effect || !mesh) {
  42746. return;
  42747. }
  42748. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42749. mesh.computeBonesUsingShaders = false;
  42750. }
  42751. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42752. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42753. if (matrices) {
  42754. effect.setMatrices("mBones", matrices);
  42755. }
  42756. }
  42757. };
  42758. /**
  42759. * Binds the morph targets information from the mesh to the effect.
  42760. * @param abstractMesh The mesh we are binding the information to render
  42761. * @param effect The effect we are binding the data to
  42762. */
  42763. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42764. var manager = abstractMesh.morphTargetManager;
  42765. if (!abstractMesh || !manager) {
  42766. return;
  42767. }
  42768. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42769. };
  42770. /**
  42771. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42772. * @param defines The generated defines used in the effect
  42773. * @param effect The effect we are binding the data to
  42774. * @param scene The scene we are willing to render with logarithmic scale for
  42775. */
  42776. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42777. if (defines["LOGARITHMICDEPTH"]) {
  42778. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42779. }
  42780. };
  42781. /**
  42782. * Binds the clip plane information from the scene to the effect.
  42783. * @param scene The scene the clip plane information are extracted from
  42784. * @param effect The effect we are binding the data to
  42785. */
  42786. MaterialHelper.BindClipPlane = function (effect, scene) {
  42787. if (scene.clipPlane) {
  42788. var clipPlane = scene.clipPlane;
  42789. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42790. }
  42791. };
  42792. return MaterialHelper;
  42793. }());
  42794. BABYLON.MaterialHelper = MaterialHelper;
  42795. })(BABYLON || (BABYLON = {}));
  42796. //# sourceMappingURL=babylon.materialHelper.js.map
  42797. var BABYLON;
  42798. (function (BABYLON) {
  42799. var PushMaterial = /** @class */ (function (_super) {
  42800. __extends(PushMaterial, _super);
  42801. function PushMaterial(name, scene) {
  42802. var _this = _super.call(this, name, scene) || this;
  42803. _this._normalMatrix = new BABYLON.Matrix();
  42804. _this.storeEffectOnSubMeshes = true;
  42805. return _this;
  42806. }
  42807. PushMaterial.prototype.getEffect = function () {
  42808. return this._activeEffect;
  42809. };
  42810. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42811. if (!mesh) {
  42812. return false;
  42813. }
  42814. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42815. return true;
  42816. }
  42817. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42818. };
  42819. /**
  42820. * Binds the given world matrix to the active effect
  42821. *
  42822. * @param world the matrix to bind
  42823. */
  42824. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42825. this._activeEffect.setMatrix("world", world);
  42826. };
  42827. /**
  42828. * Binds the given normal matrix to the active effect
  42829. *
  42830. * @param normalMatrix the matrix to bind
  42831. */
  42832. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42833. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42834. };
  42835. PushMaterial.prototype.bind = function (world, mesh) {
  42836. if (!mesh) {
  42837. return;
  42838. }
  42839. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42840. };
  42841. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42842. if (effect === void 0) { effect = null; }
  42843. _super.prototype._afterBind.call(this, mesh);
  42844. this.getScene()._cachedEffect = effect;
  42845. };
  42846. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42847. if (visibility === void 0) { visibility = 1; }
  42848. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42849. };
  42850. return PushMaterial;
  42851. }(BABYLON.Material));
  42852. BABYLON.PushMaterial = PushMaterial;
  42853. })(BABYLON || (BABYLON = {}));
  42854. //# sourceMappingURL=babylon.pushMaterial.js.map
  42855. var BABYLON;
  42856. (function (BABYLON) {
  42857. /** @hidden */
  42858. var StandardMaterialDefines = /** @class */ (function (_super) {
  42859. __extends(StandardMaterialDefines, _super);
  42860. function StandardMaterialDefines() {
  42861. var _this = _super.call(this) || this;
  42862. _this.MAINUV1 = false;
  42863. _this.MAINUV2 = false;
  42864. _this.DIFFUSE = false;
  42865. _this.DIFFUSEDIRECTUV = 0;
  42866. _this.AMBIENT = false;
  42867. _this.AMBIENTDIRECTUV = 0;
  42868. _this.OPACITY = false;
  42869. _this.OPACITYDIRECTUV = 0;
  42870. _this.OPACITYRGB = false;
  42871. _this.REFLECTION = false;
  42872. _this.EMISSIVE = false;
  42873. _this.EMISSIVEDIRECTUV = 0;
  42874. _this.SPECULAR = false;
  42875. _this.SPECULARDIRECTUV = 0;
  42876. _this.BUMP = false;
  42877. _this.BUMPDIRECTUV = 0;
  42878. _this.PARALLAX = false;
  42879. _this.PARALLAXOCCLUSION = false;
  42880. _this.SPECULAROVERALPHA = false;
  42881. _this.CLIPPLANE = false;
  42882. _this.ALPHATEST = false;
  42883. _this.DEPTHPREPASS = false;
  42884. _this.ALPHAFROMDIFFUSE = false;
  42885. _this.POINTSIZE = false;
  42886. _this.FOG = false;
  42887. _this.SPECULARTERM = false;
  42888. _this.DIFFUSEFRESNEL = false;
  42889. _this.OPACITYFRESNEL = false;
  42890. _this.REFLECTIONFRESNEL = false;
  42891. _this.REFRACTIONFRESNEL = false;
  42892. _this.EMISSIVEFRESNEL = false;
  42893. _this.FRESNEL = false;
  42894. _this.NORMAL = false;
  42895. _this.UV1 = false;
  42896. _this.UV2 = false;
  42897. _this.VERTEXCOLOR = false;
  42898. _this.VERTEXALPHA = false;
  42899. _this.NUM_BONE_INFLUENCERS = 0;
  42900. _this.BonesPerMesh = 0;
  42901. _this.INSTANCES = false;
  42902. _this.GLOSSINESS = false;
  42903. _this.ROUGHNESS = false;
  42904. _this.EMISSIVEASILLUMINATION = false;
  42905. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42906. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42907. _this.LIGHTMAP = false;
  42908. _this.LIGHTMAPDIRECTUV = 0;
  42909. _this.OBJECTSPACE_NORMALMAP = false;
  42910. _this.USELIGHTMAPASSHADOWMAP = false;
  42911. _this.REFLECTIONMAP_3D = false;
  42912. _this.REFLECTIONMAP_SPHERICAL = false;
  42913. _this.REFLECTIONMAP_PLANAR = false;
  42914. _this.REFLECTIONMAP_CUBIC = false;
  42915. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42916. _this.REFLECTIONMAP_PROJECTION = false;
  42917. _this.REFLECTIONMAP_SKYBOX = false;
  42918. _this.REFLECTIONMAP_EXPLICIT = false;
  42919. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42920. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42921. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42922. _this.INVERTCUBICMAP = false;
  42923. _this.LOGARITHMICDEPTH = false;
  42924. _this.REFRACTION = false;
  42925. _this.REFRACTIONMAP_3D = false;
  42926. _this.REFLECTIONOVERALPHA = false;
  42927. _this.TWOSIDEDLIGHTING = false;
  42928. _this.SHADOWFLOAT = false;
  42929. _this.MORPHTARGETS = false;
  42930. _this.MORPHTARGETS_NORMAL = false;
  42931. _this.MORPHTARGETS_TANGENT = false;
  42932. _this.NUM_MORPH_INFLUENCERS = 0;
  42933. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42934. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42935. _this.IMAGEPROCESSING = false;
  42936. _this.VIGNETTE = false;
  42937. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42938. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42939. _this.TONEMAPPING = false;
  42940. _this.CONTRAST = false;
  42941. _this.COLORCURVES = false;
  42942. _this.COLORGRADING = false;
  42943. _this.COLORGRADING3D = false;
  42944. _this.SAMPLER3DGREENDEPTH = false;
  42945. _this.SAMPLER3DBGRMAP = false;
  42946. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42947. /**
  42948. * If the reflection texture on this material is in linear color space
  42949. * @hidden
  42950. */
  42951. _this.IS_REFLECTION_LINEAR = false;
  42952. /**
  42953. * If the refraction texture on this material is in linear color space
  42954. * @hidden
  42955. */
  42956. _this.IS_REFRACTION_LINEAR = false;
  42957. _this.EXPOSURE = false;
  42958. _this.rebuild();
  42959. return _this;
  42960. }
  42961. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42962. var modes = [
  42963. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42964. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42965. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42966. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42967. ];
  42968. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42969. var mode = modes_1[_i];
  42970. this[mode] = (mode === modeToEnable);
  42971. }
  42972. };
  42973. return StandardMaterialDefines;
  42974. }(BABYLON.MaterialDefines));
  42975. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42976. var StandardMaterial = /** @class */ (function (_super) {
  42977. __extends(StandardMaterial, _super);
  42978. function StandardMaterial(name, scene) {
  42979. var _this = _super.call(this, name, scene) || this;
  42980. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42981. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42982. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42983. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42984. _this.specularPower = 64;
  42985. _this._useAlphaFromDiffuseTexture = false;
  42986. _this._useEmissiveAsIllumination = false;
  42987. _this._linkEmissiveWithDiffuse = false;
  42988. _this._useSpecularOverAlpha = false;
  42989. _this._useReflectionOverAlpha = false;
  42990. _this._disableLighting = false;
  42991. _this._useObjectSpaceNormalMap = false;
  42992. _this._useParallax = false;
  42993. _this._useParallaxOcclusion = false;
  42994. _this.parallaxScaleBias = 0.05;
  42995. _this._roughness = 0;
  42996. _this.indexOfRefraction = 0.98;
  42997. _this.invertRefractionY = true;
  42998. /**
  42999. * Defines the alpha limits in alpha test mode
  43000. */
  43001. _this.alphaCutOff = 0.4;
  43002. _this._useLightmapAsShadowmap = false;
  43003. _this._useReflectionFresnelFromSpecular = false;
  43004. _this._useGlossinessFromSpecularMapAlpha = false;
  43005. _this._maxSimultaneousLights = 4;
  43006. /**
  43007. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43008. */
  43009. _this._invertNormalMapX = false;
  43010. /**
  43011. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43012. */
  43013. _this._invertNormalMapY = false;
  43014. /**
  43015. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43016. */
  43017. _this._twoSidedLighting = false;
  43018. _this._renderTargets = new BABYLON.SmartArray(16);
  43019. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43020. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43021. // Setup the default processing configuration to the scene.
  43022. _this._attachImageProcessingConfiguration(null);
  43023. _this.getRenderTargetTextures = function () {
  43024. _this._renderTargets.reset();
  43025. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43026. _this._renderTargets.push(_this._reflectionTexture);
  43027. }
  43028. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43029. _this._renderTargets.push(_this._refractionTexture);
  43030. }
  43031. return _this._renderTargets;
  43032. };
  43033. return _this;
  43034. }
  43035. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43036. /**
  43037. * Gets the image processing configuration used either in this material.
  43038. */
  43039. get: function () {
  43040. return this._imageProcessingConfiguration;
  43041. },
  43042. /**
  43043. * Sets the Default image processing configuration used either in the this material.
  43044. *
  43045. * If sets to null, the scene one is in use.
  43046. */
  43047. set: function (value) {
  43048. this._attachImageProcessingConfiguration(value);
  43049. // Ensure the effect will be rebuilt.
  43050. this._markAllSubMeshesAsTexturesDirty();
  43051. },
  43052. enumerable: true,
  43053. configurable: true
  43054. });
  43055. /**
  43056. * Attaches a new image processing configuration to the Standard Material.
  43057. * @param configuration
  43058. */
  43059. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43060. var _this = this;
  43061. if (configuration === this._imageProcessingConfiguration) {
  43062. return;
  43063. }
  43064. // Detaches observer.
  43065. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43066. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43067. }
  43068. // Pick the scene configuration if needed.
  43069. if (!configuration) {
  43070. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43071. }
  43072. else {
  43073. this._imageProcessingConfiguration = configuration;
  43074. }
  43075. // Attaches observer.
  43076. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43077. _this._markAllSubMeshesAsImageProcessingDirty();
  43078. });
  43079. };
  43080. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43081. /**
  43082. * Gets wether the color curves effect is enabled.
  43083. */
  43084. get: function () {
  43085. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43086. },
  43087. /**
  43088. * Sets wether the color curves effect is enabled.
  43089. */
  43090. set: function (value) {
  43091. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43092. },
  43093. enumerable: true,
  43094. configurable: true
  43095. });
  43096. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43097. /**
  43098. * Gets wether the color grading effect is enabled.
  43099. */
  43100. get: function () {
  43101. return this.imageProcessingConfiguration.colorGradingEnabled;
  43102. },
  43103. /**
  43104. * Gets wether the color grading effect is enabled.
  43105. */
  43106. set: function (value) {
  43107. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43108. },
  43109. enumerable: true,
  43110. configurable: true
  43111. });
  43112. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43113. /**
  43114. * Gets wether tonemapping is enabled or not.
  43115. */
  43116. get: function () {
  43117. return this._imageProcessingConfiguration.toneMappingEnabled;
  43118. },
  43119. /**
  43120. * Sets wether tonemapping is enabled or not
  43121. */
  43122. set: function (value) {
  43123. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43124. },
  43125. enumerable: true,
  43126. configurable: true
  43127. });
  43128. ;
  43129. ;
  43130. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43131. /**
  43132. * The camera exposure used on this material.
  43133. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43134. * This corresponds to a photographic exposure.
  43135. */
  43136. get: function () {
  43137. return this._imageProcessingConfiguration.exposure;
  43138. },
  43139. /**
  43140. * The camera exposure used on this material.
  43141. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43142. * This corresponds to a photographic exposure.
  43143. */
  43144. set: function (value) {
  43145. this._imageProcessingConfiguration.exposure = value;
  43146. },
  43147. enumerable: true,
  43148. configurable: true
  43149. });
  43150. ;
  43151. ;
  43152. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43153. /**
  43154. * Gets The camera contrast used on this material.
  43155. */
  43156. get: function () {
  43157. return this._imageProcessingConfiguration.contrast;
  43158. },
  43159. /**
  43160. * Sets The camera contrast used on this material.
  43161. */
  43162. set: function (value) {
  43163. this._imageProcessingConfiguration.contrast = value;
  43164. },
  43165. enumerable: true,
  43166. configurable: true
  43167. });
  43168. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43169. /**
  43170. * Gets the Color Grading 2D Lookup Texture.
  43171. */
  43172. get: function () {
  43173. return this._imageProcessingConfiguration.colorGradingTexture;
  43174. },
  43175. /**
  43176. * Sets the Color Grading 2D Lookup Texture.
  43177. */
  43178. set: function (value) {
  43179. this._imageProcessingConfiguration.colorGradingTexture = value;
  43180. },
  43181. enumerable: true,
  43182. configurable: true
  43183. });
  43184. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43185. /**
  43186. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43187. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43188. * 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;
  43189. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43190. */
  43191. get: function () {
  43192. return this._imageProcessingConfiguration.colorCurves;
  43193. },
  43194. /**
  43195. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43196. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43197. * 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;
  43198. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43199. */
  43200. set: function (value) {
  43201. this._imageProcessingConfiguration.colorCurves = value;
  43202. },
  43203. enumerable: true,
  43204. configurable: true
  43205. });
  43206. StandardMaterial.prototype.getClassName = function () {
  43207. return "StandardMaterial";
  43208. };
  43209. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43210. get: function () {
  43211. return this._useLogarithmicDepth;
  43212. },
  43213. set: function (value) {
  43214. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43215. this._markAllSubMeshesAsMiscDirty();
  43216. },
  43217. enumerable: true,
  43218. configurable: true
  43219. });
  43220. StandardMaterial.prototype.needAlphaBlending = function () {
  43221. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43222. };
  43223. StandardMaterial.prototype.needAlphaTesting = function () {
  43224. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43225. };
  43226. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43227. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43228. };
  43229. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43230. return this._diffuseTexture;
  43231. };
  43232. /**
  43233. * Child classes can use it to update shaders
  43234. */
  43235. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43236. if (useInstances === void 0) { useInstances = false; }
  43237. if (subMesh.effect && this.isFrozen) {
  43238. if (this._wasPreviouslyReady && subMesh.effect) {
  43239. return true;
  43240. }
  43241. }
  43242. if (!subMesh._materialDefines) {
  43243. subMesh._materialDefines = new StandardMaterialDefines();
  43244. }
  43245. var scene = this.getScene();
  43246. var defines = subMesh._materialDefines;
  43247. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43248. if (defines._renderId === scene.getRenderId()) {
  43249. return true;
  43250. }
  43251. }
  43252. var engine = scene.getEngine();
  43253. // Lights
  43254. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43255. // Textures
  43256. if (defines._areTexturesDirty) {
  43257. defines._needUVs = false;
  43258. defines.MAINUV1 = false;
  43259. defines.MAINUV2 = false;
  43260. if (scene.texturesEnabled) {
  43261. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43262. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43263. return false;
  43264. }
  43265. else {
  43266. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43267. }
  43268. }
  43269. else {
  43270. defines.DIFFUSE = false;
  43271. }
  43272. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43273. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43274. return false;
  43275. }
  43276. else {
  43277. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43278. }
  43279. }
  43280. else {
  43281. defines.AMBIENT = false;
  43282. }
  43283. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43284. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43285. return false;
  43286. }
  43287. else {
  43288. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43289. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43290. }
  43291. }
  43292. else {
  43293. defines.OPACITY = false;
  43294. }
  43295. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43296. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43297. return false;
  43298. }
  43299. else {
  43300. defines._needNormals = true;
  43301. defines.REFLECTION = true;
  43302. defines.ROUGHNESS = (this._roughness > 0);
  43303. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43304. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43305. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43306. switch (this._reflectionTexture.coordinatesMode) {
  43307. case BABYLON.Texture.EXPLICIT_MODE:
  43308. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43309. break;
  43310. case BABYLON.Texture.PLANAR_MODE:
  43311. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43312. break;
  43313. case BABYLON.Texture.PROJECTION_MODE:
  43314. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43315. break;
  43316. case BABYLON.Texture.SKYBOX_MODE:
  43317. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43318. break;
  43319. case BABYLON.Texture.SPHERICAL_MODE:
  43320. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43321. break;
  43322. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43323. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43324. break;
  43325. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43326. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43327. break;
  43328. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43329. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43330. break;
  43331. case BABYLON.Texture.CUBIC_MODE:
  43332. case BABYLON.Texture.INVCUBIC_MODE:
  43333. default:
  43334. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43335. break;
  43336. }
  43337. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43338. }
  43339. }
  43340. else {
  43341. defines.REFLECTION = false;
  43342. }
  43343. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43344. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43345. return false;
  43346. }
  43347. else {
  43348. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43349. }
  43350. }
  43351. else {
  43352. defines.EMISSIVE = false;
  43353. }
  43354. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43355. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43356. return false;
  43357. }
  43358. else {
  43359. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43360. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43361. }
  43362. }
  43363. else {
  43364. defines.LIGHTMAP = false;
  43365. }
  43366. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43367. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43368. return false;
  43369. }
  43370. else {
  43371. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43372. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43373. }
  43374. }
  43375. else {
  43376. defines.SPECULAR = false;
  43377. }
  43378. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43379. // Bump texure can not be not blocking.
  43380. if (!this._bumpTexture.isReady()) {
  43381. return false;
  43382. }
  43383. else {
  43384. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43385. defines.PARALLAX = this._useParallax;
  43386. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43387. }
  43388. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43389. }
  43390. else {
  43391. defines.BUMP = false;
  43392. }
  43393. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43394. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43395. return false;
  43396. }
  43397. else {
  43398. defines._needUVs = true;
  43399. defines.REFRACTION = true;
  43400. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43401. }
  43402. }
  43403. else {
  43404. defines.REFRACTION = false;
  43405. }
  43406. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43407. }
  43408. else {
  43409. defines.DIFFUSE = false;
  43410. defines.AMBIENT = false;
  43411. defines.OPACITY = false;
  43412. defines.REFLECTION = false;
  43413. defines.EMISSIVE = false;
  43414. defines.LIGHTMAP = false;
  43415. defines.BUMP = false;
  43416. defines.REFRACTION = false;
  43417. }
  43418. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43419. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43420. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43421. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43422. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43423. }
  43424. if (defines._areImageProcessingDirty) {
  43425. if (!this._imageProcessingConfiguration.isReady()) {
  43426. return false;
  43427. }
  43428. this._imageProcessingConfiguration.prepareDefines(defines);
  43429. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43430. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43431. }
  43432. if (defines._areFresnelDirty) {
  43433. if (StandardMaterial.FresnelEnabled) {
  43434. // Fresnel
  43435. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43436. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43437. this._reflectionFresnelParameters) {
  43438. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43439. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43440. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43441. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43442. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43443. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43444. defines._needNormals = true;
  43445. defines.FRESNEL = true;
  43446. }
  43447. }
  43448. else {
  43449. defines.FRESNEL = false;
  43450. }
  43451. }
  43452. // Misc.
  43453. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43454. // Attribs
  43455. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43456. // Values that need to be evaluated on every frame
  43457. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43458. // Get correct effect
  43459. if (defines.isDirty) {
  43460. defines.markAsProcessed();
  43461. scene.resetCachedMaterial();
  43462. // Fallbacks
  43463. var fallbacks = new BABYLON.EffectFallbacks();
  43464. if (defines.REFLECTION) {
  43465. fallbacks.addFallback(0, "REFLECTION");
  43466. }
  43467. if (defines.SPECULAR) {
  43468. fallbacks.addFallback(0, "SPECULAR");
  43469. }
  43470. if (defines.BUMP) {
  43471. fallbacks.addFallback(0, "BUMP");
  43472. }
  43473. if (defines.PARALLAX) {
  43474. fallbacks.addFallback(1, "PARALLAX");
  43475. }
  43476. if (defines.PARALLAXOCCLUSION) {
  43477. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43478. }
  43479. if (defines.SPECULAROVERALPHA) {
  43480. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43481. }
  43482. if (defines.FOG) {
  43483. fallbacks.addFallback(1, "FOG");
  43484. }
  43485. if (defines.POINTSIZE) {
  43486. fallbacks.addFallback(0, "POINTSIZE");
  43487. }
  43488. if (defines.LOGARITHMICDEPTH) {
  43489. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43490. }
  43491. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43492. if (defines.SPECULARTERM) {
  43493. fallbacks.addFallback(0, "SPECULARTERM");
  43494. }
  43495. if (defines.DIFFUSEFRESNEL) {
  43496. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43497. }
  43498. if (defines.OPACITYFRESNEL) {
  43499. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43500. }
  43501. if (defines.REFLECTIONFRESNEL) {
  43502. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43503. }
  43504. if (defines.EMISSIVEFRESNEL) {
  43505. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43506. }
  43507. if (defines.FRESNEL) {
  43508. fallbacks.addFallback(4, "FRESNEL");
  43509. }
  43510. //Attributes
  43511. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43512. if (defines.NORMAL) {
  43513. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43514. }
  43515. if (defines.UV1) {
  43516. attribs.push(BABYLON.VertexBuffer.UVKind);
  43517. }
  43518. if (defines.UV2) {
  43519. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43520. }
  43521. if (defines.VERTEXCOLOR) {
  43522. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43523. }
  43524. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43525. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43526. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43527. var shaderName = "default";
  43528. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43529. "vFogInfos", "vFogColor", "pointSize",
  43530. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43531. "mBones",
  43532. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43533. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43534. "vReflectionPosition", "vReflectionSize",
  43535. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43536. ];
  43537. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43538. var uniformBuffers = ["Material", "Scene"];
  43539. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43540. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43541. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43542. uniformsNames: uniforms,
  43543. uniformBuffersNames: uniformBuffers,
  43544. samplers: samplers,
  43545. defines: defines,
  43546. maxSimultaneousLights: this._maxSimultaneousLights
  43547. });
  43548. if (this.customShaderNameResolve) {
  43549. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43550. }
  43551. var join = defines.toString();
  43552. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43553. attributes: attribs,
  43554. uniformsNames: uniforms,
  43555. uniformBuffersNames: uniformBuffers,
  43556. samplers: samplers,
  43557. defines: join,
  43558. fallbacks: fallbacks,
  43559. onCompiled: this.onCompiled,
  43560. onError: this.onError,
  43561. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43562. }, engine), defines);
  43563. this.buildUniformLayout();
  43564. }
  43565. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43566. return false;
  43567. }
  43568. defines._renderId = scene.getRenderId();
  43569. this._wasPreviouslyReady = true;
  43570. return true;
  43571. };
  43572. StandardMaterial.prototype.buildUniformLayout = function () {
  43573. // Order is important !
  43574. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43575. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43576. this._uniformBuffer.addUniform("opacityParts", 4);
  43577. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43578. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43579. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43580. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43581. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43582. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43583. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43584. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43585. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43586. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43587. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43588. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43589. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43590. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43591. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43592. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43593. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43594. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43595. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43596. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43597. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43598. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43599. this._uniformBuffer.addUniform("specularMatrix", 16);
  43600. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43601. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43602. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43603. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43604. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43605. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43606. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43607. this._uniformBuffer.addUniform("pointSize", 1);
  43608. this._uniformBuffer.create();
  43609. };
  43610. StandardMaterial.prototype.unbind = function () {
  43611. if (this._activeEffect) {
  43612. var needFlag = false;
  43613. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43614. this._activeEffect.setTexture("reflection2DSampler", null);
  43615. needFlag = true;
  43616. }
  43617. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43618. this._activeEffect.setTexture("refraction2DSampler", null);
  43619. needFlag = true;
  43620. }
  43621. if (needFlag) {
  43622. this._markAllSubMeshesAsTexturesDirty();
  43623. }
  43624. }
  43625. _super.prototype.unbind.call(this);
  43626. };
  43627. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43628. var scene = this.getScene();
  43629. var defines = subMesh._materialDefines;
  43630. if (!defines) {
  43631. return;
  43632. }
  43633. var effect = subMesh.effect;
  43634. if (!effect) {
  43635. return;
  43636. }
  43637. this._activeEffect = effect;
  43638. // Matrices
  43639. this.bindOnlyWorldMatrix(world);
  43640. // Normal Matrix
  43641. if (defines.OBJECTSPACE_NORMALMAP) {
  43642. world.toNormalMatrix(this._normalMatrix);
  43643. this.bindOnlyNormalMatrix(this._normalMatrix);
  43644. }
  43645. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43646. // Bones
  43647. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43648. if (mustRebind) {
  43649. this._uniformBuffer.bindToEffect(effect, "Material");
  43650. this.bindViewProjection(effect);
  43651. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43652. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43653. // Fresnel
  43654. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43655. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43656. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43657. }
  43658. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43659. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43660. }
  43661. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43662. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43663. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43664. }
  43665. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43666. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43667. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43668. }
  43669. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43670. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43671. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43672. }
  43673. }
  43674. // Textures
  43675. if (scene.texturesEnabled) {
  43676. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43677. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43678. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43679. if (this._diffuseTexture.hasAlpha) {
  43680. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43681. }
  43682. }
  43683. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43684. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43685. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43686. }
  43687. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43688. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43689. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43690. }
  43691. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43692. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43693. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43694. if (this._reflectionTexture.boundingBoxSize) {
  43695. var cubeTexture = this._reflectionTexture;
  43696. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43697. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43698. }
  43699. }
  43700. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43701. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43702. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43703. }
  43704. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43705. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43706. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43707. }
  43708. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43709. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43710. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43711. }
  43712. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43713. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43714. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43715. if (scene._mirroredCameraPosition) {
  43716. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43717. }
  43718. else {
  43719. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43720. }
  43721. }
  43722. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43723. var depth = 1.0;
  43724. if (!this._refractionTexture.isCube) {
  43725. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43726. if (this._refractionTexture.depth) {
  43727. depth = this._refractionTexture.depth;
  43728. }
  43729. }
  43730. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43731. }
  43732. }
  43733. // Point size
  43734. if (this.pointsCloud) {
  43735. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43736. }
  43737. if (defines.SPECULARTERM) {
  43738. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43739. }
  43740. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43741. // Diffuse
  43742. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43743. }
  43744. // Textures
  43745. if (scene.texturesEnabled) {
  43746. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43747. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43748. }
  43749. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43750. effect.setTexture("ambientSampler", this._ambientTexture);
  43751. }
  43752. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43753. effect.setTexture("opacitySampler", this._opacityTexture);
  43754. }
  43755. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43756. if (this._reflectionTexture.isCube) {
  43757. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43758. }
  43759. else {
  43760. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43761. }
  43762. }
  43763. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43764. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43765. }
  43766. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43767. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43768. }
  43769. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43770. effect.setTexture("specularSampler", this._specularTexture);
  43771. }
  43772. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43773. effect.setTexture("bumpSampler", this._bumpTexture);
  43774. }
  43775. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43776. var depth = 1.0;
  43777. if (this._refractionTexture.isCube) {
  43778. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43779. }
  43780. else {
  43781. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43782. }
  43783. }
  43784. }
  43785. // Clip plane
  43786. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43787. // Colors
  43788. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43789. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43790. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43791. }
  43792. if (mustRebind || !this.isFrozen) {
  43793. // Lights
  43794. if (scene.lightsEnabled && !this._disableLighting) {
  43795. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43796. }
  43797. // View
  43798. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43799. this.bindView(effect);
  43800. }
  43801. // Fog
  43802. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43803. // Morph targets
  43804. if (defines.NUM_MORPH_INFLUENCERS) {
  43805. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43806. }
  43807. // Log. depth
  43808. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43809. // image processing
  43810. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43811. this._imageProcessingConfiguration.bind(this._activeEffect);
  43812. }
  43813. }
  43814. this._uniformBuffer.update();
  43815. this._afterBind(mesh, this._activeEffect);
  43816. };
  43817. StandardMaterial.prototype.getAnimatables = function () {
  43818. var results = [];
  43819. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43820. results.push(this._diffuseTexture);
  43821. }
  43822. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43823. results.push(this._ambientTexture);
  43824. }
  43825. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43826. results.push(this._opacityTexture);
  43827. }
  43828. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43829. results.push(this._reflectionTexture);
  43830. }
  43831. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43832. results.push(this._emissiveTexture);
  43833. }
  43834. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43835. results.push(this._specularTexture);
  43836. }
  43837. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43838. results.push(this._bumpTexture);
  43839. }
  43840. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43841. results.push(this._lightmapTexture);
  43842. }
  43843. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43844. results.push(this._refractionTexture);
  43845. }
  43846. return results;
  43847. };
  43848. StandardMaterial.prototype.getActiveTextures = function () {
  43849. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43850. if (this._diffuseTexture) {
  43851. activeTextures.push(this._diffuseTexture);
  43852. }
  43853. if (this._ambientTexture) {
  43854. activeTextures.push(this._ambientTexture);
  43855. }
  43856. if (this._opacityTexture) {
  43857. activeTextures.push(this._opacityTexture);
  43858. }
  43859. if (this._reflectionTexture) {
  43860. activeTextures.push(this._reflectionTexture);
  43861. }
  43862. if (this._emissiveTexture) {
  43863. activeTextures.push(this._emissiveTexture);
  43864. }
  43865. if (this._specularTexture) {
  43866. activeTextures.push(this._specularTexture);
  43867. }
  43868. if (this._bumpTexture) {
  43869. activeTextures.push(this._bumpTexture);
  43870. }
  43871. if (this._lightmapTexture) {
  43872. activeTextures.push(this._lightmapTexture);
  43873. }
  43874. if (this._refractionTexture) {
  43875. activeTextures.push(this._refractionTexture);
  43876. }
  43877. return activeTextures;
  43878. };
  43879. StandardMaterial.prototype.hasTexture = function (texture) {
  43880. if (_super.prototype.hasTexture.call(this, texture)) {
  43881. return true;
  43882. }
  43883. if (this._diffuseTexture === texture) {
  43884. return true;
  43885. }
  43886. if (this._ambientTexture === texture) {
  43887. return true;
  43888. }
  43889. if (this._opacityTexture === texture) {
  43890. return true;
  43891. }
  43892. if (this._reflectionTexture === texture) {
  43893. return true;
  43894. }
  43895. if (this._emissiveTexture === texture) {
  43896. return true;
  43897. }
  43898. if (this._specularTexture === texture) {
  43899. return true;
  43900. }
  43901. if (this._bumpTexture === texture) {
  43902. return true;
  43903. }
  43904. if (this._lightmapTexture === texture) {
  43905. return true;
  43906. }
  43907. if (this._refractionTexture === texture) {
  43908. return true;
  43909. }
  43910. return false;
  43911. };
  43912. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43913. if (forceDisposeTextures) {
  43914. if (this._diffuseTexture) {
  43915. this._diffuseTexture.dispose();
  43916. }
  43917. if (this._ambientTexture) {
  43918. this._ambientTexture.dispose();
  43919. }
  43920. if (this._opacityTexture) {
  43921. this._opacityTexture.dispose();
  43922. }
  43923. if (this._reflectionTexture) {
  43924. this._reflectionTexture.dispose();
  43925. }
  43926. if (this._emissiveTexture) {
  43927. this._emissiveTexture.dispose();
  43928. }
  43929. if (this._specularTexture) {
  43930. this._specularTexture.dispose();
  43931. }
  43932. if (this._bumpTexture) {
  43933. this._bumpTexture.dispose();
  43934. }
  43935. if (this._lightmapTexture) {
  43936. this._lightmapTexture.dispose();
  43937. }
  43938. if (this._refractionTexture) {
  43939. this._refractionTexture.dispose();
  43940. }
  43941. }
  43942. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43943. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43944. }
  43945. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43946. };
  43947. StandardMaterial.prototype.clone = function (name) {
  43948. var _this = this;
  43949. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43950. result.name = name;
  43951. result.id = name;
  43952. return result;
  43953. };
  43954. StandardMaterial.prototype.serialize = function () {
  43955. return BABYLON.SerializationHelper.Serialize(this);
  43956. };
  43957. // Statics
  43958. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43959. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43960. };
  43961. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43962. get: function () {
  43963. return StandardMaterial._DiffuseTextureEnabled;
  43964. },
  43965. set: function (value) {
  43966. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43967. return;
  43968. }
  43969. StandardMaterial._DiffuseTextureEnabled = value;
  43970. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43971. },
  43972. enumerable: true,
  43973. configurable: true
  43974. });
  43975. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43976. get: function () {
  43977. return StandardMaterial._AmbientTextureEnabled;
  43978. },
  43979. set: function (value) {
  43980. if (StandardMaterial._AmbientTextureEnabled === value) {
  43981. return;
  43982. }
  43983. StandardMaterial._AmbientTextureEnabled = value;
  43984. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43985. },
  43986. enumerable: true,
  43987. configurable: true
  43988. });
  43989. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43990. get: function () {
  43991. return StandardMaterial._OpacityTextureEnabled;
  43992. },
  43993. set: function (value) {
  43994. if (StandardMaterial._OpacityTextureEnabled === value) {
  43995. return;
  43996. }
  43997. StandardMaterial._OpacityTextureEnabled = value;
  43998. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43999. },
  44000. enumerable: true,
  44001. configurable: true
  44002. });
  44003. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44004. get: function () {
  44005. return StandardMaterial._ReflectionTextureEnabled;
  44006. },
  44007. set: function (value) {
  44008. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44009. return;
  44010. }
  44011. StandardMaterial._ReflectionTextureEnabled = value;
  44012. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44013. },
  44014. enumerable: true,
  44015. configurable: true
  44016. });
  44017. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44018. get: function () {
  44019. return StandardMaterial._EmissiveTextureEnabled;
  44020. },
  44021. set: function (value) {
  44022. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44023. return;
  44024. }
  44025. StandardMaterial._EmissiveTextureEnabled = value;
  44026. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44027. },
  44028. enumerable: true,
  44029. configurable: true
  44030. });
  44031. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44032. get: function () {
  44033. return StandardMaterial._SpecularTextureEnabled;
  44034. },
  44035. set: function (value) {
  44036. if (StandardMaterial._SpecularTextureEnabled === value) {
  44037. return;
  44038. }
  44039. StandardMaterial._SpecularTextureEnabled = value;
  44040. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44041. },
  44042. enumerable: true,
  44043. configurable: true
  44044. });
  44045. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44046. get: function () {
  44047. return StandardMaterial._BumpTextureEnabled;
  44048. },
  44049. set: function (value) {
  44050. if (StandardMaterial._BumpTextureEnabled === value) {
  44051. return;
  44052. }
  44053. StandardMaterial._BumpTextureEnabled = value;
  44054. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44055. },
  44056. enumerable: true,
  44057. configurable: true
  44058. });
  44059. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44060. get: function () {
  44061. return StandardMaterial._LightmapTextureEnabled;
  44062. },
  44063. set: function (value) {
  44064. if (StandardMaterial._LightmapTextureEnabled === value) {
  44065. return;
  44066. }
  44067. StandardMaterial._LightmapTextureEnabled = value;
  44068. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44069. },
  44070. enumerable: true,
  44071. configurable: true
  44072. });
  44073. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44074. get: function () {
  44075. return StandardMaterial._RefractionTextureEnabled;
  44076. },
  44077. set: function (value) {
  44078. if (StandardMaterial._RefractionTextureEnabled === value) {
  44079. return;
  44080. }
  44081. StandardMaterial._RefractionTextureEnabled = value;
  44082. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44083. },
  44084. enumerable: true,
  44085. configurable: true
  44086. });
  44087. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44088. get: function () {
  44089. return StandardMaterial._ColorGradingTextureEnabled;
  44090. },
  44091. set: function (value) {
  44092. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44093. return;
  44094. }
  44095. StandardMaterial._ColorGradingTextureEnabled = value;
  44096. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44097. },
  44098. enumerable: true,
  44099. configurable: true
  44100. });
  44101. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44102. get: function () {
  44103. return StandardMaterial._FresnelEnabled;
  44104. },
  44105. set: function (value) {
  44106. if (StandardMaterial._FresnelEnabled === value) {
  44107. return;
  44108. }
  44109. StandardMaterial._FresnelEnabled = value;
  44110. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44111. },
  44112. enumerable: true,
  44113. configurable: true
  44114. });
  44115. // Flags used to enable or disable a type of texture for all Standard Materials
  44116. StandardMaterial._DiffuseTextureEnabled = true;
  44117. StandardMaterial._AmbientTextureEnabled = true;
  44118. StandardMaterial._OpacityTextureEnabled = true;
  44119. StandardMaterial._ReflectionTextureEnabled = true;
  44120. StandardMaterial._EmissiveTextureEnabled = true;
  44121. StandardMaterial._SpecularTextureEnabled = true;
  44122. StandardMaterial._BumpTextureEnabled = true;
  44123. StandardMaterial._LightmapTextureEnabled = true;
  44124. StandardMaterial._RefractionTextureEnabled = true;
  44125. StandardMaterial._ColorGradingTextureEnabled = true;
  44126. StandardMaterial._FresnelEnabled = true;
  44127. __decorate([
  44128. BABYLON.serializeAsTexture("diffuseTexture")
  44129. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44130. __decorate([
  44131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44132. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44133. __decorate([
  44134. BABYLON.serializeAsTexture("ambientTexture")
  44135. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44136. __decorate([
  44137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44138. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44139. __decorate([
  44140. BABYLON.serializeAsTexture("opacityTexture")
  44141. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44142. __decorate([
  44143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44144. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44145. __decorate([
  44146. BABYLON.serializeAsTexture("reflectionTexture")
  44147. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44148. __decorate([
  44149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44150. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44151. __decorate([
  44152. BABYLON.serializeAsTexture("emissiveTexture")
  44153. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44154. __decorate([
  44155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44156. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44157. __decorate([
  44158. BABYLON.serializeAsTexture("specularTexture")
  44159. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44160. __decorate([
  44161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44162. ], StandardMaterial.prototype, "specularTexture", void 0);
  44163. __decorate([
  44164. BABYLON.serializeAsTexture("bumpTexture")
  44165. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44166. __decorate([
  44167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44168. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44169. __decorate([
  44170. BABYLON.serializeAsTexture("lightmapTexture")
  44171. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44172. __decorate([
  44173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44174. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44175. __decorate([
  44176. BABYLON.serializeAsTexture("refractionTexture")
  44177. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44178. __decorate([
  44179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44180. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44181. __decorate([
  44182. BABYLON.serializeAsColor3("ambient")
  44183. ], StandardMaterial.prototype, "ambientColor", void 0);
  44184. __decorate([
  44185. BABYLON.serializeAsColor3("diffuse")
  44186. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44187. __decorate([
  44188. BABYLON.serializeAsColor3("specular")
  44189. ], StandardMaterial.prototype, "specularColor", void 0);
  44190. __decorate([
  44191. BABYLON.serializeAsColor3("emissive")
  44192. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44193. __decorate([
  44194. BABYLON.serialize()
  44195. ], StandardMaterial.prototype, "specularPower", void 0);
  44196. __decorate([
  44197. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44198. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44199. __decorate([
  44200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44201. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44202. __decorate([
  44203. BABYLON.serialize("useEmissiveAsIllumination")
  44204. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44205. __decorate([
  44206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44207. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44208. __decorate([
  44209. BABYLON.serialize("linkEmissiveWithDiffuse")
  44210. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44211. __decorate([
  44212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44213. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44214. __decorate([
  44215. BABYLON.serialize("useSpecularOverAlpha")
  44216. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44217. __decorate([
  44218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44219. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44220. __decorate([
  44221. BABYLON.serialize("useReflectionOverAlpha")
  44222. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44223. __decorate([
  44224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44225. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44226. __decorate([
  44227. BABYLON.serialize("disableLighting")
  44228. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44229. __decorate([
  44230. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44231. ], StandardMaterial.prototype, "disableLighting", void 0);
  44232. __decorate([
  44233. BABYLON.serialize("useObjectSpaceNormalMap")
  44234. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44235. __decorate([
  44236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44237. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44238. __decorate([
  44239. BABYLON.serialize("useParallax")
  44240. ], StandardMaterial.prototype, "_useParallax", void 0);
  44241. __decorate([
  44242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44243. ], StandardMaterial.prototype, "useParallax", void 0);
  44244. __decorate([
  44245. BABYLON.serialize("useParallaxOcclusion")
  44246. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44247. __decorate([
  44248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44249. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44250. __decorate([
  44251. BABYLON.serialize()
  44252. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44253. __decorate([
  44254. BABYLON.serialize("roughness")
  44255. ], StandardMaterial.prototype, "_roughness", void 0);
  44256. __decorate([
  44257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44258. ], StandardMaterial.prototype, "roughness", void 0);
  44259. __decorate([
  44260. BABYLON.serialize()
  44261. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44262. __decorate([
  44263. BABYLON.serialize()
  44264. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44265. __decorate([
  44266. BABYLON.serialize()
  44267. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44268. __decorate([
  44269. BABYLON.serialize("useLightmapAsShadowmap")
  44270. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44271. __decorate([
  44272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44273. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44274. __decorate([
  44275. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44276. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44277. __decorate([
  44278. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44279. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44280. __decorate([
  44281. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44282. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44283. __decorate([
  44284. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44285. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44286. __decorate([
  44287. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44288. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44289. __decorate([
  44290. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44291. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44292. __decorate([
  44293. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44294. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44295. __decorate([
  44296. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44297. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44298. __decorate([
  44299. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44300. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44301. __decorate([
  44302. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44303. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44304. __decorate([
  44305. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44306. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44307. __decorate([
  44308. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44309. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44310. __decorate([
  44311. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44312. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44313. __decorate([
  44314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44315. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44316. __decorate([
  44317. BABYLON.serialize("maxSimultaneousLights")
  44318. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44319. __decorate([
  44320. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44321. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44322. __decorate([
  44323. BABYLON.serialize("invertNormalMapX")
  44324. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44325. __decorate([
  44326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44327. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44328. __decorate([
  44329. BABYLON.serialize("invertNormalMapY")
  44330. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44331. __decorate([
  44332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44333. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44334. __decorate([
  44335. BABYLON.serialize("twoSidedLighting")
  44336. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44337. __decorate([
  44338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44339. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44340. __decorate([
  44341. BABYLON.serialize()
  44342. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44343. return StandardMaterial;
  44344. }(BABYLON.PushMaterial));
  44345. BABYLON.StandardMaterial = StandardMaterial;
  44346. })(BABYLON || (BABYLON = {}));
  44347. //# sourceMappingURL=babylon.standardMaterial.js.map
  44348. var BABYLON;
  44349. (function (BABYLON) {
  44350. /**
  44351. * Manages the defines for the PBR Material.
  44352. * @hiddenChildren
  44353. */
  44354. var PBRMaterialDefines = /** @class */ (function (_super) {
  44355. __extends(PBRMaterialDefines, _super);
  44356. /**
  44357. * Initializes the PBR Material defines.
  44358. */
  44359. function PBRMaterialDefines() {
  44360. var _this = _super.call(this) || this;
  44361. _this.PBR = true;
  44362. _this.MAINUV1 = false;
  44363. _this.MAINUV2 = false;
  44364. _this.UV1 = false;
  44365. _this.UV2 = false;
  44366. _this.ALBEDO = false;
  44367. _this.ALBEDODIRECTUV = 0;
  44368. _this.VERTEXCOLOR = false;
  44369. _this.AMBIENT = false;
  44370. _this.AMBIENTDIRECTUV = 0;
  44371. _this.AMBIENTINGRAYSCALE = false;
  44372. _this.OPACITY = false;
  44373. _this.VERTEXALPHA = false;
  44374. _this.OPACITYDIRECTUV = 0;
  44375. _this.OPACITYRGB = false;
  44376. _this.ALPHATEST = false;
  44377. _this.DEPTHPREPASS = false;
  44378. _this.ALPHABLEND = false;
  44379. _this.ALPHAFROMALBEDO = false;
  44380. _this.ALPHATESTVALUE = "0.5";
  44381. _this.SPECULAROVERALPHA = false;
  44382. _this.RADIANCEOVERALPHA = false;
  44383. _this.ALPHAFRESNEL = false;
  44384. _this.LINEARALPHAFRESNEL = false;
  44385. _this.PREMULTIPLYALPHA = false;
  44386. _this.EMISSIVE = false;
  44387. _this.EMISSIVEDIRECTUV = 0;
  44388. _this.REFLECTIVITY = false;
  44389. _this.REFLECTIVITYDIRECTUV = 0;
  44390. _this.SPECULARTERM = false;
  44391. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44392. _this.MICROSURFACEAUTOMATIC = false;
  44393. _this.LODBASEDMICROSFURACE = false;
  44394. _this.MICROSURFACEMAP = false;
  44395. _this.MICROSURFACEMAPDIRECTUV = 0;
  44396. _this.METALLICWORKFLOW = false;
  44397. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44398. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44399. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44400. _this.AOSTOREINMETALMAPRED = false;
  44401. _this.ENVIRONMENTBRDF = false;
  44402. _this.NORMAL = false;
  44403. _this.TANGENT = false;
  44404. _this.BUMP = false;
  44405. _this.BUMPDIRECTUV = 0;
  44406. _this.OBJECTSPACE_NORMALMAP = false;
  44407. _this.PARALLAX = false;
  44408. _this.PARALLAXOCCLUSION = false;
  44409. _this.NORMALXYSCALE = true;
  44410. _this.LIGHTMAP = false;
  44411. _this.LIGHTMAPDIRECTUV = 0;
  44412. _this.USELIGHTMAPASSHADOWMAP = false;
  44413. _this.GAMMALIGHTMAP = false;
  44414. _this.REFLECTION = false;
  44415. _this.REFLECTIONMAP_3D = false;
  44416. _this.REFLECTIONMAP_SPHERICAL = false;
  44417. _this.REFLECTIONMAP_PLANAR = false;
  44418. _this.REFLECTIONMAP_CUBIC = false;
  44419. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44420. _this.REFLECTIONMAP_PROJECTION = false;
  44421. _this.REFLECTIONMAP_SKYBOX = false;
  44422. _this.REFLECTIONMAP_EXPLICIT = false;
  44423. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44424. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44425. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44426. _this.INVERTCUBICMAP = false;
  44427. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44428. _this.USESPHERICALINVERTEX = false;
  44429. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44430. _this.LODINREFLECTIONALPHA = false;
  44431. _this.GAMMAREFLECTION = false;
  44432. _this.RADIANCEOCCLUSION = false;
  44433. _this.HORIZONOCCLUSION = false;
  44434. _this.REFRACTION = false;
  44435. _this.REFRACTIONMAP_3D = false;
  44436. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44437. _this.LODINREFRACTIONALPHA = false;
  44438. _this.GAMMAREFRACTION = false;
  44439. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44440. _this.INSTANCES = false;
  44441. _this.NUM_BONE_INFLUENCERS = 0;
  44442. _this.BonesPerMesh = 0;
  44443. _this.NONUNIFORMSCALING = false;
  44444. _this.MORPHTARGETS = false;
  44445. _this.MORPHTARGETS_NORMAL = false;
  44446. _this.MORPHTARGETS_TANGENT = false;
  44447. _this.NUM_MORPH_INFLUENCERS = 0;
  44448. _this.IMAGEPROCESSING = false;
  44449. _this.VIGNETTE = false;
  44450. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44451. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44452. _this.TONEMAPPING = false;
  44453. _this.CONTRAST = false;
  44454. _this.COLORCURVES = false;
  44455. _this.COLORGRADING = false;
  44456. _this.COLORGRADING3D = false;
  44457. _this.SAMPLER3DGREENDEPTH = false;
  44458. _this.SAMPLER3DBGRMAP = false;
  44459. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44460. _this.EXPOSURE = false;
  44461. _this.USEPHYSICALLIGHTFALLOFF = false;
  44462. _this.TWOSIDEDLIGHTING = false;
  44463. _this.SHADOWFLOAT = false;
  44464. _this.CLIPPLANE = false;
  44465. _this.POINTSIZE = false;
  44466. _this.FOG = false;
  44467. _this.LOGARITHMICDEPTH = false;
  44468. _this.FORCENORMALFORWARD = false;
  44469. _this.SPECULARAA = false;
  44470. _this.UNLIT = false;
  44471. _this.rebuild();
  44472. return _this;
  44473. }
  44474. /**
  44475. * Resets the PBR Material defines.
  44476. */
  44477. PBRMaterialDefines.prototype.reset = function () {
  44478. _super.prototype.reset.call(this);
  44479. this.ALPHATESTVALUE = "0.5";
  44480. this.PBR = true;
  44481. };
  44482. return PBRMaterialDefines;
  44483. }(BABYLON.MaterialDefines));
  44484. /**
  44485. * The Physically based material base class of BJS.
  44486. *
  44487. * This offers the main features of a standard PBR material.
  44488. * For more information, please refer to the documentation :
  44489. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44490. */
  44491. var PBRBaseMaterial = /** @class */ (function (_super) {
  44492. __extends(PBRBaseMaterial, _super);
  44493. /**
  44494. * Instantiates a new PBRMaterial instance.
  44495. *
  44496. * @param name The material name
  44497. * @param scene The scene the material will be use in.
  44498. */
  44499. function PBRBaseMaterial(name, scene) {
  44500. var _this = _super.call(this, name, scene) || this;
  44501. /**
  44502. * Intensity of the direct lights e.g. the four lights available in your scene.
  44503. * This impacts both the direct diffuse and specular highlights.
  44504. */
  44505. _this._directIntensity = 1.0;
  44506. /**
  44507. * Intensity of the emissive part of the material.
  44508. * This helps controlling the emissive effect without modifying the emissive color.
  44509. */
  44510. _this._emissiveIntensity = 1.0;
  44511. /**
  44512. * Intensity of the environment e.g. how much the environment will light the object
  44513. * either through harmonics for rough material or through the refelction for shiny ones.
  44514. */
  44515. _this._environmentIntensity = 1.0;
  44516. /**
  44517. * This is a special control allowing the reduction of the specular highlights coming from the
  44518. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44519. */
  44520. _this._specularIntensity = 1.0;
  44521. /**
  44522. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44523. */
  44524. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44525. /**
  44526. * Debug Control allowing disabling the bump map on this material.
  44527. */
  44528. _this._disableBumpMap = false;
  44529. /**
  44530. * AKA Occlusion Texture Intensity in other nomenclature.
  44531. */
  44532. _this._ambientTextureStrength = 1.0;
  44533. /**
  44534. * The color of a material in ambient lighting.
  44535. */
  44536. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44537. /**
  44538. * AKA Diffuse Color in other nomenclature.
  44539. */
  44540. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44541. /**
  44542. * AKA Specular Color in other nomenclature.
  44543. */
  44544. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44545. /**
  44546. * The color applied when light is reflected from a material.
  44547. */
  44548. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44549. /**
  44550. * The color applied when light is emitted from a material.
  44551. */
  44552. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44553. /**
  44554. * AKA Glossiness in other nomenclature.
  44555. */
  44556. _this._microSurface = 0.9;
  44557. /**
  44558. * source material index of refraction (IOR)' / 'destination material IOR.
  44559. */
  44560. _this._indexOfRefraction = 0.66;
  44561. /**
  44562. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44563. */
  44564. _this._invertRefractionY = false;
  44565. /**
  44566. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44567. * Materials half opaque for instance using refraction could benefit from this control.
  44568. */
  44569. _this._linkRefractionWithTransparency = false;
  44570. /**
  44571. * Specifies that the material will use the light map as a show map.
  44572. */
  44573. _this._useLightmapAsShadowmap = false;
  44574. /**
  44575. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44576. * makes the reflect vector face the model (under horizon).
  44577. */
  44578. _this._useHorizonOcclusion = true;
  44579. /**
  44580. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44581. * too much the area relying on ambient texture to define their ambient occlusion.
  44582. */
  44583. _this._useRadianceOcclusion = true;
  44584. /**
  44585. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44586. */
  44587. _this._useAlphaFromAlbedoTexture = false;
  44588. /**
  44589. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44590. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44591. */
  44592. _this._useSpecularOverAlpha = true;
  44593. /**
  44594. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44595. */
  44596. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44597. /**
  44598. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44599. */
  44600. _this._useRoughnessFromMetallicTextureAlpha = true;
  44601. /**
  44602. * Specifies if the metallic texture contains the roughness information in its green channel.
  44603. */
  44604. _this._useRoughnessFromMetallicTextureGreen = false;
  44605. /**
  44606. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44607. */
  44608. _this._useMetallnessFromMetallicTextureBlue = false;
  44609. /**
  44610. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44611. */
  44612. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44613. /**
  44614. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44615. */
  44616. _this._useAmbientInGrayScale = false;
  44617. /**
  44618. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44619. * The material will try to infer what glossiness each pixel should be.
  44620. */
  44621. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44622. /**
  44623. * BJS is using an harcoded light falloff based on a manually sets up range.
  44624. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44625. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44626. */
  44627. _this._usePhysicalLightFalloff = true;
  44628. /**
  44629. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44630. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44631. */
  44632. _this._useRadianceOverAlpha = true;
  44633. /**
  44634. * Allows using an object space normal map (instead of tangent space).
  44635. */
  44636. _this._useObjectSpaceNormalMap = false;
  44637. /**
  44638. * Allows using the bump map in parallax mode.
  44639. */
  44640. _this._useParallax = false;
  44641. /**
  44642. * Allows using the bump map in parallax occlusion mode.
  44643. */
  44644. _this._useParallaxOcclusion = false;
  44645. /**
  44646. * Controls the scale bias of the parallax mode.
  44647. */
  44648. _this._parallaxScaleBias = 0.05;
  44649. /**
  44650. * If sets to true, disables all the lights affecting the material.
  44651. */
  44652. _this._disableLighting = false;
  44653. /**
  44654. * Number of Simultaneous lights allowed on the material.
  44655. */
  44656. _this._maxSimultaneousLights = 4;
  44657. /**
  44658. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44659. */
  44660. _this._invertNormalMapX = false;
  44661. /**
  44662. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44663. */
  44664. _this._invertNormalMapY = false;
  44665. /**
  44666. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44667. */
  44668. _this._twoSidedLighting = false;
  44669. /**
  44670. * Defines the alpha limits in alpha test mode.
  44671. */
  44672. _this._alphaCutOff = 0.4;
  44673. /**
  44674. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44675. */
  44676. _this._forceAlphaTest = false;
  44677. /**
  44678. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44679. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44680. */
  44681. _this._useAlphaFresnel = false;
  44682. /**
  44683. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44684. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44685. */
  44686. _this._useLinearAlphaFresnel = false;
  44687. /**
  44688. * The transparency mode of the material.
  44689. */
  44690. _this._transparencyMode = null;
  44691. /**
  44692. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44693. * from cos thetav and roughness:
  44694. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44695. */
  44696. _this._environmentBRDFTexture = null;
  44697. /**
  44698. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44699. */
  44700. _this._forceIrradianceInFragment = false;
  44701. /**
  44702. * Force normal to face away from face.
  44703. */
  44704. _this._forceNormalForward = false;
  44705. /**
  44706. * Enables specular anti aliasing in the PBR shader.
  44707. * It will both interacts on the Geometry for analytical and IBL lighting.
  44708. * It also prefilter the roughness map based on the bump values.
  44709. */
  44710. _this._enableSpecularAntiAliasing = false;
  44711. /**
  44712. * Stores the available render targets.
  44713. */
  44714. _this._renderTargets = new BABYLON.SmartArray(16);
  44715. /**
  44716. * Sets the global ambient color for the material used in lighting calculations.
  44717. */
  44718. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44719. /**
  44720. * If set to true, no lighting calculations will be applied.
  44721. */
  44722. _this._unlit = false;
  44723. // Setup the default processing configuration to the scene.
  44724. _this._attachImageProcessingConfiguration(null);
  44725. _this.getRenderTargetTextures = function () {
  44726. _this._renderTargets.reset();
  44727. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44728. _this._renderTargets.push(_this._reflectionTexture);
  44729. }
  44730. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44731. _this._renderTargets.push(_this._refractionTexture);
  44732. }
  44733. return _this._renderTargets;
  44734. };
  44735. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44736. return _this;
  44737. }
  44738. /**
  44739. * Attaches a new image processing configuration to the PBR Material.
  44740. * @param configuration
  44741. */
  44742. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44743. var _this = this;
  44744. if (configuration === this._imageProcessingConfiguration) {
  44745. return;
  44746. }
  44747. // Detaches observer.
  44748. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44749. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44750. }
  44751. // Pick the scene configuration if needed.
  44752. if (!configuration) {
  44753. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44754. }
  44755. else {
  44756. this._imageProcessingConfiguration = configuration;
  44757. }
  44758. // Attaches observer.
  44759. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44760. _this._markAllSubMeshesAsImageProcessingDirty();
  44761. });
  44762. };
  44763. /**
  44764. * Gets the name of the material class.
  44765. */
  44766. PBRBaseMaterial.prototype.getClassName = function () {
  44767. return "PBRBaseMaterial";
  44768. };
  44769. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44770. /**
  44771. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44772. */
  44773. get: function () {
  44774. return this._useLogarithmicDepth;
  44775. },
  44776. /**
  44777. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44778. */
  44779. set: function (value) {
  44780. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44781. },
  44782. enumerable: true,
  44783. configurable: true
  44784. });
  44785. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44786. /**
  44787. * Gets the current transparency mode.
  44788. */
  44789. get: function () {
  44790. return this._transparencyMode;
  44791. },
  44792. /**
  44793. * Sets the transparency mode of the material.
  44794. */
  44795. set: function (value) {
  44796. if (this._transparencyMode === value) {
  44797. return;
  44798. }
  44799. this._transparencyMode = value;
  44800. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44801. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44802. },
  44803. enumerable: true,
  44804. configurable: true
  44805. });
  44806. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44807. /**
  44808. * Returns true if alpha blending should be disabled.
  44809. */
  44810. get: function () {
  44811. return (this._linkRefractionWithTransparency ||
  44812. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44813. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44814. },
  44815. enumerable: true,
  44816. configurable: true
  44817. });
  44818. /**
  44819. * Specifies whether or not this material should be rendered in alpha blend mode.
  44820. */
  44821. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44822. if (this._disableAlphaBlending) {
  44823. return false;
  44824. }
  44825. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44826. };
  44827. /**
  44828. * Specifies if the mesh will require alpha blending.
  44829. * @param mesh - BJS mesh.
  44830. */
  44831. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44832. if (this._disableAlphaBlending) {
  44833. return false;
  44834. }
  44835. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44836. };
  44837. /**
  44838. * Specifies whether or not this material should be rendered in alpha test mode.
  44839. */
  44840. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44841. if (this._forceAlphaTest) {
  44842. return true;
  44843. }
  44844. if (this._linkRefractionWithTransparency) {
  44845. return false;
  44846. }
  44847. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44848. };
  44849. /**
  44850. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44851. */
  44852. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44853. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44854. };
  44855. /**
  44856. * Gets the texture used for the alpha test.
  44857. */
  44858. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44859. return this._albedoTexture;
  44860. };
  44861. /**
  44862. * Specifies that the submesh is ready to be used.
  44863. * @param mesh - BJS mesh.
  44864. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44865. * @param useInstances - Specifies that instances should be used.
  44866. * @returns - boolean indicating that the submesh is ready or not.
  44867. */
  44868. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44869. if (subMesh.effect && this.isFrozen) {
  44870. if (this._wasPreviouslyReady) {
  44871. return true;
  44872. }
  44873. }
  44874. if (!subMesh._materialDefines) {
  44875. subMesh._materialDefines = new PBRMaterialDefines();
  44876. }
  44877. var defines = subMesh._materialDefines;
  44878. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44879. if (defines._renderId === this.getScene().getRenderId()) {
  44880. return true;
  44881. }
  44882. }
  44883. var scene = this.getScene();
  44884. var engine = scene.getEngine();
  44885. if (defines._areTexturesDirty) {
  44886. if (scene.texturesEnabled) {
  44887. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44888. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44889. return false;
  44890. }
  44891. }
  44892. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44893. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44894. return false;
  44895. }
  44896. }
  44897. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44898. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44899. return false;
  44900. }
  44901. }
  44902. var reflectionTexture = this._getReflectionTexture();
  44903. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44904. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44905. return false;
  44906. }
  44907. }
  44908. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44909. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44910. return false;
  44911. }
  44912. }
  44913. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44914. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44915. return false;
  44916. }
  44917. }
  44918. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44919. if (this._metallicTexture) {
  44920. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44921. return false;
  44922. }
  44923. }
  44924. else if (this._reflectivityTexture) {
  44925. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44926. return false;
  44927. }
  44928. }
  44929. if (this._microSurfaceTexture) {
  44930. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44931. return false;
  44932. }
  44933. }
  44934. }
  44935. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44936. // Bump texture cannot be not blocking.
  44937. if (!this._bumpTexture.isReady()) {
  44938. return false;
  44939. }
  44940. }
  44941. var refractionTexture = this._getRefractionTexture();
  44942. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44943. if (!refractionTexture.isReadyOrNotBlocking()) {
  44944. return false;
  44945. }
  44946. }
  44947. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44948. // This is blocking.
  44949. if (!this._environmentBRDFTexture.isReady()) {
  44950. return false;
  44951. }
  44952. }
  44953. }
  44954. }
  44955. if (defines._areImageProcessingDirty) {
  44956. if (!this._imageProcessingConfiguration.isReady()) {
  44957. return false;
  44958. }
  44959. }
  44960. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44961. mesh.createNormals(true);
  44962. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44963. }
  44964. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44965. if (effect) {
  44966. scene.resetCachedMaterial();
  44967. subMesh.setEffect(effect, defines);
  44968. this.buildUniformLayout();
  44969. }
  44970. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44971. return false;
  44972. }
  44973. defines._renderId = scene.getRenderId();
  44974. this._wasPreviouslyReady = true;
  44975. return true;
  44976. };
  44977. /**
  44978. * Specifies if the material uses metallic roughness workflow.
  44979. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44980. */
  44981. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44982. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44983. return true;
  44984. }
  44985. return false;
  44986. };
  44987. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44988. if (onCompiled === void 0) { onCompiled = null; }
  44989. if (onError === void 0) { onError = null; }
  44990. if (useInstances === void 0) { useInstances = null; }
  44991. if (useClipPlane === void 0) { useClipPlane = null; }
  44992. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44993. if (!defines.isDirty) {
  44994. return null;
  44995. }
  44996. defines.markAsProcessed();
  44997. var scene = this.getScene();
  44998. var engine = scene.getEngine();
  44999. // Fallbacks
  45000. var fallbacks = new BABYLON.EffectFallbacks();
  45001. var fallbackRank = 0;
  45002. if (defines.USESPHERICALINVERTEX) {
  45003. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45004. }
  45005. if (defines.FOG) {
  45006. fallbacks.addFallback(fallbackRank, "FOG");
  45007. }
  45008. if (defines.SPECULARAA) {
  45009. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45010. }
  45011. if (defines.POINTSIZE) {
  45012. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45013. }
  45014. if (defines.LOGARITHMICDEPTH) {
  45015. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45016. }
  45017. if (defines.PARALLAX) {
  45018. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45019. }
  45020. if (defines.PARALLAXOCCLUSION) {
  45021. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45022. }
  45023. if (defines.ENVIRONMENTBRDF) {
  45024. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45025. }
  45026. if (defines.TANGENT) {
  45027. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45028. }
  45029. if (defines.BUMP) {
  45030. fallbacks.addFallback(fallbackRank++, "BUMP");
  45031. }
  45032. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45033. if (defines.SPECULARTERM) {
  45034. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45035. }
  45036. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45037. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45038. }
  45039. if (defines.LIGHTMAP) {
  45040. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45041. }
  45042. if (defines.NORMAL) {
  45043. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45044. }
  45045. if (defines.AMBIENT) {
  45046. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45047. }
  45048. if (defines.EMISSIVE) {
  45049. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45050. }
  45051. if (defines.VERTEXCOLOR) {
  45052. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45053. }
  45054. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45055. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45056. }
  45057. if (defines.MORPHTARGETS) {
  45058. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45059. }
  45060. //Attributes
  45061. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45062. if (defines.NORMAL) {
  45063. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45064. }
  45065. if (defines.TANGENT) {
  45066. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45067. }
  45068. if (defines.UV1) {
  45069. attribs.push(BABYLON.VertexBuffer.UVKind);
  45070. }
  45071. if (defines.UV2) {
  45072. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45073. }
  45074. if (defines.VERTEXCOLOR) {
  45075. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45076. }
  45077. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45078. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45079. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45080. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45081. "vFogInfos", "vFogColor", "pointSize",
  45082. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45083. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45084. "mBones",
  45085. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45086. "vLightingIntensity",
  45087. "logarithmicDepthConstant",
  45088. "vSphericalX", "vSphericalY", "vSphericalZ",
  45089. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45090. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45091. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45092. "vTangentSpaceParams"
  45093. ];
  45094. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45095. "bumpSampler", "lightmapSampler", "opacitySampler",
  45096. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45097. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45098. "microSurfaceSampler", "environmentBrdfSampler"];
  45099. var uniformBuffers = ["Material", "Scene"];
  45100. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45101. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45102. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45103. uniformsNames: uniforms,
  45104. uniformBuffersNames: uniformBuffers,
  45105. samplers: samplers,
  45106. defines: defines,
  45107. maxSimultaneousLights: this._maxSimultaneousLights
  45108. });
  45109. var join = defines.toString();
  45110. return engine.createEffect("pbr", {
  45111. attributes: attribs,
  45112. uniformsNames: uniforms,
  45113. uniformBuffersNames: uniformBuffers,
  45114. samplers: samplers,
  45115. defines: join,
  45116. fallbacks: fallbacks,
  45117. onCompiled: onCompiled,
  45118. onError: onError,
  45119. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45120. }, engine);
  45121. };
  45122. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45123. if (useInstances === void 0) { useInstances = null; }
  45124. if (useClipPlane === void 0) { useClipPlane = null; }
  45125. var scene = this.getScene();
  45126. var engine = scene.getEngine();
  45127. // Lights
  45128. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45129. defines._needNormals = true;
  45130. // Textures
  45131. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45132. if (defines._areTexturesDirty) {
  45133. defines._needUVs = false;
  45134. if (scene.texturesEnabled) {
  45135. if (scene.getEngine().getCaps().textureLOD) {
  45136. defines.LODBASEDMICROSFURACE = true;
  45137. }
  45138. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45139. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45140. }
  45141. else {
  45142. defines.ALBEDO = false;
  45143. }
  45144. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45145. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45146. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45147. }
  45148. else {
  45149. defines.AMBIENT = false;
  45150. }
  45151. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45152. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45153. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45154. }
  45155. else {
  45156. defines.OPACITY = false;
  45157. }
  45158. var reflectionTexture = this._getReflectionTexture();
  45159. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45160. defines.REFLECTION = true;
  45161. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45162. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45163. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45164. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45165. defines.INVERTCUBICMAP = true;
  45166. }
  45167. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45168. switch (reflectionTexture.coordinatesMode) {
  45169. case BABYLON.Texture.EXPLICIT_MODE:
  45170. defines.REFLECTIONMAP_EXPLICIT = true;
  45171. break;
  45172. case BABYLON.Texture.PLANAR_MODE:
  45173. defines.REFLECTIONMAP_PLANAR = true;
  45174. break;
  45175. case BABYLON.Texture.PROJECTION_MODE:
  45176. defines.REFLECTIONMAP_PROJECTION = true;
  45177. break;
  45178. case BABYLON.Texture.SKYBOX_MODE:
  45179. defines.REFLECTIONMAP_SKYBOX = true;
  45180. break;
  45181. case BABYLON.Texture.SPHERICAL_MODE:
  45182. defines.REFLECTIONMAP_SPHERICAL = true;
  45183. break;
  45184. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45185. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45186. break;
  45187. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45188. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45189. break;
  45190. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45191. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45192. break;
  45193. case BABYLON.Texture.CUBIC_MODE:
  45194. case BABYLON.Texture.INVCUBIC_MODE:
  45195. default:
  45196. defines.REFLECTIONMAP_CUBIC = true;
  45197. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45198. break;
  45199. }
  45200. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45201. if (reflectionTexture.sphericalPolynomial) {
  45202. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45203. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45204. defines.USESPHERICALINVERTEX = false;
  45205. }
  45206. else {
  45207. defines.USESPHERICALINVERTEX = true;
  45208. }
  45209. }
  45210. }
  45211. }
  45212. else {
  45213. defines.REFLECTION = false;
  45214. defines.REFLECTIONMAP_3D = false;
  45215. defines.REFLECTIONMAP_SPHERICAL = false;
  45216. defines.REFLECTIONMAP_PLANAR = false;
  45217. defines.REFLECTIONMAP_CUBIC = false;
  45218. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45219. defines.REFLECTIONMAP_PROJECTION = false;
  45220. defines.REFLECTIONMAP_SKYBOX = false;
  45221. defines.REFLECTIONMAP_EXPLICIT = false;
  45222. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45223. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45224. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45225. defines.INVERTCUBICMAP = false;
  45226. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45227. defines.USESPHERICALINVERTEX = false;
  45228. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45229. defines.LODINREFLECTIONALPHA = false;
  45230. defines.GAMMAREFLECTION = false;
  45231. }
  45232. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45233. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45234. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45235. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45236. }
  45237. else {
  45238. defines.LIGHTMAP = false;
  45239. }
  45240. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45241. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45242. }
  45243. else {
  45244. defines.EMISSIVE = false;
  45245. }
  45246. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45247. if (this._metallicTexture) {
  45248. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45249. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45250. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45251. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45252. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45253. }
  45254. else if (this._reflectivityTexture) {
  45255. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45256. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45257. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45258. }
  45259. else {
  45260. defines.REFLECTIVITY = false;
  45261. }
  45262. if (this._microSurfaceTexture) {
  45263. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45264. }
  45265. else {
  45266. defines.MICROSURFACEMAP = false;
  45267. }
  45268. }
  45269. else {
  45270. defines.REFLECTIVITY = false;
  45271. defines.MICROSURFACEMAP = false;
  45272. }
  45273. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45274. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45275. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45276. defines.PARALLAX = true;
  45277. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45278. }
  45279. else {
  45280. defines.PARALLAX = false;
  45281. }
  45282. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45283. }
  45284. else {
  45285. defines.BUMP = false;
  45286. }
  45287. var refractionTexture = this._getRefractionTexture();
  45288. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45289. defines.REFRACTION = true;
  45290. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45291. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45292. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45293. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45294. if (this._linkRefractionWithTransparency) {
  45295. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45296. }
  45297. }
  45298. else {
  45299. defines.REFRACTION = false;
  45300. }
  45301. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45302. defines.ENVIRONMENTBRDF = true;
  45303. }
  45304. else {
  45305. defines.ENVIRONMENTBRDF = false;
  45306. }
  45307. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45308. defines.ALPHAFROMALBEDO = true;
  45309. }
  45310. else {
  45311. defines.ALPHAFROMALBEDO = false;
  45312. }
  45313. }
  45314. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45315. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45316. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45317. if (!this.backFaceCulling && this._twoSidedLighting) {
  45318. defines.TWOSIDEDLIGHTING = true;
  45319. }
  45320. else {
  45321. defines.TWOSIDEDLIGHTING = false;
  45322. }
  45323. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45324. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45325. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45326. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45327. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45328. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45329. }
  45330. if (defines._areImageProcessingDirty) {
  45331. this._imageProcessingConfiguration.prepareDefines(defines);
  45332. }
  45333. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45334. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45335. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45336. // Misc.
  45337. if (defines._areMiscDirty) {
  45338. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45339. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45340. }
  45341. // Values that need to be evaluated on every frame
  45342. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45343. // Attribs
  45344. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45345. };
  45346. /**
  45347. * Force shader compilation
  45348. */
  45349. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45350. var _this = this;
  45351. var localOptions = __assign({ clipPlane: false }, options);
  45352. var defines = new PBRMaterialDefines();
  45353. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45354. if (effect.isReady()) {
  45355. if (onCompiled) {
  45356. onCompiled(this);
  45357. }
  45358. }
  45359. else {
  45360. effect.onCompileObservable.add(function () {
  45361. if (onCompiled) {
  45362. onCompiled(_this);
  45363. }
  45364. });
  45365. }
  45366. };
  45367. /**
  45368. * Initializes the uniform buffer layout for the shader.
  45369. */
  45370. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45371. // Order is important !
  45372. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45373. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45374. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45375. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45376. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45377. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45378. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45379. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45380. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45381. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45382. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45383. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45384. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45385. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45386. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45387. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45388. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45389. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45390. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45391. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45392. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45393. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45394. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45395. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45396. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45397. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45398. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45399. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45400. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45401. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45402. this._uniformBuffer.addUniform("pointSize", 1);
  45403. this._uniformBuffer.create();
  45404. };
  45405. /**
  45406. * Unbinds the textures.
  45407. */
  45408. PBRBaseMaterial.prototype.unbind = function () {
  45409. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45410. this._uniformBuffer.setTexture("reflectionSampler", null);
  45411. }
  45412. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45413. this._uniformBuffer.setTexture("refractionSampler", null);
  45414. }
  45415. _super.prototype.unbind.call(this);
  45416. };
  45417. /**
  45418. * Binds the submesh data.
  45419. * @param world - The world matrix.
  45420. * @param mesh - The BJS mesh.
  45421. * @param subMesh - A submesh of the BJS mesh.
  45422. */
  45423. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45424. var scene = this.getScene();
  45425. var defines = subMesh._materialDefines;
  45426. if (!defines) {
  45427. return;
  45428. }
  45429. var effect = subMesh.effect;
  45430. if (!effect) {
  45431. return;
  45432. }
  45433. this._activeEffect = effect;
  45434. // Matrices
  45435. this.bindOnlyWorldMatrix(world);
  45436. // Normal Matrix
  45437. if (defines.OBJECTSPACE_NORMALMAP) {
  45438. world.toNormalMatrix(this._normalMatrix);
  45439. this.bindOnlyNormalMatrix(this._normalMatrix);
  45440. }
  45441. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45442. // Bones
  45443. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45444. var reflectionTexture = null;
  45445. if (mustRebind) {
  45446. this._uniformBuffer.bindToEffect(effect, "Material");
  45447. this.bindViewProjection(effect);
  45448. reflectionTexture = this._getReflectionTexture();
  45449. var refractionTexture = this._getRefractionTexture();
  45450. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45451. // Texture uniforms
  45452. if (scene.texturesEnabled) {
  45453. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45454. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45455. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45456. }
  45457. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45458. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45459. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45460. }
  45461. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45462. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45463. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45464. }
  45465. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45466. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45467. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45468. if (reflectionTexture.boundingBoxSize) {
  45469. var cubeTexture = reflectionTexture;
  45470. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45471. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45472. }
  45473. var polynomials = reflectionTexture.sphericalPolynomial;
  45474. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45475. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45476. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45477. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45478. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45479. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45480. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45481. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45482. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45483. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45484. }
  45485. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45486. }
  45487. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45488. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45489. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45490. }
  45491. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45492. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45493. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45494. }
  45495. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45496. if (this._metallicTexture) {
  45497. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45498. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45499. }
  45500. else if (this._reflectivityTexture) {
  45501. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45502. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45503. }
  45504. if (this._microSurfaceTexture) {
  45505. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45506. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45507. }
  45508. }
  45509. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45510. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45511. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45512. if (scene._mirroredCameraPosition) {
  45513. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45514. }
  45515. else {
  45516. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45517. }
  45518. }
  45519. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45520. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45521. var depth = 1.0;
  45522. if (!refractionTexture.isCube) {
  45523. if (refractionTexture.depth) {
  45524. depth = refractionTexture.depth;
  45525. }
  45526. }
  45527. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45528. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45529. }
  45530. }
  45531. // Point size
  45532. if (this.pointsCloud) {
  45533. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45534. }
  45535. // Colors
  45536. if (defines.METALLICWORKFLOW) {
  45537. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45538. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45539. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45540. }
  45541. else {
  45542. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45543. }
  45544. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45545. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45546. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45547. // Misc
  45548. this._lightingInfos.x = this._directIntensity;
  45549. this._lightingInfos.y = this._emissiveIntensity;
  45550. this._lightingInfos.z = this._environmentIntensity;
  45551. this._lightingInfos.w = this._specularIntensity;
  45552. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45553. }
  45554. // Textures
  45555. if (scene.texturesEnabled) {
  45556. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45557. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45558. }
  45559. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45560. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45561. }
  45562. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45563. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45564. }
  45565. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45566. if (defines.LODBASEDMICROSFURACE) {
  45567. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45568. }
  45569. else {
  45570. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45571. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45572. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45573. }
  45574. }
  45575. if (defines.ENVIRONMENTBRDF) {
  45576. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45577. }
  45578. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45579. if (defines.LODBASEDMICROSFURACE) {
  45580. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45581. }
  45582. else {
  45583. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45584. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45585. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45586. }
  45587. }
  45588. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45589. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45590. }
  45591. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45592. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45593. }
  45594. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45595. if (this._metallicTexture) {
  45596. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45597. }
  45598. else if (this._reflectivityTexture) {
  45599. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45600. }
  45601. if (this._microSurfaceTexture) {
  45602. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45603. }
  45604. }
  45605. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45606. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45607. }
  45608. }
  45609. // Clip plane
  45610. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45611. // Colors
  45612. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45613. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45614. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45615. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45616. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45617. }
  45618. if (mustRebind || !this.isFrozen) {
  45619. // Lights
  45620. if (scene.lightsEnabled && !this._disableLighting) {
  45621. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45622. }
  45623. // View
  45624. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45625. this.bindView(effect);
  45626. }
  45627. // Fog
  45628. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45629. // Morph targets
  45630. if (defines.NUM_MORPH_INFLUENCERS) {
  45631. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45632. }
  45633. // image processing
  45634. this._imageProcessingConfiguration.bind(this._activeEffect);
  45635. // Log. depth
  45636. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45637. }
  45638. this._uniformBuffer.update();
  45639. this._afterBind(mesh, this._activeEffect);
  45640. };
  45641. /**
  45642. * Returns the animatable textures.
  45643. * @returns - Array of animatable textures.
  45644. */
  45645. PBRBaseMaterial.prototype.getAnimatables = function () {
  45646. var results = [];
  45647. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45648. results.push(this._albedoTexture);
  45649. }
  45650. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45651. results.push(this._ambientTexture);
  45652. }
  45653. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45654. results.push(this._opacityTexture);
  45655. }
  45656. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45657. results.push(this._reflectionTexture);
  45658. }
  45659. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45660. results.push(this._emissiveTexture);
  45661. }
  45662. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45663. results.push(this._metallicTexture);
  45664. }
  45665. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45666. results.push(this._reflectivityTexture);
  45667. }
  45668. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45669. results.push(this._bumpTexture);
  45670. }
  45671. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45672. results.push(this._lightmapTexture);
  45673. }
  45674. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45675. results.push(this._refractionTexture);
  45676. }
  45677. return results;
  45678. };
  45679. /**
  45680. * Returns the texture used for reflections.
  45681. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45682. */
  45683. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45684. if (this._reflectionTexture) {
  45685. return this._reflectionTexture;
  45686. }
  45687. return this.getScene().environmentTexture;
  45688. };
  45689. /**
  45690. * Returns the texture used for refraction or null if none is used.
  45691. * @returns - Refection texture if present. If no refraction texture and refraction
  45692. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45693. */
  45694. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45695. if (this._refractionTexture) {
  45696. return this._refractionTexture;
  45697. }
  45698. if (this._linkRefractionWithTransparency) {
  45699. return this.getScene().environmentTexture;
  45700. }
  45701. return null;
  45702. };
  45703. /**
  45704. * Disposes the resources of the material.
  45705. * @param forceDisposeEffect - Forces the disposal of effects.
  45706. * @param forceDisposeTextures - Forces the disposal of all textures.
  45707. */
  45708. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45709. if (forceDisposeTextures) {
  45710. if (this._albedoTexture) {
  45711. this._albedoTexture.dispose();
  45712. }
  45713. if (this._ambientTexture) {
  45714. this._ambientTexture.dispose();
  45715. }
  45716. if (this._opacityTexture) {
  45717. this._opacityTexture.dispose();
  45718. }
  45719. if (this._reflectionTexture) {
  45720. this._reflectionTexture.dispose();
  45721. }
  45722. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45723. this._environmentBRDFTexture.dispose();
  45724. }
  45725. if (this._emissiveTexture) {
  45726. this._emissiveTexture.dispose();
  45727. }
  45728. if (this._metallicTexture) {
  45729. this._metallicTexture.dispose();
  45730. }
  45731. if (this._reflectivityTexture) {
  45732. this._reflectivityTexture.dispose();
  45733. }
  45734. if (this._bumpTexture) {
  45735. this._bumpTexture.dispose();
  45736. }
  45737. if (this._lightmapTexture) {
  45738. this._lightmapTexture.dispose();
  45739. }
  45740. if (this._refractionTexture) {
  45741. this._refractionTexture.dispose();
  45742. }
  45743. }
  45744. this._renderTargets.dispose();
  45745. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45746. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45747. }
  45748. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45749. };
  45750. /**
  45751. * Stores the reflectivity values based on metallic roughness workflow.
  45752. */
  45753. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45754. __decorate([
  45755. BABYLON.serializeAsImageProcessingConfiguration()
  45756. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45757. __decorate([
  45758. BABYLON.serialize()
  45759. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45760. __decorate([
  45761. BABYLON.serialize()
  45762. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45763. return PBRBaseMaterial;
  45764. }(BABYLON.PushMaterial));
  45765. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45766. })(BABYLON || (BABYLON = {}));
  45767. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45768. var BABYLON;
  45769. (function (BABYLON) {
  45770. /**
  45771. * The Physically based simple base material of BJS.
  45772. *
  45773. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45774. * It is used as the base class for both the specGloss and metalRough conventions.
  45775. */
  45776. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45777. __extends(PBRBaseSimpleMaterial, _super);
  45778. /**
  45779. * Instantiates a new PBRMaterial instance.
  45780. *
  45781. * @param name The material name
  45782. * @param scene The scene the material will be use in.
  45783. */
  45784. function PBRBaseSimpleMaterial(name, scene) {
  45785. var _this = _super.call(this, name, scene) || this;
  45786. /**
  45787. * Number of Simultaneous lights allowed on the material.
  45788. */
  45789. _this.maxSimultaneousLights = 4;
  45790. /**
  45791. * If sets to true, disables all the lights affecting the material.
  45792. */
  45793. _this.disableLighting = false;
  45794. /**
  45795. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45796. */
  45797. _this.invertNormalMapX = false;
  45798. /**
  45799. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45800. */
  45801. _this.invertNormalMapY = false;
  45802. /**
  45803. * Emissivie color used to self-illuminate the model.
  45804. */
  45805. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45806. /**
  45807. * Occlusion Channel Strenght.
  45808. */
  45809. _this.occlusionStrength = 1.0;
  45810. _this.useLightmapAsShadowmap = false;
  45811. _this._useAlphaFromAlbedoTexture = true;
  45812. _this._useAmbientInGrayScale = true;
  45813. return _this;
  45814. }
  45815. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45816. /**
  45817. * Gets the current double sided mode.
  45818. */
  45819. get: function () {
  45820. return this._twoSidedLighting;
  45821. },
  45822. /**
  45823. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45824. */
  45825. set: function (value) {
  45826. if (this._twoSidedLighting === value) {
  45827. return;
  45828. }
  45829. this._twoSidedLighting = value;
  45830. this.backFaceCulling = !value;
  45831. this._markAllSubMeshesAsTexturesDirty();
  45832. },
  45833. enumerable: true,
  45834. configurable: true
  45835. });
  45836. /**
  45837. * Return the active textures of the material.
  45838. */
  45839. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45840. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45841. if (this.environmentTexture) {
  45842. activeTextures.push(this.environmentTexture);
  45843. }
  45844. if (this.normalTexture) {
  45845. activeTextures.push(this.normalTexture);
  45846. }
  45847. if (this.emissiveTexture) {
  45848. activeTextures.push(this.emissiveTexture);
  45849. }
  45850. if (this.occlusionTexture) {
  45851. activeTextures.push(this.occlusionTexture);
  45852. }
  45853. if (this.lightmapTexture) {
  45854. activeTextures.push(this.lightmapTexture);
  45855. }
  45856. return activeTextures;
  45857. };
  45858. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45859. if (_super.prototype.hasTexture.call(this, texture)) {
  45860. return true;
  45861. }
  45862. if (this.lightmapTexture === texture) {
  45863. return true;
  45864. }
  45865. return false;
  45866. };
  45867. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45868. return "PBRBaseSimpleMaterial";
  45869. };
  45870. __decorate([
  45871. BABYLON.serialize(),
  45872. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45873. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45874. __decorate([
  45875. BABYLON.serialize(),
  45876. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45877. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45878. __decorate([
  45879. BABYLON.serializeAsTexture(),
  45880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45881. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45882. __decorate([
  45883. BABYLON.serialize(),
  45884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45885. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45886. __decorate([
  45887. BABYLON.serialize(),
  45888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45889. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45890. __decorate([
  45891. BABYLON.serializeAsTexture(),
  45892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45893. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45894. __decorate([
  45895. BABYLON.serializeAsColor3("emissive"),
  45896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45897. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45898. __decorate([
  45899. BABYLON.serializeAsTexture(),
  45900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45901. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45902. __decorate([
  45903. BABYLON.serialize(),
  45904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45905. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45906. __decorate([
  45907. BABYLON.serializeAsTexture(),
  45908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45909. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45910. __decorate([
  45911. BABYLON.serialize(),
  45912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45913. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45914. __decorate([
  45915. BABYLON.serialize()
  45916. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45917. __decorate([
  45918. BABYLON.serializeAsTexture(),
  45919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45920. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45921. __decorate([
  45922. BABYLON.serialize(),
  45923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45924. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45925. return PBRBaseSimpleMaterial;
  45926. }(BABYLON.PBRBaseMaterial));
  45927. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45928. })(BABYLON || (BABYLON = {}));
  45929. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45930. var BABYLON;
  45931. (function (BABYLON) {
  45932. /**
  45933. * The Physically based material of BJS.
  45934. *
  45935. * This offers the main features of a standard PBR material.
  45936. * For more information, please refer to the documentation :
  45937. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45938. */
  45939. var PBRMaterial = /** @class */ (function (_super) {
  45940. __extends(PBRMaterial, _super);
  45941. /**
  45942. * Instantiates a new PBRMaterial instance.
  45943. *
  45944. * @param name The material name
  45945. * @param scene The scene the material will be use in.
  45946. */
  45947. function PBRMaterial(name, scene) {
  45948. var _this = _super.call(this, name, scene) || this;
  45949. /**
  45950. * Intensity of the direct lights e.g. the four lights available in your scene.
  45951. * This impacts both the direct diffuse and specular highlights.
  45952. */
  45953. _this.directIntensity = 1.0;
  45954. /**
  45955. * Intensity of the emissive part of the material.
  45956. * This helps controlling the emissive effect without modifying the emissive color.
  45957. */
  45958. _this.emissiveIntensity = 1.0;
  45959. /**
  45960. * Intensity of the environment e.g. how much the environment will light the object
  45961. * either through harmonics for rough material or through the refelction for shiny ones.
  45962. */
  45963. _this.environmentIntensity = 1.0;
  45964. /**
  45965. * This is a special control allowing the reduction of the specular highlights coming from the
  45966. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45967. */
  45968. _this.specularIntensity = 1.0;
  45969. /**
  45970. * Debug Control allowing disabling the bump map on this material.
  45971. */
  45972. _this.disableBumpMap = false;
  45973. /**
  45974. * AKA Occlusion Texture Intensity in other nomenclature.
  45975. */
  45976. _this.ambientTextureStrength = 1.0;
  45977. /**
  45978. * The color of a material in ambient lighting.
  45979. */
  45980. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45981. /**
  45982. * AKA Diffuse Color in other nomenclature.
  45983. */
  45984. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45985. /**
  45986. * AKA Specular Color in other nomenclature.
  45987. */
  45988. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45989. /**
  45990. * The color reflected from the material.
  45991. */
  45992. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45993. /**
  45994. * The color emitted from the material.
  45995. */
  45996. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45997. /**
  45998. * AKA Glossiness in other nomenclature.
  45999. */
  46000. _this.microSurface = 1.0;
  46001. /**
  46002. * source material index of refraction (IOR)' / 'destination material IOR.
  46003. */
  46004. _this.indexOfRefraction = 0.66;
  46005. /**
  46006. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46007. */
  46008. _this.invertRefractionY = false;
  46009. /**
  46010. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46011. * Materials half opaque for instance using refraction could benefit from this control.
  46012. */
  46013. _this.linkRefractionWithTransparency = false;
  46014. _this.useLightmapAsShadowmap = false;
  46015. /**
  46016. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46017. */
  46018. _this.useAlphaFromAlbedoTexture = false;
  46019. /**
  46020. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46021. */
  46022. _this.forceAlphaTest = false;
  46023. /**
  46024. * Defines the alpha limits in alpha test mode.
  46025. */
  46026. _this.alphaCutOff = 0.4;
  46027. /**
  46028. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46029. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46030. */
  46031. _this.useSpecularOverAlpha = true;
  46032. /**
  46033. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46034. */
  46035. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46036. /**
  46037. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46038. */
  46039. _this.useRoughnessFromMetallicTextureAlpha = true;
  46040. /**
  46041. * Specifies if the metallic texture contains the roughness information in its green channel.
  46042. */
  46043. _this.useRoughnessFromMetallicTextureGreen = false;
  46044. /**
  46045. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46046. */
  46047. _this.useMetallnessFromMetallicTextureBlue = false;
  46048. /**
  46049. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46050. */
  46051. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46052. /**
  46053. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46054. */
  46055. _this.useAmbientInGrayScale = false;
  46056. /**
  46057. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46058. * The material will try to infer what glossiness each pixel should be.
  46059. */
  46060. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46061. /**
  46062. * BJS is using an harcoded light falloff based on a manually sets up range.
  46063. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46064. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46065. */
  46066. _this.usePhysicalLightFalloff = true;
  46067. /**
  46068. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46069. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46070. */
  46071. _this.useRadianceOverAlpha = true;
  46072. /**
  46073. * Allows using an object space normal map (instead of tangent space).
  46074. */
  46075. _this.useObjectSpaceNormalMap = false;
  46076. /**
  46077. * Allows using the bump map in parallax mode.
  46078. */
  46079. _this.useParallax = false;
  46080. /**
  46081. * Allows using the bump map in parallax occlusion mode.
  46082. */
  46083. _this.useParallaxOcclusion = false;
  46084. /**
  46085. * Controls the scale bias of the parallax mode.
  46086. */
  46087. _this.parallaxScaleBias = 0.05;
  46088. /**
  46089. * If sets to true, disables all the lights affecting the material.
  46090. */
  46091. _this.disableLighting = false;
  46092. /**
  46093. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46094. */
  46095. _this.forceIrradianceInFragment = false;
  46096. /**
  46097. * Number of Simultaneous lights allowed on the material.
  46098. */
  46099. _this.maxSimultaneousLights = 4;
  46100. /**
  46101. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46102. */
  46103. _this.invertNormalMapX = false;
  46104. /**
  46105. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46106. */
  46107. _this.invertNormalMapY = false;
  46108. /**
  46109. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46110. */
  46111. _this.twoSidedLighting = false;
  46112. /**
  46113. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46114. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46115. */
  46116. _this.useAlphaFresnel = false;
  46117. /**
  46118. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46119. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46120. */
  46121. _this.useLinearAlphaFresnel = false;
  46122. /**
  46123. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46124. * And/Or occlude the blended part.
  46125. */
  46126. _this.environmentBRDFTexture = null;
  46127. /**
  46128. * Force normal to face away from face.
  46129. */
  46130. _this.forceNormalForward = false;
  46131. /**
  46132. * Enables specular anti aliasing in the PBR shader.
  46133. * It will both interacts on the Geometry for analytical and IBL lighting.
  46134. * It also prefilter the roughness map based on the bump values.
  46135. */
  46136. _this.enableSpecularAntiAliasing = false;
  46137. /**
  46138. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46139. * makes the reflect vector face the model (under horizon).
  46140. */
  46141. _this.useHorizonOcclusion = true;
  46142. /**
  46143. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46144. * too much the area relying on ambient texture to define their ambient occlusion.
  46145. */
  46146. _this.useRadianceOcclusion = true;
  46147. /**
  46148. * If set to true, no lighting calculations will be applied.
  46149. */
  46150. _this.unlit = false;
  46151. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46152. return _this;
  46153. }
  46154. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46155. /**
  46156. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46157. */
  46158. get: function () {
  46159. return this._PBRMATERIAL_OPAQUE;
  46160. },
  46161. enumerable: true,
  46162. configurable: true
  46163. });
  46164. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46165. /**
  46166. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46167. */
  46168. get: function () {
  46169. return this._PBRMATERIAL_ALPHATEST;
  46170. },
  46171. enumerable: true,
  46172. configurable: true
  46173. });
  46174. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46175. /**
  46176. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46177. */
  46178. get: function () {
  46179. return this._PBRMATERIAL_ALPHABLEND;
  46180. },
  46181. enumerable: true,
  46182. configurable: true
  46183. });
  46184. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46185. /**
  46186. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46187. * They are also discarded below the alpha cutoff threshold to improve performances.
  46188. */
  46189. get: function () {
  46190. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46191. },
  46192. enumerable: true,
  46193. configurable: true
  46194. });
  46195. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46196. /**
  46197. * Gets the image processing configuration used either in this material.
  46198. */
  46199. get: function () {
  46200. return this._imageProcessingConfiguration;
  46201. },
  46202. /**
  46203. * Sets the Default image processing configuration used either in the this material.
  46204. *
  46205. * If sets to null, the scene one is in use.
  46206. */
  46207. set: function (value) {
  46208. this._attachImageProcessingConfiguration(value);
  46209. // Ensure the effect will be rebuilt.
  46210. this._markAllSubMeshesAsTexturesDirty();
  46211. },
  46212. enumerable: true,
  46213. configurable: true
  46214. });
  46215. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46216. /**
  46217. * Gets wether the color curves effect is enabled.
  46218. */
  46219. get: function () {
  46220. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46221. },
  46222. /**
  46223. * Sets wether the color curves effect is enabled.
  46224. */
  46225. set: function (value) {
  46226. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46227. },
  46228. enumerable: true,
  46229. configurable: true
  46230. });
  46231. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46232. /**
  46233. * Gets wether the color grading effect is enabled.
  46234. */
  46235. get: function () {
  46236. return this.imageProcessingConfiguration.colorGradingEnabled;
  46237. },
  46238. /**
  46239. * Gets wether the color grading effect is enabled.
  46240. */
  46241. set: function (value) {
  46242. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46243. },
  46244. enumerable: true,
  46245. configurable: true
  46246. });
  46247. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46248. /**
  46249. * Gets wether tonemapping is enabled or not.
  46250. */
  46251. get: function () {
  46252. return this._imageProcessingConfiguration.toneMappingEnabled;
  46253. },
  46254. /**
  46255. * Sets wether tonemapping is enabled or not
  46256. */
  46257. set: function (value) {
  46258. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46259. },
  46260. enumerable: true,
  46261. configurable: true
  46262. });
  46263. ;
  46264. ;
  46265. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46266. /**
  46267. * The camera exposure used on this material.
  46268. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46269. * This corresponds to a photographic exposure.
  46270. */
  46271. get: function () {
  46272. return this._imageProcessingConfiguration.exposure;
  46273. },
  46274. /**
  46275. * The camera exposure used on this material.
  46276. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46277. * This corresponds to a photographic exposure.
  46278. */
  46279. set: function (value) {
  46280. this._imageProcessingConfiguration.exposure = value;
  46281. },
  46282. enumerable: true,
  46283. configurable: true
  46284. });
  46285. ;
  46286. ;
  46287. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46288. /**
  46289. * Gets The camera contrast used on this material.
  46290. */
  46291. get: function () {
  46292. return this._imageProcessingConfiguration.contrast;
  46293. },
  46294. /**
  46295. * Sets The camera contrast used on this material.
  46296. */
  46297. set: function (value) {
  46298. this._imageProcessingConfiguration.contrast = value;
  46299. },
  46300. enumerable: true,
  46301. configurable: true
  46302. });
  46303. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46304. /**
  46305. * Gets the Color Grading 2D Lookup Texture.
  46306. */
  46307. get: function () {
  46308. return this._imageProcessingConfiguration.colorGradingTexture;
  46309. },
  46310. /**
  46311. * Sets the Color Grading 2D Lookup Texture.
  46312. */
  46313. set: function (value) {
  46314. this._imageProcessingConfiguration.colorGradingTexture = value;
  46315. },
  46316. enumerable: true,
  46317. configurable: true
  46318. });
  46319. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46320. /**
  46321. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46322. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46323. * 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;
  46324. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46325. */
  46326. get: function () {
  46327. return this._imageProcessingConfiguration.colorCurves;
  46328. },
  46329. /**
  46330. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46331. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46332. * 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;
  46333. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46334. */
  46335. set: function (value) {
  46336. this._imageProcessingConfiguration.colorCurves = value;
  46337. },
  46338. enumerable: true,
  46339. configurable: true
  46340. });
  46341. /**
  46342. * Returns the name of this material class.
  46343. */
  46344. PBRMaterial.prototype.getClassName = function () {
  46345. return "PBRMaterial";
  46346. };
  46347. /**
  46348. * Returns an array of the actively used textures.
  46349. * @returns - Array of BaseTextures
  46350. */
  46351. PBRMaterial.prototype.getActiveTextures = function () {
  46352. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46353. if (this._albedoTexture) {
  46354. activeTextures.push(this._albedoTexture);
  46355. }
  46356. if (this._ambientTexture) {
  46357. activeTextures.push(this._ambientTexture);
  46358. }
  46359. if (this._opacityTexture) {
  46360. activeTextures.push(this._opacityTexture);
  46361. }
  46362. if (this._reflectionTexture) {
  46363. activeTextures.push(this._reflectionTexture);
  46364. }
  46365. if (this._emissiveTexture) {
  46366. activeTextures.push(this._emissiveTexture);
  46367. }
  46368. if (this._reflectivityTexture) {
  46369. activeTextures.push(this._reflectivityTexture);
  46370. }
  46371. if (this._metallicTexture) {
  46372. activeTextures.push(this._metallicTexture);
  46373. }
  46374. if (this._microSurfaceTexture) {
  46375. activeTextures.push(this._microSurfaceTexture);
  46376. }
  46377. if (this._bumpTexture) {
  46378. activeTextures.push(this._bumpTexture);
  46379. }
  46380. if (this._lightmapTexture) {
  46381. activeTextures.push(this._lightmapTexture);
  46382. }
  46383. if (this._refractionTexture) {
  46384. activeTextures.push(this._refractionTexture);
  46385. }
  46386. return activeTextures;
  46387. };
  46388. /**
  46389. * Checks to see if a texture is used in the material.
  46390. * @param texture - Base texture to use.
  46391. * @returns - Boolean specifying if a texture is used in the material.
  46392. */
  46393. PBRMaterial.prototype.hasTexture = function (texture) {
  46394. if (_super.prototype.hasTexture.call(this, texture)) {
  46395. return true;
  46396. }
  46397. if (this._albedoTexture === texture) {
  46398. return true;
  46399. }
  46400. if (this._ambientTexture === texture) {
  46401. return true;
  46402. }
  46403. if (this._opacityTexture === texture) {
  46404. return true;
  46405. }
  46406. if (this._reflectionTexture === texture) {
  46407. return true;
  46408. }
  46409. if (this._reflectivityTexture === texture) {
  46410. return true;
  46411. }
  46412. if (this._metallicTexture === texture) {
  46413. return true;
  46414. }
  46415. if (this._microSurfaceTexture === texture) {
  46416. return true;
  46417. }
  46418. if (this._bumpTexture === texture) {
  46419. return true;
  46420. }
  46421. if (this._lightmapTexture === texture) {
  46422. return true;
  46423. }
  46424. if (this._refractionTexture === texture) {
  46425. return true;
  46426. }
  46427. return false;
  46428. };
  46429. /**
  46430. * Makes a duplicate of the current material.
  46431. * @param name - name to use for the new material.
  46432. */
  46433. PBRMaterial.prototype.clone = function (name) {
  46434. var _this = this;
  46435. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46436. clone.id = name;
  46437. clone.name = name;
  46438. return clone;
  46439. };
  46440. /**
  46441. * Serializes this PBR Material.
  46442. * @returns - An object with the serialized material.
  46443. */
  46444. PBRMaterial.prototype.serialize = function () {
  46445. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46446. serializationObject.customType = "BABYLON.PBRMaterial";
  46447. return serializationObject;
  46448. };
  46449. // Statics
  46450. /**
  46451. * Parses a PBR Material from a serialized object.
  46452. * @param source - Serialized object.
  46453. * @param scene - BJS scene instance.
  46454. * @param rootUrl - url for the scene object
  46455. * @returns - PBRMaterial
  46456. */
  46457. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46458. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46459. };
  46460. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46461. /**
  46462. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46463. */
  46464. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46465. /**
  46466. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46467. */
  46468. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46469. /**
  46470. * 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.
  46471. * They are also discarded below the alpha cutoff threshold to improve performances.
  46472. */
  46473. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46474. __decorate([
  46475. BABYLON.serialize(),
  46476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46477. ], PBRMaterial.prototype, "directIntensity", void 0);
  46478. __decorate([
  46479. BABYLON.serialize(),
  46480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46481. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46482. __decorate([
  46483. BABYLON.serialize(),
  46484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46485. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46486. __decorate([
  46487. BABYLON.serialize(),
  46488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46489. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46490. __decorate([
  46491. BABYLON.serialize(),
  46492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46493. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46494. __decorate([
  46495. BABYLON.serializeAsTexture(),
  46496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46497. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46498. __decorate([
  46499. BABYLON.serializeAsTexture(),
  46500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46501. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46502. __decorate([
  46503. BABYLON.serialize(),
  46504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46505. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46506. __decorate([
  46507. BABYLON.serializeAsTexture(),
  46508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46509. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46510. __decorate([
  46511. BABYLON.serializeAsTexture(),
  46512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46513. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46514. __decorate([
  46515. BABYLON.serializeAsTexture(),
  46516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46517. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46518. __decorate([
  46519. BABYLON.serializeAsTexture(),
  46520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46521. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46522. __decorate([
  46523. BABYLON.serializeAsTexture(),
  46524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46525. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46526. __decorate([
  46527. BABYLON.serialize(),
  46528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46529. ], PBRMaterial.prototype, "metallic", void 0);
  46530. __decorate([
  46531. BABYLON.serialize(),
  46532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46533. ], PBRMaterial.prototype, "roughness", void 0);
  46534. __decorate([
  46535. BABYLON.serializeAsTexture(),
  46536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46537. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46538. __decorate([
  46539. BABYLON.serializeAsTexture(),
  46540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46541. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46542. __decorate([
  46543. BABYLON.serializeAsTexture(),
  46544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46545. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46546. __decorate([
  46547. BABYLON.serializeAsTexture(),
  46548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46549. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46550. __decorate([
  46551. BABYLON.serializeAsColor3("ambient"),
  46552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46553. ], PBRMaterial.prototype, "ambientColor", void 0);
  46554. __decorate([
  46555. BABYLON.serializeAsColor3("albedo"),
  46556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46557. ], PBRMaterial.prototype, "albedoColor", void 0);
  46558. __decorate([
  46559. BABYLON.serializeAsColor3("reflectivity"),
  46560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46561. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46562. __decorate([
  46563. BABYLON.serializeAsColor3("reflection"),
  46564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46565. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46566. __decorate([
  46567. BABYLON.serializeAsColor3("emissive"),
  46568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46569. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46570. __decorate([
  46571. BABYLON.serialize(),
  46572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46573. ], PBRMaterial.prototype, "microSurface", void 0);
  46574. __decorate([
  46575. BABYLON.serialize(),
  46576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46577. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46578. __decorate([
  46579. BABYLON.serialize(),
  46580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46581. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46582. __decorate([
  46583. BABYLON.serialize(),
  46584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46585. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46586. __decorate([
  46587. BABYLON.serialize(),
  46588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46589. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46590. __decorate([
  46591. BABYLON.serialize(),
  46592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46593. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46594. __decorate([
  46595. BABYLON.serialize(),
  46596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46597. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46598. __decorate([
  46599. BABYLON.serialize(),
  46600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46601. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46602. __decorate([
  46603. BABYLON.serialize(),
  46604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46605. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46606. __decorate([
  46607. BABYLON.serialize(),
  46608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46609. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46610. __decorate([
  46611. BABYLON.serialize(),
  46612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46613. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46614. __decorate([
  46615. BABYLON.serialize(),
  46616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46617. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46618. __decorate([
  46619. BABYLON.serialize(),
  46620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46621. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46622. __decorate([
  46623. BABYLON.serialize(),
  46624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46625. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46626. __decorate([
  46627. BABYLON.serialize(),
  46628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46629. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46630. __decorate([
  46631. BABYLON.serialize(),
  46632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46633. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46634. __decorate([
  46635. BABYLON.serialize(),
  46636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46637. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46638. __decorate([
  46639. BABYLON.serialize(),
  46640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46641. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46642. __decorate([
  46643. BABYLON.serialize(),
  46644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46645. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46646. __decorate([
  46647. BABYLON.serialize(),
  46648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46649. ], PBRMaterial.prototype, "useParallax", void 0);
  46650. __decorate([
  46651. BABYLON.serialize(),
  46652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46653. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46654. __decorate([
  46655. BABYLON.serialize(),
  46656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46657. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46658. __decorate([
  46659. BABYLON.serialize(),
  46660. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46661. ], PBRMaterial.prototype, "disableLighting", void 0);
  46662. __decorate([
  46663. BABYLON.serialize(),
  46664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46665. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46666. __decorate([
  46667. BABYLON.serialize(),
  46668. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46669. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46670. __decorate([
  46671. BABYLON.serialize(),
  46672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46673. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46674. __decorate([
  46675. BABYLON.serialize(),
  46676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46677. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46678. __decorate([
  46679. BABYLON.serialize(),
  46680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46681. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46682. __decorate([
  46683. BABYLON.serialize(),
  46684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46685. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46686. __decorate([
  46687. BABYLON.serialize(),
  46688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46689. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46690. __decorate([
  46691. BABYLON.serializeAsTexture(),
  46692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46693. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46694. __decorate([
  46695. BABYLON.serialize(),
  46696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46697. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46698. __decorate([
  46699. BABYLON.serialize(),
  46700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46701. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46702. __decorate([
  46703. BABYLON.serialize(),
  46704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46705. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46706. __decorate([
  46707. BABYLON.serialize(),
  46708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46709. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46710. __decorate([
  46711. BABYLON.serialize(),
  46712. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46713. ], PBRMaterial.prototype, "unlit", void 0);
  46714. return PBRMaterial;
  46715. }(BABYLON.PBRBaseMaterial));
  46716. BABYLON.PBRMaterial = PBRMaterial;
  46717. })(BABYLON || (BABYLON = {}));
  46718. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46719. var BABYLON;
  46720. (function (BABYLON) {
  46721. /**
  46722. * The PBR material of BJS following the metal roughness convention.
  46723. *
  46724. * This fits to the PBR convention in the GLTF definition:
  46725. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46726. */
  46727. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46728. __extends(PBRMetallicRoughnessMaterial, _super);
  46729. /**
  46730. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46731. *
  46732. * @param name The material name
  46733. * @param scene The scene the material will be use in.
  46734. */
  46735. function PBRMetallicRoughnessMaterial(name, scene) {
  46736. var _this = _super.call(this, name, scene) || this;
  46737. _this._useRoughnessFromMetallicTextureAlpha = false;
  46738. _this._useRoughnessFromMetallicTextureGreen = true;
  46739. _this._useMetallnessFromMetallicTextureBlue = true;
  46740. _this.metallic = 1.0;
  46741. _this.roughness = 1.0;
  46742. return _this;
  46743. }
  46744. /**
  46745. * Return the currrent class name of the material.
  46746. */
  46747. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46748. return "PBRMetallicRoughnessMaterial";
  46749. };
  46750. /**
  46751. * Return the active textures of the material.
  46752. */
  46753. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46754. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46755. if (this.baseTexture) {
  46756. activeTextures.push(this.baseTexture);
  46757. }
  46758. if (this.metallicRoughnessTexture) {
  46759. activeTextures.push(this.metallicRoughnessTexture);
  46760. }
  46761. return activeTextures;
  46762. };
  46763. /**
  46764. * Checks to see if a texture is used in the material.
  46765. * @param texture - Base texture to use.
  46766. * @returns - Boolean specifying if a texture is used in the material.
  46767. */
  46768. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46769. if (_super.prototype.hasTexture.call(this, texture)) {
  46770. return true;
  46771. }
  46772. if (this.baseTexture === texture) {
  46773. return true;
  46774. }
  46775. if (this.metallicRoughnessTexture === texture) {
  46776. return true;
  46777. }
  46778. return false;
  46779. };
  46780. /**
  46781. * Makes a duplicate of the current material.
  46782. * @param name - name to use for the new material.
  46783. */
  46784. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46785. var _this = this;
  46786. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46787. clone.id = name;
  46788. clone.name = name;
  46789. return clone;
  46790. };
  46791. /**
  46792. * Serialize the material to a parsable JSON object.
  46793. */
  46794. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46795. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46796. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46797. return serializationObject;
  46798. };
  46799. /**
  46800. * Parses a JSON object correponding to the serialize function.
  46801. */
  46802. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46803. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46804. };
  46805. __decorate([
  46806. BABYLON.serializeAsColor3(),
  46807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46808. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46809. __decorate([
  46810. BABYLON.serializeAsTexture(),
  46811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46812. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46813. __decorate([
  46814. BABYLON.serialize(),
  46815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46816. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46817. __decorate([
  46818. BABYLON.serialize(),
  46819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46820. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46821. __decorate([
  46822. BABYLON.serializeAsTexture(),
  46823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46824. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46825. return PBRMetallicRoughnessMaterial;
  46826. }(BABYLON.PBRBaseSimpleMaterial));
  46827. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46828. })(BABYLON || (BABYLON = {}));
  46829. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46830. var BABYLON;
  46831. (function (BABYLON) {
  46832. /**
  46833. * The PBR material of BJS following the specular glossiness convention.
  46834. *
  46835. * This fits to the PBR convention in the GLTF definition:
  46836. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46837. */
  46838. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46839. __extends(PBRSpecularGlossinessMaterial, _super);
  46840. /**
  46841. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46842. *
  46843. * @param name The material name
  46844. * @param scene The scene the material will be use in.
  46845. */
  46846. function PBRSpecularGlossinessMaterial(name, scene) {
  46847. var _this = _super.call(this, name, scene) || this;
  46848. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46849. return _this;
  46850. }
  46851. /**
  46852. * Return the currrent class name of the material.
  46853. */
  46854. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46855. return "PBRSpecularGlossinessMaterial";
  46856. };
  46857. /**
  46858. * Return the active textures of the material.
  46859. */
  46860. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46861. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46862. if (this.diffuseTexture) {
  46863. activeTextures.push(this.diffuseTexture);
  46864. }
  46865. if (this.specularGlossinessTexture) {
  46866. activeTextures.push(this.specularGlossinessTexture);
  46867. }
  46868. return activeTextures;
  46869. };
  46870. /**
  46871. * Checks to see if a texture is used in the material.
  46872. * @param texture - Base texture to use.
  46873. * @returns - Boolean specifying if a texture is used in the material.
  46874. */
  46875. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46876. if (_super.prototype.hasTexture.call(this, texture)) {
  46877. return true;
  46878. }
  46879. if (this.diffuseTexture === texture) {
  46880. return true;
  46881. }
  46882. if (this.specularGlossinessTexture === texture) {
  46883. return true;
  46884. }
  46885. return false;
  46886. };
  46887. /**
  46888. * Makes a duplicate of the current material.
  46889. * @param name - name to use for the new material.
  46890. */
  46891. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46892. var _this = this;
  46893. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46894. clone.id = name;
  46895. clone.name = name;
  46896. return clone;
  46897. };
  46898. /**
  46899. * Serialize the material to a parsable JSON object.
  46900. */
  46901. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46902. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46903. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46904. return serializationObject;
  46905. };
  46906. /**
  46907. * Parses a JSON object correponding to the serialize function.
  46908. */
  46909. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46910. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46911. };
  46912. __decorate([
  46913. BABYLON.serializeAsColor3("diffuse"),
  46914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46915. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46916. __decorate([
  46917. BABYLON.serializeAsTexture(),
  46918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46919. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46920. __decorate([
  46921. BABYLON.serializeAsColor3("specular"),
  46922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46923. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46924. __decorate([
  46925. BABYLON.serialize(),
  46926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46927. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46928. __decorate([
  46929. BABYLON.serializeAsTexture(),
  46930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46931. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46932. return PBRSpecularGlossinessMaterial;
  46933. }(BABYLON.PBRBaseSimpleMaterial));
  46934. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46935. })(BABYLON || (BABYLON = {}));
  46936. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46937. var BABYLON;
  46938. (function (BABYLON) {
  46939. BABYLON.CameraInputTypes = {};
  46940. var CameraInputsManager = /** @class */ (function () {
  46941. function CameraInputsManager(camera) {
  46942. this.attached = {};
  46943. this.camera = camera;
  46944. this.checkInputs = function () { };
  46945. }
  46946. /**
  46947. * Add an input method to a camera.
  46948. * builtin inputs example: camera.inputs.addGamepad();
  46949. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46950. * @param input camera input method
  46951. */
  46952. CameraInputsManager.prototype.add = function (input) {
  46953. var type = input.getSimpleName();
  46954. if (this.attached[type]) {
  46955. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46956. return;
  46957. }
  46958. this.attached[type] = input;
  46959. input.camera = this.camera;
  46960. //for checkInputs, we are dynamically creating a function
  46961. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46962. if (input.checkInputs) {
  46963. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46964. }
  46965. if (this.attachedElement) {
  46966. input.attachControl(this.attachedElement);
  46967. }
  46968. };
  46969. /**
  46970. * Remove a specific input method from a camera
  46971. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46972. * @param inputToRemove camera input method
  46973. */
  46974. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46975. for (var cam in this.attached) {
  46976. var input = this.attached[cam];
  46977. if (input === inputToRemove) {
  46978. input.detachControl(this.attachedElement);
  46979. input.camera = null;
  46980. delete this.attached[cam];
  46981. this.rebuildInputCheck();
  46982. }
  46983. }
  46984. };
  46985. CameraInputsManager.prototype.removeByType = function (inputType) {
  46986. for (var cam in this.attached) {
  46987. var input = this.attached[cam];
  46988. if (input.getClassName() === inputType) {
  46989. input.detachControl(this.attachedElement);
  46990. input.camera = null;
  46991. delete this.attached[cam];
  46992. this.rebuildInputCheck();
  46993. }
  46994. }
  46995. };
  46996. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46997. var current = this.checkInputs;
  46998. return function () {
  46999. current();
  47000. fn();
  47001. };
  47002. };
  47003. CameraInputsManager.prototype.attachInput = function (input) {
  47004. if (this.attachedElement) {
  47005. input.attachControl(this.attachedElement, this.noPreventDefault);
  47006. }
  47007. };
  47008. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47009. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47010. if (this.attachedElement) {
  47011. return;
  47012. }
  47013. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47014. this.attachedElement = element;
  47015. this.noPreventDefault = noPreventDefault;
  47016. for (var cam in this.attached) {
  47017. this.attached[cam].attachControl(element, noPreventDefault);
  47018. }
  47019. };
  47020. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47021. if (disconnect === void 0) { disconnect = false; }
  47022. if (this.attachedElement !== element) {
  47023. return;
  47024. }
  47025. for (var cam in this.attached) {
  47026. this.attached[cam].detachControl(element);
  47027. if (disconnect) {
  47028. this.attached[cam].camera = null;
  47029. }
  47030. }
  47031. this.attachedElement = null;
  47032. };
  47033. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47034. this.checkInputs = function () { };
  47035. for (var cam in this.attached) {
  47036. var input = this.attached[cam];
  47037. if (input.checkInputs) {
  47038. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47039. }
  47040. }
  47041. };
  47042. /**
  47043. * Remove all attached input methods from a camera
  47044. */
  47045. CameraInputsManager.prototype.clear = function () {
  47046. if (this.attachedElement) {
  47047. this.detachElement(this.attachedElement, true);
  47048. }
  47049. this.attached = {};
  47050. this.attachedElement = null;
  47051. this.checkInputs = function () { };
  47052. };
  47053. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47054. var inputs = {};
  47055. for (var cam in this.attached) {
  47056. var input = this.attached[cam];
  47057. var res = BABYLON.SerializationHelper.Serialize(input);
  47058. inputs[input.getClassName()] = res;
  47059. }
  47060. serializedCamera.inputsmgr = inputs;
  47061. };
  47062. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47063. var parsedInputs = parsedCamera.inputsmgr;
  47064. if (parsedInputs) {
  47065. this.clear();
  47066. for (var n in parsedInputs) {
  47067. var construct = BABYLON.CameraInputTypes[n];
  47068. if (construct) {
  47069. var parsedinput = parsedInputs[n];
  47070. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47071. this.add(input);
  47072. }
  47073. }
  47074. }
  47075. else {
  47076. //2016-03-08 this part is for managing backward compatibility
  47077. for (var n in this.attached) {
  47078. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47079. if (construct) {
  47080. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47081. this.remove(this.attached[n]);
  47082. this.add(input);
  47083. }
  47084. }
  47085. }
  47086. };
  47087. return CameraInputsManager;
  47088. }());
  47089. BABYLON.CameraInputsManager = CameraInputsManager;
  47090. })(BABYLON || (BABYLON = {}));
  47091. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47092. var BABYLON;
  47093. (function (BABYLON) {
  47094. var TargetCamera = /** @class */ (function (_super) {
  47095. __extends(TargetCamera, _super);
  47096. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47097. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47098. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47099. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47100. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47101. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47102. _this.speed = 2.0;
  47103. _this.noRotationConstraint = false;
  47104. _this.lockedTarget = null;
  47105. _this._currentTarget = BABYLON.Vector3.Zero();
  47106. _this._viewMatrix = BABYLON.Matrix.Zero();
  47107. _this._camMatrix = BABYLON.Matrix.Zero();
  47108. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47109. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47110. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47111. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47112. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47113. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47114. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47115. return _this;
  47116. }
  47117. TargetCamera.prototype.getFrontPosition = function (distance) {
  47118. this.getWorldMatrix();
  47119. var direction = this.getTarget().subtract(this.position);
  47120. direction.normalize();
  47121. direction.scaleInPlace(distance);
  47122. return this.globalPosition.add(direction);
  47123. };
  47124. TargetCamera.prototype._getLockedTargetPosition = function () {
  47125. if (!this.lockedTarget) {
  47126. return null;
  47127. }
  47128. if (this.lockedTarget.absolutePosition) {
  47129. this.lockedTarget.computeWorldMatrix();
  47130. }
  47131. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47132. };
  47133. TargetCamera.prototype.storeState = function () {
  47134. this._storedPosition = this.position.clone();
  47135. this._storedRotation = this.rotation.clone();
  47136. if (this.rotationQuaternion) {
  47137. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47138. }
  47139. return _super.prototype.storeState.call(this);
  47140. };
  47141. /**
  47142. * Restored camera state. You must call storeState() first
  47143. */
  47144. TargetCamera.prototype._restoreStateValues = function () {
  47145. if (!_super.prototype._restoreStateValues.call(this)) {
  47146. return false;
  47147. }
  47148. this.position = this._storedPosition.clone();
  47149. this.rotation = this._storedRotation.clone();
  47150. if (this.rotationQuaternion) {
  47151. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47152. }
  47153. this.cameraDirection.copyFromFloats(0, 0, 0);
  47154. this.cameraRotation.copyFromFloats(0, 0);
  47155. return true;
  47156. };
  47157. // Cache
  47158. TargetCamera.prototype._initCache = function () {
  47159. _super.prototype._initCache.call(this);
  47160. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47161. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47162. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47163. };
  47164. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47165. if (!ignoreParentClass) {
  47166. _super.prototype._updateCache.call(this);
  47167. }
  47168. var lockedTargetPosition = this._getLockedTargetPosition();
  47169. if (!lockedTargetPosition) {
  47170. this._cache.lockedTarget = null;
  47171. }
  47172. else {
  47173. if (!this._cache.lockedTarget) {
  47174. this._cache.lockedTarget = lockedTargetPosition.clone();
  47175. }
  47176. else {
  47177. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47178. }
  47179. }
  47180. this._cache.rotation.copyFrom(this.rotation);
  47181. if (this.rotationQuaternion)
  47182. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47183. };
  47184. // Synchronized
  47185. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47186. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47187. return false;
  47188. }
  47189. var lockedTargetPosition = this._getLockedTargetPosition();
  47190. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47191. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47192. };
  47193. // Methods
  47194. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47195. var engine = this.getEngine();
  47196. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47197. };
  47198. // Target
  47199. TargetCamera.prototype.setTarget = function (target) {
  47200. this.upVector.normalize();
  47201. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47202. this._camMatrix.invert();
  47203. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47204. var vDir = target.subtract(this.position);
  47205. if (vDir.x >= 0.0) {
  47206. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47207. }
  47208. else {
  47209. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47210. }
  47211. this.rotation.z = 0;
  47212. if (isNaN(this.rotation.x)) {
  47213. this.rotation.x = 0;
  47214. }
  47215. if (isNaN(this.rotation.y)) {
  47216. this.rotation.y = 0;
  47217. }
  47218. if (isNaN(this.rotation.z)) {
  47219. this.rotation.z = 0;
  47220. }
  47221. if (this.rotationQuaternion) {
  47222. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47223. }
  47224. };
  47225. /**
  47226. * Return the current target position of the camera. This value is expressed in local space.
  47227. */
  47228. TargetCamera.prototype.getTarget = function () {
  47229. return this._currentTarget;
  47230. };
  47231. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47232. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47233. };
  47234. TargetCamera.prototype._updatePosition = function () {
  47235. if (this.parent) {
  47236. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47237. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47238. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47239. return;
  47240. }
  47241. this.position.addInPlace(this.cameraDirection);
  47242. };
  47243. TargetCamera.prototype._checkInputs = function () {
  47244. var needToMove = this._decideIfNeedsToMove();
  47245. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47246. // Move
  47247. if (needToMove) {
  47248. this._updatePosition();
  47249. }
  47250. // Rotate
  47251. if (needToRotate) {
  47252. this.rotation.x += this.cameraRotation.x;
  47253. this.rotation.y += this.cameraRotation.y;
  47254. //rotate, if quaternion is set and rotation was used
  47255. if (this.rotationQuaternion) {
  47256. var len = this.rotation.lengthSquared();
  47257. if (len) {
  47258. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47259. }
  47260. }
  47261. if (!this.noRotationConstraint) {
  47262. var limit = (Math.PI / 2) * 0.95;
  47263. if (this.rotation.x > limit)
  47264. this.rotation.x = limit;
  47265. if (this.rotation.x < -limit)
  47266. this.rotation.x = -limit;
  47267. }
  47268. }
  47269. // Inertia
  47270. if (needToMove) {
  47271. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47272. this.cameraDirection.x = 0;
  47273. }
  47274. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47275. this.cameraDirection.y = 0;
  47276. }
  47277. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47278. this.cameraDirection.z = 0;
  47279. }
  47280. this.cameraDirection.scaleInPlace(this.inertia);
  47281. }
  47282. if (needToRotate) {
  47283. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47284. this.cameraRotation.x = 0;
  47285. }
  47286. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47287. this.cameraRotation.y = 0;
  47288. }
  47289. this.cameraRotation.scaleInPlace(this.inertia);
  47290. }
  47291. _super.prototype._checkInputs.call(this);
  47292. };
  47293. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47294. if (this.rotationQuaternion) {
  47295. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47296. }
  47297. else {
  47298. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47299. }
  47300. //update the up vector!
  47301. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47302. };
  47303. TargetCamera.prototype._getViewMatrix = function () {
  47304. if (this.lockedTarget) {
  47305. this.setTarget(this._getLockedTargetPosition());
  47306. }
  47307. // Compute
  47308. this._updateCameraRotationMatrix();
  47309. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47310. // Computing target and final matrix
  47311. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47312. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47313. return this._viewMatrix;
  47314. };
  47315. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47316. if (this.parent) {
  47317. var parentWorldMatrix = this.parent.getWorldMatrix();
  47318. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47319. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47320. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47321. this._markSyncedWithParent();
  47322. }
  47323. else {
  47324. this._globalPosition.copyFrom(this.position);
  47325. this._globalCurrentTarget.copyFrom(target);
  47326. this._globalCurrentUpVector.copyFrom(up);
  47327. }
  47328. if (this.getScene().useRightHandedSystem) {
  47329. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47330. }
  47331. else {
  47332. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47333. }
  47334. };
  47335. /**
  47336. * @override
  47337. * Override Camera.createRigCamera
  47338. */
  47339. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47340. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47341. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47342. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47343. if (!this.rotationQuaternion) {
  47344. this.rotationQuaternion = new BABYLON.Quaternion();
  47345. }
  47346. rigCamera._cameraRigParams = {};
  47347. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47348. }
  47349. return rigCamera;
  47350. }
  47351. return null;
  47352. };
  47353. /**
  47354. * @override
  47355. * Override Camera._updateRigCameras
  47356. */
  47357. TargetCamera.prototype._updateRigCameras = function () {
  47358. var camLeft = this._rigCameras[0];
  47359. var camRight = this._rigCameras[1];
  47360. switch (this.cameraRigMode) {
  47361. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47362. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47363. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47364. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47365. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47366. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47367. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47368. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47369. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47370. camLeft.setTarget(this.getTarget());
  47371. camRight.setTarget(this.getTarget());
  47372. break;
  47373. case BABYLON.Camera.RIG_MODE_VR:
  47374. if (camLeft.rotationQuaternion) {
  47375. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47376. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47377. }
  47378. else {
  47379. camLeft.rotation.copyFrom(this.rotation);
  47380. camRight.rotation.copyFrom(this.rotation);
  47381. }
  47382. camLeft.position.copyFrom(this.position);
  47383. camRight.position.copyFrom(this.position);
  47384. break;
  47385. }
  47386. _super.prototype._updateRigCameras.call(this);
  47387. };
  47388. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47389. if (!this._rigCamTransformMatrix) {
  47390. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47391. }
  47392. var target = this.getTarget();
  47393. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47394. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47395. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47396. };
  47397. TargetCamera.prototype.getClassName = function () {
  47398. return "TargetCamera";
  47399. };
  47400. __decorate([
  47401. BABYLON.serializeAsVector3()
  47402. ], TargetCamera.prototype, "rotation", void 0);
  47403. __decorate([
  47404. BABYLON.serialize()
  47405. ], TargetCamera.prototype, "speed", void 0);
  47406. __decorate([
  47407. BABYLON.serializeAsMeshReference("lockedTargetId")
  47408. ], TargetCamera.prototype, "lockedTarget", void 0);
  47409. return TargetCamera;
  47410. }(BABYLON.Camera));
  47411. BABYLON.TargetCamera = TargetCamera;
  47412. })(BABYLON || (BABYLON = {}));
  47413. //# sourceMappingURL=babylon.targetCamera.js.map
  47414. var BABYLON;
  47415. (function (BABYLON) {
  47416. var FreeCameraMouseInput = /** @class */ (function () {
  47417. function FreeCameraMouseInput(touchEnabled) {
  47418. if (touchEnabled === void 0) { touchEnabled = true; }
  47419. this.touchEnabled = touchEnabled;
  47420. this.buttons = [0, 1, 2];
  47421. this.angularSensibility = 2000.0;
  47422. this.previousPosition = null;
  47423. }
  47424. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47425. var _this = this;
  47426. var engine = this.camera.getEngine();
  47427. if (!this._pointerInput) {
  47428. this._pointerInput = function (p, s) {
  47429. var evt = p.event;
  47430. if (engine.isInVRExclusivePointerMode) {
  47431. return;
  47432. }
  47433. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47434. return;
  47435. }
  47436. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47437. return;
  47438. }
  47439. var srcElement = (evt.srcElement || evt.target);
  47440. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47441. try {
  47442. srcElement.setPointerCapture(evt.pointerId);
  47443. }
  47444. catch (e) {
  47445. //Nothing to do with the error. Execution will continue.
  47446. }
  47447. _this.previousPosition = {
  47448. x: evt.clientX,
  47449. y: evt.clientY
  47450. };
  47451. if (!noPreventDefault) {
  47452. evt.preventDefault();
  47453. element.focus();
  47454. }
  47455. }
  47456. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47457. try {
  47458. srcElement.releasePointerCapture(evt.pointerId);
  47459. }
  47460. catch (e) {
  47461. //Nothing to do with the error.
  47462. }
  47463. _this.previousPosition = null;
  47464. if (!noPreventDefault) {
  47465. evt.preventDefault();
  47466. }
  47467. }
  47468. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47469. if (!_this.previousPosition || engine.isPointerLock) {
  47470. return;
  47471. }
  47472. var offsetX = evt.clientX - _this.previousPosition.x;
  47473. if (_this.camera.getScene().useRightHandedSystem)
  47474. offsetX *= -1;
  47475. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47476. offsetX *= -1;
  47477. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47478. var offsetY = evt.clientY - _this.previousPosition.y;
  47479. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47480. _this.previousPosition = {
  47481. x: evt.clientX,
  47482. y: evt.clientY
  47483. };
  47484. if (!noPreventDefault) {
  47485. evt.preventDefault();
  47486. }
  47487. }
  47488. };
  47489. }
  47490. this._onMouseMove = function (evt) {
  47491. if (!engine.isPointerLock) {
  47492. return;
  47493. }
  47494. if (engine.isInVRExclusivePointerMode) {
  47495. return;
  47496. }
  47497. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47498. if (_this.camera.getScene().useRightHandedSystem)
  47499. offsetX *= -1;
  47500. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47501. offsetX *= -1;
  47502. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47503. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47504. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47505. _this.previousPosition = null;
  47506. if (!noPreventDefault) {
  47507. evt.preventDefault();
  47508. }
  47509. };
  47510. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47511. element.addEventListener("mousemove", this._onMouseMove, false);
  47512. };
  47513. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47514. if (this._observer && element) {
  47515. this.camera.getScene().onPointerObservable.remove(this._observer);
  47516. if (this._onMouseMove) {
  47517. element.removeEventListener("mousemove", this._onMouseMove);
  47518. }
  47519. this._observer = null;
  47520. this._onMouseMove = null;
  47521. this.previousPosition = null;
  47522. }
  47523. };
  47524. FreeCameraMouseInput.prototype.getClassName = function () {
  47525. return "FreeCameraMouseInput";
  47526. };
  47527. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47528. return "mouse";
  47529. };
  47530. __decorate([
  47531. BABYLON.serialize()
  47532. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47533. __decorate([
  47534. BABYLON.serialize()
  47535. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47536. return FreeCameraMouseInput;
  47537. }());
  47538. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47539. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47540. })(BABYLON || (BABYLON = {}));
  47541. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47542. var BABYLON;
  47543. (function (BABYLON) {
  47544. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47545. function FreeCameraKeyboardMoveInput() {
  47546. this._keys = new Array();
  47547. this.keysUp = [38];
  47548. this.keysDown = [40];
  47549. this.keysLeft = [37];
  47550. this.keysRight = [39];
  47551. }
  47552. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47553. var _this = this;
  47554. if (this._onCanvasBlurObserver) {
  47555. return;
  47556. }
  47557. this._scene = this.camera.getScene();
  47558. this._engine = this._scene.getEngine();
  47559. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47560. _this._keys = [];
  47561. });
  47562. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47563. var evt = info.event;
  47564. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47565. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47566. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47567. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47568. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47569. var index = _this._keys.indexOf(evt.keyCode);
  47570. if (index === -1) {
  47571. _this._keys.push(evt.keyCode);
  47572. }
  47573. if (!noPreventDefault) {
  47574. evt.preventDefault();
  47575. }
  47576. }
  47577. }
  47578. else {
  47579. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47580. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47581. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47582. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47583. var index = _this._keys.indexOf(evt.keyCode);
  47584. if (index >= 0) {
  47585. _this._keys.splice(index, 1);
  47586. }
  47587. if (!noPreventDefault) {
  47588. evt.preventDefault();
  47589. }
  47590. }
  47591. }
  47592. });
  47593. };
  47594. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47595. if (this._scene) {
  47596. if (this._onKeyboardObserver) {
  47597. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47598. }
  47599. if (this._onCanvasBlurObserver) {
  47600. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47601. }
  47602. this._onKeyboardObserver = null;
  47603. this._onCanvasBlurObserver = null;
  47604. }
  47605. this._keys = [];
  47606. };
  47607. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47608. if (this._onKeyboardObserver) {
  47609. var camera = this.camera;
  47610. // Keyboard
  47611. for (var index = 0; index < this._keys.length; index++) {
  47612. var keyCode = this._keys[index];
  47613. var speed = camera._computeLocalCameraSpeed();
  47614. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47615. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47616. }
  47617. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47618. camera._localDirection.copyFromFloats(0, 0, speed);
  47619. }
  47620. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47621. camera._localDirection.copyFromFloats(speed, 0, 0);
  47622. }
  47623. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47624. camera._localDirection.copyFromFloats(0, 0, -speed);
  47625. }
  47626. if (camera.getScene().useRightHandedSystem) {
  47627. camera._localDirection.z *= -1;
  47628. }
  47629. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47630. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47631. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47632. }
  47633. }
  47634. };
  47635. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47636. return "FreeCameraKeyboardMoveInput";
  47637. };
  47638. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47639. this._keys = [];
  47640. };
  47641. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47642. return "keyboard";
  47643. };
  47644. __decorate([
  47645. BABYLON.serialize()
  47646. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47647. __decorate([
  47648. BABYLON.serialize()
  47649. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47650. __decorate([
  47651. BABYLON.serialize()
  47652. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47653. __decorate([
  47654. BABYLON.serialize()
  47655. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47656. return FreeCameraKeyboardMoveInput;
  47657. }());
  47658. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47659. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47660. })(BABYLON || (BABYLON = {}));
  47661. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47662. var BABYLON;
  47663. (function (BABYLON) {
  47664. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47665. __extends(FreeCameraInputsManager, _super);
  47666. function FreeCameraInputsManager(camera) {
  47667. return _super.call(this, camera) || this;
  47668. }
  47669. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47670. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47671. return this;
  47672. };
  47673. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47674. if (touchEnabled === void 0) { touchEnabled = true; }
  47675. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47676. return this;
  47677. };
  47678. FreeCameraInputsManager.prototype.addGamepad = function () {
  47679. this.add(new BABYLON.FreeCameraGamepadInput());
  47680. return this;
  47681. };
  47682. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47683. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47684. return this;
  47685. };
  47686. FreeCameraInputsManager.prototype.addTouch = function () {
  47687. this.add(new BABYLON.FreeCameraTouchInput());
  47688. return this;
  47689. };
  47690. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47691. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47692. return this;
  47693. };
  47694. return FreeCameraInputsManager;
  47695. }(BABYLON.CameraInputsManager));
  47696. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47697. })(BABYLON || (BABYLON = {}));
  47698. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47699. var BABYLON;
  47700. (function (BABYLON) {
  47701. var FreeCamera = /** @class */ (function (_super) {
  47702. __extends(FreeCamera, _super);
  47703. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47704. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47705. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47706. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47707. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47708. _this.checkCollisions = false;
  47709. _this.applyGravity = false;
  47710. _this._needMoveForGravity = false;
  47711. _this._oldPosition = BABYLON.Vector3.Zero();
  47712. _this._diffPosition = BABYLON.Vector3.Zero();
  47713. _this._newPosition = BABYLON.Vector3.Zero();
  47714. // Collisions
  47715. _this._collisionMask = -1;
  47716. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47717. if (collidedMesh === void 0) { collidedMesh = null; }
  47718. //TODO move this to the collision coordinator!
  47719. if (_this.getScene().workerCollisions)
  47720. newPosition.multiplyInPlace(_this._collider._radius);
  47721. var updatePosition = function (newPos) {
  47722. _this._newPosition.copyFrom(newPos);
  47723. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47724. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47725. _this.position.addInPlace(_this._diffPosition);
  47726. if (_this.onCollide && collidedMesh) {
  47727. _this.onCollide(collidedMesh);
  47728. }
  47729. }
  47730. };
  47731. updatePosition(newPosition);
  47732. };
  47733. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47734. _this.inputs.addKeyboard().addMouse();
  47735. return _this;
  47736. }
  47737. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47738. //-- begin properties for backward compatibility for inputs
  47739. /**
  47740. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47741. * Higher values reduce sensitivity.
  47742. */
  47743. get: function () {
  47744. var mouse = this.inputs.attached["mouse"];
  47745. if (mouse)
  47746. return mouse.angularSensibility;
  47747. return 0;
  47748. },
  47749. /**
  47750. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47751. * Higher values reduce sensitivity.
  47752. */
  47753. set: function (value) {
  47754. var mouse = this.inputs.attached["mouse"];
  47755. if (mouse)
  47756. mouse.angularSensibility = value;
  47757. },
  47758. enumerable: true,
  47759. configurable: true
  47760. });
  47761. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47762. get: function () {
  47763. var keyboard = this.inputs.attached["keyboard"];
  47764. if (keyboard)
  47765. return keyboard.keysUp;
  47766. return [];
  47767. },
  47768. set: function (value) {
  47769. var keyboard = this.inputs.attached["keyboard"];
  47770. if (keyboard)
  47771. keyboard.keysUp = value;
  47772. },
  47773. enumerable: true,
  47774. configurable: true
  47775. });
  47776. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47777. get: function () {
  47778. var keyboard = this.inputs.attached["keyboard"];
  47779. if (keyboard)
  47780. return keyboard.keysDown;
  47781. return [];
  47782. },
  47783. set: function (value) {
  47784. var keyboard = this.inputs.attached["keyboard"];
  47785. if (keyboard)
  47786. keyboard.keysDown = value;
  47787. },
  47788. enumerable: true,
  47789. configurable: true
  47790. });
  47791. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47792. get: function () {
  47793. var keyboard = this.inputs.attached["keyboard"];
  47794. if (keyboard)
  47795. return keyboard.keysLeft;
  47796. return [];
  47797. },
  47798. set: function (value) {
  47799. var keyboard = this.inputs.attached["keyboard"];
  47800. if (keyboard)
  47801. keyboard.keysLeft = value;
  47802. },
  47803. enumerable: true,
  47804. configurable: true
  47805. });
  47806. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47807. get: function () {
  47808. var keyboard = this.inputs.attached["keyboard"];
  47809. if (keyboard)
  47810. return keyboard.keysRight;
  47811. return [];
  47812. },
  47813. set: function (value) {
  47814. var keyboard = this.inputs.attached["keyboard"];
  47815. if (keyboard)
  47816. keyboard.keysRight = value;
  47817. },
  47818. enumerable: true,
  47819. configurable: true
  47820. });
  47821. // Controls
  47822. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47823. this.inputs.attachElement(element, noPreventDefault);
  47824. };
  47825. FreeCamera.prototype.detachControl = function (element) {
  47826. this.inputs.detachElement(element);
  47827. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47828. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47829. };
  47830. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47831. get: function () {
  47832. return this._collisionMask;
  47833. },
  47834. set: function (mask) {
  47835. this._collisionMask = !isNaN(mask) ? mask : -1;
  47836. },
  47837. enumerable: true,
  47838. configurable: true
  47839. });
  47840. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47841. var globalPosition;
  47842. if (this.parent) {
  47843. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47844. }
  47845. else {
  47846. globalPosition = this.position;
  47847. }
  47848. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47849. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47850. if (!this._collider) {
  47851. this._collider = new BABYLON.Collider();
  47852. }
  47853. this._collider._radius = this.ellipsoid;
  47854. this._collider.collisionMask = this._collisionMask;
  47855. //no need for clone, as long as gravity is not on.
  47856. var actualDisplacement = displacement;
  47857. //add gravity to the direction to prevent the dual-collision checking
  47858. if (this.applyGravity) {
  47859. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47860. actualDisplacement = displacement.add(this.getScene().gravity);
  47861. }
  47862. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47863. };
  47864. FreeCamera.prototype._checkInputs = function () {
  47865. if (!this._localDirection) {
  47866. this._localDirection = BABYLON.Vector3.Zero();
  47867. this._transformedDirection = BABYLON.Vector3.Zero();
  47868. }
  47869. this.inputs.checkInputs();
  47870. _super.prototype._checkInputs.call(this);
  47871. };
  47872. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47873. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47874. };
  47875. FreeCamera.prototype._updatePosition = function () {
  47876. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47877. this._collideWithWorld(this.cameraDirection);
  47878. }
  47879. else {
  47880. _super.prototype._updatePosition.call(this);
  47881. }
  47882. };
  47883. FreeCamera.prototype.dispose = function () {
  47884. this.inputs.clear();
  47885. _super.prototype.dispose.call(this);
  47886. };
  47887. FreeCamera.prototype.getClassName = function () {
  47888. return "FreeCamera";
  47889. };
  47890. __decorate([
  47891. BABYLON.serializeAsVector3()
  47892. ], FreeCamera.prototype, "ellipsoid", void 0);
  47893. __decorate([
  47894. BABYLON.serializeAsVector3()
  47895. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47896. __decorate([
  47897. BABYLON.serialize()
  47898. ], FreeCamera.prototype, "checkCollisions", void 0);
  47899. __decorate([
  47900. BABYLON.serialize()
  47901. ], FreeCamera.prototype, "applyGravity", void 0);
  47902. return FreeCamera;
  47903. }(BABYLON.TargetCamera));
  47904. BABYLON.FreeCamera = FreeCamera;
  47905. })(BABYLON || (BABYLON = {}));
  47906. //# sourceMappingURL=babylon.freeCamera.js.map
  47907. var BABYLON;
  47908. (function (BABYLON) {
  47909. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47910. function ArcRotateCameraKeyboardMoveInput() {
  47911. this._keys = new Array();
  47912. this.keysUp = [38];
  47913. this.keysDown = [40];
  47914. this.keysLeft = [37];
  47915. this.keysRight = [39];
  47916. this.keysReset = [220];
  47917. this.panningSensibility = 50.0;
  47918. this.zoomingSensibility = 25.0;
  47919. this.useAltToZoom = true;
  47920. }
  47921. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47922. var _this = this;
  47923. if (this._onCanvasBlurObserver) {
  47924. return;
  47925. }
  47926. this._scene = this.camera.getScene();
  47927. this._engine = this._scene.getEngine();
  47928. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47929. _this._keys = [];
  47930. });
  47931. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47932. var evt = info.event;
  47933. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47934. _this._ctrlPressed = evt.ctrlKey;
  47935. _this._altPressed = evt.altKey;
  47936. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47937. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47938. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47939. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47940. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47941. var index = _this._keys.indexOf(evt.keyCode);
  47942. if (index === -1) {
  47943. _this._keys.push(evt.keyCode);
  47944. }
  47945. if (evt.preventDefault) {
  47946. if (!noPreventDefault) {
  47947. evt.preventDefault();
  47948. }
  47949. }
  47950. }
  47951. }
  47952. else {
  47953. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47954. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47955. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47956. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47957. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47958. var index = _this._keys.indexOf(evt.keyCode);
  47959. if (index >= 0) {
  47960. _this._keys.splice(index, 1);
  47961. }
  47962. if (evt.preventDefault) {
  47963. if (!noPreventDefault) {
  47964. evt.preventDefault();
  47965. }
  47966. }
  47967. }
  47968. }
  47969. });
  47970. };
  47971. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47972. if (this._scene) {
  47973. if (this._onKeyboardObserver) {
  47974. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47975. }
  47976. if (this._onCanvasBlurObserver) {
  47977. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47978. }
  47979. this._onKeyboardObserver = null;
  47980. this._onCanvasBlurObserver = null;
  47981. }
  47982. this._keys = [];
  47983. };
  47984. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47985. if (this._onKeyboardObserver) {
  47986. var camera = this.camera;
  47987. for (var index = 0; index < this._keys.length; index++) {
  47988. var keyCode = this._keys[index];
  47989. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47990. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47991. camera.inertialPanningX -= 1 / this.panningSensibility;
  47992. }
  47993. else {
  47994. camera.inertialAlphaOffset -= 0.01;
  47995. }
  47996. }
  47997. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47998. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47999. camera.inertialPanningY += 1 / this.panningSensibility;
  48000. }
  48001. else if (this._altPressed && this.useAltToZoom) {
  48002. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48003. }
  48004. else {
  48005. camera.inertialBetaOffset -= 0.01;
  48006. }
  48007. }
  48008. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48009. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48010. camera.inertialPanningX += 1 / this.panningSensibility;
  48011. }
  48012. else {
  48013. camera.inertialAlphaOffset += 0.01;
  48014. }
  48015. }
  48016. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48017. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48018. camera.inertialPanningY -= 1 / this.panningSensibility;
  48019. }
  48020. else if (this._altPressed && this.useAltToZoom) {
  48021. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48022. }
  48023. else {
  48024. camera.inertialBetaOffset += 0.01;
  48025. }
  48026. }
  48027. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48028. camera.restoreState();
  48029. }
  48030. }
  48031. }
  48032. };
  48033. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48034. return "ArcRotateCameraKeyboardMoveInput";
  48035. };
  48036. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48037. return "keyboard";
  48038. };
  48039. __decorate([
  48040. BABYLON.serialize()
  48041. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48042. __decorate([
  48043. BABYLON.serialize()
  48044. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48045. __decorate([
  48046. BABYLON.serialize()
  48047. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48048. __decorate([
  48049. BABYLON.serialize()
  48050. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48051. __decorate([
  48052. BABYLON.serialize()
  48053. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48054. __decorate([
  48055. BABYLON.serialize()
  48056. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48057. __decorate([
  48058. BABYLON.serialize()
  48059. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48060. __decorate([
  48061. BABYLON.serialize()
  48062. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48063. return ArcRotateCameraKeyboardMoveInput;
  48064. }());
  48065. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48066. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48067. })(BABYLON || (BABYLON = {}));
  48068. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48069. var BABYLON;
  48070. (function (BABYLON) {
  48071. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48072. function ArcRotateCameraMouseWheelInput() {
  48073. this.wheelPrecision = 3.0;
  48074. /**
  48075. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48076. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48077. */
  48078. this.wheelDeltaPercentage = 0;
  48079. }
  48080. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48081. var _this = this;
  48082. this._wheel = function (p, s) {
  48083. //sanity check - this should be a PointerWheel event.
  48084. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48085. return;
  48086. var event = p.event;
  48087. var delta = 0;
  48088. if (event.wheelDelta) {
  48089. if (_this.wheelDeltaPercentage) {
  48090. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48091. if (event.wheelDelta > 0) {
  48092. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48093. }
  48094. else {
  48095. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48096. }
  48097. }
  48098. else {
  48099. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48100. }
  48101. }
  48102. else if (event.detail) {
  48103. delta = -event.detail / _this.wheelPrecision;
  48104. }
  48105. if (delta)
  48106. _this.camera.inertialRadiusOffset += delta;
  48107. if (event.preventDefault) {
  48108. if (!noPreventDefault) {
  48109. event.preventDefault();
  48110. }
  48111. }
  48112. };
  48113. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48114. };
  48115. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48116. if (this._observer && element) {
  48117. this.camera.getScene().onPointerObservable.remove(this._observer);
  48118. this._observer = null;
  48119. this._wheel = null;
  48120. }
  48121. };
  48122. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48123. return "ArcRotateCameraMouseWheelInput";
  48124. };
  48125. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48126. return "mousewheel";
  48127. };
  48128. __decorate([
  48129. BABYLON.serialize()
  48130. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48131. __decorate([
  48132. BABYLON.serialize()
  48133. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48134. return ArcRotateCameraMouseWheelInput;
  48135. }());
  48136. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48137. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48138. })(BABYLON || (BABYLON = {}));
  48139. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48140. var BABYLON;
  48141. (function (BABYLON) {
  48142. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48143. function ArcRotateCameraPointersInput() {
  48144. this.buttons = [0, 1, 2];
  48145. this.angularSensibilityX = 1000.0;
  48146. this.angularSensibilityY = 1000.0;
  48147. this.pinchPrecision = 12.0;
  48148. /**
  48149. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48150. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48151. */
  48152. this.pinchDeltaPercentage = 0;
  48153. this.panningSensibility = 1000.0;
  48154. this.multiTouchPanning = true;
  48155. this.multiTouchPanAndZoom = true;
  48156. this._isPanClick = false;
  48157. this.pinchInwards = true;
  48158. }
  48159. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48160. var _this = this;
  48161. var engine = this.camera.getEngine();
  48162. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48163. var pointA = null;
  48164. var pointB = null;
  48165. var previousPinchSquaredDistance = 0;
  48166. var initialDistance = 0;
  48167. var twoFingerActivityCount = 0;
  48168. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48169. this._pointerInput = function (p, s) {
  48170. var evt = p.event;
  48171. var isTouch = p.event.pointerType === "touch";
  48172. if (engine.isInVRExclusivePointerMode) {
  48173. return;
  48174. }
  48175. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48176. return;
  48177. }
  48178. var srcElement = (evt.srcElement || evt.target);
  48179. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48180. try {
  48181. srcElement.setPointerCapture(evt.pointerId);
  48182. }
  48183. catch (e) {
  48184. //Nothing to do with the error. Execution will continue.
  48185. }
  48186. // Manage panning with pan button click
  48187. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48188. // manage pointers
  48189. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48190. if (pointA === null) {
  48191. pointA = cacheSoloPointer;
  48192. }
  48193. else if (pointB === null) {
  48194. pointB = cacheSoloPointer;
  48195. }
  48196. if (!noPreventDefault) {
  48197. evt.preventDefault();
  48198. element.focus();
  48199. }
  48200. }
  48201. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48202. _this.camera.restoreState();
  48203. }
  48204. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48205. try {
  48206. srcElement.releasePointerCapture(evt.pointerId);
  48207. }
  48208. catch (e) {
  48209. //Nothing to do with the error.
  48210. }
  48211. cacheSoloPointer = null;
  48212. previousPinchSquaredDistance = 0;
  48213. previousMultiTouchPanPosition.isPaning = false;
  48214. previousMultiTouchPanPosition.isPinching = false;
  48215. twoFingerActivityCount = 0;
  48216. initialDistance = 0;
  48217. if (!isTouch) {
  48218. pointB = null; // Mouse and pen are mono pointer
  48219. }
  48220. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48221. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48222. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48223. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48224. if (engine._badOS) {
  48225. pointA = pointB = null;
  48226. }
  48227. else {
  48228. //only remove the impacted pointer in case of multitouch allowing on most
  48229. //platforms switching from rotate to zoom and pan seamlessly.
  48230. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48231. pointA = pointB;
  48232. pointB = null;
  48233. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48234. }
  48235. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48236. pointB = null;
  48237. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48238. }
  48239. else {
  48240. pointA = pointB = null;
  48241. }
  48242. }
  48243. if (!noPreventDefault) {
  48244. evt.preventDefault();
  48245. }
  48246. }
  48247. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48248. if (!noPreventDefault) {
  48249. evt.preventDefault();
  48250. }
  48251. // One button down
  48252. if (pointA && pointB === null && cacheSoloPointer) {
  48253. if (_this.panningSensibility !== 0 &&
  48254. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48255. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48256. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48257. }
  48258. else {
  48259. var offsetX = evt.clientX - cacheSoloPointer.x;
  48260. var offsetY = evt.clientY - cacheSoloPointer.y;
  48261. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48262. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48263. }
  48264. cacheSoloPointer.x = evt.clientX;
  48265. cacheSoloPointer.y = evt.clientY;
  48266. }
  48267. // Two buttons down: pinch/pan
  48268. else if (pointA && pointB) {
  48269. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48270. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48271. ed.x = evt.clientX;
  48272. ed.y = evt.clientY;
  48273. var direction = _this.pinchInwards ? 1 : -1;
  48274. var distX = pointA.x - pointB.x;
  48275. var distY = pointA.y - pointB.y;
  48276. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48277. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48278. if (previousPinchSquaredDistance === 0) {
  48279. initialDistance = pinchDistance;
  48280. previousPinchSquaredDistance = pinchSquaredDistance;
  48281. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48282. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48283. return;
  48284. }
  48285. if (_this.multiTouchPanAndZoom) {
  48286. if (_this.pinchDeltaPercentage) {
  48287. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48288. }
  48289. else {
  48290. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48291. (_this.pinchPrecision *
  48292. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48293. direction);
  48294. }
  48295. if (_this.panningSensibility !== 0) {
  48296. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48297. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48298. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48299. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48300. previousMultiTouchPanPosition.x = pointersCenterX;
  48301. previousMultiTouchPanPosition.y = pointersCenterY;
  48302. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48303. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48304. }
  48305. }
  48306. else {
  48307. twoFingerActivityCount++;
  48308. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48309. if (_this.pinchDeltaPercentage) {
  48310. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48311. }
  48312. else {
  48313. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48314. (_this.pinchPrecision *
  48315. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48316. direction);
  48317. }
  48318. previousMultiTouchPanPosition.isPaning = false;
  48319. previousMultiTouchPanPosition.isPinching = true;
  48320. }
  48321. else {
  48322. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48323. if (!previousMultiTouchPanPosition.isPaning) {
  48324. previousMultiTouchPanPosition.isPaning = true;
  48325. previousMultiTouchPanPosition.isPinching = false;
  48326. previousMultiTouchPanPosition.x = ed.x;
  48327. previousMultiTouchPanPosition.y = ed.y;
  48328. return;
  48329. }
  48330. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48331. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48332. }
  48333. }
  48334. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48335. previousMultiTouchPanPosition.x = ed.x;
  48336. previousMultiTouchPanPosition.y = ed.y;
  48337. }
  48338. }
  48339. previousPinchSquaredDistance = pinchSquaredDistance;
  48340. }
  48341. }
  48342. };
  48343. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48344. this._onContextMenu = function (evt) {
  48345. evt.preventDefault();
  48346. };
  48347. if (!this.camera._useCtrlForPanning) {
  48348. element.addEventListener("contextmenu", this._onContextMenu, false);
  48349. }
  48350. this._onLostFocus = function () {
  48351. //this._keys = [];
  48352. pointA = pointB = null;
  48353. previousPinchSquaredDistance = 0;
  48354. previousMultiTouchPanPosition.isPaning = false;
  48355. previousMultiTouchPanPosition.isPinching = false;
  48356. twoFingerActivityCount = 0;
  48357. cacheSoloPointer = null;
  48358. initialDistance = 0;
  48359. };
  48360. this._onMouseMove = function (evt) {
  48361. if (!engine.isPointerLock) {
  48362. return;
  48363. }
  48364. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48365. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48366. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48367. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48368. if (!noPreventDefault) {
  48369. evt.preventDefault();
  48370. }
  48371. };
  48372. this._onGestureStart = function (e) {
  48373. if (window.MSGesture === undefined) {
  48374. return;
  48375. }
  48376. if (!_this._MSGestureHandler) {
  48377. _this._MSGestureHandler = new MSGesture();
  48378. _this._MSGestureHandler.target = element;
  48379. }
  48380. _this._MSGestureHandler.addPointer(e.pointerId);
  48381. };
  48382. this._onGesture = function (e) {
  48383. _this.camera.radius *= e.scale;
  48384. if (e.preventDefault) {
  48385. if (!noPreventDefault) {
  48386. e.stopPropagation();
  48387. e.preventDefault();
  48388. }
  48389. }
  48390. };
  48391. element.addEventListener("mousemove", this._onMouseMove, false);
  48392. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48393. element.addEventListener("MSGestureChange", this._onGesture, false);
  48394. BABYLON.Tools.RegisterTopRootEvents([
  48395. { name: "blur", handler: this._onLostFocus }
  48396. ]);
  48397. };
  48398. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48399. if (this._onLostFocus) {
  48400. BABYLON.Tools.UnregisterTopRootEvents([
  48401. { name: "blur", handler: this._onLostFocus }
  48402. ]);
  48403. }
  48404. if (element && this._observer) {
  48405. this.camera.getScene().onPointerObservable.remove(this._observer);
  48406. this._observer = null;
  48407. if (this._onContextMenu) {
  48408. element.removeEventListener("contextmenu", this._onContextMenu);
  48409. }
  48410. if (this._onMouseMove) {
  48411. element.removeEventListener("mousemove", this._onMouseMove);
  48412. }
  48413. if (this._onGestureStart) {
  48414. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48415. }
  48416. if (this._onGesture) {
  48417. element.removeEventListener("MSGestureChange", this._onGesture);
  48418. }
  48419. this._isPanClick = false;
  48420. this.pinchInwards = true;
  48421. this._onMouseMove = null;
  48422. this._onGestureStart = null;
  48423. this._onGesture = null;
  48424. this._MSGestureHandler = null;
  48425. this._onLostFocus = null;
  48426. this._onContextMenu = null;
  48427. }
  48428. };
  48429. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48430. return "ArcRotateCameraPointersInput";
  48431. };
  48432. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48433. return "pointers";
  48434. };
  48435. __decorate([
  48436. BABYLON.serialize()
  48437. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48438. __decorate([
  48439. BABYLON.serialize()
  48440. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48441. __decorate([
  48442. BABYLON.serialize()
  48443. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48444. __decorate([
  48445. BABYLON.serialize()
  48446. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48447. __decorate([
  48448. BABYLON.serialize()
  48449. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48450. __decorate([
  48451. BABYLON.serialize()
  48452. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48453. __decorate([
  48454. BABYLON.serialize()
  48455. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48456. __decorate([
  48457. BABYLON.serialize()
  48458. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48459. return ArcRotateCameraPointersInput;
  48460. }());
  48461. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48462. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48463. })(BABYLON || (BABYLON = {}));
  48464. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48465. var BABYLON;
  48466. (function (BABYLON) {
  48467. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48468. __extends(ArcRotateCameraInputsManager, _super);
  48469. function ArcRotateCameraInputsManager(camera) {
  48470. return _super.call(this, camera) || this;
  48471. }
  48472. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48473. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48474. return this;
  48475. };
  48476. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48477. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48478. return this;
  48479. };
  48480. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48481. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48482. return this;
  48483. };
  48484. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48485. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48486. return this;
  48487. };
  48488. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48489. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48490. return this;
  48491. };
  48492. return ArcRotateCameraInputsManager;
  48493. }(BABYLON.CameraInputsManager));
  48494. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48495. })(BABYLON || (BABYLON = {}));
  48496. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48497. var BABYLON;
  48498. (function (BABYLON) {
  48499. var ArcRotateCamera = /** @class */ (function (_super) {
  48500. __extends(ArcRotateCamera, _super);
  48501. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48502. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48503. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48504. _this.inertialAlphaOffset = 0;
  48505. _this.inertialBetaOffset = 0;
  48506. _this.inertialRadiusOffset = 0;
  48507. _this.lowerAlphaLimit = null;
  48508. _this.upperAlphaLimit = null;
  48509. _this.lowerBetaLimit = 0.01;
  48510. _this.upperBetaLimit = Math.PI;
  48511. _this.lowerRadiusLimit = null;
  48512. _this.upperRadiusLimit = null;
  48513. _this.inertialPanningX = 0;
  48514. _this.inertialPanningY = 0;
  48515. _this.pinchToPanMaxDistance = 20;
  48516. _this.panningDistanceLimit = null;
  48517. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48518. _this.panningInertia = 0.9;
  48519. //-- end properties for backward compatibility for inputs
  48520. _this.zoomOnFactor = 1;
  48521. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48522. _this.allowUpsideDown = true;
  48523. _this._viewMatrix = new BABYLON.Matrix();
  48524. // Panning
  48525. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48526. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48527. _this.checkCollisions = false;
  48528. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48529. _this._previousPosition = BABYLON.Vector3.Zero();
  48530. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48531. _this._newPosition = BABYLON.Vector3.Zero();
  48532. _this._computationVector = BABYLON.Vector3.Zero();
  48533. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48534. if (collidedMesh === void 0) { collidedMesh = null; }
  48535. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48536. newPosition.multiplyInPlace(_this._collider._radius);
  48537. }
  48538. if (!collidedMesh) {
  48539. _this._previousPosition.copyFrom(_this.position);
  48540. }
  48541. else {
  48542. _this.setPosition(newPosition);
  48543. if (_this.onCollide) {
  48544. _this.onCollide(collidedMesh);
  48545. }
  48546. }
  48547. // Recompute because of constraints
  48548. var cosa = Math.cos(_this.alpha);
  48549. var sina = Math.sin(_this.alpha);
  48550. var cosb = Math.cos(_this.beta);
  48551. var sinb = Math.sin(_this.beta);
  48552. if (sinb === 0) {
  48553. sinb = 0.0001;
  48554. }
  48555. var target = _this._getTargetPosition();
  48556. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48557. target.addToRef(_this._computationVector, _this._newPosition);
  48558. _this.position.copyFrom(_this._newPosition);
  48559. var up = _this.upVector;
  48560. if (_this.allowUpsideDown && _this.beta < 0) {
  48561. up = up.clone();
  48562. up = up.negate();
  48563. }
  48564. _this._computeViewMatrix(_this.position, target, up);
  48565. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48566. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48567. _this._collisionTriggered = false;
  48568. };
  48569. _this._target = BABYLON.Vector3.Zero();
  48570. if (target) {
  48571. _this.setTarget(target);
  48572. }
  48573. _this.alpha = alpha;
  48574. _this.beta = beta;
  48575. _this.radius = radius;
  48576. _this.getViewMatrix();
  48577. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48578. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48579. return _this;
  48580. }
  48581. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48582. get: function () {
  48583. return this._target;
  48584. },
  48585. set: function (value) {
  48586. this.setTarget(value);
  48587. },
  48588. enumerable: true,
  48589. configurable: true
  48590. });
  48591. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48592. //-- begin properties for backward compatibility for inputs
  48593. get: function () {
  48594. var pointers = this.inputs.attached["pointers"];
  48595. if (pointers)
  48596. return pointers.angularSensibilityX;
  48597. return 0;
  48598. },
  48599. set: function (value) {
  48600. var pointers = this.inputs.attached["pointers"];
  48601. if (pointers) {
  48602. pointers.angularSensibilityX = value;
  48603. }
  48604. },
  48605. enumerable: true,
  48606. configurable: true
  48607. });
  48608. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48609. get: function () {
  48610. var pointers = this.inputs.attached["pointers"];
  48611. if (pointers)
  48612. return pointers.angularSensibilityY;
  48613. return 0;
  48614. },
  48615. set: function (value) {
  48616. var pointers = this.inputs.attached["pointers"];
  48617. if (pointers) {
  48618. pointers.angularSensibilityY = value;
  48619. }
  48620. },
  48621. enumerable: true,
  48622. configurable: true
  48623. });
  48624. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48625. get: function () {
  48626. var pointers = this.inputs.attached["pointers"];
  48627. if (pointers)
  48628. return pointers.pinchPrecision;
  48629. return 0;
  48630. },
  48631. set: function (value) {
  48632. var pointers = this.inputs.attached["pointers"];
  48633. if (pointers) {
  48634. pointers.pinchPrecision = value;
  48635. }
  48636. },
  48637. enumerable: true,
  48638. configurable: true
  48639. });
  48640. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48641. get: function () {
  48642. var pointers = this.inputs.attached["pointers"];
  48643. if (pointers)
  48644. return pointers.pinchDeltaPercentage;
  48645. return 0;
  48646. },
  48647. set: function (value) {
  48648. var pointers = this.inputs.attached["pointers"];
  48649. if (pointers) {
  48650. pointers.pinchDeltaPercentage = value;
  48651. }
  48652. },
  48653. enumerable: true,
  48654. configurable: true
  48655. });
  48656. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48657. get: function () {
  48658. var pointers = this.inputs.attached["pointers"];
  48659. if (pointers)
  48660. return pointers.panningSensibility;
  48661. return 0;
  48662. },
  48663. set: function (value) {
  48664. var pointers = this.inputs.attached["pointers"];
  48665. if (pointers) {
  48666. pointers.panningSensibility = value;
  48667. }
  48668. },
  48669. enumerable: true,
  48670. configurable: true
  48671. });
  48672. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48673. get: function () {
  48674. var keyboard = this.inputs.attached["keyboard"];
  48675. if (keyboard)
  48676. return keyboard.keysUp;
  48677. return [];
  48678. },
  48679. set: function (value) {
  48680. var keyboard = this.inputs.attached["keyboard"];
  48681. if (keyboard)
  48682. keyboard.keysUp = value;
  48683. },
  48684. enumerable: true,
  48685. configurable: true
  48686. });
  48687. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48688. get: function () {
  48689. var keyboard = this.inputs.attached["keyboard"];
  48690. if (keyboard)
  48691. return keyboard.keysDown;
  48692. return [];
  48693. },
  48694. set: function (value) {
  48695. var keyboard = this.inputs.attached["keyboard"];
  48696. if (keyboard)
  48697. keyboard.keysDown = value;
  48698. },
  48699. enumerable: true,
  48700. configurable: true
  48701. });
  48702. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48703. get: function () {
  48704. var keyboard = this.inputs.attached["keyboard"];
  48705. if (keyboard)
  48706. return keyboard.keysLeft;
  48707. return [];
  48708. },
  48709. set: function (value) {
  48710. var keyboard = this.inputs.attached["keyboard"];
  48711. if (keyboard)
  48712. keyboard.keysLeft = value;
  48713. },
  48714. enumerable: true,
  48715. configurable: true
  48716. });
  48717. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48718. get: function () {
  48719. var keyboard = this.inputs.attached["keyboard"];
  48720. if (keyboard)
  48721. return keyboard.keysRight;
  48722. return [];
  48723. },
  48724. set: function (value) {
  48725. var keyboard = this.inputs.attached["keyboard"];
  48726. if (keyboard)
  48727. keyboard.keysRight = value;
  48728. },
  48729. enumerable: true,
  48730. configurable: true
  48731. });
  48732. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48733. get: function () {
  48734. var mousewheel = this.inputs.attached["mousewheel"];
  48735. if (mousewheel)
  48736. return mousewheel.wheelPrecision;
  48737. return 0;
  48738. },
  48739. set: function (value) {
  48740. var mousewheel = this.inputs.attached["mousewheel"];
  48741. if (mousewheel)
  48742. mousewheel.wheelPrecision = value;
  48743. },
  48744. enumerable: true,
  48745. configurable: true
  48746. });
  48747. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48748. get: function () {
  48749. var mousewheel = this.inputs.attached["mousewheel"];
  48750. if (mousewheel)
  48751. return mousewheel.wheelDeltaPercentage;
  48752. return 0;
  48753. },
  48754. set: function (value) {
  48755. var mousewheel = this.inputs.attached["mousewheel"];
  48756. if (mousewheel)
  48757. mousewheel.wheelDeltaPercentage = value;
  48758. },
  48759. enumerable: true,
  48760. configurable: true
  48761. });
  48762. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48763. get: function () {
  48764. return this._bouncingBehavior;
  48765. },
  48766. enumerable: true,
  48767. configurable: true
  48768. });
  48769. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48770. get: function () {
  48771. return this._bouncingBehavior != null;
  48772. },
  48773. set: function (value) {
  48774. if (value === this.useBouncingBehavior) {
  48775. return;
  48776. }
  48777. if (value) {
  48778. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48779. this.addBehavior(this._bouncingBehavior);
  48780. }
  48781. else if (this._bouncingBehavior) {
  48782. this.removeBehavior(this._bouncingBehavior);
  48783. this._bouncingBehavior = null;
  48784. }
  48785. },
  48786. enumerable: true,
  48787. configurable: true
  48788. });
  48789. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48790. get: function () {
  48791. return this._framingBehavior;
  48792. },
  48793. enumerable: true,
  48794. configurable: true
  48795. });
  48796. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48797. get: function () {
  48798. return this._framingBehavior != null;
  48799. },
  48800. set: function (value) {
  48801. if (value === this.useFramingBehavior) {
  48802. return;
  48803. }
  48804. if (value) {
  48805. this._framingBehavior = new BABYLON.FramingBehavior();
  48806. this.addBehavior(this._framingBehavior);
  48807. }
  48808. else if (this._framingBehavior) {
  48809. this.removeBehavior(this._framingBehavior);
  48810. this._framingBehavior = null;
  48811. }
  48812. },
  48813. enumerable: true,
  48814. configurable: true
  48815. });
  48816. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48817. get: function () {
  48818. return this._autoRotationBehavior;
  48819. },
  48820. enumerable: true,
  48821. configurable: true
  48822. });
  48823. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48824. get: function () {
  48825. return this._autoRotationBehavior != null;
  48826. },
  48827. set: function (value) {
  48828. if (value === this.useAutoRotationBehavior) {
  48829. return;
  48830. }
  48831. if (value) {
  48832. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48833. this.addBehavior(this._autoRotationBehavior);
  48834. }
  48835. else if (this._autoRotationBehavior) {
  48836. this.removeBehavior(this._autoRotationBehavior);
  48837. this._autoRotationBehavior = null;
  48838. }
  48839. },
  48840. enumerable: true,
  48841. configurable: true
  48842. });
  48843. // Cache
  48844. ArcRotateCamera.prototype._initCache = function () {
  48845. _super.prototype._initCache.call(this);
  48846. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48847. this._cache.alpha = undefined;
  48848. this._cache.beta = undefined;
  48849. this._cache.radius = undefined;
  48850. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48851. };
  48852. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48853. if (!ignoreParentClass) {
  48854. _super.prototype._updateCache.call(this);
  48855. }
  48856. this._cache._target.copyFrom(this._getTargetPosition());
  48857. this._cache.alpha = this.alpha;
  48858. this._cache.beta = this.beta;
  48859. this._cache.radius = this.radius;
  48860. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48861. };
  48862. ArcRotateCamera.prototype._getTargetPosition = function () {
  48863. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48864. var pos = this._targetHost.getAbsolutePosition();
  48865. if (this._targetBoundingCenter) {
  48866. pos.addToRef(this._targetBoundingCenter, this._target);
  48867. }
  48868. else {
  48869. this._target.copyFrom(pos);
  48870. }
  48871. }
  48872. var lockedTargetPosition = this._getLockedTargetPosition();
  48873. if (lockedTargetPosition) {
  48874. return lockedTargetPosition;
  48875. }
  48876. return this._target;
  48877. };
  48878. ArcRotateCamera.prototype.storeState = function () {
  48879. this._storedAlpha = this.alpha;
  48880. this._storedBeta = this.beta;
  48881. this._storedRadius = this.radius;
  48882. this._storedTarget = this._getTargetPosition().clone();
  48883. return _super.prototype.storeState.call(this);
  48884. };
  48885. /**
  48886. * Restored camera state. You must call storeState() first
  48887. */
  48888. ArcRotateCamera.prototype._restoreStateValues = function () {
  48889. if (!_super.prototype._restoreStateValues.call(this)) {
  48890. return false;
  48891. }
  48892. this.alpha = this._storedAlpha;
  48893. this.beta = this._storedBeta;
  48894. this.radius = this._storedRadius;
  48895. this.setTarget(this._storedTarget.clone());
  48896. this.inertialAlphaOffset = 0;
  48897. this.inertialBetaOffset = 0;
  48898. this.inertialRadiusOffset = 0;
  48899. this.inertialPanningX = 0;
  48900. this.inertialPanningY = 0;
  48901. return true;
  48902. };
  48903. // Synchronized
  48904. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48905. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48906. return false;
  48907. return this._cache._target.equals(this._getTargetPosition())
  48908. && this._cache.alpha === this.alpha
  48909. && this._cache.beta === this.beta
  48910. && this._cache.radius === this.radius
  48911. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48912. };
  48913. // Methods
  48914. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48915. var _this = this;
  48916. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48917. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48918. this._useCtrlForPanning = useCtrlForPanning;
  48919. this._panningMouseButton = panningMouseButton;
  48920. this.inputs.attachElement(element, noPreventDefault);
  48921. this._reset = function () {
  48922. _this.inertialAlphaOffset = 0;
  48923. _this.inertialBetaOffset = 0;
  48924. _this.inertialRadiusOffset = 0;
  48925. _this.inertialPanningX = 0;
  48926. _this.inertialPanningY = 0;
  48927. };
  48928. };
  48929. ArcRotateCamera.prototype.detachControl = function (element) {
  48930. this.inputs.detachElement(element);
  48931. if (this._reset) {
  48932. this._reset();
  48933. }
  48934. };
  48935. ArcRotateCamera.prototype._checkInputs = function () {
  48936. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48937. if (this._collisionTriggered) {
  48938. return;
  48939. }
  48940. this.inputs.checkInputs();
  48941. // Inertia
  48942. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48943. var inertialAlphaOffset = this.inertialAlphaOffset;
  48944. if (this.beta <= 0)
  48945. inertialAlphaOffset *= -1;
  48946. if (this.getScene().useRightHandedSystem)
  48947. inertialAlphaOffset *= -1;
  48948. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48949. inertialAlphaOffset *= -1;
  48950. this.alpha += inertialAlphaOffset;
  48951. this.beta += this.inertialBetaOffset;
  48952. this.radius -= this.inertialRadiusOffset;
  48953. this.inertialAlphaOffset *= this.inertia;
  48954. this.inertialBetaOffset *= this.inertia;
  48955. this.inertialRadiusOffset *= this.inertia;
  48956. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48957. this.inertialAlphaOffset = 0;
  48958. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48959. this.inertialBetaOffset = 0;
  48960. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48961. this.inertialRadiusOffset = 0;
  48962. }
  48963. // Panning inertia
  48964. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48965. if (!this._localDirection) {
  48966. this._localDirection = BABYLON.Vector3.Zero();
  48967. this._transformedDirection = BABYLON.Vector3.Zero();
  48968. }
  48969. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48970. this._localDirection.multiplyInPlace(this.panningAxis);
  48971. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48972. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48973. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48974. if (!this.panningAxis.y) {
  48975. this._transformedDirection.y = 0;
  48976. }
  48977. if (!this._targetHost) {
  48978. if (this.panningDistanceLimit) {
  48979. this._transformedDirection.addInPlace(this._target);
  48980. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48981. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48982. this._target.copyFrom(this._transformedDirection);
  48983. }
  48984. }
  48985. else {
  48986. this._target.addInPlace(this._transformedDirection);
  48987. }
  48988. }
  48989. this.inertialPanningX *= this.panningInertia;
  48990. this.inertialPanningY *= this.panningInertia;
  48991. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48992. this.inertialPanningX = 0;
  48993. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48994. this.inertialPanningY = 0;
  48995. }
  48996. // Limits
  48997. this._checkLimits();
  48998. _super.prototype._checkInputs.call(this);
  48999. };
  49000. ArcRotateCamera.prototype._checkLimits = function () {
  49001. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49002. if (this.allowUpsideDown && this.beta > Math.PI) {
  49003. this.beta = this.beta - (2 * Math.PI);
  49004. }
  49005. }
  49006. else {
  49007. if (this.beta < this.lowerBetaLimit) {
  49008. this.beta = this.lowerBetaLimit;
  49009. }
  49010. }
  49011. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49012. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49013. this.beta = this.beta + (2 * Math.PI);
  49014. }
  49015. }
  49016. else {
  49017. if (this.beta > this.upperBetaLimit) {
  49018. this.beta = this.upperBetaLimit;
  49019. }
  49020. }
  49021. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  49022. this.alpha = this.lowerAlphaLimit;
  49023. }
  49024. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  49025. this.alpha = this.upperAlphaLimit;
  49026. }
  49027. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  49028. this.radius = this.lowerRadiusLimit;
  49029. }
  49030. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49031. this.radius = this.upperRadiusLimit;
  49032. }
  49033. };
  49034. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49035. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49036. this.radius = this._computationVector.length();
  49037. if (this.radius === 0) {
  49038. this.radius = 0.0001; // Just to avoid division by zero
  49039. }
  49040. // Alpha
  49041. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49042. if (this._computationVector.z < 0) {
  49043. this.alpha = 2 * Math.PI - this.alpha;
  49044. }
  49045. // Beta
  49046. this.beta = Math.acos(this._computationVector.y / this.radius);
  49047. this._checkLimits();
  49048. };
  49049. ArcRotateCamera.prototype.setPosition = function (position) {
  49050. if (this.position.equals(position)) {
  49051. return;
  49052. }
  49053. this.position.copyFrom(position);
  49054. this.rebuildAnglesAndRadius();
  49055. };
  49056. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49057. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49058. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49059. if (target.getBoundingInfo) {
  49060. if (toBoundingCenter) {
  49061. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49062. }
  49063. else {
  49064. this._targetBoundingCenter = null;
  49065. }
  49066. this._targetHost = target;
  49067. this._target = this._getTargetPosition();
  49068. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49069. }
  49070. else {
  49071. var newTarget = target;
  49072. var currentTarget = this._getTargetPosition();
  49073. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49074. return;
  49075. }
  49076. this._targetHost = null;
  49077. this._target = newTarget;
  49078. this._targetBoundingCenter = null;
  49079. this.onMeshTargetChangedObservable.notifyObservers(null);
  49080. }
  49081. this.rebuildAnglesAndRadius();
  49082. };
  49083. ArcRotateCamera.prototype._getViewMatrix = function () {
  49084. // Compute
  49085. var cosa = Math.cos(this.alpha);
  49086. var sina = Math.sin(this.alpha);
  49087. var cosb = Math.cos(this.beta);
  49088. var sinb = Math.sin(this.beta);
  49089. if (sinb === 0) {
  49090. sinb = 0.0001;
  49091. }
  49092. var target = this._getTargetPosition();
  49093. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49094. target.addToRef(this._computationVector, this._newPosition);
  49095. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49096. if (!this._collider) {
  49097. this._collider = new BABYLON.Collider();
  49098. }
  49099. this._collider._radius = this.collisionRadius;
  49100. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49101. this._collisionTriggered = true;
  49102. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49103. }
  49104. else {
  49105. this.position.copyFrom(this._newPosition);
  49106. var up = this.upVector;
  49107. if (this.allowUpsideDown && sinb < 0) {
  49108. up = up.clone();
  49109. up = up.negate();
  49110. }
  49111. this._computeViewMatrix(this.position, target, up);
  49112. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49113. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49114. }
  49115. this._currentTarget = target;
  49116. return this._viewMatrix;
  49117. };
  49118. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49119. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49120. meshes = meshes || this.getScene().meshes;
  49121. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49122. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49123. this.radius = distance * this.zoomOnFactor;
  49124. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49125. };
  49126. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49127. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49128. var meshesOrMinMaxVector;
  49129. var distance;
  49130. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49131. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49132. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49133. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49134. }
  49135. else { //minMaxVector and distance
  49136. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49137. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49138. distance = minMaxVectorAndDistance.distance;
  49139. }
  49140. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49141. if (!doNotUpdateMaxZ) {
  49142. this.maxZ = distance * 2;
  49143. }
  49144. };
  49145. /**
  49146. * @override
  49147. * Override Camera.createRigCamera
  49148. */
  49149. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49150. var alphaShift = 0;
  49151. switch (this.cameraRigMode) {
  49152. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49153. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49154. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49155. case BABYLON.Camera.RIG_MODE_VR:
  49156. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49157. break;
  49158. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49159. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49160. break;
  49161. }
  49162. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49163. rigCam._cameraRigParams = {};
  49164. return rigCam;
  49165. };
  49166. /**
  49167. * @override
  49168. * Override Camera._updateRigCameras
  49169. */
  49170. ArcRotateCamera.prototype._updateRigCameras = function () {
  49171. var camLeft = this._rigCameras[0];
  49172. var camRight = this._rigCameras[1];
  49173. camLeft.beta = camRight.beta = this.beta;
  49174. camLeft.radius = camRight.radius = this.radius;
  49175. switch (this.cameraRigMode) {
  49176. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49177. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49178. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49179. case BABYLON.Camera.RIG_MODE_VR:
  49180. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49181. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49182. break;
  49183. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49184. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49185. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49186. break;
  49187. }
  49188. _super.prototype._updateRigCameras.call(this);
  49189. };
  49190. ArcRotateCamera.prototype.dispose = function () {
  49191. this.inputs.clear();
  49192. _super.prototype.dispose.call(this);
  49193. };
  49194. ArcRotateCamera.prototype.getClassName = function () {
  49195. return "ArcRotateCamera";
  49196. };
  49197. __decorate([
  49198. BABYLON.serialize()
  49199. ], ArcRotateCamera.prototype, "alpha", void 0);
  49200. __decorate([
  49201. BABYLON.serialize()
  49202. ], ArcRotateCamera.prototype, "beta", void 0);
  49203. __decorate([
  49204. BABYLON.serialize()
  49205. ], ArcRotateCamera.prototype, "radius", void 0);
  49206. __decorate([
  49207. BABYLON.serializeAsVector3("target")
  49208. ], ArcRotateCamera.prototype, "_target", void 0);
  49209. __decorate([
  49210. BABYLON.serialize()
  49211. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49212. __decorate([
  49213. BABYLON.serialize()
  49214. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49215. __decorate([
  49216. BABYLON.serialize()
  49217. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49218. __decorate([
  49219. BABYLON.serialize()
  49220. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49221. __decorate([
  49222. BABYLON.serialize()
  49223. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49224. __decorate([
  49225. BABYLON.serialize()
  49226. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49227. __decorate([
  49228. BABYLON.serialize()
  49229. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49230. __decorate([
  49231. BABYLON.serialize()
  49232. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49233. __decorate([
  49234. BABYLON.serialize()
  49235. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49236. __decorate([
  49237. BABYLON.serialize()
  49238. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49239. __decorate([
  49240. BABYLON.serialize()
  49241. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49242. __decorate([
  49243. BABYLON.serialize()
  49244. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49245. __decorate([
  49246. BABYLON.serialize()
  49247. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49248. __decorate([
  49249. BABYLON.serializeAsVector3()
  49250. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49251. __decorate([
  49252. BABYLON.serialize()
  49253. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49254. __decorate([
  49255. BABYLON.serialize()
  49256. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49257. __decorate([
  49258. BABYLON.serialize()
  49259. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49260. return ArcRotateCamera;
  49261. }(BABYLON.TargetCamera));
  49262. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49263. })(BABYLON || (BABYLON = {}));
  49264. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49265. var BABYLON;
  49266. (function (BABYLON) {
  49267. /**
  49268. * The HemisphericLight simulates the ambient environment light,
  49269. * so the passed direction is the light reflection direction, not the incoming direction.
  49270. */
  49271. var HemisphericLight = /** @class */ (function (_super) {
  49272. __extends(HemisphericLight, _super);
  49273. /**
  49274. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49275. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49276. * The HemisphericLight can't cast shadows.
  49277. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49278. * @param name The friendly name of the light
  49279. * @param direction The direction of the light reflection
  49280. * @param scene The scene the light belongs to
  49281. */
  49282. function HemisphericLight(name, direction, scene) {
  49283. var _this = _super.call(this, name, scene) || this;
  49284. /**
  49285. * The groundColor is the light in the opposite direction to the one specified during creation.
  49286. * 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.
  49287. */
  49288. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49289. _this.direction = direction || BABYLON.Vector3.Up();
  49290. return _this;
  49291. }
  49292. HemisphericLight.prototype._buildUniformLayout = function () {
  49293. this._uniformBuffer.addUniform("vLightData", 4);
  49294. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49295. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49296. this._uniformBuffer.addUniform("vLightGround", 3);
  49297. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49298. this._uniformBuffer.addUniform("depthValues", 2);
  49299. this._uniformBuffer.create();
  49300. };
  49301. /**
  49302. * Returns the string "HemisphericLight".
  49303. * @return The class name
  49304. */
  49305. HemisphericLight.prototype.getClassName = function () {
  49306. return "HemisphericLight";
  49307. };
  49308. /**
  49309. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49310. * Returns the updated direction.
  49311. * @param target The target the direction should point to
  49312. * @return The computed direction
  49313. */
  49314. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49315. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49316. return this.direction;
  49317. };
  49318. /**
  49319. * Returns the shadow generator associated to the light.
  49320. * @returns Always null for hemispheric lights because it does not support shadows.
  49321. */
  49322. HemisphericLight.prototype.getShadowGenerator = function () {
  49323. return null;
  49324. };
  49325. /**
  49326. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49327. * @param effect The effect to update
  49328. * @param lightIndex The index of the light in the effect to update
  49329. * @returns The hemispheric light
  49330. */
  49331. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49332. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49333. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49334. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49335. return this;
  49336. };
  49337. /**
  49338. * @hidden internal use only.
  49339. */
  49340. HemisphericLight.prototype._getWorldMatrix = function () {
  49341. if (!this._worldMatrix) {
  49342. this._worldMatrix = BABYLON.Matrix.Identity();
  49343. }
  49344. return this._worldMatrix;
  49345. };
  49346. /**
  49347. * Returns the integer 3.
  49348. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49349. */
  49350. HemisphericLight.prototype.getTypeID = function () {
  49351. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49352. };
  49353. __decorate([
  49354. BABYLON.serializeAsColor3()
  49355. ], HemisphericLight.prototype, "groundColor", void 0);
  49356. __decorate([
  49357. BABYLON.serializeAsVector3()
  49358. ], HemisphericLight.prototype, "direction", void 0);
  49359. return HemisphericLight;
  49360. }(BABYLON.Light));
  49361. BABYLON.HemisphericLight = HemisphericLight;
  49362. })(BABYLON || (BABYLON = {}));
  49363. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49364. var BABYLON;
  49365. (function (BABYLON) {
  49366. /**
  49367. * Base implementation IShadowLight
  49368. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49369. */
  49370. var ShadowLight = /** @class */ (function (_super) {
  49371. __extends(ShadowLight, _super);
  49372. function ShadowLight() {
  49373. var _this = _super !== null && _super.apply(this, arguments) || this;
  49374. _this._needProjectionMatrixCompute = true;
  49375. return _this;
  49376. }
  49377. ShadowLight.prototype._setPosition = function (value) {
  49378. this._position = value;
  49379. };
  49380. Object.defineProperty(ShadowLight.prototype, "position", {
  49381. /**
  49382. * Sets the position the shadow will be casted from. Also use as the light position for both
  49383. * point and spot lights.
  49384. */
  49385. get: function () {
  49386. return this._position;
  49387. },
  49388. /**
  49389. * Sets the position the shadow will be casted from. Also use as the light position for both
  49390. * point and spot lights.
  49391. */
  49392. set: function (value) {
  49393. this._setPosition(value);
  49394. },
  49395. enumerable: true,
  49396. configurable: true
  49397. });
  49398. ShadowLight.prototype._setDirection = function (value) {
  49399. this._direction = value;
  49400. };
  49401. Object.defineProperty(ShadowLight.prototype, "direction", {
  49402. /**
  49403. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49404. * Also use as the light direction on spot and directional lights.
  49405. */
  49406. get: function () {
  49407. return this._direction;
  49408. },
  49409. /**
  49410. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49411. * Also use as the light direction on spot and directional lights.
  49412. */
  49413. set: function (value) {
  49414. this._setDirection(value);
  49415. },
  49416. enumerable: true,
  49417. configurable: true
  49418. });
  49419. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49420. /**
  49421. * Gets the shadow projection clipping minimum z value.
  49422. */
  49423. get: function () {
  49424. return this._shadowMinZ;
  49425. },
  49426. /**
  49427. * Sets the shadow projection clipping minimum z value.
  49428. */
  49429. set: function (value) {
  49430. this._shadowMinZ = value;
  49431. this.forceProjectionMatrixCompute();
  49432. },
  49433. enumerable: true,
  49434. configurable: true
  49435. });
  49436. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49437. /**
  49438. * Sets the shadow projection clipping maximum z value.
  49439. */
  49440. get: function () {
  49441. return this._shadowMaxZ;
  49442. },
  49443. /**
  49444. * Gets the shadow projection clipping maximum z value.
  49445. */
  49446. set: function (value) {
  49447. this._shadowMaxZ = value;
  49448. this.forceProjectionMatrixCompute();
  49449. },
  49450. enumerable: true,
  49451. configurable: true
  49452. });
  49453. /**
  49454. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49455. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49456. */
  49457. ShadowLight.prototype.computeTransformedInformation = function () {
  49458. if (this.parent && this.parent.getWorldMatrix) {
  49459. if (!this.transformedPosition) {
  49460. this.transformedPosition = BABYLON.Vector3.Zero();
  49461. }
  49462. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49463. // In case the direction is present.
  49464. if (this.direction) {
  49465. if (!this.transformedDirection) {
  49466. this.transformedDirection = BABYLON.Vector3.Zero();
  49467. }
  49468. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49469. }
  49470. return true;
  49471. }
  49472. return false;
  49473. };
  49474. /**
  49475. * Return the depth scale used for the shadow map.
  49476. * @returns the depth scale.
  49477. */
  49478. ShadowLight.prototype.getDepthScale = function () {
  49479. return 50.0;
  49480. };
  49481. /**
  49482. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49483. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49484. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49485. */
  49486. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49487. return this.transformedDirection ? this.transformedDirection : this.direction;
  49488. };
  49489. /**
  49490. * Returns the ShadowLight absolute position in the World.
  49491. * @returns the position vector in world space
  49492. */
  49493. ShadowLight.prototype.getAbsolutePosition = function () {
  49494. return this.transformedPosition ? this.transformedPosition : this.position;
  49495. };
  49496. /**
  49497. * Sets the ShadowLight direction toward the passed target.
  49498. * @param target The point tot target in local space
  49499. * @returns the updated ShadowLight direction
  49500. */
  49501. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49502. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49503. return this.direction;
  49504. };
  49505. /**
  49506. * Returns the light rotation in euler definition.
  49507. * @returns the x y z rotation in local space.
  49508. */
  49509. ShadowLight.prototype.getRotation = function () {
  49510. this.direction.normalize();
  49511. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49512. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49513. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49514. };
  49515. /**
  49516. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49517. * @returns true if a cube texture needs to be use
  49518. */
  49519. ShadowLight.prototype.needCube = function () {
  49520. return false;
  49521. };
  49522. /**
  49523. * Detects if the projection matrix requires to be recomputed this frame.
  49524. * @returns true if it requires to be recomputed otherwise, false.
  49525. */
  49526. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49527. return this._needProjectionMatrixCompute;
  49528. };
  49529. /**
  49530. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49531. */
  49532. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49533. this._needProjectionMatrixCompute = true;
  49534. };
  49535. /**
  49536. * Get the world matrix of the sahdow lights.
  49537. * @hidden Internal Use Only
  49538. */
  49539. ShadowLight.prototype._getWorldMatrix = function () {
  49540. if (!this._worldMatrix) {
  49541. this._worldMatrix = BABYLON.Matrix.Identity();
  49542. }
  49543. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49544. return this._worldMatrix;
  49545. };
  49546. /**
  49547. * Gets the minZ used for shadow according to both the scene and the light.
  49548. * @param activeCamera The camera we are returning the min for
  49549. * @returns the depth min z
  49550. */
  49551. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49552. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49553. };
  49554. /**
  49555. * Gets the maxZ used for shadow according to both the scene and the light.
  49556. * @param activeCamera The camera we are returning the max for
  49557. * @returns the depth max z
  49558. */
  49559. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49560. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49561. };
  49562. /**
  49563. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49564. * @param matrix The materix to updated with the projection information
  49565. * @param viewMatrix The transform matrix of the light
  49566. * @param renderList The list of mesh to render in the map
  49567. * @returns The current light
  49568. */
  49569. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49570. if (this.customProjectionMatrixBuilder) {
  49571. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49572. }
  49573. else {
  49574. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49575. }
  49576. return this;
  49577. };
  49578. __decorate([
  49579. BABYLON.serializeAsVector3()
  49580. ], ShadowLight.prototype, "position", null);
  49581. __decorate([
  49582. BABYLON.serializeAsVector3()
  49583. ], ShadowLight.prototype, "direction", null);
  49584. __decorate([
  49585. BABYLON.serialize()
  49586. ], ShadowLight.prototype, "shadowMinZ", null);
  49587. __decorate([
  49588. BABYLON.serialize()
  49589. ], ShadowLight.prototype, "shadowMaxZ", null);
  49590. return ShadowLight;
  49591. }(BABYLON.Light));
  49592. BABYLON.ShadowLight = ShadowLight;
  49593. })(BABYLON || (BABYLON = {}));
  49594. //# sourceMappingURL=babylon.shadowLight.js.map
  49595. var BABYLON;
  49596. (function (BABYLON) {
  49597. /**
  49598. * A point light is a light defined by an unique point in world space.
  49599. * The light is emitted in every direction from this point.
  49600. * A good example of a point light is a standard light bulb.
  49601. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49602. */
  49603. var PointLight = /** @class */ (function (_super) {
  49604. __extends(PointLight, _super);
  49605. /**
  49606. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49607. * A PointLight emits the light in every direction.
  49608. * It can cast shadows.
  49609. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49610. * ```javascript
  49611. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49612. * ```
  49613. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49614. * @param name The light friendly name
  49615. * @param position The position of the point light in the scene
  49616. * @param scene The scene the lights belongs to
  49617. */
  49618. function PointLight(name, position, scene) {
  49619. var _this = _super.call(this, name, scene) || this;
  49620. _this._shadowAngle = Math.PI / 2;
  49621. _this.position = position;
  49622. return _this;
  49623. }
  49624. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49625. /**
  49626. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49627. * This specifies what angle the shadow will use to be created.
  49628. *
  49629. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49630. */
  49631. get: function () {
  49632. return this._shadowAngle;
  49633. },
  49634. /**
  49635. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49636. * This specifies what angle the shadow will use to be created.
  49637. *
  49638. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49639. */
  49640. set: function (value) {
  49641. this._shadowAngle = value;
  49642. this.forceProjectionMatrixCompute();
  49643. },
  49644. enumerable: true,
  49645. configurable: true
  49646. });
  49647. Object.defineProperty(PointLight.prototype, "direction", {
  49648. /**
  49649. * Gets the direction if it has been set.
  49650. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49651. */
  49652. get: function () {
  49653. return this._direction;
  49654. },
  49655. /**
  49656. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49657. */
  49658. set: function (value) {
  49659. var previousNeedCube = this.needCube();
  49660. this._direction = value;
  49661. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49662. this._shadowGenerator.recreateShadowMap();
  49663. }
  49664. },
  49665. enumerable: true,
  49666. configurable: true
  49667. });
  49668. /**
  49669. * Returns the string "PointLight"
  49670. * @returns the class name
  49671. */
  49672. PointLight.prototype.getClassName = function () {
  49673. return "PointLight";
  49674. };
  49675. /**
  49676. * Returns the integer 0.
  49677. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49678. */
  49679. PointLight.prototype.getTypeID = function () {
  49680. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49681. };
  49682. /**
  49683. * Specifies wether or not the shadowmap should be a cube texture.
  49684. * @returns true if the shadowmap needs to be a cube texture.
  49685. */
  49686. PointLight.prototype.needCube = function () {
  49687. return !this.direction;
  49688. };
  49689. /**
  49690. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49691. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49692. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49693. */
  49694. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49695. if (this.direction) {
  49696. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49697. }
  49698. else {
  49699. switch (faceIndex) {
  49700. case 0:
  49701. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49702. case 1:
  49703. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49704. case 2:
  49705. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49706. case 3:
  49707. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49708. case 4:
  49709. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49710. case 5:
  49711. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49712. }
  49713. }
  49714. return BABYLON.Vector3.Zero();
  49715. };
  49716. /**
  49717. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49718. * - fov = PI / 2
  49719. * - aspect ratio : 1.0
  49720. * - z-near and far equal to the active camera minZ and maxZ.
  49721. * Returns the PointLight.
  49722. */
  49723. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49724. var activeCamera = this.getScene().activeCamera;
  49725. if (!activeCamera) {
  49726. return;
  49727. }
  49728. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49729. };
  49730. PointLight.prototype._buildUniformLayout = function () {
  49731. this._uniformBuffer.addUniform("vLightData", 4);
  49732. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49733. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49734. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49735. this._uniformBuffer.addUniform("depthValues", 2);
  49736. this._uniformBuffer.create();
  49737. };
  49738. /**
  49739. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49740. * @param effect The effect to update
  49741. * @param lightIndex The index of the light in the effect to update
  49742. * @returns The point light
  49743. */
  49744. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49745. if (this.computeTransformedInformation()) {
  49746. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49747. return this;
  49748. }
  49749. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49750. return this;
  49751. };
  49752. __decorate([
  49753. BABYLON.serialize()
  49754. ], PointLight.prototype, "shadowAngle", null);
  49755. return PointLight;
  49756. }(BABYLON.ShadowLight));
  49757. BABYLON.PointLight = PointLight;
  49758. })(BABYLON || (BABYLON = {}));
  49759. //# sourceMappingURL=babylon.pointLight.js.map
  49760. var BABYLON;
  49761. (function (BABYLON) {
  49762. /**
  49763. * A directional light is defined by a direction (what a surprise!).
  49764. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49765. * 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.
  49766. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49767. */
  49768. var DirectionalLight = /** @class */ (function (_super) {
  49769. __extends(DirectionalLight, _super);
  49770. /**
  49771. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49772. * The directional light is emitted from everywhere in the given direction.
  49773. * It can cast shawdows.
  49774. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49775. * @param name The friendly name of the light
  49776. * @param direction The direction of the light
  49777. * @param scene The scene the light belongs to
  49778. */
  49779. function DirectionalLight(name, direction, scene) {
  49780. var _this = _super.call(this, name, scene) || this;
  49781. _this._shadowFrustumSize = 0;
  49782. _this._shadowOrthoScale = 0.1;
  49783. /**
  49784. * Automatically compute the projection matrix to best fit (including all the casters)
  49785. * on each frame.
  49786. */
  49787. _this.autoUpdateExtends = true;
  49788. // Cache
  49789. _this._orthoLeft = Number.MAX_VALUE;
  49790. _this._orthoRight = Number.MIN_VALUE;
  49791. _this._orthoTop = Number.MIN_VALUE;
  49792. _this._orthoBottom = Number.MAX_VALUE;
  49793. _this.position = direction.scale(-1.0);
  49794. _this.direction = direction;
  49795. return _this;
  49796. }
  49797. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49798. /**
  49799. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49800. */
  49801. get: function () {
  49802. return this._shadowFrustumSize;
  49803. },
  49804. /**
  49805. * Specifies a fix frustum size for the shadow generation.
  49806. */
  49807. set: function (value) {
  49808. this._shadowFrustumSize = value;
  49809. this.forceProjectionMatrixCompute();
  49810. },
  49811. enumerable: true,
  49812. configurable: true
  49813. });
  49814. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49815. /**
  49816. * Gets the shadow projection scale against the optimal computed one.
  49817. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49818. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49819. */
  49820. get: function () {
  49821. return this._shadowOrthoScale;
  49822. },
  49823. /**
  49824. * Sets the shadow projection scale against the optimal computed one.
  49825. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49826. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49827. */
  49828. set: function (value) {
  49829. this._shadowOrthoScale = value;
  49830. this.forceProjectionMatrixCompute();
  49831. },
  49832. enumerable: true,
  49833. configurable: true
  49834. });
  49835. /**
  49836. * Returns the string "DirectionalLight".
  49837. * @return The class name
  49838. */
  49839. DirectionalLight.prototype.getClassName = function () {
  49840. return "DirectionalLight";
  49841. };
  49842. /**
  49843. * Returns the integer 1.
  49844. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49845. */
  49846. DirectionalLight.prototype.getTypeID = function () {
  49847. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49848. };
  49849. /**
  49850. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49851. * Returns the DirectionalLight Shadow projection matrix.
  49852. */
  49853. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49854. if (this.shadowFrustumSize > 0) {
  49855. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49856. }
  49857. else {
  49858. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49859. }
  49860. };
  49861. /**
  49862. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49863. * Returns the DirectionalLight Shadow projection matrix.
  49864. */
  49865. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49866. var activeCamera = this.getScene().activeCamera;
  49867. if (!activeCamera) {
  49868. return;
  49869. }
  49870. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49871. };
  49872. /**
  49873. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49874. * Returns the DirectionalLight Shadow projection matrix.
  49875. */
  49876. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49877. var activeCamera = this.getScene().activeCamera;
  49878. if (!activeCamera) {
  49879. return;
  49880. }
  49881. // Check extends
  49882. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49883. var tempVector3 = BABYLON.Vector3.Zero();
  49884. this._orthoLeft = Number.MAX_VALUE;
  49885. this._orthoRight = Number.MIN_VALUE;
  49886. this._orthoTop = Number.MIN_VALUE;
  49887. this._orthoBottom = Number.MAX_VALUE;
  49888. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49889. var mesh = renderList[meshIndex];
  49890. if (!mesh) {
  49891. continue;
  49892. }
  49893. var boundingInfo = mesh.getBoundingInfo();
  49894. var boundingBox = boundingInfo.boundingBox;
  49895. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49896. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49897. if (tempVector3.x < this._orthoLeft)
  49898. this._orthoLeft = tempVector3.x;
  49899. if (tempVector3.y < this._orthoBottom)
  49900. this._orthoBottom = tempVector3.y;
  49901. if (tempVector3.x > this._orthoRight)
  49902. this._orthoRight = tempVector3.x;
  49903. if (tempVector3.y > this._orthoTop)
  49904. this._orthoTop = tempVector3.y;
  49905. }
  49906. }
  49907. }
  49908. var xOffset = this._orthoRight - this._orthoLeft;
  49909. var yOffset = this._orthoTop - this._orthoBottom;
  49910. 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);
  49911. };
  49912. DirectionalLight.prototype._buildUniformLayout = function () {
  49913. this._uniformBuffer.addUniform("vLightData", 4);
  49914. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49915. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49916. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49917. this._uniformBuffer.addUniform("depthValues", 2);
  49918. this._uniformBuffer.create();
  49919. };
  49920. /**
  49921. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49922. * @param effect The effect to update
  49923. * @param lightIndex The index of the light in the effect to update
  49924. * @returns The directional light
  49925. */
  49926. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49927. if (this.computeTransformedInformation()) {
  49928. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49929. return this;
  49930. }
  49931. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49932. return this;
  49933. };
  49934. /**
  49935. * Gets the minZ used for shadow according to both the scene and the light.
  49936. *
  49937. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49938. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49939. * @param activeCamera The camera we are returning the min for
  49940. * @returns the depth min z
  49941. */
  49942. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49943. return 1;
  49944. };
  49945. /**
  49946. * Gets the maxZ used for shadow according to both the scene and the light.
  49947. *
  49948. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49949. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49950. * @param activeCamera The camera we are returning the max for
  49951. * @returns the depth max z
  49952. */
  49953. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49954. return 1;
  49955. };
  49956. __decorate([
  49957. BABYLON.serialize()
  49958. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49959. __decorate([
  49960. BABYLON.serialize()
  49961. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49962. __decorate([
  49963. BABYLON.serialize()
  49964. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49965. return DirectionalLight;
  49966. }(BABYLON.ShadowLight));
  49967. BABYLON.DirectionalLight = DirectionalLight;
  49968. })(BABYLON || (BABYLON = {}));
  49969. //# sourceMappingURL=babylon.directionalLight.js.map
  49970. var BABYLON;
  49971. (function (BABYLON) {
  49972. /**
  49973. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49974. * These values define a cone of light starting from the position, emitting toward the direction.
  49975. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49976. * and the exponent defines the speed of the decay of the light with distance (reach).
  49977. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49978. */
  49979. var SpotLight = /** @class */ (function (_super) {
  49980. __extends(SpotLight, _super);
  49981. /**
  49982. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49983. * It can cast shadows.
  49984. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49985. * @param name The light friendly name
  49986. * @param position The position of the spot light in the scene
  49987. * @param direction The direction of the light in the scene
  49988. * @param angle The cone angle of the light in Radians
  49989. * @param exponent The light decay speed with the distance from the emission spot
  49990. * @param scene The scene the lights belongs to
  49991. */
  49992. function SpotLight(name, position, direction, angle, exponent, scene) {
  49993. var _this = _super.call(this, name, scene) || this;
  49994. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49995. _this._projectionTextureLightNear = 1e-6;
  49996. _this._projectionTextureLightFar = 1000.0;
  49997. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49998. _this._projectionTextureViewLightDirty = true;
  49999. _this._projectionTextureProjectionLightDirty = true;
  50000. _this._projectionTextureDirty = true;
  50001. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50002. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50003. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50004. _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);
  50005. _this.position = position;
  50006. _this.direction = direction;
  50007. _this.angle = angle;
  50008. _this.exponent = exponent;
  50009. return _this;
  50010. }
  50011. Object.defineProperty(SpotLight.prototype, "angle", {
  50012. /**
  50013. * Gets the cone angle of the spot light in Radians.
  50014. */
  50015. get: function () {
  50016. return this._angle;
  50017. },
  50018. /**
  50019. * Sets the cone angle of the spot light in Radians.
  50020. */
  50021. set: function (value) {
  50022. this._angle = value;
  50023. this._projectionTextureProjectionLightDirty = true;
  50024. this.forceProjectionMatrixCompute();
  50025. },
  50026. enumerable: true,
  50027. configurable: true
  50028. });
  50029. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50030. /**
  50031. * Allows scaling the angle of the light for shadow generation only.
  50032. */
  50033. get: function () {
  50034. return this._shadowAngleScale;
  50035. },
  50036. /**
  50037. * Allows scaling the angle of the light for shadow generation only.
  50038. */
  50039. set: function (value) {
  50040. this._shadowAngleScale = value;
  50041. this.forceProjectionMatrixCompute();
  50042. },
  50043. enumerable: true,
  50044. configurable: true
  50045. });
  50046. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50047. /**
  50048. * Allows reading the projecton texture
  50049. */
  50050. get: function () {
  50051. return this._projectionTextureMatrix;
  50052. },
  50053. enumerable: true,
  50054. configurable: true
  50055. });
  50056. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50057. /**
  50058. * Gets the near clip of the Spotlight for texture projection.
  50059. */
  50060. get: function () {
  50061. return this._projectionTextureLightNear;
  50062. },
  50063. /**
  50064. * Sets the near clip of the Spotlight for texture projection.
  50065. */
  50066. set: function (value) {
  50067. this._projectionTextureLightNear = value;
  50068. this._projectionTextureProjectionLightDirty = true;
  50069. },
  50070. enumerable: true,
  50071. configurable: true
  50072. });
  50073. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50074. /**
  50075. * Gets the far clip of the Spotlight for texture projection.
  50076. */
  50077. get: function () {
  50078. return this._projectionTextureLightFar;
  50079. },
  50080. /**
  50081. * Sets the far clip of the Spotlight for texture projection.
  50082. */
  50083. set: function (value) {
  50084. this._projectionTextureLightFar = value;
  50085. this._projectionTextureProjectionLightDirty = true;
  50086. },
  50087. enumerable: true,
  50088. configurable: true
  50089. });
  50090. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50091. /**
  50092. * Gets the Up vector of the Spotlight for texture projection.
  50093. */
  50094. get: function () {
  50095. return this._projectionTextureUpDirection;
  50096. },
  50097. /**
  50098. * Sets the Up vector of the Spotlight for texture projection.
  50099. */
  50100. set: function (value) {
  50101. this._projectionTextureUpDirection = value;
  50102. this._projectionTextureProjectionLightDirty = true;
  50103. },
  50104. enumerable: true,
  50105. configurable: true
  50106. });
  50107. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50108. /**
  50109. * Gets the projection texture of the light.
  50110. */
  50111. get: function () {
  50112. return this._projectionTexture;
  50113. },
  50114. /**
  50115. * Sets the projection texture of the light.
  50116. */
  50117. set: function (value) {
  50118. this._projectionTexture = value;
  50119. this._projectionTextureDirty = true;
  50120. },
  50121. enumerable: true,
  50122. configurable: true
  50123. });
  50124. /**
  50125. * Returns the string "SpotLight".
  50126. * @returns the class name
  50127. */
  50128. SpotLight.prototype.getClassName = function () {
  50129. return "SpotLight";
  50130. };
  50131. /**
  50132. * Returns the integer 2.
  50133. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50134. */
  50135. SpotLight.prototype.getTypeID = function () {
  50136. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50137. };
  50138. /**
  50139. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50140. */
  50141. SpotLight.prototype._setDirection = function (value) {
  50142. _super.prototype._setDirection.call(this, value);
  50143. this._projectionTextureViewLightDirty = true;
  50144. };
  50145. /**
  50146. * Overrides the position setter to recompute the projection texture view light Matrix.
  50147. */
  50148. SpotLight.prototype._setPosition = function (value) {
  50149. _super.prototype._setPosition.call(this, value);
  50150. this._projectionTextureViewLightDirty = true;
  50151. };
  50152. /**
  50153. * 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.
  50154. * Returns the SpotLight.
  50155. */
  50156. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50157. var activeCamera = this.getScene().activeCamera;
  50158. if (!activeCamera) {
  50159. return;
  50160. }
  50161. this._shadowAngleScale = this._shadowAngleScale || 1;
  50162. var angle = this._shadowAngleScale * this._angle;
  50163. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50164. };
  50165. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50166. this._projectionTextureViewLightDirty = false;
  50167. this._projectionTextureDirty = true;
  50168. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50169. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50170. };
  50171. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50172. this._projectionTextureProjectionLightDirty = false;
  50173. this._projectionTextureDirty = true;
  50174. var light_far = this.projectionTextureLightFar;
  50175. var light_near = this.projectionTextureLightNear;
  50176. var P = light_far / (light_far - light_near);
  50177. var Q = -P * light_near;
  50178. var S = 1.0 / Math.tan(this._angle / 2.0);
  50179. var A = 1.0;
  50180. 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);
  50181. };
  50182. /**
  50183. * Main function for light texture projection matrix computing.
  50184. */
  50185. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50186. this._projectionTextureDirty = false;
  50187. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50188. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50189. };
  50190. SpotLight.prototype._buildUniformLayout = function () {
  50191. this._uniformBuffer.addUniform("vLightData", 4);
  50192. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50193. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50194. this._uniformBuffer.addUniform("vLightDirection", 3);
  50195. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50196. this._uniformBuffer.addUniform("depthValues", 2);
  50197. this._uniformBuffer.create();
  50198. };
  50199. /**
  50200. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50201. * @param effect The effect to update
  50202. * @param lightIndex The index of the light in the effect to update
  50203. * @returns The spot light
  50204. */
  50205. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50206. var normalizeDirection;
  50207. if (this.computeTransformedInformation()) {
  50208. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50209. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50210. }
  50211. else {
  50212. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50213. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50214. }
  50215. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50216. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50217. if (this._projectionTextureViewLightDirty) {
  50218. this._computeProjectionTextureViewLightMatrix();
  50219. }
  50220. if (this._projectionTextureProjectionLightDirty) {
  50221. this._computeProjectionTextureProjectionLightMatrix();
  50222. }
  50223. if (this._projectionTextureDirty) {
  50224. this._computeProjectionTextureMatrix();
  50225. }
  50226. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50227. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50228. }
  50229. return this;
  50230. };
  50231. /**
  50232. * Disposes the light and the associated resources.
  50233. */
  50234. SpotLight.prototype.dispose = function () {
  50235. _super.prototype.dispose.call(this);
  50236. if (this._projectionTexture) {
  50237. this._projectionTexture.dispose();
  50238. }
  50239. };
  50240. __decorate([
  50241. BABYLON.serialize()
  50242. ], SpotLight.prototype, "angle", null);
  50243. __decorate([
  50244. BABYLON.serialize()
  50245. ], SpotLight.prototype, "shadowAngleScale", null);
  50246. __decorate([
  50247. BABYLON.serialize()
  50248. ], SpotLight.prototype, "exponent", void 0);
  50249. __decorate([
  50250. BABYLON.serialize()
  50251. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50252. __decorate([
  50253. BABYLON.serialize()
  50254. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50255. __decorate([
  50256. BABYLON.serialize()
  50257. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50258. __decorate([
  50259. BABYLON.serializeAsTexture("projectedLightTexture")
  50260. ], SpotLight.prototype, "_projectionTexture", void 0);
  50261. return SpotLight;
  50262. }(BABYLON.ShadowLight));
  50263. BABYLON.SpotLight = SpotLight;
  50264. })(BABYLON || (BABYLON = {}));
  50265. //# sourceMappingURL=babylon.spotLight.js.map
  50266. var BABYLON;
  50267. (function (BABYLON) {
  50268. /**
  50269. * Class used to override all child animations of a given target
  50270. */
  50271. var AnimationPropertiesOverride = /** @class */ (function () {
  50272. function AnimationPropertiesOverride() {
  50273. /**
  50274. * Gets or sets a value indicating if animation blending must be used
  50275. */
  50276. this.enableBlending = false;
  50277. /**
  50278. * Gets or sets the blending speed to use when enableBlending is true
  50279. */
  50280. this.blendingSpeed = 0.01;
  50281. /**
  50282. * Gets or sets the default loop mode to use
  50283. */
  50284. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50285. }
  50286. return AnimationPropertiesOverride;
  50287. }());
  50288. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50289. })(BABYLON || (BABYLON = {}));
  50290. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50291. var BABYLON;
  50292. (function (BABYLON) {
  50293. /**
  50294. * Represents the range of an animation
  50295. */
  50296. var AnimationRange = /** @class */ (function () {
  50297. /**
  50298. * Initializes the range of an animation
  50299. * @param name The name of the animation range
  50300. * @param from The starting frame of the animation
  50301. * @param to The ending frame of the animation
  50302. */
  50303. function AnimationRange(
  50304. /**The name of the animation range**/
  50305. name,
  50306. /**The starting frame of the animation */
  50307. from,
  50308. /**The ending frame of the animation*/
  50309. to) {
  50310. this.name = name;
  50311. this.from = from;
  50312. this.to = to;
  50313. }
  50314. /**
  50315. * Makes a copy of the animation range
  50316. * @returns A copy of the animation range
  50317. */
  50318. AnimationRange.prototype.clone = function () {
  50319. return new AnimationRange(this.name, this.from, this.to);
  50320. };
  50321. return AnimationRange;
  50322. }());
  50323. BABYLON.AnimationRange = AnimationRange;
  50324. /**
  50325. * Composed of a frame, and an action function
  50326. */
  50327. var AnimationEvent = /** @class */ (function () {
  50328. /**
  50329. * Initializes the animation event
  50330. * @param frame The frame for which the event is triggered
  50331. * @param action The event to perform when triggered
  50332. * @param onlyOnce Specifies if the event should be triggered only once
  50333. */
  50334. function AnimationEvent(
  50335. /** The frame for which the event is triggered **/
  50336. frame,
  50337. /** The event to perform when triggered **/
  50338. action,
  50339. /** Specifies if the event should be triggered only once**/
  50340. onlyOnce) {
  50341. this.frame = frame;
  50342. this.action = action;
  50343. this.onlyOnce = onlyOnce;
  50344. /**
  50345. * Specifies if the animation event is done
  50346. */
  50347. this.isDone = false;
  50348. }
  50349. /** @hidden */
  50350. AnimationEvent.prototype._clone = function () {
  50351. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50352. };
  50353. return AnimationEvent;
  50354. }());
  50355. BABYLON.AnimationEvent = AnimationEvent;
  50356. /**
  50357. * A cursor which tracks a point on a path
  50358. */
  50359. var PathCursor = /** @class */ (function () {
  50360. /**
  50361. * Initializes the path cursor
  50362. * @param path The path to track
  50363. */
  50364. function PathCursor(path) {
  50365. this.path = path;
  50366. /**
  50367. * Stores path cursor callbacks for when an onchange event is triggered
  50368. */
  50369. this._onchange = new Array();
  50370. /**
  50371. * The value of the path cursor
  50372. */
  50373. this.value = 0;
  50374. /**
  50375. * The animation array of the path cursor
  50376. */
  50377. this.animations = new Array();
  50378. }
  50379. /**
  50380. * Gets the cursor point on the path
  50381. * @returns A point on the path cursor at the cursor location
  50382. */
  50383. PathCursor.prototype.getPoint = function () {
  50384. var point = this.path.getPointAtLengthPosition(this.value);
  50385. return new BABYLON.Vector3(point.x, 0, point.y);
  50386. };
  50387. /**
  50388. * Moves the cursor ahead by the step amount
  50389. * @param step The amount to move the cursor forward
  50390. * @returns This path cursor
  50391. */
  50392. PathCursor.prototype.moveAhead = function (step) {
  50393. if (step === void 0) { step = 0.002; }
  50394. this.move(step);
  50395. return this;
  50396. };
  50397. /**
  50398. * Moves the cursor behind by the step amount
  50399. * @param step The amount to move the cursor back
  50400. * @returns This path cursor
  50401. */
  50402. PathCursor.prototype.moveBack = function (step) {
  50403. if (step === void 0) { step = 0.002; }
  50404. this.move(-step);
  50405. return this;
  50406. };
  50407. /**
  50408. * Moves the cursor by the step amount
  50409. * If the step amount is greater than one, an exception is thrown
  50410. * @param step The amount to move the cursor
  50411. * @returns This path cursor
  50412. */
  50413. PathCursor.prototype.move = function (step) {
  50414. if (Math.abs(step) > 1) {
  50415. throw "step size should be less than 1.";
  50416. }
  50417. this.value += step;
  50418. this.ensureLimits();
  50419. this.raiseOnChange();
  50420. return this;
  50421. };
  50422. /**
  50423. * Ensures that the value is limited between zero and one
  50424. * @returns This path cursor
  50425. */
  50426. PathCursor.prototype.ensureLimits = function () {
  50427. while (this.value > 1) {
  50428. this.value -= 1;
  50429. }
  50430. while (this.value < 0) {
  50431. this.value += 1;
  50432. }
  50433. return this;
  50434. };
  50435. /**
  50436. * Runs onchange callbacks on change (used by the animation engine)
  50437. * @returns This path cursor
  50438. */
  50439. PathCursor.prototype.raiseOnChange = function () {
  50440. var _this = this;
  50441. this._onchange.forEach(function (f) { return f(_this); });
  50442. return this;
  50443. };
  50444. /**
  50445. * Executes a function on change
  50446. * @param f A path cursor onchange callback
  50447. * @returns This path cursor
  50448. */
  50449. PathCursor.prototype.onchange = function (f) {
  50450. this._onchange.push(f);
  50451. return this;
  50452. };
  50453. return PathCursor;
  50454. }());
  50455. BABYLON.PathCursor = PathCursor;
  50456. /**
  50457. * Enum for the animation key frame interpolation type
  50458. */
  50459. var AnimationKeyInterpolation;
  50460. (function (AnimationKeyInterpolation) {
  50461. /**
  50462. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50463. */
  50464. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50465. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50466. /**
  50467. * Class used to store any kind of animation
  50468. */
  50469. var Animation = /** @class */ (function () {
  50470. /**
  50471. * Initializes the animation
  50472. * @param name Name of the animation
  50473. * @param targetProperty Property to animate
  50474. * @param framePerSecond The frames per second of the animation
  50475. * @param dataType The data type of the animation
  50476. * @param loopMode The loop mode of the animation
  50477. * @param enableBlendings Specifies if blending should be enabled
  50478. */
  50479. function Animation(
  50480. /**Name of the animation */
  50481. name,
  50482. /**Property to animate */
  50483. targetProperty,
  50484. /**The frames per second of the animation */
  50485. framePerSecond,
  50486. /**The data type of the animation */
  50487. dataType,
  50488. /**The loop mode of the animation */
  50489. loopMode,
  50490. /**Specifies if blending should be enabled */
  50491. enableBlending) {
  50492. this.name = name;
  50493. this.targetProperty = targetProperty;
  50494. this.framePerSecond = framePerSecond;
  50495. this.dataType = dataType;
  50496. this.loopMode = loopMode;
  50497. this.enableBlending = enableBlending;
  50498. /**
  50499. * @hidden Internal use only
  50500. */
  50501. this._runtimeAnimations = new Array();
  50502. /**
  50503. * The set of event that will be linked to this animation
  50504. */
  50505. this._events = new Array();
  50506. /**
  50507. * Stores the blending speed of the animation
  50508. */
  50509. this.blendingSpeed = 0.01;
  50510. /**
  50511. * Stores the animation ranges for the animation
  50512. */
  50513. this._ranges = {};
  50514. this.targetPropertyPath = targetProperty.split(".");
  50515. this.dataType = dataType;
  50516. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50517. }
  50518. /**
  50519. * @hidden Internal use
  50520. */
  50521. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50522. var dataType = undefined;
  50523. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50524. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50525. }
  50526. else if (from instanceof BABYLON.Quaternion) {
  50527. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50528. }
  50529. else if (from instanceof BABYLON.Vector3) {
  50530. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50531. }
  50532. else if (from instanceof BABYLON.Vector2) {
  50533. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50534. }
  50535. else if (from instanceof BABYLON.Color3) {
  50536. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50537. }
  50538. else if (from instanceof BABYLON.Size) {
  50539. dataType = Animation.ANIMATIONTYPE_SIZE;
  50540. }
  50541. if (dataType == undefined) {
  50542. return null;
  50543. }
  50544. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50545. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50546. animation.setKeys(keys);
  50547. if (easingFunction !== undefined) {
  50548. animation.setEasingFunction(easingFunction);
  50549. }
  50550. return animation;
  50551. };
  50552. /**
  50553. * Sets up an animation
  50554. * @param property The property to animate
  50555. * @param animationType The animation type to apply
  50556. * @param framePerSecond The frames per second of the animation
  50557. * @param easingFunction The easing function used in the animation
  50558. * @returns The created animation
  50559. */
  50560. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50561. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50562. animation.setEasingFunction(easingFunction);
  50563. return animation;
  50564. };
  50565. /**
  50566. * Create and start an animation on a node
  50567. * @param name defines the name of the global animation that will be run on all nodes
  50568. * @param node defines the root node where the animation will take place
  50569. * @param targetProperty defines property to animate
  50570. * @param framePerSecond defines the number of frame per second yo use
  50571. * @param totalFrame defines the number of frames in total
  50572. * @param from defines the initial value
  50573. * @param to defines the final value
  50574. * @param loopMode defines which loop mode you want to use (off by default)
  50575. * @param easingFunction defines the easing function to use (linear by default)
  50576. * @param onAnimationEnd defines the callback to call when animation end
  50577. * @returns the animatable created for this animation
  50578. */
  50579. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50580. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50581. if (!animation) {
  50582. return null;
  50583. }
  50584. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50585. };
  50586. /**
  50587. * Create and start an animation on a node and its descendants
  50588. * @param name defines the name of the global animation that will be run on all nodes
  50589. * @param node defines the root node where the animation will take place
  50590. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used
  50591. * @param targetProperty defines property to animate
  50592. * @param framePerSecond defines the number of frame per second to use
  50593. * @param totalFrame defines the number of frames in total
  50594. * @param from defines the initial value
  50595. * @param to defines the final value
  50596. * @param loopMode defines which loop mode you want to use (off by default)
  50597. * @param easingFunction defines the easing function to use (linear by default)
  50598. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50599. * @returns the list of animatables created for all nodes
  50600. * @example https://www.babylonjs-playground.com/#MH0VLI
  50601. */
  50602. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50603. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50604. if (!animation) {
  50605. return null;
  50606. }
  50607. var scene = node.getScene();
  50608. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50609. };
  50610. /**
  50611. * Creates a new animation, merges it with the existing animations and starts it
  50612. * @param name Name of the animation
  50613. * @param node Node which contains the scene that begins the animations
  50614. * @param targetProperty Specifies which property to animate
  50615. * @param framePerSecond The frames per second of the animation
  50616. * @param totalFrame The total number of frames
  50617. * @param from The frame at the beginning of the animation
  50618. * @param to The frame at the end of the animation
  50619. * @param loopMode Specifies the loop mode of the animation
  50620. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50621. * @param onAnimationEnd Callback to run once the animation is complete
  50622. * @returns Nullable animation
  50623. */
  50624. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50625. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50626. if (!animation) {
  50627. return null;
  50628. }
  50629. node.animations.push(animation);
  50630. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50631. };
  50632. /**
  50633. * Transition property of the Camera to the target Value
  50634. * @param property The property to transition
  50635. * @param targetValue The target Value of the property
  50636. * @param host The object where the property to animate belongs
  50637. * @param scene Scene used to run the animation
  50638. * @param frameRate Framerate (in frame/s) to use
  50639. * @param transition The transition type we want to use
  50640. * @param duration The duration of the animation, in milliseconds
  50641. * @param onAnimationEnd Callback trigger at the end of the animation
  50642. * @returns Nullable animation
  50643. */
  50644. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50645. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50646. if (duration <= 0) {
  50647. host[property] = targetValue;
  50648. if (onAnimationEnd) {
  50649. onAnimationEnd();
  50650. }
  50651. return null;
  50652. }
  50653. var endFrame = frameRate * (duration / 1000);
  50654. transition.setKeys([{
  50655. frame: 0,
  50656. value: host[property].clone ? host[property].clone() : host[property]
  50657. },
  50658. {
  50659. frame: endFrame,
  50660. value: targetValue
  50661. }]);
  50662. if (!host.animations) {
  50663. host.animations = [];
  50664. }
  50665. host.animations.push(transition);
  50666. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50667. animation.onAnimationEnd = onAnimationEnd;
  50668. return animation;
  50669. };
  50670. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50671. /**
  50672. * Return the array of runtime animations currently using this animation
  50673. */
  50674. get: function () {
  50675. return this._runtimeAnimations;
  50676. },
  50677. enumerable: true,
  50678. configurable: true
  50679. });
  50680. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50681. /**
  50682. * Specifies if any of the runtime animations are currently running
  50683. */
  50684. get: function () {
  50685. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50686. var runtimeAnimation = _a[_i];
  50687. if (!runtimeAnimation.isStopped) {
  50688. return true;
  50689. }
  50690. }
  50691. return false;
  50692. },
  50693. enumerable: true,
  50694. configurable: true
  50695. });
  50696. // Methods
  50697. /**
  50698. * Converts the animation to a string
  50699. * @param fullDetails support for multiple levels of logging within scene loading
  50700. * @returns String form of the animation
  50701. */
  50702. Animation.prototype.toString = function (fullDetails) {
  50703. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50704. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50705. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50706. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50707. if (fullDetails) {
  50708. ret += ", Ranges: {";
  50709. var first = true;
  50710. for (var name in this._ranges) {
  50711. if (first) {
  50712. ret += ", ";
  50713. first = false;
  50714. }
  50715. ret += name;
  50716. }
  50717. ret += "}";
  50718. }
  50719. return ret;
  50720. };
  50721. /**
  50722. * Add an event to this animation
  50723. * @param event Event to add
  50724. */
  50725. Animation.prototype.addEvent = function (event) {
  50726. this._events.push(event);
  50727. };
  50728. /**
  50729. * Remove all events found at the given frame
  50730. * @param frame The frame to remove events from
  50731. */
  50732. Animation.prototype.removeEvents = function (frame) {
  50733. for (var index = 0; index < this._events.length; index++) {
  50734. if (this._events[index].frame === frame) {
  50735. this._events.splice(index, 1);
  50736. index--;
  50737. }
  50738. }
  50739. };
  50740. /**
  50741. * Retrieves all the events from the animation
  50742. * @returns Events from the animation
  50743. */
  50744. Animation.prototype.getEvents = function () {
  50745. return this._events;
  50746. };
  50747. /**
  50748. * Creates an animation range
  50749. * @param name Name of the animation range
  50750. * @param from Starting frame of the animation range
  50751. * @param to Ending frame of the animation
  50752. */
  50753. Animation.prototype.createRange = function (name, from, to) {
  50754. // check name not already in use; could happen for bones after serialized
  50755. if (!this._ranges[name]) {
  50756. this._ranges[name] = new AnimationRange(name, from, to);
  50757. }
  50758. };
  50759. /**
  50760. * Deletes an animation range by name
  50761. * @param name Name of the animation range to delete
  50762. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50763. */
  50764. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50765. if (deleteFrames === void 0) { deleteFrames = true; }
  50766. var range = this._ranges[name];
  50767. if (!range) {
  50768. return;
  50769. }
  50770. if (deleteFrames) {
  50771. var from = range.from;
  50772. var to = range.to;
  50773. // this loop MUST go high to low for multiple splices to work
  50774. for (var key = this._keys.length - 1; key >= 0; key--) {
  50775. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50776. this._keys.splice(key, 1);
  50777. }
  50778. }
  50779. }
  50780. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50781. };
  50782. /**
  50783. * Gets the animation range by name, or null if not defined
  50784. * @param name Name of the animation range
  50785. * @returns Nullable animation range
  50786. */
  50787. Animation.prototype.getRange = function (name) {
  50788. return this._ranges[name];
  50789. };
  50790. /**
  50791. * Gets the key frames from the animation
  50792. * @returns The key frames of the animation
  50793. */
  50794. Animation.prototype.getKeys = function () {
  50795. return this._keys;
  50796. };
  50797. /**
  50798. * Gets the highest frame rate of the animation
  50799. * @returns Highest frame rate of the animation
  50800. */
  50801. Animation.prototype.getHighestFrame = function () {
  50802. var ret = 0;
  50803. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50804. if (ret < this._keys[key].frame) {
  50805. ret = this._keys[key].frame;
  50806. }
  50807. }
  50808. return ret;
  50809. };
  50810. /**
  50811. * Gets the easing function of the animation
  50812. * @returns Easing function of the animation
  50813. */
  50814. Animation.prototype.getEasingFunction = function () {
  50815. return this._easingFunction;
  50816. };
  50817. /**
  50818. * Sets the easing function of the animation
  50819. * @param easingFunction A custom mathematical formula for animation
  50820. */
  50821. Animation.prototype.setEasingFunction = function (easingFunction) {
  50822. this._easingFunction = easingFunction;
  50823. };
  50824. /**
  50825. * Interpolates a scalar linearly
  50826. * @param startValue Start value of the animation curve
  50827. * @param endValue End value of the animation curve
  50828. * @param gradient Scalar amount to interpolate
  50829. * @returns Interpolated scalar value
  50830. */
  50831. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50832. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50833. };
  50834. /**
  50835. * Interpolates a scalar cubically
  50836. * @param startValue Start value of the animation curve
  50837. * @param outTangent End tangent of the animation
  50838. * @param endValue End value of the animation curve
  50839. * @param inTangent Start tangent of the animation curve
  50840. * @param gradient Scalar amount to interpolate
  50841. * @returns Interpolated scalar value
  50842. */
  50843. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50844. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50845. };
  50846. /**
  50847. * Interpolates a quaternion using a spherical linear interpolation
  50848. * @param startValue Start value of the animation curve
  50849. * @param endValue End value of the animation curve
  50850. * @param gradient Scalar amount to interpolate
  50851. * @returns Interpolated quaternion value
  50852. */
  50853. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50854. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50855. };
  50856. /**
  50857. * Interpolates a quaternion cubically
  50858. * @param startValue Start value of the animation curve
  50859. * @param outTangent End tangent of the animation curve
  50860. * @param endValue End value of the animation curve
  50861. * @param inTangent Start tangent of the animation curve
  50862. * @param gradient Scalar amount to interpolate
  50863. * @returns Interpolated quaternion value
  50864. */
  50865. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50866. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50867. };
  50868. /**
  50869. * Interpolates a Vector3 linearl
  50870. * @param startValue Start value of the animation curve
  50871. * @param endValue End value of the animation curve
  50872. * @param gradient Scalar amount to interpolate
  50873. * @returns Interpolated scalar value
  50874. */
  50875. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50876. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50877. };
  50878. /**
  50879. * Interpolates a Vector3 cubically
  50880. * @param startValue Start value of the animation curve
  50881. * @param outTangent End tangent of the animation
  50882. * @param endValue End value of the animation curve
  50883. * @param inTangent Start tangent of the animation curve
  50884. * @param gradient Scalar amount to interpolate
  50885. * @returns InterpolatedVector3 value
  50886. */
  50887. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50888. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50889. };
  50890. /**
  50891. * Interpolates a Vector2 linearly
  50892. * @param startValue Start value of the animation curve
  50893. * @param endValue End value of the animation curve
  50894. * @param gradient Scalar amount to interpolate
  50895. * @returns Interpolated Vector2 value
  50896. */
  50897. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50898. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50899. };
  50900. /**
  50901. * Interpolates a Vector2 cubically
  50902. * @param startValue Start value of the animation curve
  50903. * @param outTangent End tangent of the animation
  50904. * @param endValue End value of the animation curve
  50905. * @param inTangent Start tangent of the animation curve
  50906. * @param gradient Scalar amount to interpolate
  50907. * @returns Interpolated Vector2 value
  50908. */
  50909. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50910. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50911. };
  50912. /**
  50913. * Interpolates a size linearly
  50914. * @param startValue Start value of the animation curve
  50915. * @param endValue End value of the animation curve
  50916. * @param gradient Scalar amount to interpolate
  50917. * @returns Interpolated Size value
  50918. */
  50919. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50920. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50921. };
  50922. /**
  50923. * Interpolates a Color3 linearly
  50924. * @param startValue Start value of the animation curve
  50925. * @param endValue End value of the animation curve
  50926. * @param gradient Scalar amount to interpolate
  50927. * @returns Interpolated Color3 value
  50928. */
  50929. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50930. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50931. };
  50932. /**
  50933. * @hidden Internal use only
  50934. */
  50935. Animation.prototype._getKeyValue = function (value) {
  50936. if (typeof value === "function") {
  50937. return value();
  50938. }
  50939. return value;
  50940. };
  50941. /**
  50942. * @hidden Internal use only
  50943. */
  50944. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50945. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50946. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50947. }
  50948. var keys = this.getKeys();
  50949. // Try to get a hash to find the right key
  50950. 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));
  50951. if (keys[startKeyIndex].frame >= currentFrame) {
  50952. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50953. startKeyIndex--;
  50954. }
  50955. }
  50956. for (var key = startKeyIndex; key < keys.length; key++) {
  50957. var endKey = keys[key + 1];
  50958. if (endKey.frame >= currentFrame) {
  50959. var startKey = keys[key];
  50960. var startValue = this._getKeyValue(startKey.value);
  50961. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50962. return startValue;
  50963. }
  50964. var endValue = this._getKeyValue(endKey.value);
  50965. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50966. var frameDelta = endKey.frame - startKey.frame;
  50967. // gradient : percent of currentFrame between the frame inf and the frame sup
  50968. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50969. // check for easingFunction and correction of gradient
  50970. var easingFunction = this.getEasingFunction();
  50971. if (easingFunction != null) {
  50972. gradient = easingFunction.ease(gradient);
  50973. }
  50974. switch (this.dataType) {
  50975. // Float
  50976. case Animation.ANIMATIONTYPE_FLOAT:
  50977. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50978. switch (loopMode) {
  50979. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50980. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50981. return floatValue;
  50982. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50983. return offsetValue * repeatCount + floatValue;
  50984. }
  50985. break;
  50986. // Quaternion
  50987. case Animation.ANIMATIONTYPE_QUATERNION:
  50988. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50989. switch (loopMode) {
  50990. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50991. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50992. return quatValue;
  50993. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50994. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50995. }
  50996. return quatValue;
  50997. // Vector3
  50998. case Animation.ANIMATIONTYPE_VECTOR3:
  50999. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51000. switch (loopMode) {
  51001. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51002. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51003. return vec3Value;
  51004. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51005. return vec3Value.add(offsetValue.scale(repeatCount));
  51006. }
  51007. // Vector2
  51008. case Animation.ANIMATIONTYPE_VECTOR2:
  51009. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51010. switch (loopMode) {
  51011. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51012. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51013. return vec2Value;
  51014. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51015. return vec2Value.add(offsetValue.scale(repeatCount));
  51016. }
  51017. // Size
  51018. case Animation.ANIMATIONTYPE_SIZE:
  51019. switch (loopMode) {
  51020. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51021. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51022. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51023. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51024. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51025. }
  51026. // Color3
  51027. case Animation.ANIMATIONTYPE_COLOR3:
  51028. switch (loopMode) {
  51029. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51030. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51031. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51032. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51033. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51034. }
  51035. // Matrix
  51036. case Animation.ANIMATIONTYPE_MATRIX:
  51037. switch (loopMode) {
  51038. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51039. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51040. if (Animation.AllowMatricesInterpolation) {
  51041. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51042. }
  51043. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51044. return startValue;
  51045. }
  51046. default:
  51047. break;
  51048. }
  51049. break;
  51050. }
  51051. }
  51052. return this._getKeyValue(keys[keys.length - 1].value);
  51053. };
  51054. /**
  51055. * Defines the function to use to interpolate matrices
  51056. * @param startValue defines the start matrix
  51057. * @param endValue defines the end matrix
  51058. * @param gradient defines the gradient between both matrices
  51059. * @param result defines an optional target matrix where to store the interpolation
  51060. * @returns the interpolated matrix
  51061. */
  51062. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51063. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51064. if (result) {
  51065. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51066. return result;
  51067. }
  51068. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51069. }
  51070. if (result) {
  51071. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51072. return result;
  51073. }
  51074. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51075. };
  51076. /**
  51077. * Makes a copy of the animation
  51078. * @returns Cloned animation
  51079. */
  51080. Animation.prototype.clone = function () {
  51081. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51082. clone.enableBlending = this.enableBlending;
  51083. clone.blendingSpeed = this.blendingSpeed;
  51084. if (this._keys) {
  51085. clone.setKeys(this._keys);
  51086. }
  51087. if (this._ranges) {
  51088. clone._ranges = {};
  51089. for (var name in this._ranges) {
  51090. var range = this._ranges[name];
  51091. if (!range) {
  51092. continue;
  51093. }
  51094. clone._ranges[name] = range.clone();
  51095. }
  51096. }
  51097. return clone;
  51098. };
  51099. /**
  51100. * Sets the key frames of the animation
  51101. * @param values The animation key frames to set
  51102. */
  51103. Animation.prototype.setKeys = function (values) {
  51104. this._keys = values.slice(0);
  51105. };
  51106. /**
  51107. * Serializes the animation to an object
  51108. * @returns Serialized object
  51109. */
  51110. Animation.prototype.serialize = function () {
  51111. var serializationObject = {};
  51112. serializationObject.name = this.name;
  51113. serializationObject.property = this.targetProperty;
  51114. serializationObject.framePerSecond = this.framePerSecond;
  51115. serializationObject.dataType = this.dataType;
  51116. serializationObject.loopBehavior = this.loopMode;
  51117. serializationObject.enableBlending = this.enableBlending;
  51118. serializationObject.blendingSpeed = this.blendingSpeed;
  51119. var dataType = this.dataType;
  51120. serializationObject.keys = [];
  51121. var keys = this.getKeys();
  51122. for (var index = 0; index < keys.length; index++) {
  51123. var animationKey = keys[index];
  51124. var key = {};
  51125. key.frame = animationKey.frame;
  51126. switch (dataType) {
  51127. case Animation.ANIMATIONTYPE_FLOAT:
  51128. key.values = [animationKey.value];
  51129. break;
  51130. case Animation.ANIMATIONTYPE_QUATERNION:
  51131. case Animation.ANIMATIONTYPE_MATRIX:
  51132. case Animation.ANIMATIONTYPE_VECTOR3:
  51133. case Animation.ANIMATIONTYPE_COLOR3:
  51134. key.values = animationKey.value.asArray();
  51135. break;
  51136. }
  51137. serializationObject.keys.push(key);
  51138. }
  51139. serializationObject.ranges = [];
  51140. for (var name in this._ranges) {
  51141. var source = this._ranges[name];
  51142. if (!source) {
  51143. continue;
  51144. }
  51145. var range = {};
  51146. range.name = name;
  51147. range.from = source.from;
  51148. range.to = source.to;
  51149. serializationObject.ranges.push(range);
  51150. }
  51151. return serializationObject;
  51152. };
  51153. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51154. /**
  51155. * Get the float animation type
  51156. */
  51157. get: function () {
  51158. return Animation._ANIMATIONTYPE_FLOAT;
  51159. },
  51160. enumerable: true,
  51161. configurable: true
  51162. });
  51163. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51164. /**
  51165. * Get the Vector3 animation type
  51166. */
  51167. get: function () {
  51168. return Animation._ANIMATIONTYPE_VECTOR3;
  51169. },
  51170. enumerable: true,
  51171. configurable: true
  51172. });
  51173. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51174. /**
  51175. * Get the Vectpr2 animation type
  51176. */
  51177. get: function () {
  51178. return Animation._ANIMATIONTYPE_VECTOR2;
  51179. },
  51180. enumerable: true,
  51181. configurable: true
  51182. });
  51183. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51184. /**
  51185. * Get the Size animation type
  51186. */
  51187. get: function () {
  51188. return Animation._ANIMATIONTYPE_SIZE;
  51189. },
  51190. enumerable: true,
  51191. configurable: true
  51192. });
  51193. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51194. /**
  51195. * Get the Quaternion animation type
  51196. */
  51197. get: function () {
  51198. return Animation._ANIMATIONTYPE_QUATERNION;
  51199. },
  51200. enumerable: true,
  51201. configurable: true
  51202. });
  51203. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51204. /**
  51205. * Get the Matrix animation type
  51206. */
  51207. get: function () {
  51208. return Animation._ANIMATIONTYPE_MATRIX;
  51209. },
  51210. enumerable: true,
  51211. configurable: true
  51212. });
  51213. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51214. /**
  51215. * Get the Color3 animation type
  51216. */
  51217. get: function () {
  51218. return Animation._ANIMATIONTYPE_COLOR3;
  51219. },
  51220. enumerable: true,
  51221. configurable: true
  51222. });
  51223. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51224. /**
  51225. * Get the Relative Loop Mode
  51226. */
  51227. get: function () {
  51228. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51229. },
  51230. enumerable: true,
  51231. configurable: true
  51232. });
  51233. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51234. /**
  51235. * Get the Cycle Loop Mode
  51236. */
  51237. get: function () {
  51238. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51239. },
  51240. enumerable: true,
  51241. configurable: true
  51242. });
  51243. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51244. /**
  51245. * Get the Constant Loop Mode
  51246. */
  51247. get: function () {
  51248. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51249. },
  51250. enumerable: true,
  51251. configurable: true
  51252. });
  51253. /** @hidden */
  51254. Animation._UniversalLerp = function (left, right, amount) {
  51255. var constructor = left.constructor;
  51256. if (constructor.Lerp) { // Lerp supported
  51257. return constructor.Lerp(left, right, amount);
  51258. }
  51259. else if (constructor.Slerp) { // Slerp supported
  51260. return constructor.Slerp(left, right, amount);
  51261. }
  51262. else if (left.toFixed) { // Number
  51263. return left * (1.0 - amount) + amount * right;
  51264. }
  51265. else { // Blending not supported
  51266. return right;
  51267. }
  51268. };
  51269. /**
  51270. * Parses an animation object and creates an animation
  51271. * @param parsedAnimation Parsed animation object
  51272. * @returns Animation object
  51273. */
  51274. Animation.Parse = function (parsedAnimation) {
  51275. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51276. var dataType = parsedAnimation.dataType;
  51277. var keys = [];
  51278. var data;
  51279. var index;
  51280. if (parsedAnimation.enableBlending) {
  51281. animation.enableBlending = parsedAnimation.enableBlending;
  51282. }
  51283. if (parsedAnimation.blendingSpeed) {
  51284. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51285. }
  51286. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51287. var key = parsedAnimation.keys[index];
  51288. var inTangent;
  51289. var outTangent;
  51290. switch (dataType) {
  51291. case Animation.ANIMATIONTYPE_FLOAT:
  51292. data = key.values[0];
  51293. if (key.values.length >= 1) {
  51294. inTangent = key.values[1];
  51295. }
  51296. if (key.values.length >= 2) {
  51297. outTangent = key.values[2];
  51298. }
  51299. break;
  51300. case Animation.ANIMATIONTYPE_QUATERNION:
  51301. data = BABYLON.Quaternion.FromArray(key.values);
  51302. if (key.values.length >= 8) {
  51303. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51304. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51305. inTangent = _inTangent;
  51306. }
  51307. }
  51308. if (key.values.length >= 12) {
  51309. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51310. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51311. outTangent = _outTangent;
  51312. }
  51313. }
  51314. break;
  51315. case Animation.ANIMATIONTYPE_MATRIX:
  51316. data = BABYLON.Matrix.FromArray(key.values);
  51317. break;
  51318. case Animation.ANIMATIONTYPE_COLOR3:
  51319. data = BABYLON.Color3.FromArray(key.values);
  51320. break;
  51321. case Animation.ANIMATIONTYPE_VECTOR3:
  51322. default:
  51323. data = BABYLON.Vector3.FromArray(key.values);
  51324. break;
  51325. }
  51326. var keyData = {};
  51327. keyData.frame = key.frame;
  51328. keyData.value = data;
  51329. if (inTangent != undefined) {
  51330. keyData.inTangent = inTangent;
  51331. }
  51332. if (outTangent != undefined) {
  51333. keyData.outTangent = outTangent;
  51334. }
  51335. keys.push(keyData);
  51336. }
  51337. animation.setKeys(keys);
  51338. if (parsedAnimation.ranges) {
  51339. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51340. data = parsedAnimation.ranges[index];
  51341. animation.createRange(data.name, data.from, data.to);
  51342. }
  51343. }
  51344. return animation;
  51345. };
  51346. /**
  51347. * Appends the serialized animations from the source animations
  51348. * @param source Source containing the animations
  51349. * @param destination Target to store the animations
  51350. */
  51351. Animation.AppendSerializedAnimations = function (source, destination) {
  51352. if (source.animations) {
  51353. destination.animations = [];
  51354. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51355. var animation = source.animations[animationIndex];
  51356. destination.animations.push(animation.serialize());
  51357. }
  51358. }
  51359. };
  51360. /**
  51361. * Use matrix interpolation instead of using direct key value when animating matrices
  51362. */
  51363. Animation.AllowMatricesInterpolation = false;
  51364. /**
  51365. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51366. */
  51367. Animation.AllowMatrixDecomposeForInterpolation = true;
  51368. // Statics
  51369. /**
  51370. * Float animation type
  51371. */
  51372. Animation._ANIMATIONTYPE_FLOAT = 0;
  51373. /**
  51374. * Vector3 animation type
  51375. */
  51376. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51377. /**
  51378. * Quaternion animation type
  51379. */
  51380. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51381. /**
  51382. * Matrix animation type
  51383. */
  51384. Animation._ANIMATIONTYPE_MATRIX = 3;
  51385. /**
  51386. * Color3 animation type
  51387. */
  51388. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51389. /**
  51390. * Vector2 animation type
  51391. */
  51392. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51393. /**
  51394. * Size animation type
  51395. */
  51396. Animation._ANIMATIONTYPE_SIZE = 6;
  51397. /**
  51398. * Relative Loop Mode
  51399. */
  51400. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51401. /**
  51402. * Cycle Loop Mode
  51403. */
  51404. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51405. /**
  51406. * Constant Loop Mode
  51407. */
  51408. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51409. return Animation;
  51410. }());
  51411. BABYLON.Animation = Animation;
  51412. })(BABYLON || (BABYLON = {}));
  51413. //# sourceMappingURL=babylon.animation.js.map
  51414. var BABYLON;
  51415. (function (BABYLON) {
  51416. /**
  51417. * This class defines the direct association between an animation and a target
  51418. */
  51419. var TargetedAnimation = /** @class */ (function () {
  51420. function TargetedAnimation() {
  51421. }
  51422. return TargetedAnimation;
  51423. }());
  51424. BABYLON.TargetedAnimation = TargetedAnimation;
  51425. /**
  51426. * Use this class to create coordinated animations on multiple targets
  51427. */
  51428. var AnimationGroup = /** @class */ (function () {
  51429. function AnimationGroup(name, scene) {
  51430. if (scene === void 0) { scene = null; }
  51431. this.name = name;
  51432. this._targetedAnimations = new Array();
  51433. this._animatables = new Array();
  51434. this._from = Number.MAX_VALUE;
  51435. this._to = -Number.MAX_VALUE;
  51436. this._speedRatio = 1;
  51437. this.onAnimationEndObservable = new BABYLON.Observable();
  51438. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51439. this._scene.animationGroups.push(this);
  51440. }
  51441. Object.defineProperty(AnimationGroup.prototype, "from", {
  51442. /**
  51443. * Gets the first frame
  51444. */
  51445. get: function () {
  51446. return this._from;
  51447. },
  51448. enumerable: true,
  51449. configurable: true
  51450. });
  51451. Object.defineProperty(AnimationGroup.prototype, "to", {
  51452. /**
  51453. * Gets the last frame
  51454. */
  51455. get: function () {
  51456. return this._to;
  51457. },
  51458. enumerable: true,
  51459. configurable: true
  51460. });
  51461. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51462. /**
  51463. * Define if the animations are started
  51464. */
  51465. get: function () {
  51466. return this._isStarted;
  51467. },
  51468. enumerable: true,
  51469. configurable: true
  51470. });
  51471. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51472. /**
  51473. * Gets or sets the speed ratio to use for all animations
  51474. */
  51475. get: function () {
  51476. return this._speedRatio;
  51477. },
  51478. /**
  51479. * Gets or sets the speed ratio to use for all animations
  51480. */
  51481. set: function (value) {
  51482. if (this._speedRatio === value) {
  51483. return;
  51484. }
  51485. this._speedRatio = value;
  51486. for (var index = 0; index < this._animatables.length; index++) {
  51487. var animatable = this._animatables[index];
  51488. animatable.speedRatio = this._speedRatio;
  51489. }
  51490. },
  51491. enumerable: true,
  51492. configurable: true
  51493. });
  51494. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51495. /**
  51496. * Gets the targeted animations for this animation group
  51497. */
  51498. get: function () {
  51499. return this._targetedAnimations;
  51500. },
  51501. enumerable: true,
  51502. configurable: true
  51503. });
  51504. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51505. /**
  51506. * returning the list of animatables controlled by this animation group.
  51507. */
  51508. get: function () {
  51509. return this._animatables;
  51510. },
  51511. enumerable: true,
  51512. configurable: true
  51513. });
  51514. /**
  51515. * Add an animation (with its target) in the group
  51516. * @param animation defines the animation we want to add
  51517. * @param target defines the target of the animation
  51518. * @returns the {BABYLON.TargetedAnimation} object
  51519. */
  51520. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51521. var targetedAnimation = {
  51522. animation: animation,
  51523. target: target
  51524. };
  51525. var keys = animation.getKeys();
  51526. if (this._from > keys[0].frame) {
  51527. this._from = keys[0].frame;
  51528. }
  51529. if (this._to < keys[keys.length - 1].frame) {
  51530. this._to = keys[keys.length - 1].frame;
  51531. }
  51532. this._targetedAnimations.push(targetedAnimation);
  51533. return targetedAnimation;
  51534. };
  51535. /**
  51536. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51537. * It can add constant keys at begin or end
  51538. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51539. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51540. */
  51541. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51542. if (beginFrame === void 0) { beginFrame = null; }
  51543. if (endFrame === void 0) { endFrame = null; }
  51544. if (beginFrame == null)
  51545. beginFrame = this._from;
  51546. if (endFrame == null)
  51547. endFrame = this._to;
  51548. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51549. var targetedAnimation = this._targetedAnimations[index];
  51550. var keys = targetedAnimation.animation.getKeys();
  51551. var startKey = keys[0];
  51552. var endKey = keys[keys.length - 1];
  51553. if (startKey.frame > beginFrame) {
  51554. var newKey = {
  51555. frame: beginFrame,
  51556. value: startKey.value,
  51557. inTangent: startKey.inTangent,
  51558. outTangent: startKey.outTangent,
  51559. interpolation: startKey.interpolation
  51560. };
  51561. keys.splice(0, 0, newKey);
  51562. }
  51563. if (endKey.frame < endFrame) {
  51564. var newKey = {
  51565. frame: endFrame,
  51566. value: endKey.value,
  51567. inTangent: endKey.outTangent,
  51568. outTangent: endKey.outTangent,
  51569. interpolation: endKey.interpolation
  51570. };
  51571. keys.push(newKey);
  51572. }
  51573. }
  51574. this._from = beginFrame;
  51575. this._to = endFrame;
  51576. return this;
  51577. };
  51578. /**
  51579. * Start all animations on given targets
  51580. * @param loop defines if animations must loop
  51581. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51582. * @param from defines the from key (optional)
  51583. * @param to defines the to key (optional)
  51584. * @returns the current animation group
  51585. */
  51586. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51587. var _this = this;
  51588. if (loop === void 0) { loop = false; }
  51589. if (speedRatio === void 0) { speedRatio = 1; }
  51590. if (this._isStarted || this._targetedAnimations.length === 0) {
  51591. return this;
  51592. }
  51593. var _loop_1 = function (targetedAnimation) {
  51594. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  51595. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51596. }));
  51597. };
  51598. var this_1 = this;
  51599. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51600. var targetedAnimation = _a[_i];
  51601. _loop_1(targetedAnimation);
  51602. }
  51603. this._speedRatio = speedRatio;
  51604. this._isStarted = true;
  51605. return this;
  51606. };
  51607. /**
  51608. * Pause all animations
  51609. */
  51610. AnimationGroup.prototype.pause = function () {
  51611. if (!this._isStarted) {
  51612. return this;
  51613. }
  51614. for (var index = 0; index < this._animatables.length; index++) {
  51615. var animatable = this._animatables[index];
  51616. animatable.pause();
  51617. }
  51618. return this;
  51619. };
  51620. /**
  51621. * Play all animations to initial state
  51622. * This function will start() the animations if they were not started or will restart() them if they were paused
  51623. * @param loop defines if animations must loop
  51624. */
  51625. AnimationGroup.prototype.play = function (loop) {
  51626. if (this.isStarted) {
  51627. if (loop !== undefined) {
  51628. for (var index = 0; index < this._animatables.length; index++) {
  51629. var animatable = this._animatables[index];
  51630. animatable.loopAnimation = loop;
  51631. }
  51632. }
  51633. this.restart();
  51634. }
  51635. else {
  51636. this.start(loop, this._speedRatio);
  51637. }
  51638. return this;
  51639. };
  51640. /**
  51641. * Reset all animations to initial state
  51642. */
  51643. AnimationGroup.prototype.reset = function () {
  51644. if (!this._isStarted) {
  51645. return this;
  51646. }
  51647. for (var index = 0; index < this._animatables.length; index++) {
  51648. var animatable = this._animatables[index];
  51649. animatable.reset();
  51650. }
  51651. return this;
  51652. };
  51653. /**
  51654. * Restart animations from key 0
  51655. */
  51656. AnimationGroup.prototype.restart = function () {
  51657. if (!this._isStarted) {
  51658. return this;
  51659. }
  51660. for (var index = 0; index < this._animatables.length; index++) {
  51661. var animatable = this._animatables[index];
  51662. animatable.restart();
  51663. }
  51664. return this;
  51665. };
  51666. /**
  51667. * Stop all animations
  51668. */
  51669. AnimationGroup.prototype.stop = function () {
  51670. if (!this._isStarted) {
  51671. return this;
  51672. }
  51673. for (var index = 0; index < this._animatables.length; index++) {
  51674. var animatable = this._animatables[index];
  51675. animatable.stop();
  51676. }
  51677. this._isStarted = false;
  51678. return this;
  51679. };
  51680. /**
  51681. * Set animation weight for all animatables
  51682. * @param weight defines the weight to use
  51683. * @return the animationGroup
  51684. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51685. */
  51686. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51687. for (var index = 0; index < this._animatables.length; index++) {
  51688. var animatable = this._animatables[index];
  51689. animatable.weight = weight;
  51690. }
  51691. return this;
  51692. };
  51693. /**
  51694. * Synchronize and normalize all animatables with a source animatable
  51695. * @param root defines the root animatable to synchronize with
  51696. * @return the animationGroup
  51697. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51698. */
  51699. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51700. for (var index = 0; index < this._animatables.length; index++) {
  51701. var animatable = this._animatables[index];
  51702. animatable.syncWith(root);
  51703. }
  51704. return this;
  51705. };
  51706. /**
  51707. * Goes to a specific frame in this animation group
  51708. * @param frame the frame number to go to
  51709. * @return the animationGroup
  51710. */
  51711. AnimationGroup.prototype.goToFrame = function (frame) {
  51712. if (!this._isStarted) {
  51713. return this;
  51714. }
  51715. for (var index = 0; index < this._animatables.length; index++) {
  51716. var animatable = this._animatables[index];
  51717. animatable.goToFrame(frame);
  51718. }
  51719. return this;
  51720. };
  51721. /**
  51722. * Dispose all associated resources
  51723. */
  51724. AnimationGroup.prototype.dispose = function () {
  51725. this._targetedAnimations = [];
  51726. this._animatables = [];
  51727. var index = this._scene.animationGroups.indexOf(this);
  51728. if (index > -1) {
  51729. this._scene.animationGroups.splice(index, 1);
  51730. }
  51731. };
  51732. return AnimationGroup;
  51733. }());
  51734. BABYLON.AnimationGroup = AnimationGroup;
  51735. })(BABYLON || (BABYLON = {}));
  51736. //# sourceMappingURL=babylon.animationGroup.js.map
  51737. var BABYLON;
  51738. (function (BABYLON) {
  51739. /**
  51740. * Defines a runtime animation
  51741. */
  51742. var RuntimeAnimation = /** @class */ (function () {
  51743. /**
  51744. * Create a new RuntimeAnimation object
  51745. * @param target defines the target of the animation
  51746. * @param animation defines the source animation object
  51747. * @param scene defines the hosting scene
  51748. * @param host defines the initiating Animatable
  51749. */
  51750. function RuntimeAnimation(target, animation, scene, host) {
  51751. var _this = this;
  51752. this._events = new Array();
  51753. /**
  51754. * The current frame of the runtime animation
  51755. */
  51756. this._currentFrame = 0;
  51757. /**
  51758. * The original value of the runtime animation
  51759. */
  51760. this._originalValue = new Array();
  51761. /**
  51762. * The offsets cache of the runtime animation
  51763. */
  51764. this._offsetsCache = {};
  51765. /**
  51766. * The high limits cache of the runtime animation
  51767. */
  51768. this._highLimitsCache = {};
  51769. /**
  51770. * Specifies if the runtime animation has been stopped
  51771. */
  51772. this._stopped = false;
  51773. /**
  51774. * The blending factor of the runtime animation
  51775. */
  51776. this._blendingFactor = 0;
  51777. /**
  51778. * The target path of the runtime animation
  51779. */
  51780. this._targetPath = "";
  51781. /**
  51782. * The weight of the runtime animation
  51783. */
  51784. this._weight = 1.0;
  51785. /**
  51786. * The ratio offset of the runtime animation
  51787. */
  51788. this._ratioOffset = 0;
  51789. /**
  51790. * The previous delay of the runtime animation
  51791. */
  51792. this._previousDelay = 0;
  51793. /**
  51794. * The previous ratio of the runtime animation
  51795. */
  51796. this._previousRatio = 0;
  51797. this._animation = animation;
  51798. this._target = target;
  51799. this._scene = scene;
  51800. this._host = host;
  51801. animation._runtimeAnimations.push(this);
  51802. // Cloning events locally
  51803. var events = animation.getEvents();
  51804. if (events && events.length > 0) {
  51805. events.forEach(function (e) {
  51806. _this._events.push(e._clone());
  51807. });
  51808. }
  51809. }
  51810. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51811. /**
  51812. * Gets the current frame of the runtime animation
  51813. */
  51814. get: function () {
  51815. return this._currentFrame;
  51816. },
  51817. enumerable: true,
  51818. configurable: true
  51819. });
  51820. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51821. /**
  51822. * Gets the weight of the runtime animation
  51823. */
  51824. get: function () {
  51825. return this._weight;
  51826. },
  51827. enumerable: true,
  51828. configurable: true
  51829. });
  51830. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51831. /**
  51832. * Gets the current value of the runtime animation
  51833. */
  51834. get: function () {
  51835. return this._currentValue;
  51836. },
  51837. enumerable: true,
  51838. configurable: true
  51839. });
  51840. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51841. /**
  51842. * Gets the target path of the runtime animation
  51843. */
  51844. get: function () {
  51845. return this._targetPath;
  51846. },
  51847. enumerable: true,
  51848. configurable: true
  51849. });
  51850. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51851. /**
  51852. * Gets the actual target of the runtime animation
  51853. */
  51854. get: function () {
  51855. return this._activeTarget;
  51856. },
  51857. enumerable: true,
  51858. configurable: true
  51859. });
  51860. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51861. /**
  51862. * Gets the animation from the runtime animation
  51863. */
  51864. get: function () {
  51865. return this._animation;
  51866. },
  51867. enumerable: true,
  51868. configurable: true
  51869. });
  51870. /**
  51871. * Resets the runtime animation to the beginning
  51872. * @param restoreOriginal defines whether to restore the target property to the original value
  51873. */
  51874. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51875. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51876. if (restoreOriginal) {
  51877. if (this._target instanceof Array) {
  51878. var index = 0;
  51879. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51880. var target = _a[_i];
  51881. if (this._originalValue[index] !== undefined) {
  51882. this._setValue(target, this._originalValue[index], -1);
  51883. }
  51884. index++;
  51885. }
  51886. }
  51887. else {
  51888. if (this._originalValue[0] !== undefined) {
  51889. this._setValue(this._target, this._originalValue[0], -1);
  51890. }
  51891. }
  51892. }
  51893. this._offsetsCache = {};
  51894. this._highLimitsCache = {};
  51895. this._currentFrame = 0;
  51896. this._blendingFactor = 0;
  51897. this._originalValue = new Array();
  51898. // Events
  51899. for (var index = 0; index < this._events.length; index++) {
  51900. this._events[index].isDone = false;
  51901. }
  51902. };
  51903. /**
  51904. * Specifies if the runtime animation is stopped
  51905. * @returns Boolean specifying if the runtime animation is stopped
  51906. */
  51907. RuntimeAnimation.prototype.isStopped = function () {
  51908. return this._stopped;
  51909. };
  51910. /**
  51911. * Disposes of the runtime animation
  51912. */
  51913. RuntimeAnimation.prototype.dispose = function () {
  51914. var index = this._animation.runtimeAnimations.indexOf(this);
  51915. if (index > -1) {
  51916. this._animation.runtimeAnimations.splice(index, 1);
  51917. }
  51918. };
  51919. /**
  51920. * Interpolates the animation from the current frame
  51921. * @param currentFrame The frame to interpolate the animation to
  51922. * @param repeatCount The number of times that the animation should loop
  51923. * @param loopMode The type of looping mode to use
  51924. * @param offsetValue Animation offset value
  51925. * @param highLimitValue The high limit value
  51926. * @returns The interpolated value
  51927. */
  51928. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51929. this._currentFrame = currentFrame;
  51930. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51931. this._workValue = BABYLON.Matrix.Zero();
  51932. }
  51933. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51934. };
  51935. /**
  51936. * Apply the interpolated value to the target
  51937. * @param currentValue defines the value computed by the animation
  51938. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51939. */
  51940. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51941. if (weight === void 0) { weight = 1.0; }
  51942. if (this._target instanceof Array) {
  51943. var index = 0;
  51944. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51945. var target = _a[_i];
  51946. this._setValue(target, currentValue, weight, index);
  51947. index++;
  51948. }
  51949. }
  51950. else {
  51951. this._setValue(this._target, currentValue, weight);
  51952. }
  51953. };
  51954. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51955. if (targetIndex === void 0) { targetIndex = 0; }
  51956. // Set value
  51957. var path;
  51958. var destination;
  51959. var targetPropertyPath = this._animation.targetPropertyPath;
  51960. if (targetPropertyPath.length > 1) {
  51961. var property = target[targetPropertyPath[0]];
  51962. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51963. property = property[targetPropertyPath[index]];
  51964. }
  51965. path = targetPropertyPath[targetPropertyPath.length - 1];
  51966. destination = property;
  51967. }
  51968. else {
  51969. path = targetPropertyPath[0];
  51970. destination = target;
  51971. }
  51972. this._targetPath = path;
  51973. this._activeTarget = destination;
  51974. this._weight = weight;
  51975. if (this._originalValue[targetIndex] === undefined) {
  51976. var originalValue = void 0;
  51977. if (destination.getRestPose && path === "_matrix") { // For bones
  51978. originalValue = destination.getRestPose();
  51979. }
  51980. else {
  51981. originalValue = destination[path];
  51982. }
  51983. if (originalValue && originalValue.clone) {
  51984. this._originalValue[targetIndex] = originalValue.clone();
  51985. }
  51986. else {
  51987. this._originalValue[targetIndex] = originalValue;
  51988. }
  51989. }
  51990. // Blending
  51991. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51992. if (enableBlending && this._blendingFactor <= 1.0) {
  51993. if (!this._originalBlendValue) {
  51994. var originalValue = destination[path];
  51995. if (originalValue.clone) {
  51996. this._originalBlendValue = originalValue.clone();
  51997. }
  51998. else {
  51999. this._originalBlendValue = originalValue;
  52000. }
  52001. }
  52002. if (this._originalBlendValue.m) { // Matrix
  52003. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52004. if (this._currentValue) {
  52005. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52006. }
  52007. else {
  52008. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52009. }
  52010. }
  52011. else {
  52012. if (this._currentValue) {
  52013. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52014. }
  52015. else {
  52016. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52017. }
  52018. }
  52019. }
  52020. else {
  52021. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52022. }
  52023. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52024. this._blendingFactor += blendingSpeed;
  52025. }
  52026. else {
  52027. this._currentValue = currentValue;
  52028. }
  52029. if (weight !== -1.0) {
  52030. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52031. }
  52032. else {
  52033. destination[path] = this._currentValue;
  52034. }
  52035. if (target.markAsDirty) {
  52036. target.markAsDirty(this._animation.targetProperty);
  52037. }
  52038. };
  52039. /**
  52040. * Gets the loop pmode of the runtime animation
  52041. * @returns Loop Mode
  52042. */
  52043. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52044. if (this._target && this._target.animationPropertiesOverride) {
  52045. return this._target.animationPropertiesOverride.loopMode;
  52046. }
  52047. return this._animation.loopMode;
  52048. };
  52049. /**
  52050. * Move the current animation to a given frame
  52051. * @param frame defines the frame to move to
  52052. */
  52053. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52054. var keys = this._animation.getKeys();
  52055. if (frame < keys[0].frame) {
  52056. frame = keys[0].frame;
  52057. }
  52058. else if (frame > keys[keys.length - 1].frame) {
  52059. frame = keys[keys.length - 1].frame;
  52060. }
  52061. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52062. this.setValue(currentValue, -1);
  52063. };
  52064. /**
  52065. * @hidden Internal use only
  52066. */
  52067. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52068. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52069. this._ratioOffset = this._previousRatio - newRatio;
  52070. };
  52071. /**
  52072. * Execute the current animation
  52073. * @param delay defines the delay to add to the current frame
  52074. * @param from defines the lower bound of the animation range
  52075. * @param to defines the upper bound of the animation range
  52076. * @param loop defines if the current animation must loop
  52077. * @param speedRatio defines the current speed ratio
  52078. * @param weight defines the weight of the animation (default is -1 so no weight)
  52079. * @returns a boolean indicating if the animation has ended
  52080. */
  52081. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52082. if (weight === void 0) { weight = -1.0; }
  52083. var targetPropertyPath = this._animation.targetPropertyPath;
  52084. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52085. this._stopped = true;
  52086. return false;
  52087. }
  52088. var returnValue = true;
  52089. var keys = this._animation.getKeys();
  52090. // Adding a start key at frame 0 if missing
  52091. if (keys[0].frame !== 0) {
  52092. var newKey = { frame: 0, value: keys[0].value };
  52093. keys.splice(0, 0, newKey);
  52094. }
  52095. // Check limits
  52096. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52097. from = keys[0].frame;
  52098. }
  52099. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52100. to = keys[keys.length - 1].frame;
  52101. }
  52102. //to and from cannot be the same key
  52103. if (from === to) {
  52104. if (from > keys[0].frame) {
  52105. from--;
  52106. }
  52107. else if (to < keys[keys.length - 1].frame) {
  52108. to++;
  52109. }
  52110. }
  52111. // Compute ratio
  52112. var range = to - from;
  52113. var offsetValue;
  52114. // ratio represents the frame delta between from and to
  52115. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52116. var highLimitValue = 0;
  52117. this._previousDelay = delay;
  52118. this._previousRatio = ratio;
  52119. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  52120. returnValue = false;
  52121. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52122. }
  52123. else {
  52124. // Get max value if required
  52125. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52126. var keyOffset = to.toString() + from.toString();
  52127. if (!this._offsetsCache[keyOffset]) {
  52128. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52129. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52130. switch (this._animation.dataType) {
  52131. // Float
  52132. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52133. this._offsetsCache[keyOffset] = toValue - fromValue;
  52134. break;
  52135. // Quaternion
  52136. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52137. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52138. break;
  52139. // Vector3
  52140. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52141. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52142. // Vector2
  52143. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52144. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52145. // Size
  52146. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52147. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52148. // Color3
  52149. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52150. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52151. default:
  52152. break;
  52153. }
  52154. this._highLimitsCache[keyOffset] = toValue;
  52155. }
  52156. highLimitValue = this._highLimitsCache[keyOffset];
  52157. offsetValue = this._offsetsCache[keyOffset];
  52158. }
  52159. }
  52160. if (offsetValue === undefined) {
  52161. switch (this._animation.dataType) {
  52162. // Float
  52163. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52164. offsetValue = 0;
  52165. break;
  52166. // Quaternion
  52167. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52168. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52169. break;
  52170. // Vector3
  52171. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52172. offsetValue = BABYLON.Vector3.Zero();
  52173. break;
  52174. // Vector2
  52175. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52176. offsetValue = BABYLON.Vector2.Zero();
  52177. break;
  52178. // Size
  52179. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52180. offsetValue = BABYLON.Size.Zero();
  52181. break;
  52182. // Color3
  52183. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52184. offsetValue = BABYLON.Color3.Black();
  52185. }
  52186. }
  52187. // Compute value
  52188. var repeatCount = (ratio / range) >> 0;
  52189. var currentFrame = returnValue ? from + ratio % range : to;
  52190. // Need to normalize?
  52191. if (this._host && this._host.syncRoot) {
  52192. var syncRoot = this._host.syncRoot;
  52193. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52194. currentFrame = from + (to - from) * hostNormalizedFrame;
  52195. }
  52196. // Reset events if looping
  52197. var events = this._events;
  52198. if (range > 0 && this.currentFrame > currentFrame ||
  52199. range < 0 && this.currentFrame < currentFrame) {
  52200. // Need to reset animation events
  52201. for (var index = 0; index < events.length; index++) {
  52202. if (!events[index].onlyOnce) {
  52203. // reset event, the animation is looping
  52204. events[index].isDone = false;
  52205. }
  52206. }
  52207. }
  52208. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52209. // Set value
  52210. this.setValue(currentValue, weight);
  52211. // Check events
  52212. for (var index = 0; index < events.length; index++) {
  52213. // Make sure current frame has passed event frame and that event frame is within the current range
  52214. // Also, handle both forward and reverse animations
  52215. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52216. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52217. var event = events[index];
  52218. if (!event.isDone) {
  52219. // If event should be done only once, remove it.
  52220. if (event.onlyOnce) {
  52221. events.splice(index, 1);
  52222. index--;
  52223. }
  52224. event.isDone = true;
  52225. event.action();
  52226. } // Don't do anything if the event has already be done.
  52227. }
  52228. }
  52229. if (!returnValue) {
  52230. this._stopped = true;
  52231. }
  52232. return returnValue;
  52233. };
  52234. return RuntimeAnimation;
  52235. }());
  52236. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52237. })(BABYLON || (BABYLON = {}));
  52238. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52239. var BABYLON;
  52240. (function (BABYLON) {
  52241. var Animatable = /** @class */ (function () {
  52242. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52243. if (fromFrame === void 0) { fromFrame = 0; }
  52244. if (toFrame === void 0) { toFrame = 100; }
  52245. if (loopAnimation === void 0) { loopAnimation = false; }
  52246. if (speedRatio === void 0) { speedRatio = 1.0; }
  52247. this.target = target;
  52248. this.fromFrame = fromFrame;
  52249. this.toFrame = toFrame;
  52250. this.loopAnimation = loopAnimation;
  52251. this.onAnimationEnd = onAnimationEnd;
  52252. this._localDelayOffset = null;
  52253. this._pausedDelay = null;
  52254. this._runtimeAnimations = new Array();
  52255. this._paused = false;
  52256. this._speedRatio = 1;
  52257. this._weight = -1.0;
  52258. this.animationStarted = false;
  52259. /**
  52260. * Observer raised when the animation ends
  52261. */
  52262. this.onAnimationEndObservable = new BABYLON.Observable();
  52263. this._scene = scene;
  52264. if (animations) {
  52265. this.appendAnimations(target, animations);
  52266. }
  52267. this._speedRatio = speedRatio;
  52268. scene._activeAnimatables.push(this);
  52269. }
  52270. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52271. /**
  52272. * Gets the root Animatable used to synchronize and normalize animations
  52273. */
  52274. get: function () {
  52275. return this._syncRoot;
  52276. },
  52277. enumerable: true,
  52278. configurable: true
  52279. });
  52280. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52281. /**
  52282. * Gets the current frame of the first RuntimeAnimation
  52283. * Used to synchronize Animatables
  52284. */
  52285. get: function () {
  52286. if (this._runtimeAnimations.length === 0) {
  52287. return 0;
  52288. }
  52289. return this._runtimeAnimations[0].currentFrame;
  52290. },
  52291. enumerable: true,
  52292. configurable: true
  52293. });
  52294. Object.defineProperty(Animatable.prototype, "weight", {
  52295. /**
  52296. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52297. */
  52298. get: function () {
  52299. return this._weight;
  52300. },
  52301. set: function (value) {
  52302. if (value === -1) { // -1 is ok and means no weight
  52303. this._weight = -1;
  52304. return;
  52305. }
  52306. // Else weight must be in [0, 1] range
  52307. this._weight = Math.min(Math.max(value, 0), 1.0);
  52308. },
  52309. enumerable: true,
  52310. configurable: true
  52311. });
  52312. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52313. /**
  52314. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52315. */
  52316. get: function () {
  52317. return this._speedRatio;
  52318. },
  52319. set: function (value) {
  52320. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52321. var animation = this._runtimeAnimations[index];
  52322. animation._prepareForSpeedRatioChange(value);
  52323. }
  52324. this._speedRatio = value;
  52325. },
  52326. enumerable: true,
  52327. configurable: true
  52328. });
  52329. // Methods
  52330. /**
  52331. * Synchronize and normalize current Animatable with a source Animatable
  52332. * This is useful when using animation weights and when animations are not of the same length
  52333. * @param root defines the root Animatable to synchronize with
  52334. * @returns the current Animatable
  52335. */
  52336. Animatable.prototype.syncWith = function (root) {
  52337. this._syncRoot = root;
  52338. if (root) {
  52339. // Make sure this animatable will animate after the root
  52340. var index = this._scene._activeAnimatables.indexOf(this);
  52341. if (index > -1) {
  52342. this._scene._activeAnimatables.splice(index, 1);
  52343. this._scene._activeAnimatables.push(this);
  52344. }
  52345. }
  52346. return this;
  52347. };
  52348. Animatable.prototype.getAnimations = function () {
  52349. return this._runtimeAnimations;
  52350. };
  52351. Animatable.prototype.appendAnimations = function (target, animations) {
  52352. for (var index = 0; index < animations.length; index++) {
  52353. var animation = animations[index];
  52354. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52355. }
  52356. };
  52357. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52358. var runtimeAnimations = this._runtimeAnimations;
  52359. for (var index = 0; index < runtimeAnimations.length; index++) {
  52360. if (runtimeAnimations[index].animation.targetProperty === property) {
  52361. return runtimeAnimations[index].animation;
  52362. }
  52363. }
  52364. return null;
  52365. };
  52366. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52367. var runtimeAnimations = this._runtimeAnimations;
  52368. for (var index = 0; index < runtimeAnimations.length; index++) {
  52369. if (runtimeAnimations[index].animation.targetProperty === property) {
  52370. return runtimeAnimations[index];
  52371. }
  52372. }
  52373. return null;
  52374. };
  52375. Animatable.prototype.reset = function () {
  52376. var runtimeAnimations = this._runtimeAnimations;
  52377. for (var index = 0; index < runtimeAnimations.length; index++) {
  52378. runtimeAnimations[index].reset(true);
  52379. }
  52380. this._localDelayOffset = null;
  52381. this._pausedDelay = null;
  52382. };
  52383. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52384. var runtimeAnimations = this._runtimeAnimations;
  52385. for (var index = 0; index < runtimeAnimations.length; index++) {
  52386. runtimeAnimations[index].animation.enableBlending = true;
  52387. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52388. }
  52389. };
  52390. Animatable.prototype.disableBlending = function () {
  52391. var runtimeAnimations = this._runtimeAnimations;
  52392. for (var index = 0; index < runtimeAnimations.length; index++) {
  52393. runtimeAnimations[index].animation.enableBlending = false;
  52394. }
  52395. };
  52396. Animatable.prototype.goToFrame = function (frame) {
  52397. var runtimeAnimations = this._runtimeAnimations;
  52398. if (runtimeAnimations[0]) {
  52399. var fps = runtimeAnimations[0].animation.framePerSecond;
  52400. var currentFrame = runtimeAnimations[0].currentFrame;
  52401. var adjustTime = frame - currentFrame;
  52402. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52403. if (this._localDelayOffset === null) {
  52404. this._localDelayOffset = 0;
  52405. }
  52406. this._localDelayOffset -= delay;
  52407. }
  52408. for (var index = 0; index < runtimeAnimations.length; index++) {
  52409. runtimeAnimations[index].goToFrame(frame);
  52410. }
  52411. };
  52412. Animatable.prototype.pause = function () {
  52413. if (this._paused) {
  52414. return;
  52415. }
  52416. this._paused = true;
  52417. };
  52418. Animatable.prototype.restart = function () {
  52419. this._paused = false;
  52420. };
  52421. Animatable.prototype._raiseOnAnimationEnd = function () {
  52422. if (this.onAnimationEnd) {
  52423. this.onAnimationEnd();
  52424. }
  52425. this.onAnimationEndObservable.notifyObservers(this);
  52426. };
  52427. Animatable.prototype.stop = function (animationName) {
  52428. if (animationName) {
  52429. var idx = this._scene._activeAnimatables.indexOf(this);
  52430. if (idx > -1) {
  52431. var runtimeAnimations = this._runtimeAnimations;
  52432. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52433. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52434. continue;
  52435. }
  52436. runtimeAnimations[index].dispose();
  52437. runtimeAnimations.splice(index, 1);
  52438. }
  52439. if (runtimeAnimations.length == 0) {
  52440. this._scene._activeAnimatables.splice(idx, 1);
  52441. this._raiseOnAnimationEnd();
  52442. }
  52443. }
  52444. }
  52445. else {
  52446. var index = this._scene._activeAnimatables.indexOf(this);
  52447. if (index > -1) {
  52448. this._scene._activeAnimatables.splice(index, 1);
  52449. var runtimeAnimations = this._runtimeAnimations;
  52450. for (var index = 0; index < runtimeAnimations.length; index++) {
  52451. runtimeAnimations[index].dispose();
  52452. }
  52453. this._raiseOnAnimationEnd();
  52454. }
  52455. }
  52456. };
  52457. Animatable.prototype.waitAsync = function () {
  52458. var _this = this;
  52459. return new Promise(function (resolve, reject) {
  52460. _this.onAnimationEndObservable.add(function () {
  52461. resolve(_this);
  52462. }, undefined, undefined, _this, true);
  52463. });
  52464. };
  52465. /** @hidden */
  52466. Animatable.prototype._animate = function (delay) {
  52467. if (this._paused) {
  52468. this.animationStarted = false;
  52469. if (this._pausedDelay === null) {
  52470. this._pausedDelay = delay;
  52471. }
  52472. return true;
  52473. }
  52474. if (this._localDelayOffset === null) {
  52475. this._localDelayOffset = delay;
  52476. this._pausedDelay = null;
  52477. }
  52478. else if (this._pausedDelay !== null) {
  52479. this._localDelayOffset += delay - this._pausedDelay;
  52480. this._pausedDelay = null;
  52481. }
  52482. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52483. return true;
  52484. }
  52485. // Animating
  52486. var running = false;
  52487. var runtimeAnimations = this._runtimeAnimations;
  52488. var index;
  52489. for (index = 0; index < runtimeAnimations.length; index++) {
  52490. var animation = runtimeAnimations[index];
  52491. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52492. running = running || isRunning;
  52493. }
  52494. this.animationStarted = running;
  52495. if (!running) {
  52496. // Remove from active animatables
  52497. index = this._scene._activeAnimatables.indexOf(this);
  52498. this._scene._activeAnimatables.splice(index, 1);
  52499. // Dispose all runtime animations
  52500. for (index = 0; index < runtimeAnimations.length; index++) {
  52501. runtimeAnimations[index].dispose();
  52502. }
  52503. }
  52504. if (!running) {
  52505. this._raiseOnAnimationEnd();
  52506. this.onAnimationEnd = null;
  52507. }
  52508. return running;
  52509. };
  52510. return Animatable;
  52511. }());
  52512. BABYLON.Animatable = Animatable;
  52513. })(BABYLON || (BABYLON = {}));
  52514. //# sourceMappingURL=babylon.animatable.js.map
  52515. var BABYLON;
  52516. (function (BABYLON) {
  52517. var EasingFunction = /** @class */ (function () {
  52518. function EasingFunction() {
  52519. // Properties
  52520. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52521. }
  52522. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52523. get: function () {
  52524. return EasingFunction._EASINGMODE_EASEIN;
  52525. },
  52526. enumerable: true,
  52527. configurable: true
  52528. });
  52529. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52530. get: function () {
  52531. return EasingFunction._EASINGMODE_EASEOUT;
  52532. },
  52533. enumerable: true,
  52534. configurable: true
  52535. });
  52536. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52537. get: function () {
  52538. return EasingFunction._EASINGMODE_EASEINOUT;
  52539. },
  52540. enumerable: true,
  52541. configurable: true
  52542. });
  52543. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52544. var n = Math.min(Math.max(easingMode, 0), 2);
  52545. this._easingMode = n;
  52546. };
  52547. EasingFunction.prototype.getEasingMode = function () {
  52548. return this._easingMode;
  52549. };
  52550. EasingFunction.prototype.easeInCore = function (gradient) {
  52551. throw new Error('You must implement this method');
  52552. };
  52553. EasingFunction.prototype.ease = function (gradient) {
  52554. switch (this._easingMode) {
  52555. case EasingFunction.EASINGMODE_EASEIN:
  52556. return this.easeInCore(gradient);
  52557. case EasingFunction.EASINGMODE_EASEOUT:
  52558. return (1 - this.easeInCore(1 - gradient));
  52559. }
  52560. if (gradient >= 0.5) {
  52561. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52562. }
  52563. return (this.easeInCore(gradient * 2) * 0.5);
  52564. };
  52565. //Statics
  52566. EasingFunction._EASINGMODE_EASEIN = 0;
  52567. EasingFunction._EASINGMODE_EASEOUT = 1;
  52568. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52569. return EasingFunction;
  52570. }());
  52571. BABYLON.EasingFunction = EasingFunction;
  52572. var CircleEase = /** @class */ (function (_super) {
  52573. __extends(CircleEase, _super);
  52574. function CircleEase() {
  52575. return _super !== null && _super.apply(this, arguments) || this;
  52576. }
  52577. CircleEase.prototype.easeInCore = function (gradient) {
  52578. gradient = Math.max(0, Math.min(1, gradient));
  52579. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52580. };
  52581. return CircleEase;
  52582. }(EasingFunction));
  52583. BABYLON.CircleEase = CircleEase;
  52584. var BackEase = /** @class */ (function (_super) {
  52585. __extends(BackEase, _super);
  52586. function BackEase(amplitude) {
  52587. if (amplitude === void 0) { amplitude = 1; }
  52588. var _this = _super.call(this) || this;
  52589. _this.amplitude = amplitude;
  52590. return _this;
  52591. }
  52592. BackEase.prototype.easeInCore = function (gradient) {
  52593. var num = Math.max(0, this.amplitude);
  52594. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52595. };
  52596. return BackEase;
  52597. }(EasingFunction));
  52598. BABYLON.BackEase = BackEase;
  52599. var BounceEase = /** @class */ (function (_super) {
  52600. __extends(BounceEase, _super);
  52601. function BounceEase(bounces, bounciness) {
  52602. if (bounces === void 0) { bounces = 3; }
  52603. if (bounciness === void 0) { bounciness = 2; }
  52604. var _this = _super.call(this) || this;
  52605. _this.bounces = bounces;
  52606. _this.bounciness = bounciness;
  52607. return _this;
  52608. }
  52609. BounceEase.prototype.easeInCore = function (gradient) {
  52610. var y = Math.max(0.0, this.bounces);
  52611. var bounciness = this.bounciness;
  52612. if (bounciness <= 1.0) {
  52613. bounciness = 1.001;
  52614. }
  52615. var num9 = Math.pow(bounciness, y);
  52616. var num5 = 1.0 - bounciness;
  52617. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52618. var num15 = gradient * num4;
  52619. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52620. var num3 = Math.floor(num65);
  52621. var num13 = num3 + 1.0;
  52622. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52623. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52624. var num7 = (num8 + num12) * 0.5;
  52625. var num6 = gradient - num7;
  52626. var num2 = num7 - num8;
  52627. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52628. };
  52629. return BounceEase;
  52630. }(EasingFunction));
  52631. BABYLON.BounceEase = BounceEase;
  52632. var CubicEase = /** @class */ (function (_super) {
  52633. __extends(CubicEase, _super);
  52634. function CubicEase() {
  52635. return _super !== null && _super.apply(this, arguments) || this;
  52636. }
  52637. CubicEase.prototype.easeInCore = function (gradient) {
  52638. return (gradient * gradient * gradient);
  52639. };
  52640. return CubicEase;
  52641. }(EasingFunction));
  52642. BABYLON.CubicEase = CubicEase;
  52643. var ElasticEase = /** @class */ (function (_super) {
  52644. __extends(ElasticEase, _super);
  52645. function ElasticEase(oscillations, springiness) {
  52646. if (oscillations === void 0) { oscillations = 3; }
  52647. if (springiness === void 0) { springiness = 3; }
  52648. var _this = _super.call(this) || this;
  52649. _this.oscillations = oscillations;
  52650. _this.springiness = springiness;
  52651. return _this;
  52652. }
  52653. ElasticEase.prototype.easeInCore = function (gradient) {
  52654. var num2;
  52655. var num3 = Math.max(0.0, this.oscillations);
  52656. var num = Math.max(0.0, this.springiness);
  52657. if (num == 0) {
  52658. num2 = gradient;
  52659. }
  52660. else {
  52661. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52662. }
  52663. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52664. };
  52665. return ElasticEase;
  52666. }(EasingFunction));
  52667. BABYLON.ElasticEase = ElasticEase;
  52668. var ExponentialEase = /** @class */ (function (_super) {
  52669. __extends(ExponentialEase, _super);
  52670. function ExponentialEase(exponent) {
  52671. if (exponent === void 0) { exponent = 2; }
  52672. var _this = _super.call(this) || this;
  52673. _this.exponent = exponent;
  52674. return _this;
  52675. }
  52676. ExponentialEase.prototype.easeInCore = function (gradient) {
  52677. if (this.exponent <= 0) {
  52678. return gradient;
  52679. }
  52680. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52681. };
  52682. return ExponentialEase;
  52683. }(EasingFunction));
  52684. BABYLON.ExponentialEase = ExponentialEase;
  52685. var PowerEase = /** @class */ (function (_super) {
  52686. __extends(PowerEase, _super);
  52687. function PowerEase(power) {
  52688. if (power === void 0) { power = 2; }
  52689. var _this = _super.call(this) || this;
  52690. _this.power = power;
  52691. return _this;
  52692. }
  52693. PowerEase.prototype.easeInCore = function (gradient) {
  52694. var y = Math.max(0.0, this.power);
  52695. return Math.pow(gradient, y);
  52696. };
  52697. return PowerEase;
  52698. }(EasingFunction));
  52699. BABYLON.PowerEase = PowerEase;
  52700. var QuadraticEase = /** @class */ (function (_super) {
  52701. __extends(QuadraticEase, _super);
  52702. function QuadraticEase() {
  52703. return _super !== null && _super.apply(this, arguments) || this;
  52704. }
  52705. QuadraticEase.prototype.easeInCore = function (gradient) {
  52706. return (gradient * gradient);
  52707. };
  52708. return QuadraticEase;
  52709. }(EasingFunction));
  52710. BABYLON.QuadraticEase = QuadraticEase;
  52711. var QuarticEase = /** @class */ (function (_super) {
  52712. __extends(QuarticEase, _super);
  52713. function QuarticEase() {
  52714. return _super !== null && _super.apply(this, arguments) || this;
  52715. }
  52716. QuarticEase.prototype.easeInCore = function (gradient) {
  52717. return (gradient * gradient * gradient * gradient);
  52718. };
  52719. return QuarticEase;
  52720. }(EasingFunction));
  52721. BABYLON.QuarticEase = QuarticEase;
  52722. var QuinticEase = /** @class */ (function (_super) {
  52723. __extends(QuinticEase, _super);
  52724. function QuinticEase() {
  52725. return _super !== null && _super.apply(this, arguments) || this;
  52726. }
  52727. QuinticEase.prototype.easeInCore = function (gradient) {
  52728. return (gradient * gradient * gradient * gradient * gradient);
  52729. };
  52730. return QuinticEase;
  52731. }(EasingFunction));
  52732. BABYLON.QuinticEase = QuinticEase;
  52733. var SineEase = /** @class */ (function (_super) {
  52734. __extends(SineEase, _super);
  52735. function SineEase() {
  52736. return _super !== null && _super.apply(this, arguments) || this;
  52737. }
  52738. SineEase.prototype.easeInCore = function (gradient) {
  52739. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52740. };
  52741. return SineEase;
  52742. }(EasingFunction));
  52743. BABYLON.SineEase = SineEase;
  52744. var BezierCurveEase = /** @class */ (function (_super) {
  52745. __extends(BezierCurveEase, _super);
  52746. function BezierCurveEase(x1, y1, x2, y2) {
  52747. if (x1 === void 0) { x1 = 0; }
  52748. if (y1 === void 0) { y1 = 0; }
  52749. if (x2 === void 0) { x2 = 1; }
  52750. if (y2 === void 0) { y2 = 1; }
  52751. var _this = _super.call(this) || this;
  52752. _this.x1 = x1;
  52753. _this.y1 = y1;
  52754. _this.x2 = x2;
  52755. _this.y2 = y2;
  52756. return _this;
  52757. }
  52758. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52759. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52760. };
  52761. return BezierCurveEase;
  52762. }(EasingFunction));
  52763. BABYLON.BezierCurveEase = BezierCurveEase;
  52764. })(BABYLON || (BABYLON = {}));
  52765. //# sourceMappingURL=babylon.easing.js.map
  52766. var BABYLON;
  52767. (function (BABYLON) {
  52768. /**
  52769. * A Condition applied to an Action
  52770. */
  52771. var Condition = /** @class */ (function () {
  52772. /**
  52773. * Creates a new Condition
  52774. * @param actionManager the manager of the action the condition is applied to
  52775. */
  52776. function Condition(actionManager) {
  52777. this._actionManager = actionManager;
  52778. }
  52779. /**
  52780. * Check if the current condition is valid
  52781. * @returns a boolean
  52782. */
  52783. Condition.prototype.isValid = function () {
  52784. return true;
  52785. };
  52786. /**
  52787. * Internal only
  52788. * @hidden
  52789. */
  52790. Condition.prototype._getProperty = function (propertyPath) {
  52791. return this._actionManager._getProperty(propertyPath);
  52792. };
  52793. /**
  52794. * Internal only
  52795. * @hidden
  52796. */
  52797. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52798. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52799. };
  52800. /**
  52801. * Serialize placeholder for child classes
  52802. * @returns the serialized object
  52803. */
  52804. Condition.prototype.serialize = function () {
  52805. };
  52806. /**
  52807. * Internal only
  52808. * @hidden
  52809. */
  52810. Condition.prototype._serialize = function (serializedCondition) {
  52811. return {
  52812. type: 2,
  52813. children: [],
  52814. name: serializedCondition.name,
  52815. properties: serializedCondition.properties
  52816. };
  52817. };
  52818. return Condition;
  52819. }());
  52820. BABYLON.Condition = Condition;
  52821. /**
  52822. * Defines specific conditional operators as extensions of Condition
  52823. */
  52824. var ValueCondition = /** @class */ (function (_super) {
  52825. __extends(ValueCondition, _super);
  52826. /**
  52827. * Creates a new ValueCondition
  52828. * @param actionManager manager for the action the condition applies to
  52829. * @param target for the action
  52830. * @param propertyPath path to specify the property of the target the conditional operator uses
  52831. * @param value the value compared by the conditional operator against the current value of the property
  52832. * @param operator the conditional operator, default ValueCondition.IsEqual
  52833. */
  52834. function ValueCondition(actionManager, target,
  52835. /** path to specify the property of the target the conditional operator uses */
  52836. propertyPath,
  52837. /** the value compared by the conditional operator against the current value of the property */
  52838. value,
  52839. /** the conditional operator, default ValueCondition.IsEqual */
  52840. operator) {
  52841. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52842. var _this = _super.call(this, actionManager) || this;
  52843. _this.propertyPath = propertyPath;
  52844. _this.value = value;
  52845. _this.operator = operator;
  52846. _this._target = target;
  52847. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52848. _this._property = _this._getProperty(_this.propertyPath);
  52849. return _this;
  52850. }
  52851. Object.defineProperty(ValueCondition, "IsEqual", {
  52852. /**
  52853. * returns the number for IsEqual
  52854. */
  52855. get: function () {
  52856. return ValueCondition._IsEqual;
  52857. },
  52858. enumerable: true,
  52859. configurable: true
  52860. });
  52861. Object.defineProperty(ValueCondition, "IsDifferent", {
  52862. /**
  52863. * Returns the number for IsDifferent
  52864. */
  52865. get: function () {
  52866. return ValueCondition._IsDifferent;
  52867. },
  52868. enumerable: true,
  52869. configurable: true
  52870. });
  52871. Object.defineProperty(ValueCondition, "IsGreater", {
  52872. /**
  52873. * Returns the number for IsGreater
  52874. */
  52875. get: function () {
  52876. return ValueCondition._IsGreater;
  52877. },
  52878. enumerable: true,
  52879. configurable: true
  52880. });
  52881. Object.defineProperty(ValueCondition, "IsLesser", {
  52882. /**
  52883. * Returns the number for IsLesser
  52884. */
  52885. get: function () {
  52886. return ValueCondition._IsLesser;
  52887. },
  52888. enumerable: true,
  52889. configurable: true
  52890. });
  52891. /**
  52892. * Compares the given value with the property value for the specified conditional operator
  52893. * @returns the result of the comparison
  52894. */
  52895. ValueCondition.prototype.isValid = function () {
  52896. switch (this.operator) {
  52897. case ValueCondition.IsGreater:
  52898. return this._effectiveTarget[this._property] > this.value;
  52899. case ValueCondition.IsLesser:
  52900. return this._effectiveTarget[this._property] < this.value;
  52901. case ValueCondition.IsEqual:
  52902. case ValueCondition.IsDifferent:
  52903. var check;
  52904. if (this.value.equals) {
  52905. check = this.value.equals(this._effectiveTarget[this._property]);
  52906. }
  52907. else {
  52908. check = this.value === this._effectiveTarget[this._property];
  52909. }
  52910. return this.operator === ValueCondition.IsEqual ? check : !check;
  52911. }
  52912. return false;
  52913. };
  52914. /**
  52915. * Serialize the ValueCondition into a JSON compatible object
  52916. * @returns serialization object
  52917. */
  52918. ValueCondition.prototype.serialize = function () {
  52919. return this._serialize({
  52920. name: "ValueCondition",
  52921. properties: [
  52922. BABYLON.Action._GetTargetProperty(this._target),
  52923. { name: "propertyPath", value: this.propertyPath },
  52924. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52925. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52926. ]
  52927. });
  52928. };
  52929. /**
  52930. * Gets the name of the conditional operator for the ValueCondition
  52931. * @param operator the conditional operator
  52932. * @returns the name
  52933. */
  52934. ValueCondition.GetOperatorName = function (operator) {
  52935. switch (operator) {
  52936. case ValueCondition._IsEqual: return "IsEqual";
  52937. case ValueCondition._IsDifferent: return "IsDifferent";
  52938. case ValueCondition._IsGreater: return "IsGreater";
  52939. case ValueCondition._IsLesser: return "IsLesser";
  52940. default: return "";
  52941. }
  52942. };
  52943. /**
  52944. * Internal only
  52945. * @hidden
  52946. */
  52947. ValueCondition._IsEqual = 0;
  52948. /**
  52949. * Internal only
  52950. * @hidden
  52951. */
  52952. ValueCondition._IsDifferent = 1;
  52953. /**
  52954. * Internal only
  52955. * @hidden
  52956. */
  52957. ValueCondition._IsGreater = 2;
  52958. /**
  52959. * Internal only
  52960. * @hidden
  52961. */
  52962. ValueCondition._IsLesser = 3;
  52963. return ValueCondition;
  52964. }(Condition));
  52965. BABYLON.ValueCondition = ValueCondition;
  52966. /**
  52967. * Defines a predicate condition as an extension of Condition
  52968. */
  52969. var PredicateCondition = /** @class */ (function (_super) {
  52970. __extends(PredicateCondition, _super);
  52971. /**
  52972. * Creates a new PredicateCondition
  52973. * @param actionManager manager for the action the condition applies to
  52974. * @param predicate defines the predicate function used to validate the condition
  52975. */
  52976. function PredicateCondition(actionManager,
  52977. /** defines the predicate function used to validate the condition */
  52978. predicate) {
  52979. var _this = _super.call(this, actionManager) || this;
  52980. _this.predicate = predicate;
  52981. return _this;
  52982. }
  52983. /**
  52984. * @returns the validity of the predicate condition
  52985. */
  52986. PredicateCondition.prototype.isValid = function () {
  52987. return this.predicate();
  52988. };
  52989. return PredicateCondition;
  52990. }(Condition));
  52991. BABYLON.PredicateCondition = PredicateCondition;
  52992. /**
  52993. * Defines a state condition as an extension of Condition
  52994. */
  52995. var StateCondition = /** @class */ (function (_super) {
  52996. __extends(StateCondition, _super);
  52997. /**
  52998. * Creates a new StateCondition
  52999. * @param actionManager manager for the action the condition applies to
  53000. * @param target of the condition
  53001. * @param value to compare with target state
  53002. */
  53003. function StateCondition(actionManager, target, value) {
  53004. var _this = _super.call(this, actionManager) || this;
  53005. _this.value = value;
  53006. _this._target = target;
  53007. return _this;
  53008. }
  53009. /**
  53010. * @returns the validity of the state
  53011. */
  53012. StateCondition.prototype.isValid = function () {
  53013. return this._target.state === this.value;
  53014. };
  53015. /**
  53016. * Serialize the StateCondition into a JSON compatible object
  53017. * @returns serialization object
  53018. */
  53019. StateCondition.prototype.serialize = function () {
  53020. return this._serialize({
  53021. name: "StateCondition",
  53022. properties: [
  53023. BABYLON.Action._GetTargetProperty(this._target),
  53024. { name: "value", value: this.value }
  53025. ]
  53026. });
  53027. };
  53028. return StateCondition;
  53029. }(Condition));
  53030. BABYLON.StateCondition = StateCondition;
  53031. })(BABYLON || (BABYLON = {}));
  53032. //# sourceMappingURL=babylon.condition.js.map
  53033. var BABYLON;
  53034. (function (BABYLON) {
  53035. /**
  53036. * The action to be carried out following a trigger
  53037. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53038. */
  53039. var Action = /** @class */ (function () {
  53040. /**
  53041. * Creates a new Action
  53042. * @param triggerOptions the trigger, with or without parameters, for the action
  53043. * @param condition an optional determinant of action
  53044. */
  53045. function Action(
  53046. /** the trigger, with or without parameters, for the action */
  53047. triggerOptions, condition) {
  53048. this.triggerOptions = triggerOptions;
  53049. /**
  53050. * An event triggered prior to action being executed.
  53051. */
  53052. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53053. if (triggerOptions.parameter) {
  53054. this.trigger = triggerOptions.trigger;
  53055. this._triggerParameter = triggerOptions.parameter;
  53056. }
  53057. else {
  53058. this.trigger = triggerOptions;
  53059. }
  53060. this._nextActiveAction = this;
  53061. this._condition = condition;
  53062. }
  53063. /**
  53064. * Internal only
  53065. * @hidden
  53066. */
  53067. Action.prototype._prepare = function () {
  53068. };
  53069. /**
  53070. * Gets the trigger parameters
  53071. * @returns the trigger parameters
  53072. */
  53073. Action.prototype.getTriggerParameter = function () {
  53074. return this._triggerParameter;
  53075. };
  53076. /**
  53077. * Internal only - executes current action event
  53078. * @hidden
  53079. */
  53080. Action.prototype._executeCurrent = function (evt) {
  53081. if (this._nextActiveAction._condition) {
  53082. var condition = this._nextActiveAction._condition;
  53083. var currentRenderId = this._actionManager.getScene().getRenderId();
  53084. // We cache the current evaluation for the current frame
  53085. if (condition._evaluationId === currentRenderId) {
  53086. if (!condition._currentResult) {
  53087. return;
  53088. }
  53089. }
  53090. else {
  53091. condition._evaluationId = currentRenderId;
  53092. if (!condition.isValid()) {
  53093. condition._currentResult = false;
  53094. return;
  53095. }
  53096. condition._currentResult = true;
  53097. }
  53098. }
  53099. this.onBeforeExecuteObservable.notifyObservers(this);
  53100. this._nextActiveAction.execute(evt);
  53101. this.skipToNextActiveAction();
  53102. };
  53103. /**
  53104. * Execute placeholder for child classes
  53105. * @param evt optional action event
  53106. */
  53107. Action.prototype.execute = function (evt) {
  53108. };
  53109. /**
  53110. * Skips to next active action
  53111. */
  53112. Action.prototype.skipToNextActiveAction = function () {
  53113. if (this._nextActiveAction._child) {
  53114. if (!this._nextActiveAction._child._actionManager) {
  53115. this._nextActiveAction._child._actionManager = this._actionManager;
  53116. }
  53117. this._nextActiveAction = this._nextActiveAction._child;
  53118. }
  53119. else {
  53120. this._nextActiveAction = this;
  53121. }
  53122. };
  53123. /**
  53124. * Adds action to chain of actions, may be a DoNothingAction
  53125. * @param action defines the next action to execute
  53126. * @returns The action passed in
  53127. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53128. */
  53129. Action.prototype.then = function (action) {
  53130. this._child = action;
  53131. action._actionManager = this._actionManager;
  53132. action._prepare();
  53133. return action;
  53134. };
  53135. /**
  53136. * Internal only
  53137. * @hidden
  53138. */
  53139. Action.prototype._getProperty = function (propertyPath) {
  53140. return this._actionManager._getProperty(propertyPath);
  53141. };
  53142. /**
  53143. * Internal only
  53144. * @hidden
  53145. */
  53146. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53147. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53148. };
  53149. /**
  53150. * Serialize placeholder for child classes
  53151. * @param parent of child
  53152. * @returns the serialized object
  53153. */
  53154. Action.prototype.serialize = function (parent) {
  53155. };
  53156. /**
  53157. * Internal only called by serialize
  53158. * @hidden
  53159. */
  53160. Action.prototype._serialize = function (serializedAction, parent) {
  53161. var serializationObject = {
  53162. type: 1,
  53163. children: [],
  53164. name: serializedAction.name,
  53165. properties: serializedAction.properties || []
  53166. };
  53167. // Serialize child
  53168. if (this._child) {
  53169. this._child.serialize(serializationObject);
  53170. }
  53171. // Check if "this" has a condition
  53172. if (this._condition) {
  53173. var serializedCondition = this._condition.serialize();
  53174. serializedCondition.children.push(serializationObject);
  53175. if (parent) {
  53176. parent.children.push(serializedCondition);
  53177. }
  53178. return serializedCondition;
  53179. }
  53180. if (parent) {
  53181. parent.children.push(serializationObject);
  53182. }
  53183. return serializationObject;
  53184. };
  53185. /**
  53186. * Internal only
  53187. * @hidden
  53188. */
  53189. Action._SerializeValueAsString = function (value) {
  53190. if (typeof value === "number") {
  53191. return value.toString();
  53192. }
  53193. if (typeof value === "boolean") {
  53194. return value ? "true" : "false";
  53195. }
  53196. if (value instanceof BABYLON.Vector2) {
  53197. return value.x + ", " + value.y;
  53198. }
  53199. if (value instanceof BABYLON.Vector3) {
  53200. return value.x + ", " + value.y + ", " + value.z;
  53201. }
  53202. if (value instanceof BABYLON.Color3) {
  53203. return value.r + ", " + value.g + ", " + value.b;
  53204. }
  53205. if (value instanceof BABYLON.Color4) {
  53206. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53207. }
  53208. return value; // string
  53209. };
  53210. /**
  53211. * Internal only
  53212. * @hidden
  53213. */
  53214. Action._GetTargetProperty = function (target) {
  53215. return {
  53216. name: "target",
  53217. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53218. : target instanceof BABYLON.Light ? "LightProperties"
  53219. : target instanceof BABYLON.Camera ? "CameraProperties"
  53220. : "SceneProperties",
  53221. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53222. };
  53223. };
  53224. return Action;
  53225. }());
  53226. BABYLON.Action = Action;
  53227. })(BABYLON || (BABYLON = {}));
  53228. //# sourceMappingURL=babylon.action.js.map
  53229. var BABYLON;
  53230. (function (BABYLON) {
  53231. /**
  53232. * ActionEvent is the event being sent when an action is triggered.
  53233. */
  53234. var ActionEvent = /** @class */ (function () {
  53235. /**
  53236. * Creates a new ActionEvent
  53237. * @param source The mesh or sprite that triggered the action
  53238. * @param pointerX The X mouse cursor position at the time of the event
  53239. * @param pointerY The Y mouse cursor position at the time of the event
  53240. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53241. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53242. * @param additionalData additional data for the event
  53243. */
  53244. function ActionEvent(
  53245. /** The mesh or sprite that triggered the action */
  53246. source,
  53247. /** The X mouse cursor position at the time of the event */
  53248. pointerX,
  53249. /** The Y mouse cursor position at the time of the event */
  53250. pointerY,
  53251. /** The mesh that is currently pointed at (can be null) */
  53252. meshUnderPointer,
  53253. /** the original (browser) event that triggered the ActionEvent */
  53254. sourceEvent,
  53255. /** additional data for the event */
  53256. additionalData) {
  53257. this.source = source;
  53258. this.pointerX = pointerX;
  53259. this.pointerY = pointerY;
  53260. this.meshUnderPointer = meshUnderPointer;
  53261. this.sourceEvent = sourceEvent;
  53262. this.additionalData = additionalData;
  53263. }
  53264. /**
  53265. * Helper function to auto-create an ActionEvent from a source mesh.
  53266. * @param source The source mesh that triggered the event
  53267. * @param evt The original (browser) event
  53268. * @param additionalData additional data for the event
  53269. * @returns the new ActionEvent
  53270. */
  53271. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53272. var scene = source.getScene();
  53273. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53274. };
  53275. /**
  53276. * Helper function to auto-create an ActionEvent from a source sprite
  53277. * @param source The source sprite that triggered the event
  53278. * @param scene Scene associated with the sprite
  53279. * @param evt The original (browser) event
  53280. * @param additionalData additional data for the event
  53281. * @returns the new ActionEvent
  53282. */
  53283. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53284. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53285. };
  53286. /**
  53287. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53288. * @param scene the scene where the event occurred
  53289. * @param evt The original (browser) event
  53290. * @returns the new ActionEvent
  53291. */
  53292. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53293. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53294. };
  53295. /**
  53296. * Helper function to auto-create an ActionEvent from a primitive
  53297. * @param prim defines the target primitive
  53298. * @param pointerPos defines the pointer position
  53299. * @param evt The original (browser) event
  53300. * @param additionalData additional data for the event
  53301. * @returns the new ActionEvent
  53302. */
  53303. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53304. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53305. };
  53306. return ActionEvent;
  53307. }());
  53308. BABYLON.ActionEvent = ActionEvent;
  53309. /**
  53310. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53311. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53312. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53313. */
  53314. var ActionManager = /** @class */ (function () {
  53315. /**
  53316. * Creates a new action manager
  53317. * @param scene defines the hosting scene
  53318. */
  53319. function ActionManager(scene) {
  53320. // Members
  53321. /** Gets the list of actions */
  53322. this.actions = new Array();
  53323. /** Gets the cursor to use when hovering items */
  53324. this.hoverCursor = '';
  53325. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53326. scene._actionManagers.push(this);
  53327. }
  53328. Object.defineProperty(ActionManager, "NothingTrigger", {
  53329. /**
  53330. * Nothing
  53331. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53332. */
  53333. get: function () {
  53334. return ActionManager._NothingTrigger;
  53335. },
  53336. enumerable: true,
  53337. configurable: true
  53338. });
  53339. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53340. /**
  53341. * On pick
  53342. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53343. */
  53344. get: function () {
  53345. return ActionManager._OnPickTrigger;
  53346. },
  53347. enumerable: true,
  53348. configurable: true
  53349. });
  53350. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53351. /**
  53352. * On left pick
  53353. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53354. */
  53355. get: function () {
  53356. return ActionManager._OnLeftPickTrigger;
  53357. },
  53358. enumerable: true,
  53359. configurable: true
  53360. });
  53361. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53362. /**
  53363. * On right pick
  53364. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53365. */
  53366. get: function () {
  53367. return ActionManager._OnRightPickTrigger;
  53368. },
  53369. enumerable: true,
  53370. configurable: true
  53371. });
  53372. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53373. /**
  53374. * On center pick
  53375. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53376. */
  53377. get: function () {
  53378. return ActionManager._OnCenterPickTrigger;
  53379. },
  53380. enumerable: true,
  53381. configurable: true
  53382. });
  53383. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53384. /**
  53385. * On pick down
  53386. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53387. */
  53388. get: function () {
  53389. return ActionManager._OnPickDownTrigger;
  53390. },
  53391. enumerable: true,
  53392. configurable: true
  53393. });
  53394. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53395. /**
  53396. * On double pick
  53397. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53398. */
  53399. get: function () {
  53400. return ActionManager._OnDoublePickTrigger;
  53401. },
  53402. enumerable: true,
  53403. configurable: true
  53404. });
  53405. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53406. /**
  53407. * On pick up
  53408. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53409. */
  53410. get: function () {
  53411. return ActionManager._OnPickUpTrigger;
  53412. },
  53413. enumerable: true,
  53414. configurable: true
  53415. });
  53416. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53417. /**
  53418. * On pick out.
  53419. * This trigger will only be raised if you also declared a OnPickDown
  53420. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53421. */
  53422. get: function () {
  53423. return ActionManager._OnPickOutTrigger;
  53424. },
  53425. enumerable: true,
  53426. configurable: true
  53427. });
  53428. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53429. /**
  53430. * On long press
  53431. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53432. */
  53433. get: function () {
  53434. return ActionManager._OnLongPressTrigger;
  53435. },
  53436. enumerable: true,
  53437. configurable: true
  53438. });
  53439. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53440. /**
  53441. * On pointer over
  53442. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53443. */
  53444. get: function () {
  53445. return ActionManager._OnPointerOverTrigger;
  53446. },
  53447. enumerable: true,
  53448. configurable: true
  53449. });
  53450. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53451. /**
  53452. * On pointer out
  53453. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53454. */
  53455. get: function () {
  53456. return ActionManager._OnPointerOutTrigger;
  53457. },
  53458. enumerable: true,
  53459. configurable: true
  53460. });
  53461. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53462. /**
  53463. * On every frame
  53464. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53465. */
  53466. get: function () {
  53467. return ActionManager._OnEveryFrameTrigger;
  53468. },
  53469. enumerable: true,
  53470. configurable: true
  53471. });
  53472. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53473. /**
  53474. * On intersection enter
  53475. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53476. */
  53477. get: function () {
  53478. return ActionManager._OnIntersectionEnterTrigger;
  53479. },
  53480. enumerable: true,
  53481. configurable: true
  53482. });
  53483. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53484. /**
  53485. * On intersection exit
  53486. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53487. */
  53488. get: function () {
  53489. return ActionManager._OnIntersectionExitTrigger;
  53490. },
  53491. enumerable: true,
  53492. configurable: true
  53493. });
  53494. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53495. /**
  53496. * On key down
  53497. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53498. */
  53499. get: function () {
  53500. return ActionManager._OnKeyDownTrigger;
  53501. },
  53502. enumerable: true,
  53503. configurable: true
  53504. });
  53505. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53506. /**
  53507. * On key up
  53508. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53509. */
  53510. get: function () {
  53511. return ActionManager._OnKeyUpTrigger;
  53512. },
  53513. enumerable: true,
  53514. configurable: true
  53515. });
  53516. // Methods
  53517. /**
  53518. * Releases all associated resources
  53519. */
  53520. ActionManager.prototype.dispose = function () {
  53521. var index = this._scene._actionManagers.indexOf(this);
  53522. for (var i = 0; i < this.actions.length; i++) {
  53523. var action = this.actions[i];
  53524. ActionManager.Triggers[action.trigger]--;
  53525. if (ActionManager.Triggers[action.trigger] === 0) {
  53526. delete ActionManager.Triggers[action.trigger];
  53527. }
  53528. }
  53529. if (index > -1) {
  53530. this._scene._actionManagers.splice(index, 1);
  53531. }
  53532. };
  53533. /**
  53534. * Gets hosting scene
  53535. * @returns the hosting scene
  53536. */
  53537. ActionManager.prototype.getScene = function () {
  53538. return this._scene;
  53539. };
  53540. /**
  53541. * Does this action manager handles actions of any of the given triggers
  53542. * @param triggers defines the triggers to be tested
  53543. * @return a boolean indicating whether one (or more) of the triggers is handled
  53544. */
  53545. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53546. for (var index = 0; index < this.actions.length; index++) {
  53547. var action = this.actions[index];
  53548. if (triggers.indexOf(action.trigger) > -1) {
  53549. return true;
  53550. }
  53551. }
  53552. return false;
  53553. };
  53554. /**
  53555. * Does this action manager handles actions of a given trigger
  53556. * @param trigger defines the trigger to be tested
  53557. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53558. * @return whether the trigger is handled
  53559. */
  53560. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53561. for (var index = 0; index < this.actions.length; index++) {
  53562. var action = this.actions[index];
  53563. if (action.trigger === trigger) {
  53564. if (parameterPredicate) {
  53565. if (parameterPredicate(action.getTriggerParameter())) {
  53566. return true;
  53567. }
  53568. }
  53569. else {
  53570. return true;
  53571. }
  53572. }
  53573. }
  53574. return false;
  53575. };
  53576. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53577. /**
  53578. * Does this action manager has pointer triggers
  53579. */
  53580. get: function () {
  53581. for (var index = 0; index < this.actions.length; index++) {
  53582. var action = this.actions[index];
  53583. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53584. return true;
  53585. }
  53586. }
  53587. return false;
  53588. },
  53589. enumerable: true,
  53590. configurable: true
  53591. });
  53592. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53593. /**
  53594. * Does this action manager has pick triggers
  53595. */
  53596. get: function () {
  53597. for (var index = 0; index < this.actions.length; index++) {
  53598. var action = this.actions[index];
  53599. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53600. return true;
  53601. }
  53602. }
  53603. return false;
  53604. },
  53605. enumerable: true,
  53606. configurable: true
  53607. });
  53608. Object.defineProperty(ActionManager, "HasTriggers", {
  53609. /**
  53610. * Does exist one action manager with at least one trigger
  53611. **/
  53612. get: function () {
  53613. for (var t in ActionManager.Triggers) {
  53614. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53615. return true;
  53616. }
  53617. }
  53618. return false;
  53619. },
  53620. enumerable: true,
  53621. configurable: true
  53622. });
  53623. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53624. /**
  53625. * Does exist one action manager with at least one pick trigger
  53626. **/
  53627. get: function () {
  53628. for (var t in ActionManager.Triggers) {
  53629. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53630. var t_int = parseInt(t);
  53631. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53632. return true;
  53633. }
  53634. }
  53635. }
  53636. return false;
  53637. },
  53638. enumerable: true,
  53639. configurable: true
  53640. });
  53641. /**
  53642. * Does exist one action manager that handles actions of a given trigger
  53643. * @param trigger defines the trigger to be tested
  53644. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53645. **/
  53646. ActionManager.HasSpecificTrigger = function (trigger) {
  53647. for (var t in ActionManager.Triggers) {
  53648. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53649. var t_int = parseInt(t);
  53650. if (t_int === trigger) {
  53651. return true;
  53652. }
  53653. }
  53654. }
  53655. return false;
  53656. };
  53657. /**
  53658. * Registers an action to this action manager
  53659. * @param action defines the action to be registered
  53660. * @return the action amended (prepared) after registration
  53661. */
  53662. ActionManager.prototype.registerAction = function (action) {
  53663. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53664. if (this.getScene().actionManager !== this) {
  53665. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53666. return null;
  53667. }
  53668. }
  53669. this.actions.push(action);
  53670. if (ActionManager.Triggers[action.trigger]) {
  53671. ActionManager.Triggers[action.trigger]++;
  53672. }
  53673. else {
  53674. ActionManager.Triggers[action.trigger] = 1;
  53675. }
  53676. action._actionManager = this;
  53677. action._prepare();
  53678. return action;
  53679. };
  53680. /**
  53681. * Unregisters an action to this action manager
  53682. * @param action defines the action to be unregistered
  53683. * @return a boolean indicating whether the action has been unregistered
  53684. */
  53685. ActionManager.prototype.unregisterAction = function (action) {
  53686. var index = this.actions.indexOf(action);
  53687. if (index !== -1) {
  53688. this.actions.splice(index, 1);
  53689. ActionManager.Triggers[action.trigger] -= 1;
  53690. if (ActionManager.Triggers[action.trigger] === 0) {
  53691. delete ActionManager.Triggers[action.trigger];
  53692. }
  53693. delete action._actionManager;
  53694. return true;
  53695. }
  53696. return false;
  53697. };
  53698. /**
  53699. * Process a specific trigger
  53700. * @param trigger defines the trigger to process
  53701. * @param evt defines the event details to be processed
  53702. */
  53703. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53704. for (var index = 0; index < this.actions.length; index++) {
  53705. var action = this.actions[index];
  53706. if (action.trigger === trigger) {
  53707. if (evt) {
  53708. if (trigger === ActionManager.OnKeyUpTrigger
  53709. || trigger === ActionManager.OnKeyDownTrigger) {
  53710. var parameter = action.getTriggerParameter();
  53711. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53712. if (!parameter.toLowerCase) {
  53713. continue;
  53714. }
  53715. var lowerCase = parameter.toLowerCase();
  53716. if (lowerCase !== evt.sourceEvent.key) {
  53717. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53718. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53719. if (actualkey !== lowerCase) {
  53720. continue;
  53721. }
  53722. }
  53723. }
  53724. }
  53725. }
  53726. action._executeCurrent(evt);
  53727. }
  53728. }
  53729. };
  53730. /** @hidden */
  53731. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53732. var properties = propertyPath.split(".");
  53733. for (var index = 0; index < properties.length - 1; index++) {
  53734. target = target[properties[index]];
  53735. }
  53736. return target;
  53737. };
  53738. /** @hidden */
  53739. ActionManager.prototype._getProperty = function (propertyPath) {
  53740. var properties = propertyPath.split(".");
  53741. return properties[properties.length - 1];
  53742. };
  53743. /**
  53744. * Serialize this manager to a JSON object
  53745. * @param name defines the property name to store this manager
  53746. * @returns a JSON representation of this manager
  53747. */
  53748. ActionManager.prototype.serialize = function (name) {
  53749. var root = {
  53750. children: new Array(),
  53751. name: name,
  53752. type: 3,
  53753. properties: new Array() // Empty for root but required
  53754. };
  53755. for (var i = 0; i < this.actions.length; i++) {
  53756. var triggerObject = {
  53757. type: 0,
  53758. children: new Array(),
  53759. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53760. properties: new Array()
  53761. };
  53762. var triggerOptions = this.actions[i].triggerOptions;
  53763. if (triggerOptions && typeof triggerOptions !== "number") {
  53764. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53765. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53766. }
  53767. else {
  53768. var parameter = {};
  53769. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53770. if (triggerOptions.parameter.mesh) {
  53771. parameter._meshId = triggerOptions.parameter.mesh.id;
  53772. }
  53773. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53774. }
  53775. }
  53776. // Serialize child action, recursively
  53777. this.actions[i].serialize(triggerObject);
  53778. // Add serialized trigger
  53779. root.children.push(triggerObject);
  53780. }
  53781. return root;
  53782. };
  53783. /**
  53784. * Creates a new ActionManager from a JSON data
  53785. * @param parsedActions defines the JSON data to read from
  53786. * @param object defines the hosting mesh
  53787. * @param scene defines the hosting scene
  53788. */
  53789. ActionManager.Parse = function (parsedActions, object, scene) {
  53790. var actionManager = new ActionManager(scene);
  53791. if (object === null)
  53792. scene.actionManager = actionManager;
  53793. else
  53794. object.actionManager = actionManager;
  53795. // instanciate a new object
  53796. var instanciate = function (name, params) {
  53797. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53798. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53799. newInstance.constructor.apply(newInstance, params);
  53800. return newInstance;
  53801. };
  53802. var parseParameter = function (name, value, target, propertyPath) {
  53803. if (propertyPath === null) {
  53804. // String, boolean or float
  53805. var floatValue = parseFloat(value);
  53806. if (value === "true" || value === "false")
  53807. return value === "true";
  53808. else
  53809. return isNaN(floatValue) ? value : floatValue;
  53810. }
  53811. var effectiveTarget = propertyPath.split(".");
  53812. var values = value.split(",");
  53813. // Get effective Target
  53814. for (var i = 0; i < effectiveTarget.length; i++) {
  53815. target = target[effectiveTarget[i]];
  53816. }
  53817. // Return appropriate value with its type
  53818. if (typeof (target) === "boolean")
  53819. return values[0] === "true";
  53820. if (typeof (target) === "string")
  53821. return values[0];
  53822. // Parameters with multiple values such as Vector3 etc.
  53823. var split = new Array();
  53824. for (var i = 0; i < values.length; i++)
  53825. split.push(parseFloat(values[i]));
  53826. if (target instanceof BABYLON.Vector3)
  53827. return BABYLON.Vector3.FromArray(split);
  53828. if (target instanceof BABYLON.Vector4)
  53829. return BABYLON.Vector4.FromArray(split);
  53830. if (target instanceof BABYLON.Color3)
  53831. return BABYLON.Color3.FromArray(split);
  53832. if (target instanceof BABYLON.Color4)
  53833. return BABYLON.Color4.FromArray(split);
  53834. return parseFloat(values[0]);
  53835. };
  53836. // traverse graph per trigger
  53837. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53838. if (combineArray === void 0) { combineArray = null; }
  53839. if (parsedAction.detached)
  53840. return;
  53841. var parameters = new Array();
  53842. var target = null;
  53843. var propertyPath = null;
  53844. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53845. // Parameters
  53846. if (parsedAction.type === 2)
  53847. parameters.push(actionManager);
  53848. else
  53849. parameters.push(trigger);
  53850. if (combine) {
  53851. var actions = new Array();
  53852. for (var j = 0; j < parsedAction.combine.length; j++) {
  53853. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53854. }
  53855. parameters.push(actions);
  53856. }
  53857. else {
  53858. for (var i = 0; i < parsedAction.properties.length; i++) {
  53859. var value = parsedAction.properties[i].value;
  53860. var name = parsedAction.properties[i].name;
  53861. var targetType = parsedAction.properties[i].targetType;
  53862. if (name === "target")
  53863. if (targetType !== null && targetType === "SceneProperties")
  53864. value = target = scene;
  53865. else
  53866. value = target = scene.getNodeByName(value);
  53867. else if (name === "parent")
  53868. value = scene.getNodeByName(value);
  53869. else if (name === "sound")
  53870. value = scene.getSoundByName(value);
  53871. else if (name !== "propertyPath") {
  53872. if (parsedAction.type === 2 && name === "operator")
  53873. value = BABYLON.ValueCondition[value];
  53874. else
  53875. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53876. }
  53877. else {
  53878. propertyPath = value;
  53879. }
  53880. parameters.push(value);
  53881. }
  53882. }
  53883. if (combineArray === null) {
  53884. parameters.push(condition);
  53885. }
  53886. else {
  53887. parameters.push(null);
  53888. }
  53889. // If interpolate value action
  53890. if (parsedAction.name === "InterpolateValueAction") {
  53891. var param = parameters[parameters.length - 2];
  53892. parameters[parameters.length - 1] = param;
  53893. parameters[parameters.length - 2] = condition;
  53894. }
  53895. // Action or condition(s) and not CombineAction
  53896. var newAction = instanciate(parsedAction.name, parameters);
  53897. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53898. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53899. if (action)
  53900. action.then(nothing);
  53901. else
  53902. actionManager.registerAction(nothing);
  53903. action = nothing;
  53904. }
  53905. if (combineArray === null) {
  53906. if (newAction instanceof BABYLON.Condition) {
  53907. condition = newAction;
  53908. newAction = action;
  53909. }
  53910. else {
  53911. condition = null;
  53912. if (action)
  53913. action.then(newAction);
  53914. else
  53915. actionManager.registerAction(newAction);
  53916. }
  53917. }
  53918. else {
  53919. combineArray.push(newAction);
  53920. }
  53921. for (var i = 0; i < parsedAction.children.length; i++)
  53922. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53923. };
  53924. // triggers
  53925. for (var i = 0; i < parsedActions.children.length; i++) {
  53926. var triggerParams;
  53927. var trigger = parsedActions.children[i];
  53928. if (trigger.properties.length > 0) {
  53929. var param = trigger.properties[0].value;
  53930. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53931. if (value._meshId) {
  53932. value.mesh = scene.getMeshByID(value._meshId);
  53933. }
  53934. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53935. }
  53936. else
  53937. triggerParams = ActionManager[trigger.name];
  53938. for (var j = 0; j < trigger.children.length; j++) {
  53939. if (!trigger.detached)
  53940. traverse(trigger.children[j], triggerParams, null, null);
  53941. }
  53942. }
  53943. };
  53944. /**
  53945. * Get a trigger name by index
  53946. * @param trigger defines the trigger index
  53947. * @returns a trigger name
  53948. */
  53949. ActionManager.GetTriggerName = function (trigger) {
  53950. switch (trigger) {
  53951. case 0: return "NothingTrigger";
  53952. case 1: return "OnPickTrigger";
  53953. case 2: return "OnLeftPickTrigger";
  53954. case 3: return "OnRightPickTrigger";
  53955. case 4: return "OnCenterPickTrigger";
  53956. case 5: return "OnPickDownTrigger";
  53957. case 6: return "OnPickUpTrigger";
  53958. case 7: return "OnLongPressTrigger";
  53959. case 8: return "OnPointerOverTrigger";
  53960. case 9: return "OnPointerOutTrigger";
  53961. case 10: return "OnEveryFrameTrigger";
  53962. case 11: return "OnIntersectionEnterTrigger";
  53963. case 12: return "OnIntersectionExitTrigger";
  53964. case 13: return "OnKeyDownTrigger";
  53965. case 14: return "OnKeyUpTrigger";
  53966. case 15: return "OnPickOutTrigger";
  53967. default: return "";
  53968. }
  53969. };
  53970. // Statics
  53971. ActionManager._NothingTrigger = 0;
  53972. ActionManager._OnPickTrigger = 1;
  53973. ActionManager._OnLeftPickTrigger = 2;
  53974. ActionManager._OnRightPickTrigger = 3;
  53975. ActionManager._OnCenterPickTrigger = 4;
  53976. ActionManager._OnPickDownTrigger = 5;
  53977. ActionManager._OnDoublePickTrigger = 6;
  53978. ActionManager._OnPickUpTrigger = 7;
  53979. ActionManager._OnLongPressTrigger = 8;
  53980. ActionManager._OnPointerOverTrigger = 9;
  53981. ActionManager._OnPointerOutTrigger = 10;
  53982. ActionManager._OnEveryFrameTrigger = 11;
  53983. ActionManager._OnIntersectionEnterTrigger = 12;
  53984. ActionManager._OnIntersectionExitTrigger = 13;
  53985. ActionManager._OnKeyDownTrigger = 14;
  53986. ActionManager._OnKeyUpTrigger = 15;
  53987. ActionManager._OnPickOutTrigger = 16;
  53988. /** Gets the list of active triggers */
  53989. ActionManager.Triggers = {};
  53990. return ActionManager;
  53991. }());
  53992. BABYLON.ActionManager = ActionManager;
  53993. })(BABYLON || (BABYLON = {}));
  53994. //# sourceMappingURL=babylon.actionManager.js.map
  53995. var BABYLON;
  53996. (function (BABYLON) {
  53997. var InterpolateValueAction = /** @class */ (function (_super) {
  53998. __extends(InterpolateValueAction, _super);
  53999. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54000. if (duration === void 0) { duration = 1000; }
  54001. var _this = _super.call(this, triggerOptions, condition) || this;
  54002. _this.propertyPath = propertyPath;
  54003. _this.value = value;
  54004. _this.duration = duration;
  54005. _this.stopOtherAnimations = stopOtherAnimations;
  54006. _this.onInterpolationDone = onInterpolationDone;
  54007. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54008. _this._target = _this._effectiveTarget = target;
  54009. return _this;
  54010. }
  54011. InterpolateValueAction.prototype._prepare = function () {
  54012. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54013. this._property = this._getProperty(this.propertyPath);
  54014. };
  54015. InterpolateValueAction.prototype.execute = function () {
  54016. var _this = this;
  54017. var scene = this._actionManager.getScene();
  54018. var keys = [
  54019. {
  54020. frame: 0,
  54021. value: this._effectiveTarget[this._property]
  54022. }, {
  54023. frame: 100,
  54024. value: this.value
  54025. }
  54026. ];
  54027. var dataType;
  54028. if (typeof this.value === "number") {
  54029. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54030. }
  54031. else if (this.value instanceof BABYLON.Color3) {
  54032. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54033. }
  54034. else if (this.value instanceof BABYLON.Vector3) {
  54035. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54036. }
  54037. else if (this.value instanceof BABYLON.Matrix) {
  54038. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54039. }
  54040. else if (this.value instanceof BABYLON.Quaternion) {
  54041. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54042. }
  54043. else {
  54044. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54045. return;
  54046. }
  54047. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54048. animation.setKeys(keys);
  54049. if (this.stopOtherAnimations) {
  54050. scene.stopAnimation(this._effectiveTarget);
  54051. }
  54052. var wrapper = function () {
  54053. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54054. if (_this.onInterpolationDone) {
  54055. _this.onInterpolationDone();
  54056. }
  54057. };
  54058. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54059. };
  54060. InterpolateValueAction.prototype.serialize = function (parent) {
  54061. return _super.prototype._serialize.call(this, {
  54062. name: "InterpolateValueAction",
  54063. properties: [
  54064. BABYLON.Action._GetTargetProperty(this._target),
  54065. { name: "propertyPath", value: this.propertyPath },
  54066. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54067. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54068. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54069. ]
  54070. }, parent);
  54071. };
  54072. return InterpolateValueAction;
  54073. }(BABYLON.Action));
  54074. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54075. })(BABYLON || (BABYLON = {}));
  54076. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54077. var BABYLON;
  54078. (function (BABYLON) {
  54079. var SwitchBooleanAction = /** @class */ (function (_super) {
  54080. __extends(SwitchBooleanAction, _super);
  54081. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54082. var _this = _super.call(this, triggerOptions, condition) || this;
  54083. _this.propertyPath = propertyPath;
  54084. _this._target = _this._effectiveTarget = target;
  54085. return _this;
  54086. }
  54087. SwitchBooleanAction.prototype._prepare = function () {
  54088. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54089. this._property = this._getProperty(this.propertyPath);
  54090. };
  54091. SwitchBooleanAction.prototype.execute = function () {
  54092. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54093. };
  54094. SwitchBooleanAction.prototype.serialize = function (parent) {
  54095. return _super.prototype._serialize.call(this, {
  54096. name: "SwitchBooleanAction",
  54097. properties: [
  54098. BABYLON.Action._GetTargetProperty(this._target),
  54099. { name: "propertyPath", value: this.propertyPath }
  54100. ]
  54101. }, parent);
  54102. };
  54103. return SwitchBooleanAction;
  54104. }(BABYLON.Action));
  54105. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54106. var SetStateAction = /** @class */ (function (_super) {
  54107. __extends(SetStateAction, _super);
  54108. function SetStateAction(triggerOptions, target, value, condition) {
  54109. var _this = _super.call(this, triggerOptions, condition) || this;
  54110. _this.value = value;
  54111. _this._target = target;
  54112. return _this;
  54113. }
  54114. SetStateAction.prototype.execute = function () {
  54115. this._target.state = this.value;
  54116. };
  54117. SetStateAction.prototype.serialize = function (parent) {
  54118. return _super.prototype._serialize.call(this, {
  54119. name: "SetStateAction",
  54120. properties: [
  54121. BABYLON.Action._GetTargetProperty(this._target),
  54122. { name: "value", value: this.value }
  54123. ]
  54124. }, parent);
  54125. };
  54126. return SetStateAction;
  54127. }(BABYLON.Action));
  54128. BABYLON.SetStateAction = SetStateAction;
  54129. var SetValueAction = /** @class */ (function (_super) {
  54130. __extends(SetValueAction, _super);
  54131. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54132. var _this = _super.call(this, triggerOptions, condition) || this;
  54133. _this.propertyPath = propertyPath;
  54134. _this.value = value;
  54135. _this._target = _this._effectiveTarget = target;
  54136. return _this;
  54137. }
  54138. SetValueAction.prototype._prepare = function () {
  54139. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54140. this._property = this._getProperty(this.propertyPath);
  54141. };
  54142. SetValueAction.prototype.execute = function () {
  54143. this._effectiveTarget[this._property] = this.value;
  54144. if (this._target.markAsDirty) {
  54145. this._target.markAsDirty(this._property);
  54146. }
  54147. };
  54148. SetValueAction.prototype.serialize = function (parent) {
  54149. return _super.prototype._serialize.call(this, {
  54150. name: "SetValueAction",
  54151. properties: [
  54152. BABYLON.Action._GetTargetProperty(this._target),
  54153. { name: "propertyPath", value: this.propertyPath },
  54154. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54155. ]
  54156. }, parent);
  54157. };
  54158. return SetValueAction;
  54159. }(BABYLON.Action));
  54160. BABYLON.SetValueAction = SetValueAction;
  54161. var IncrementValueAction = /** @class */ (function (_super) {
  54162. __extends(IncrementValueAction, _super);
  54163. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54164. var _this = _super.call(this, triggerOptions, condition) || this;
  54165. _this.propertyPath = propertyPath;
  54166. _this.value = value;
  54167. _this._target = _this._effectiveTarget = target;
  54168. return _this;
  54169. }
  54170. IncrementValueAction.prototype._prepare = function () {
  54171. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54172. this._property = this._getProperty(this.propertyPath);
  54173. if (typeof this._effectiveTarget[this._property] !== "number") {
  54174. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54175. }
  54176. };
  54177. IncrementValueAction.prototype.execute = function () {
  54178. this._effectiveTarget[this._property] += this.value;
  54179. if (this._target.markAsDirty) {
  54180. this._target.markAsDirty(this._property);
  54181. }
  54182. };
  54183. IncrementValueAction.prototype.serialize = function (parent) {
  54184. return _super.prototype._serialize.call(this, {
  54185. name: "IncrementValueAction",
  54186. properties: [
  54187. BABYLON.Action._GetTargetProperty(this._target),
  54188. { name: "propertyPath", value: this.propertyPath },
  54189. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54190. ]
  54191. }, parent);
  54192. };
  54193. return IncrementValueAction;
  54194. }(BABYLON.Action));
  54195. BABYLON.IncrementValueAction = IncrementValueAction;
  54196. var PlayAnimationAction = /** @class */ (function (_super) {
  54197. __extends(PlayAnimationAction, _super);
  54198. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54199. var _this = _super.call(this, triggerOptions, condition) || this;
  54200. _this.from = from;
  54201. _this.to = to;
  54202. _this.loop = loop;
  54203. _this._target = target;
  54204. return _this;
  54205. }
  54206. PlayAnimationAction.prototype._prepare = function () {
  54207. };
  54208. PlayAnimationAction.prototype.execute = function () {
  54209. var scene = this._actionManager.getScene();
  54210. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54211. };
  54212. PlayAnimationAction.prototype.serialize = function (parent) {
  54213. return _super.prototype._serialize.call(this, {
  54214. name: "PlayAnimationAction",
  54215. properties: [
  54216. BABYLON.Action._GetTargetProperty(this._target),
  54217. { name: "from", value: String(this.from) },
  54218. { name: "to", value: String(this.to) },
  54219. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54220. ]
  54221. }, parent);
  54222. };
  54223. return PlayAnimationAction;
  54224. }(BABYLON.Action));
  54225. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54226. var StopAnimationAction = /** @class */ (function (_super) {
  54227. __extends(StopAnimationAction, _super);
  54228. function StopAnimationAction(triggerOptions, target, condition) {
  54229. var _this = _super.call(this, triggerOptions, condition) || this;
  54230. _this._target = target;
  54231. return _this;
  54232. }
  54233. StopAnimationAction.prototype._prepare = function () {
  54234. };
  54235. StopAnimationAction.prototype.execute = function () {
  54236. var scene = this._actionManager.getScene();
  54237. scene.stopAnimation(this._target);
  54238. };
  54239. StopAnimationAction.prototype.serialize = function (parent) {
  54240. return _super.prototype._serialize.call(this, {
  54241. name: "StopAnimationAction",
  54242. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54243. }, parent);
  54244. };
  54245. return StopAnimationAction;
  54246. }(BABYLON.Action));
  54247. BABYLON.StopAnimationAction = StopAnimationAction;
  54248. var DoNothingAction = /** @class */ (function (_super) {
  54249. __extends(DoNothingAction, _super);
  54250. function DoNothingAction(triggerOptions, condition) {
  54251. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54252. return _super.call(this, triggerOptions, condition) || this;
  54253. }
  54254. DoNothingAction.prototype.execute = function () {
  54255. };
  54256. DoNothingAction.prototype.serialize = function (parent) {
  54257. return _super.prototype._serialize.call(this, {
  54258. name: "DoNothingAction",
  54259. properties: []
  54260. }, parent);
  54261. };
  54262. return DoNothingAction;
  54263. }(BABYLON.Action));
  54264. BABYLON.DoNothingAction = DoNothingAction;
  54265. var CombineAction = /** @class */ (function (_super) {
  54266. __extends(CombineAction, _super);
  54267. function CombineAction(triggerOptions, children, condition) {
  54268. var _this = _super.call(this, triggerOptions, condition) || this;
  54269. _this.children = children;
  54270. return _this;
  54271. }
  54272. CombineAction.prototype._prepare = function () {
  54273. for (var index = 0; index < this.children.length; index++) {
  54274. this.children[index]._actionManager = this._actionManager;
  54275. this.children[index]._prepare();
  54276. }
  54277. };
  54278. CombineAction.prototype.execute = function (evt) {
  54279. for (var index = 0; index < this.children.length; index++) {
  54280. this.children[index].execute(evt);
  54281. }
  54282. };
  54283. CombineAction.prototype.serialize = function (parent) {
  54284. var serializationObject = _super.prototype._serialize.call(this, {
  54285. name: "CombineAction",
  54286. properties: [],
  54287. combine: []
  54288. }, parent);
  54289. for (var i = 0; i < this.children.length; i++) {
  54290. serializationObject.combine.push(this.children[i].serialize(null));
  54291. }
  54292. return serializationObject;
  54293. };
  54294. return CombineAction;
  54295. }(BABYLON.Action));
  54296. BABYLON.CombineAction = CombineAction;
  54297. var ExecuteCodeAction = /** @class */ (function (_super) {
  54298. __extends(ExecuteCodeAction, _super);
  54299. function ExecuteCodeAction(triggerOptions, func, condition) {
  54300. var _this = _super.call(this, triggerOptions, condition) || this;
  54301. _this.func = func;
  54302. return _this;
  54303. }
  54304. ExecuteCodeAction.prototype.execute = function (evt) {
  54305. this.func(evt);
  54306. };
  54307. return ExecuteCodeAction;
  54308. }(BABYLON.Action));
  54309. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54310. var SetParentAction = /** @class */ (function (_super) {
  54311. __extends(SetParentAction, _super);
  54312. function SetParentAction(triggerOptions, target, parent, condition) {
  54313. var _this = _super.call(this, triggerOptions, condition) || this;
  54314. _this._target = target;
  54315. _this._parent = parent;
  54316. return _this;
  54317. }
  54318. SetParentAction.prototype._prepare = function () {
  54319. };
  54320. SetParentAction.prototype.execute = function () {
  54321. if (this._target.parent === this._parent) {
  54322. return;
  54323. }
  54324. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54325. invertParentWorldMatrix.invert();
  54326. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54327. this._target.parent = this._parent;
  54328. };
  54329. SetParentAction.prototype.serialize = function (parent) {
  54330. return _super.prototype._serialize.call(this, {
  54331. name: "SetParentAction",
  54332. properties: [
  54333. BABYLON.Action._GetTargetProperty(this._target),
  54334. BABYLON.Action._GetTargetProperty(this._parent),
  54335. ]
  54336. }, parent);
  54337. };
  54338. return SetParentAction;
  54339. }(BABYLON.Action));
  54340. BABYLON.SetParentAction = SetParentAction;
  54341. var PlaySoundAction = /** @class */ (function (_super) {
  54342. __extends(PlaySoundAction, _super);
  54343. function PlaySoundAction(triggerOptions, sound, condition) {
  54344. var _this = _super.call(this, triggerOptions, condition) || this;
  54345. _this._sound = sound;
  54346. return _this;
  54347. }
  54348. PlaySoundAction.prototype._prepare = function () {
  54349. };
  54350. PlaySoundAction.prototype.execute = function () {
  54351. if (this._sound !== undefined)
  54352. this._sound.play();
  54353. };
  54354. PlaySoundAction.prototype.serialize = function (parent) {
  54355. return _super.prototype._serialize.call(this, {
  54356. name: "PlaySoundAction",
  54357. properties: [{ name: "sound", value: this._sound.name }]
  54358. }, parent);
  54359. };
  54360. return PlaySoundAction;
  54361. }(BABYLON.Action));
  54362. BABYLON.PlaySoundAction = PlaySoundAction;
  54363. var StopSoundAction = /** @class */ (function (_super) {
  54364. __extends(StopSoundAction, _super);
  54365. function StopSoundAction(triggerOptions, sound, condition) {
  54366. var _this = _super.call(this, triggerOptions, condition) || this;
  54367. _this._sound = sound;
  54368. return _this;
  54369. }
  54370. StopSoundAction.prototype._prepare = function () {
  54371. };
  54372. StopSoundAction.prototype.execute = function () {
  54373. if (this._sound !== undefined)
  54374. this._sound.stop();
  54375. };
  54376. StopSoundAction.prototype.serialize = function (parent) {
  54377. return _super.prototype._serialize.call(this, {
  54378. name: "StopSoundAction",
  54379. properties: [{ name: "sound", value: this._sound.name }]
  54380. }, parent);
  54381. };
  54382. return StopSoundAction;
  54383. }(BABYLON.Action));
  54384. BABYLON.StopSoundAction = StopSoundAction;
  54385. })(BABYLON || (BABYLON = {}));
  54386. //# sourceMappingURL=babylon.directActions.js.map
  54387. var BABYLON;
  54388. (function (BABYLON) {
  54389. var SpriteManager = /** @class */ (function () {
  54390. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54391. if (epsilon === void 0) { epsilon = 0.01; }
  54392. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54393. this.name = name;
  54394. this.sprites = new Array();
  54395. this.renderingGroupId = 0;
  54396. this.layerMask = 0x0FFFFFFF;
  54397. this.fogEnabled = true;
  54398. this.isPickable = false;
  54399. /**
  54400. * An event triggered when the manager is disposed.
  54401. */
  54402. this.onDisposeObservable = new BABYLON.Observable();
  54403. this._vertexBuffers = {};
  54404. this._capacity = capacity;
  54405. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54406. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54407. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54408. if (cellSize.width && cellSize.height) {
  54409. this.cellWidth = cellSize.width;
  54410. this.cellHeight = cellSize.height;
  54411. }
  54412. else if (cellSize !== undefined) {
  54413. this.cellWidth = cellSize;
  54414. this.cellHeight = cellSize;
  54415. }
  54416. else {
  54417. return;
  54418. }
  54419. this._epsilon = epsilon;
  54420. this._scene = scene;
  54421. this._scene.spriteManagers.push(this);
  54422. var indices = [];
  54423. var index = 0;
  54424. for (var count = 0; count < capacity; count++) {
  54425. indices.push(index);
  54426. indices.push(index + 1);
  54427. indices.push(index + 2);
  54428. indices.push(index);
  54429. indices.push(index + 2);
  54430. indices.push(index + 3);
  54431. index += 4;
  54432. }
  54433. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54434. // VBO
  54435. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54436. this._vertexData = new Float32Array(capacity * 16 * 4);
  54437. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54438. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54439. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54440. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54441. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54442. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54443. this._vertexBuffers["options"] = options;
  54444. this._vertexBuffers["cellInfo"] = cellInfo;
  54445. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54446. // Effects
  54447. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54448. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54449. }
  54450. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54451. set: function (callback) {
  54452. if (this._onDisposeObserver) {
  54453. this.onDisposeObservable.remove(this._onDisposeObserver);
  54454. }
  54455. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54456. },
  54457. enumerable: true,
  54458. configurable: true
  54459. });
  54460. Object.defineProperty(SpriteManager.prototype, "texture", {
  54461. get: function () {
  54462. return this._spriteTexture;
  54463. },
  54464. set: function (value) {
  54465. this._spriteTexture = value;
  54466. },
  54467. enumerable: true,
  54468. configurable: true
  54469. });
  54470. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54471. var arrayOffset = index * 16;
  54472. if (offsetX === 0)
  54473. offsetX = this._epsilon;
  54474. else if (offsetX === 1)
  54475. offsetX = 1 - this._epsilon;
  54476. if (offsetY === 0)
  54477. offsetY = this._epsilon;
  54478. else if (offsetY === 1)
  54479. offsetY = 1 - this._epsilon;
  54480. this._vertexData[arrayOffset] = sprite.position.x;
  54481. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54482. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54483. this._vertexData[arrayOffset + 3] = sprite.angle;
  54484. this._vertexData[arrayOffset + 4] = sprite.width;
  54485. this._vertexData[arrayOffset + 5] = sprite.height;
  54486. this._vertexData[arrayOffset + 6] = offsetX;
  54487. this._vertexData[arrayOffset + 7] = offsetY;
  54488. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54489. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54490. var offset = (sprite.cellIndex / rowSize) >> 0;
  54491. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54492. this._vertexData[arrayOffset + 11] = offset;
  54493. // Color
  54494. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54495. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54496. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54497. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54498. };
  54499. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54500. var count = Math.min(this._capacity, this.sprites.length);
  54501. var min = BABYLON.Vector3.Zero();
  54502. var max = BABYLON.Vector3.Zero();
  54503. var distance = Number.MAX_VALUE;
  54504. var currentSprite = null;
  54505. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54506. var cameraView = camera.getViewMatrix();
  54507. for (var index = 0; index < count; index++) {
  54508. var sprite = this.sprites[index];
  54509. if (!sprite) {
  54510. continue;
  54511. }
  54512. if (predicate) {
  54513. if (!predicate(sprite)) {
  54514. continue;
  54515. }
  54516. }
  54517. else if (!sprite.isPickable) {
  54518. continue;
  54519. }
  54520. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54521. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54522. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54523. if (ray.intersectsBoxMinMax(min, max)) {
  54524. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54525. if (distance > currentDistance) {
  54526. distance = currentDistance;
  54527. currentSprite = sprite;
  54528. if (fastCheck) {
  54529. break;
  54530. }
  54531. }
  54532. }
  54533. }
  54534. if (currentSprite) {
  54535. var result = new BABYLON.PickingInfo();
  54536. result.hit = true;
  54537. result.pickedSprite = currentSprite;
  54538. result.distance = distance;
  54539. return result;
  54540. }
  54541. return null;
  54542. };
  54543. SpriteManager.prototype.render = function () {
  54544. // Check
  54545. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54546. return;
  54547. var engine = this._scene.getEngine();
  54548. var baseSize = this._spriteTexture.getBaseSize();
  54549. // Sprites
  54550. var deltaTime = engine.getDeltaTime();
  54551. var max = Math.min(this._capacity, this.sprites.length);
  54552. var rowSize = baseSize.width / this.cellWidth;
  54553. var offset = 0;
  54554. for (var index = 0; index < max; index++) {
  54555. var sprite = this.sprites[index];
  54556. if (!sprite) {
  54557. continue;
  54558. }
  54559. sprite._animate(deltaTime);
  54560. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54561. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54562. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54563. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54564. }
  54565. this._buffer.update(this._vertexData);
  54566. // Render
  54567. var effect = this._effectBase;
  54568. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54569. effect = this._effectFog;
  54570. }
  54571. engine.enableEffect(effect);
  54572. var viewMatrix = this._scene.getViewMatrix();
  54573. effect.setTexture("diffuseSampler", this._spriteTexture);
  54574. effect.setMatrix("view", viewMatrix);
  54575. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54576. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54577. // Fog
  54578. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54579. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54580. effect.setColor3("vFogColor", this._scene.fogColor);
  54581. }
  54582. // VBOs
  54583. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54584. // Draw order
  54585. engine.setDepthFunctionToLessOrEqual();
  54586. effect.setBool("alphaTest", true);
  54587. engine.setColorWrite(false);
  54588. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54589. engine.setColorWrite(true);
  54590. effect.setBool("alphaTest", false);
  54591. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54592. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54593. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54594. };
  54595. SpriteManager.prototype.dispose = function () {
  54596. if (this._buffer) {
  54597. this._buffer.dispose();
  54598. this._buffer = null;
  54599. }
  54600. if (this._indexBuffer) {
  54601. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54602. this._indexBuffer = null;
  54603. }
  54604. if (this._spriteTexture) {
  54605. this._spriteTexture.dispose();
  54606. this._spriteTexture = null;
  54607. }
  54608. // Remove from scene
  54609. var index = this._scene.spriteManagers.indexOf(this);
  54610. this._scene.spriteManagers.splice(index, 1);
  54611. // Callback
  54612. this.onDisposeObservable.notifyObservers(this);
  54613. this.onDisposeObservable.clear();
  54614. };
  54615. return SpriteManager;
  54616. }());
  54617. BABYLON.SpriteManager = SpriteManager;
  54618. })(BABYLON || (BABYLON = {}));
  54619. //# sourceMappingURL=babylon.spriteManager.js.map
  54620. var BABYLON;
  54621. (function (BABYLON) {
  54622. var Sprite = /** @class */ (function () {
  54623. function Sprite(name, manager) {
  54624. this.name = name;
  54625. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54626. this.width = 1.0;
  54627. this.height = 1.0;
  54628. this.angle = 0;
  54629. this.cellIndex = 0;
  54630. this.invertU = 0;
  54631. this.invertV = 0;
  54632. this.animations = new Array();
  54633. this.isPickable = false;
  54634. this._animationStarted = false;
  54635. this._loopAnimation = false;
  54636. this._fromIndex = 0;
  54637. this._toIndex = 0;
  54638. this._delay = 0;
  54639. this._direction = 1;
  54640. this._time = 0;
  54641. this._manager = manager;
  54642. this._manager.sprites.push(this);
  54643. this.position = BABYLON.Vector3.Zero();
  54644. }
  54645. Object.defineProperty(Sprite.prototype, "size", {
  54646. get: function () {
  54647. return this.width;
  54648. },
  54649. set: function (value) {
  54650. this.width = value;
  54651. this.height = value;
  54652. },
  54653. enumerable: true,
  54654. configurable: true
  54655. });
  54656. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54657. this._fromIndex = from;
  54658. this._toIndex = to;
  54659. this._loopAnimation = loop;
  54660. this._delay = delay;
  54661. this._animationStarted = true;
  54662. this._direction = from < to ? 1 : -1;
  54663. this.cellIndex = from;
  54664. this._time = 0;
  54665. this._onAnimationEnd = onAnimationEnd;
  54666. };
  54667. Sprite.prototype.stopAnimation = function () {
  54668. this._animationStarted = false;
  54669. };
  54670. Sprite.prototype._animate = function (deltaTime) {
  54671. if (!this._animationStarted)
  54672. return;
  54673. this._time += deltaTime;
  54674. if (this._time > this._delay) {
  54675. this._time = this._time % this._delay;
  54676. this.cellIndex += this._direction;
  54677. if (this.cellIndex > this._toIndex) {
  54678. if (this._loopAnimation) {
  54679. this.cellIndex = this._fromIndex;
  54680. }
  54681. else {
  54682. this.cellIndex = this._toIndex;
  54683. this._animationStarted = false;
  54684. if (this._onAnimationEnd) {
  54685. this._onAnimationEnd();
  54686. }
  54687. if (this.disposeWhenFinishedAnimating) {
  54688. this.dispose();
  54689. }
  54690. }
  54691. }
  54692. }
  54693. };
  54694. Sprite.prototype.dispose = function () {
  54695. for (var i = 0; i < this._manager.sprites.length; i++) {
  54696. if (this._manager.sprites[i] == this) {
  54697. this._manager.sprites.splice(i, 1);
  54698. }
  54699. }
  54700. };
  54701. return Sprite;
  54702. }());
  54703. BABYLON.Sprite = Sprite;
  54704. })(BABYLON || (BABYLON = {}));
  54705. //# sourceMappingURL=babylon.sprite.js.map
  54706. var BABYLON;
  54707. (function (BABYLON) {
  54708. var IntersectionInfo = /** @class */ (function () {
  54709. function IntersectionInfo(bu, bv, distance) {
  54710. this.bu = bu;
  54711. this.bv = bv;
  54712. this.distance = distance;
  54713. this.faceId = 0;
  54714. this.subMeshId = 0;
  54715. }
  54716. return IntersectionInfo;
  54717. }());
  54718. BABYLON.IntersectionInfo = IntersectionInfo;
  54719. var PickingInfo = /** @class */ (function () {
  54720. function PickingInfo() {
  54721. this.hit = false;
  54722. this.distance = 0;
  54723. this.pickedPoint = null;
  54724. this.pickedMesh = null;
  54725. this.bu = 0;
  54726. this.bv = 0;
  54727. this.faceId = -1;
  54728. this.subMeshId = 0;
  54729. this.pickedSprite = null;
  54730. }
  54731. // Methods
  54732. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54733. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54734. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54735. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54736. return null;
  54737. }
  54738. var indices = this.pickedMesh.getIndices();
  54739. if (!indices) {
  54740. return null;
  54741. }
  54742. var result;
  54743. if (useVerticesNormals) {
  54744. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54745. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54746. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54747. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54748. normal0 = normal0.scale(this.bu);
  54749. normal1 = normal1.scale(this.bv);
  54750. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54751. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54752. }
  54753. else {
  54754. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54755. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54756. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54757. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54758. var p1p2 = vertex1.subtract(vertex2);
  54759. var p3p2 = vertex3.subtract(vertex2);
  54760. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54761. }
  54762. if (useWorldCoordinates) {
  54763. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54764. }
  54765. return BABYLON.Vector3.Normalize(result);
  54766. };
  54767. PickingInfo.prototype.getTextureCoordinates = function () {
  54768. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54769. return null;
  54770. }
  54771. var indices = this.pickedMesh.getIndices();
  54772. if (!indices) {
  54773. return null;
  54774. }
  54775. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54776. if (!uvs) {
  54777. return null;
  54778. }
  54779. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54780. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54781. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54782. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54783. uv1 = uv1.scale(this.bu);
  54784. uv2 = uv2.scale(this.bv);
  54785. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54786. };
  54787. return PickingInfo;
  54788. }());
  54789. BABYLON.PickingInfo = PickingInfo;
  54790. })(BABYLON || (BABYLON = {}));
  54791. //# sourceMappingURL=babylon.pickingInfo.js.map
  54792. var BABYLON;
  54793. (function (BABYLON) {
  54794. var Ray = /** @class */ (function () {
  54795. function Ray(origin, direction, length) {
  54796. if (length === void 0) { length = Number.MAX_VALUE; }
  54797. this.origin = origin;
  54798. this.direction = direction;
  54799. this.length = length;
  54800. }
  54801. // Methods
  54802. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54803. var d = 0.0;
  54804. var maxValue = Number.MAX_VALUE;
  54805. var inv;
  54806. var min;
  54807. var max;
  54808. var temp;
  54809. if (Math.abs(this.direction.x) < 0.0000001) {
  54810. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54811. return false;
  54812. }
  54813. }
  54814. else {
  54815. inv = 1.0 / this.direction.x;
  54816. min = (minimum.x - this.origin.x) * inv;
  54817. max = (maximum.x - this.origin.x) * inv;
  54818. if (max === -Infinity) {
  54819. max = Infinity;
  54820. }
  54821. if (min > max) {
  54822. temp = min;
  54823. min = max;
  54824. max = temp;
  54825. }
  54826. d = Math.max(min, d);
  54827. maxValue = Math.min(max, maxValue);
  54828. if (d > maxValue) {
  54829. return false;
  54830. }
  54831. }
  54832. if (Math.abs(this.direction.y) < 0.0000001) {
  54833. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54834. return false;
  54835. }
  54836. }
  54837. else {
  54838. inv = 1.0 / this.direction.y;
  54839. min = (minimum.y - this.origin.y) * inv;
  54840. max = (maximum.y - this.origin.y) * inv;
  54841. if (max === -Infinity) {
  54842. max = Infinity;
  54843. }
  54844. if (min > max) {
  54845. temp = min;
  54846. min = max;
  54847. max = temp;
  54848. }
  54849. d = Math.max(min, d);
  54850. maxValue = Math.min(max, maxValue);
  54851. if (d > maxValue) {
  54852. return false;
  54853. }
  54854. }
  54855. if (Math.abs(this.direction.z) < 0.0000001) {
  54856. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54857. return false;
  54858. }
  54859. }
  54860. else {
  54861. inv = 1.0 / this.direction.z;
  54862. min = (minimum.z - this.origin.z) * inv;
  54863. max = (maximum.z - this.origin.z) * inv;
  54864. if (max === -Infinity) {
  54865. max = Infinity;
  54866. }
  54867. if (min > max) {
  54868. temp = min;
  54869. min = max;
  54870. max = temp;
  54871. }
  54872. d = Math.max(min, d);
  54873. maxValue = Math.min(max, maxValue);
  54874. if (d > maxValue) {
  54875. return false;
  54876. }
  54877. }
  54878. return true;
  54879. };
  54880. Ray.prototype.intersectsBox = function (box) {
  54881. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54882. };
  54883. Ray.prototype.intersectsSphere = function (sphere) {
  54884. var x = sphere.center.x - this.origin.x;
  54885. var y = sphere.center.y - this.origin.y;
  54886. var z = sphere.center.z - this.origin.z;
  54887. var pyth = (x * x) + (y * y) + (z * z);
  54888. var rr = sphere.radius * sphere.radius;
  54889. if (pyth <= rr) {
  54890. return true;
  54891. }
  54892. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54893. if (dot < 0.0) {
  54894. return false;
  54895. }
  54896. var temp = pyth - (dot * dot);
  54897. return temp <= rr;
  54898. };
  54899. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54900. if (!this._edge1) {
  54901. this._edge1 = BABYLON.Vector3.Zero();
  54902. this._edge2 = BABYLON.Vector3.Zero();
  54903. this._pvec = BABYLON.Vector3.Zero();
  54904. this._tvec = BABYLON.Vector3.Zero();
  54905. this._qvec = BABYLON.Vector3.Zero();
  54906. }
  54907. vertex1.subtractToRef(vertex0, this._edge1);
  54908. vertex2.subtractToRef(vertex0, this._edge2);
  54909. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54910. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54911. if (det === 0) {
  54912. return null;
  54913. }
  54914. var invdet = 1 / det;
  54915. this.origin.subtractToRef(vertex0, this._tvec);
  54916. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54917. if (bu < 0 || bu > 1.0) {
  54918. return null;
  54919. }
  54920. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54921. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54922. if (bv < 0 || bu + bv > 1.0) {
  54923. return null;
  54924. }
  54925. //check if the distance is longer than the predefined length.
  54926. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54927. if (distance > this.length) {
  54928. return null;
  54929. }
  54930. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54931. };
  54932. Ray.prototype.intersectsPlane = function (plane) {
  54933. var distance;
  54934. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54935. if (Math.abs(result1) < 9.99999997475243E-07) {
  54936. return null;
  54937. }
  54938. else {
  54939. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54940. distance = (-plane.d - result2) / result1;
  54941. if (distance < 0.0) {
  54942. if (distance < -9.99999997475243E-07) {
  54943. return null;
  54944. }
  54945. else {
  54946. return 0;
  54947. }
  54948. }
  54949. return distance;
  54950. }
  54951. };
  54952. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54953. var tm = BABYLON.Tmp.Matrix[0];
  54954. mesh.getWorldMatrix().invertToRef(tm);
  54955. if (this._tmpRay) {
  54956. Ray.TransformToRef(this, tm, this._tmpRay);
  54957. }
  54958. else {
  54959. this._tmpRay = Ray.Transform(this, tm);
  54960. }
  54961. return mesh.intersects(this._tmpRay, fastCheck);
  54962. };
  54963. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54964. if (results) {
  54965. results.length = 0;
  54966. }
  54967. else {
  54968. results = [];
  54969. }
  54970. for (var i = 0; i < meshes.length; i++) {
  54971. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54972. if (pickInfo.hit) {
  54973. results.push(pickInfo);
  54974. }
  54975. }
  54976. results.sort(this._comparePickingInfo);
  54977. return results;
  54978. };
  54979. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54980. if (pickingInfoA.distance < pickingInfoB.distance) {
  54981. return -1;
  54982. }
  54983. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54984. return 1;
  54985. }
  54986. else {
  54987. return 0;
  54988. }
  54989. };
  54990. /**
  54991. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54992. * @param sega the first point of the segment to test the intersection against
  54993. * @param segb the second point of the segment to test the intersection against
  54994. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54995. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54996. */
  54997. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54998. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54999. var u = segb.subtract(sega);
  55000. var v = rsegb.subtract(this.origin);
  55001. var w = sega.subtract(this.origin);
  55002. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55003. var b = BABYLON.Vector3.Dot(u, v);
  55004. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55005. var d = BABYLON.Vector3.Dot(u, w);
  55006. var e = BABYLON.Vector3.Dot(v, w);
  55007. var D = a * c - b * b; // always >= 0
  55008. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55009. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55010. // compute the line parameters of the two closest points
  55011. if (D < Ray.smallnum) { // the lines are almost parallel
  55012. sN = 0.0; // force using point P0 on segment S1
  55013. sD = 1.0; // to prevent possible division by 0.0 later
  55014. tN = e;
  55015. tD = c;
  55016. }
  55017. else { // get the closest points on the infinite lines
  55018. sN = (b * e - c * d);
  55019. tN = (a * e - b * d);
  55020. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55021. sN = 0.0;
  55022. tN = e;
  55023. tD = c;
  55024. }
  55025. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55026. sN = sD;
  55027. tN = e + b;
  55028. tD = c;
  55029. }
  55030. }
  55031. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55032. tN = 0.0;
  55033. // recompute sc for this edge
  55034. if (-d < 0.0) {
  55035. sN = 0.0;
  55036. }
  55037. else if (-d > a)
  55038. sN = sD;
  55039. else {
  55040. sN = -d;
  55041. sD = a;
  55042. }
  55043. }
  55044. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55045. tN = tD;
  55046. // recompute sc for this edge
  55047. if ((-d + b) < 0.0) {
  55048. sN = 0;
  55049. }
  55050. else if ((-d + b) > a) {
  55051. sN = sD;
  55052. }
  55053. else {
  55054. sN = (-d + b);
  55055. sD = a;
  55056. }
  55057. }
  55058. // finally do the division to get sc and tc
  55059. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55060. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55061. // get the difference of the two closest points
  55062. var qtc = v.multiplyByFloats(tc, tc, tc);
  55063. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55064. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55065. if (isIntersected) {
  55066. return qtc.length();
  55067. }
  55068. return -1;
  55069. };
  55070. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55071. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55072. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55073. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55074. this.direction.normalize();
  55075. return this;
  55076. };
  55077. // Statics
  55078. Ray.Zero = function () {
  55079. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55080. };
  55081. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55082. var result = Ray.Zero();
  55083. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55084. };
  55085. /**
  55086. * 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
  55087. * transformed to the given world matrix.
  55088. * @param origin The origin point
  55089. * @param end The end point
  55090. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55091. */
  55092. Ray.CreateNewFromTo = function (origin, end, world) {
  55093. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55094. var direction = end.subtract(origin);
  55095. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55096. direction.normalize();
  55097. return Ray.Transform(new Ray(origin, direction, length), world);
  55098. };
  55099. Ray.Transform = function (ray, matrix) {
  55100. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55101. Ray.TransformToRef(ray, matrix, result);
  55102. return result;
  55103. };
  55104. Ray.TransformToRef = function (ray, matrix, result) {
  55105. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55106. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55107. result.length = ray.length;
  55108. var dir = result.direction;
  55109. var len = dir.length();
  55110. if (!(len === 0 || len === 1)) {
  55111. var num = 1.0 / len;
  55112. dir.x *= num;
  55113. dir.y *= num;
  55114. dir.z *= num;
  55115. result.length *= len;
  55116. }
  55117. };
  55118. Ray.smallnum = 0.00000001;
  55119. Ray.rayl = 10e8;
  55120. return Ray;
  55121. }());
  55122. BABYLON.Ray = Ray;
  55123. })(BABYLON || (BABYLON = {}));
  55124. //# sourceMappingURL=babylon.ray.js.map
  55125. var BABYLON;
  55126. (function (BABYLON) {
  55127. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55128. if (boxMin.x > sphereCenter.x + sphereRadius)
  55129. return false;
  55130. if (sphereCenter.x - sphereRadius > boxMax.x)
  55131. return false;
  55132. if (boxMin.y > sphereCenter.y + sphereRadius)
  55133. return false;
  55134. if (sphereCenter.y - sphereRadius > boxMax.y)
  55135. return false;
  55136. if (boxMin.z > sphereCenter.z + sphereRadius)
  55137. return false;
  55138. if (sphereCenter.z - sphereRadius > boxMax.z)
  55139. return false;
  55140. return true;
  55141. };
  55142. var getLowestRoot = (function () {
  55143. var result = { root: 0, found: false };
  55144. return function (a, b, c, maxR) {
  55145. result.root = 0;
  55146. result.found = false;
  55147. var determinant = b * b - 4.0 * a * c;
  55148. if (determinant < 0)
  55149. return result;
  55150. var sqrtD = Math.sqrt(determinant);
  55151. var r1 = (-b - sqrtD) / (2.0 * a);
  55152. var r2 = (-b + sqrtD) / (2.0 * a);
  55153. if (r1 > r2) {
  55154. var temp = r2;
  55155. r2 = r1;
  55156. r1 = temp;
  55157. }
  55158. if (r1 > 0 && r1 < maxR) {
  55159. result.root = r1;
  55160. result.found = true;
  55161. return result;
  55162. }
  55163. if (r2 > 0 && r2 < maxR) {
  55164. result.root = r2;
  55165. result.found = true;
  55166. return result;
  55167. }
  55168. return result;
  55169. };
  55170. })();
  55171. var Collider = /** @class */ (function () {
  55172. function Collider() {
  55173. this._collisionPoint = BABYLON.Vector3.Zero();
  55174. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55175. this._tempVector = BABYLON.Vector3.Zero();
  55176. this._tempVector2 = BABYLON.Vector3.Zero();
  55177. this._tempVector3 = BABYLON.Vector3.Zero();
  55178. this._tempVector4 = BABYLON.Vector3.Zero();
  55179. this._edge = BABYLON.Vector3.Zero();
  55180. this._baseToVertex = BABYLON.Vector3.Zero();
  55181. this._destinationPoint = BABYLON.Vector3.Zero();
  55182. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55183. this._displacementVector = BABYLON.Vector3.Zero();
  55184. this._radius = BABYLON.Vector3.One();
  55185. this._retry = 0;
  55186. this._basePointWorld = BABYLON.Vector3.Zero();
  55187. this._velocityWorld = BABYLON.Vector3.Zero();
  55188. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55189. this._collisionMask = -1;
  55190. }
  55191. Object.defineProperty(Collider.prototype, "collisionMask", {
  55192. get: function () {
  55193. return this._collisionMask;
  55194. },
  55195. set: function (mask) {
  55196. this._collisionMask = !isNaN(mask) ? mask : -1;
  55197. },
  55198. enumerable: true,
  55199. configurable: true
  55200. });
  55201. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55202. /**
  55203. * Gets the plane normal used to compute the sliding response (in local space)
  55204. */
  55205. get: function () {
  55206. return this._slidePlaneNormal;
  55207. },
  55208. enumerable: true,
  55209. configurable: true
  55210. });
  55211. // Methods
  55212. Collider.prototype._initialize = function (source, dir, e) {
  55213. this._velocity = dir;
  55214. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55215. this._basePoint = source;
  55216. source.multiplyToRef(this._radius, this._basePointWorld);
  55217. dir.multiplyToRef(this._radius, this._velocityWorld);
  55218. this._velocityWorldLength = this._velocityWorld.length();
  55219. this._epsilon = e;
  55220. this.collisionFound = false;
  55221. };
  55222. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55223. pa.subtractToRef(point, this._tempVector);
  55224. pb.subtractToRef(point, this._tempVector2);
  55225. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55226. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55227. if (d < 0)
  55228. return false;
  55229. pc.subtractToRef(point, this._tempVector3);
  55230. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55231. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55232. if (d < 0)
  55233. return false;
  55234. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55235. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55236. return d >= 0;
  55237. };
  55238. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55239. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55240. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55241. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55242. return false;
  55243. }
  55244. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55245. return false;
  55246. return true;
  55247. };
  55248. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55249. var t0;
  55250. var embeddedInPlane = false;
  55251. //defensive programming, actually not needed.
  55252. if (!trianglePlaneArray) {
  55253. trianglePlaneArray = [];
  55254. }
  55255. if (!trianglePlaneArray[faceIndex]) {
  55256. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55257. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55258. }
  55259. var trianglePlane = trianglePlaneArray[faceIndex];
  55260. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55261. return;
  55262. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55263. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55264. if (normalDotVelocity == 0) {
  55265. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55266. return;
  55267. embeddedInPlane = true;
  55268. t0 = 0;
  55269. }
  55270. else {
  55271. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55272. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55273. if (t0 > t1) {
  55274. var temp = t1;
  55275. t1 = t0;
  55276. t0 = temp;
  55277. }
  55278. if (t0 > 1.0 || t1 < 0.0)
  55279. return;
  55280. if (t0 < 0)
  55281. t0 = 0;
  55282. if (t0 > 1.0)
  55283. t0 = 1.0;
  55284. }
  55285. this._collisionPoint.copyFromFloats(0, 0, 0);
  55286. var found = false;
  55287. var t = 1.0;
  55288. if (!embeddedInPlane) {
  55289. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55290. this._velocity.scaleToRef(t0, this._tempVector);
  55291. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55292. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55293. found = true;
  55294. t = t0;
  55295. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55296. }
  55297. }
  55298. if (!found) {
  55299. var velocitySquaredLength = this._velocity.lengthSquared();
  55300. var a = velocitySquaredLength;
  55301. this._basePoint.subtractToRef(p1, this._tempVector);
  55302. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55303. var c = this._tempVector.lengthSquared() - 1.0;
  55304. var lowestRoot = getLowestRoot(a, b, c, t);
  55305. if (lowestRoot.found) {
  55306. t = lowestRoot.root;
  55307. found = true;
  55308. this._collisionPoint.copyFrom(p1);
  55309. }
  55310. this._basePoint.subtractToRef(p2, this._tempVector);
  55311. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55312. c = this._tempVector.lengthSquared() - 1.0;
  55313. lowestRoot = getLowestRoot(a, b, c, t);
  55314. if (lowestRoot.found) {
  55315. t = lowestRoot.root;
  55316. found = true;
  55317. this._collisionPoint.copyFrom(p2);
  55318. }
  55319. this._basePoint.subtractToRef(p3, this._tempVector);
  55320. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55321. c = this._tempVector.lengthSquared() - 1.0;
  55322. lowestRoot = getLowestRoot(a, b, c, t);
  55323. if (lowestRoot.found) {
  55324. t = lowestRoot.root;
  55325. found = true;
  55326. this._collisionPoint.copyFrom(p3);
  55327. }
  55328. p2.subtractToRef(p1, this._edge);
  55329. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55330. var edgeSquaredLength = this._edge.lengthSquared();
  55331. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55332. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55333. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55334. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55335. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55336. lowestRoot = getLowestRoot(a, b, c, t);
  55337. if (lowestRoot.found) {
  55338. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55339. if (f >= 0.0 && f <= 1.0) {
  55340. t = lowestRoot.root;
  55341. found = true;
  55342. this._edge.scaleInPlace(f);
  55343. p1.addToRef(this._edge, this._collisionPoint);
  55344. }
  55345. }
  55346. p3.subtractToRef(p2, this._edge);
  55347. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55348. edgeSquaredLength = this._edge.lengthSquared();
  55349. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55350. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55351. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55352. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55353. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55354. lowestRoot = getLowestRoot(a, b, c, t);
  55355. if (lowestRoot.found) {
  55356. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55357. if (f >= 0.0 && f <= 1.0) {
  55358. t = lowestRoot.root;
  55359. found = true;
  55360. this._edge.scaleInPlace(f);
  55361. p2.addToRef(this._edge, this._collisionPoint);
  55362. }
  55363. }
  55364. p1.subtractToRef(p3, this._edge);
  55365. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55366. edgeSquaredLength = this._edge.lengthSquared();
  55367. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55368. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55369. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55370. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55371. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55372. lowestRoot = getLowestRoot(a, b, c, t);
  55373. if (lowestRoot.found) {
  55374. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55375. if (f >= 0.0 && f <= 1.0) {
  55376. t = lowestRoot.root;
  55377. found = true;
  55378. this._edge.scaleInPlace(f);
  55379. p3.addToRef(this._edge, this._collisionPoint);
  55380. }
  55381. }
  55382. }
  55383. if (found) {
  55384. var distToCollision = t * this._velocity.length();
  55385. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55386. if (!this.intersectionPoint) {
  55387. this.intersectionPoint = this._collisionPoint.clone();
  55388. }
  55389. else {
  55390. this.intersectionPoint.copyFrom(this._collisionPoint);
  55391. }
  55392. this._nearestDistance = distToCollision;
  55393. this.collisionFound = true;
  55394. }
  55395. }
  55396. };
  55397. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55398. for (var i = indexStart; i < indexEnd; i += 3) {
  55399. var p1 = pts[indices[i] - decal];
  55400. var p2 = pts[indices[i + 1] - decal];
  55401. var p3 = pts[indices[i + 2] - decal];
  55402. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55403. }
  55404. };
  55405. Collider.prototype._getResponse = function (pos, vel) {
  55406. pos.addToRef(vel, this._destinationPoint);
  55407. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55408. this._basePoint.addToRef(vel, pos);
  55409. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55410. this._slidePlaneNormal.normalize();
  55411. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55412. pos.addInPlace(this._displacementVector);
  55413. this.intersectionPoint.addInPlace(this._displacementVector);
  55414. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55415. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55416. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55417. };
  55418. return Collider;
  55419. }());
  55420. BABYLON.Collider = Collider;
  55421. })(BABYLON || (BABYLON = {}));
  55422. //# sourceMappingURL=babylon.collider.js.map
  55423. var BABYLON;
  55424. (function (BABYLON) {
  55425. //WebWorker code will be inserted to this variable.
  55426. BABYLON.CollisionWorker = "";
  55427. /** Defines supported task for worker process */
  55428. var WorkerTaskType;
  55429. (function (WorkerTaskType) {
  55430. /** Initialization */
  55431. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55432. /** Update of geometry */
  55433. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55434. /** Evaluate collision */
  55435. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55436. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55437. /** Defines kind of replies returned by worker */
  55438. var WorkerReplyType;
  55439. (function (WorkerReplyType) {
  55440. /** Success */
  55441. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55442. /** Unkown error */
  55443. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55444. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55445. var CollisionCoordinatorWorker = /** @class */ (function () {
  55446. function CollisionCoordinatorWorker() {
  55447. var _this = this;
  55448. this._scaledPosition = BABYLON.Vector3.Zero();
  55449. this._scaledVelocity = BABYLON.Vector3.Zero();
  55450. this.onMeshUpdated = function (transformNode) {
  55451. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55452. };
  55453. this.onGeometryUpdated = function (geometry) {
  55454. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55455. };
  55456. this._afterRender = function () {
  55457. if (!_this._init)
  55458. return;
  55459. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55460. return;
  55461. }
  55462. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55463. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55464. if (_this._runningUpdated > 4) {
  55465. return;
  55466. }
  55467. ++_this._runningUpdated;
  55468. var payload = {
  55469. updatedMeshes: _this._addUpdateMeshesList,
  55470. updatedGeometries: _this._addUpdateGeometriesList,
  55471. removedGeometries: _this._toRemoveGeometryArray,
  55472. removedMeshes: _this._toRemoveMeshesArray
  55473. };
  55474. var message = {
  55475. payload: payload,
  55476. taskType: WorkerTaskType.UPDATE
  55477. };
  55478. var serializable = [];
  55479. for (var id in payload.updatedGeometries) {
  55480. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55481. //prepare transferables
  55482. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55483. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55484. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55485. }
  55486. }
  55487. _this._worker.postMessage(message, serializable);
  55488. _this._addUpdateMeshesList = {};
  55489. _this._addUpdateGeometriesList = {};
  55490. _this._toRemoveGeometryArray = [];
  55491. _this._toRemoveMeshesArray = [];
  55492. };
  55493. this._onMessageFromWorker = function (e) {
  55494. var returnData = e.data;
  55495. if (returnData.error != WorkerReplyType.SUCCESS) {
  55496. //TODO what errors can be returned from the worker?
  55497. BABYLON.Tools.Warn("error returned from worker!");
  55498. return;
  55499. }
  55500. switch (returnData.taskType) {
  55501. case WorkerTaskType.INIT:
  55502. _this._init = true;
  55503. //Update the worked with ALL of the scene's current state
  55504. _this._scene.meshes.forEach(function (mesh) {
  55505. _this.onMeshAdded(mesh);
  55506. });
  55507. _this._scene.getGeometries().forEach(function (geometry) {
  55508. _this.onGeometryAdded(geometry);
  55509. });
  55510. break;
  55511. case WorkerTaskType.UPDATE:
  55512. _this._runningUpdated--;
  55513. break;
  55514. case WorkerTaskType.COLLIDE:
  55515. var returnPayload = returnData.payload;
  55516. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55517. return;
  55518. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55519. if (callback) {
  55520. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55521. if (mesh) {
  55522. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55523. }
  55524. }
  55525. //cleanup
  55526. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55527. break;
  55528. }
  55529. };
  55530. this._collisionsCallbackArray = [];
  55531. this._init = false;
  55532. this._runningUpdated = 0;
  55533. this._addUpdateMeshesList = {};
  55534. this._addUpdateGeometriesList = {};
  55535. this._toRemoveGeometryArray = [];
  55536. this._toRemoveMeshesArray = [];
  55537. }
  55538. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55539. if (!this._init)
  55540. return;
  55541. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55542. return;
  55543. position.divideToRef(collider._radius, this._scaledPosition);
  55544. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55545. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55546. var payload = {
  55547. collider: {
  55548. position: this._scaledPosition.asArray(),
  55549. velocity: this._scaledVelocity.asArray(),
  55550. radius: collider._radius.asArray()
  55551. },
  55552. collisionId: collisionIndex,
  55553. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55554. maximumRetry: maximumRetry
  55555. };
  55556. var message = {
  55557. payload: payload,
  55558. taskType: WorkerTaskType.COLLIDE
  55559. };
  55560. this._worker.postMessage(message);
  55561. };
  55562. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55563. this._scene = scene;
  55564. this._scene.registerAfterRender(this._afterRender);
  55565. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55566. this._worker = new Worker(workerUrl);
  55567. this._worker.onmessage = this._onMessageFromWorker;
  55568. var message = {
  55569. payload: {},
  55570. taskType: WorkerTaskType.INIT
  55571. };
  55572. this._worker.postMessage(message);
  55573. };
  55574. CollisionCoordinatorWorker.prototype.destroy = function () {
  55575. this._scene.unregisterAfterRender(this._afterRender);
  55576. this._worker.terminate();
  55577. };
  55578. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55579. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55580. this.onMeshUpdated(mesh);
  55581. };
  55582. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55583. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55584. };
  55585. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55586. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55587. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55588. this.onGeometryUpdated(geometry);
  55589. };
  55590. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55591. this._toRemoveGeometryArray.push(geometry.id);
  55592. };
  55593. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55594. var submeshes = [];
  55595. if (mesh.subMeshes) {
  55596. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55597. var boundingInfo = sm.getBoundingInfo();
  55598. return {
  55599. position: idx,
  55600. verticesStart: sm.verticesStart,
  55601. verticesCount: sm.verticesCount,
  55602. indexStart: sm.indexStart,
  55603. indexCount: sm.indexCount,
  55604. hasMaterial: !!sm.getMaterial(),
  55605. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55606. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55607. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55608. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55609. };
  55610. });
  55611. }
  55612. var geometryId = null;
  55613. if (mesh instanceof BABYLON.Mesh) {
  55614. var geometry = mesh.geometry;
  55615. geometryId = geometry ? geometry.id : null;
  55616. }
  55617. else if (mesh instanceof BABYLON.InstancedMesh) {
  55618. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55619. geometryId = geometry ? geometry.id : null;
  55620. }
  55621. var boundingInfo = mesh.getBoundingInfo();
  55622. return {
  55623. uniqueId: mesh.uniqueId,
  55624. id: mesh.id,
  55625. name: mesh.name,
  55626. geometryId: geometryId,
  55627. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55628. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55629. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55630. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55631. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55632. subMeshes: submeshes,
  55633. checkCollisions: mesh.checkCollisions
  55634. };
  55635. };
  55636. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55637. return {
  55638. id: geometry.id,
  55639. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55640. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55641. indices: new Uint32Array(geometry.getIndices() || []),
  55642. };
  55643. };
  55644. return CollisionCoordinatorWorker;
  55645. }());
  55646. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55647. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55648. function CollisionCoordinatorLegacy() {
  55649. this._scaledPosition = BABYLON.Vector3.Zero();
  55650. this._scaledVelocity = BABYLON.Vector3.Zero();
  55651. this._finalPosition = BABYLON.Vector3.Zero();
  55652. }
  55653. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55654. position.divideToRef(collider._radius, this._scaledPosition);
  55655. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55656. collider.collidedMesh = null;
  55657. collider._retry = 0;
  55658. collider._initialVelocity = this._scaledVelocity;
  55659. collider._initialPosition = this._scaledPosition;
  55660. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55661. this._finalPosition.multiplyInPlace(collider._radius);
  55662. //run the callback
  55663. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55664. };
  55665. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55666. this._scene = scene;
  55667. };
  55668. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55669. //Legacy need no destruction method.
  55670. };
  55671. //No update in legacy mode
  55672. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55673. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55674. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55675. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55676. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55677. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55678. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55679. if (excludedMesh === void 0) { excludedMesh = null; }
  55680. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55681. if (collider._retry >= maximumRetry) {
  55682. finalPosition.copyFrom(position);
  55683. return;
  55684. }
  55685. // Check if this is a mesh else camera or -1
  55686. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55687. collider._initialize(position, velocity, closeDistance);
  55688. // Check all meshes
  55689. for (var index = 0; index < this._scene.meshes.length; index++) {
  55690. var mesh = this._scene.meshes[index];
  55691. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55692. mesh._checkCollision(collider);
  55693. }
  55694. }
  55695. if (!collider.collisionFound) {
  55696. position.addToRef(velocity, finalPosition);
  55697. return;
  55698. }
  55699. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55700. collider._getResponse(position, velocity);
  55701. }
  55702. if (velocity.length() <= closeDistance) {
  55703. finalPosition.copyFrom(position);
  55704. return;
  55705. }
  55706. collider._retry++;
  55707. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55708. };
  55709. return CollisionCoordinatorLegacy;
  55710. }());
  55711. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55712. })(BABYLON || (BABYLON = {}));
  55713. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55714. var BABYLON;
  55715. (function (BABYLON) {
  55716. /**
  55717. * A particle represents one of the element emitted by a particle system.
  55718. * This is mainly define by its coordinates, direction, velocity and age.
  55719. */
  55720. var Particle = /** @class */ (function () {
  55721. /**
  55722. * Creates a new instance Particle
  55723. * @param particleSystem the particle system the particle belongs to
  55724. */
  55725. function Particle(
  55726. /**
  55727. * particleSystem the particle system the particle belongs to.
  55728. */
  55729. particleSystem) {
  55730. this.particleSystem = particleSystem;
  55731. /**
  55732. * The world position of the particle in the scene.
  55733. */
  55734. this.position = BABYLON.Vector3.Zero();
  55735. /**
  55736. * The world direction of the particle in the scene.
  55737. */
  55738. this.direction = BABYLON.Vector3.Zero();
  55739. /**
  55740. * The color of the particle.
  55741. */
  55742. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55743. /**
  55744. * The color change of the particle per step.
  55745. */
  55746. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55747. /**
  55748. * Defines how long will the life of the particle be.
  55749. */
  55750. this.lifeTime = 1.0;
  55751. /**
  55752. * The current age of the particle.
  55753. */
  55754. this.age = 0;
  55755. /**
  55756. * The current size of the particle.
  55757. */
  55758. this.size = 0;
  55759. /**
  55760. * The current angle of the particle.
  55761. */
  55762. this.angle = 0;
  55763. /**
  55764. * Defines how fast is the angle changing.
  55765. */
  55766. this.angularSpeed = 0;
  55767. /**
  55768. * Defines the cell index used by the particle to be rendered from a sprite.
  55769. */
  55770. this.cellIndex = 0;
  55771. this._currentFrameCounter = 0;
  55772. if (!this.particleSystem.isAnimationSheetEnabled) {
  55773. return;
  55774. }
  55775. this.updateCellInfoFromSystem();
  55776. }
  55777. Particle.prototype.updateCellInfoFromSystem = function () {
  55778. this.cellIndex = this.particleSystem.startSpriteCellID;
  55779. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55780. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55781. }
  55782. else {
  55783. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55784. }
  55785. };
  55786. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55787. // (ageOffset / scaledUpdateSpeed) / available cells
  55788. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55789. this._currentFrameCounter += scaledUpdateSpeed;
  55790. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55791. this._currentFrameCounter = 0;
  55792. this.cellIndex++;
  55793. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55794. this.cellIndex = this.particleSystem.endSpriteCellID;
  55795. }
  55796. }
  55797. };
  55798. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55799. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55800. this.cellIndex++;
  55801. this._currentFrameCounter = 0;
  55802. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55803. if (this.particleSystem.spriteCellLoop) {
  55804. this.cellIndex = this.particleSystem.startSpriteCellID;
  55805. }
  55806. else {
  55807. this.cellIndex = this.particleSystem.endSpriteCellID;
  55808. }
  55809. }
  55810. }
  55811. else {
  55812. this._currentFrameCounter++;
  55813. }
  55814. };
  55815. /**
  55816. * Copy the properties of particle to another one.
  55817. * @param other the particle to copy the information to.
  55818. */
  55819. Particle.prototype.copyTo = function (other) {
  55820. other.position.copyFrom(this.position);
  55821. other.direction.copyFrom(this.direction);
  55822. other.color.copyFrom(this.color);
  55823. other.colorStep.copyFrom(this.colorStep);
  55824. other.lifeTime = this.lifeTime;
  55825. other.age = this.age;
  55826. other.size = this.size;
  55827. other.angle = this.angle;
  55828. other.angularSpeed = this.angularSpeed;
  55829. other.particleSystem = this.particleSystem;
  55830. other.cellIndex = this.cellIndex;
  55831. };
  55832. return Particle;
  55833. }());
  55834. BABYLON.Particle = Particle;
  55835. })(BABYLON || (BABYLON = {}));
  55836. //# sourceMappingURL=babylon.particle.js.map
  55837. var BABYLON;
  55838. (function (BABYLON) {
  55839. /**
  55840. * This represents a particle system in Babylon.
  55841. * 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.
  55842. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55843. * @example https://doc.babylonjs.com/babylon101/particles
  55844. */
  55845. var ParticleSystem = /** @class */ (function () {
  55846. /**
  55847. * Instantiates a particle system.
  55848. * 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.
  55849. * @param name The name of the particle system
  55850. * @param capacity The max number of particles alive at the same time
  55851. * @param scene The scene the particle system belongs to
  55852. * @param customEffect a custom effect used to change the way particles are rendered by default
  55853. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55854. * @param epsilon Offset used to render the particles
  55855. */
  55856. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55857. if (customEffect === void 0) { customEffect = null; }
  55858. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55859. if (epsilon === void 0) { epsilon = 0.01; }
  55860. var _this = this;
  55861. /**
  55862. * List of animations used by the particle system.
  55863. */
  55864. this.animations = [];
  55865. /**
  55866. * The rendering group used by the Particle system to chose when to render.
  55867. */
  55868. this.renderingGroupId = 0;
  55869. /**
  55870. * The emitter represents the Mesh or position we are attaching the particle system to.
  55871. */
  55872. this.emitter = null;
  55873. /**
  55874. * The maximum number of particles to emit per frame
  55875. */
  55876. this.emitRate = 10;
  55877. /**
  55878. * If you want to launch only a few particles at once, that can be done, as well.
  55879. */
  55880. this.manualEmitCount = -1;
  55881. /**
  55882. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55883. */
  55884. this.updateSpeed = 0.01;
  55885. /**
  55886. * The amount of time the particle system is running (depends of the overall update speed).
  55887. */
  55888. this.targetStopDuration = 0;
  55889. /**
  55890. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55891. */
  55892. this.disposeOnStop = false;
  55893. /**
  55894. * Minimum power of emitting particles.
  55895. */
  55896. this.minEmitPower = 1;
  55897. /**
  55898. * Maximum power of emitting particles.
  55899. */
  55900. this.maxEmitPower = 1;
  55901. /**
  55902. * Minimum life time of emitting particles.
  55903. */
  55904. this.minLifeTime = 1;
  55905. /**
  55906. * Maximum life time of emitting particles.
  55907. */
  55908. this.maxLifeTime = 1;
  55909. /**
  55910. * Minimum Size of emitting particles.
  55911. */
  55912. this.minSize = 1;
  55913. /**
  55914. * Maximum Size of emitting particles.
  55915. */
  55916. this.maxSize = 1;
  55917. /**
  55918. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55919. */
  55920. this.minAngularSpeed = 0;
  55921. /**
  55922. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55923. */
  55924. this.maxAngularSpeed = 0;
  55925. /**
  55926. * The layer mask we are rendering the particles through.
  55927. */
  55928. this.layerMask = 0x0FFFFFFF;
  55929. /**
  55930. * This can help using your own shader to render the particle system.
  55931. * The according effect will be created
  55932. */
  55933. this.customShader = null;
  55934. /**
  55935. * By default particle system starts as soon as they are created. This prevents the
  55936. * automatic start to happen and let you decide when to start emitting particles.
  55937. */
  55938. this.preventAutoStart = false;
  55939. /**
  55940. * Callback triggered when the particle animation is ending.
  55941. */
  55942. this.onAnimationEnd = null;
  55943. /**
  55944. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55945. */
  55946. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55947. /**
  55948. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55949. * to override the particles.
  55950. */
  55951. this.forceDepthWrite = false;
  55952. /**
  55953. * You can use gravity if you want to give an orientation to your particles.
  55954. */
  55955. this.gravity = BABYLON.Vector3.Zero();
  55956. /**
  55957. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55958. */
  55959. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55960. /**
  55961. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55962. */
  55963. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55964. /**
  55965. * Color the particle will have at the end of its lifetime.
  55966. */
  55967. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55968. /**
  55969. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55970. */
  55971. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55972. /**
  55973. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55974. */
  55975. this.spriteCellLoop = true;
  55976. /**
  55977. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55978. */
  55979. this.spriteCellChangeSpeed = 0;
  55980. /**
  55981. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55982. */
  55983. this.startSpriteCellID = 0;
  55984. /**
  55985. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55986. */
  55987. this.endSpriteCellID = 0;
  55988. /**
  55989. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55990. */
  55991. this.spriteCellWidth = 0;
  55992. /**
  55993. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55994. */
  55995. this.spriteCellHeight = 0;
  55996. /**
  55997. * An event triggered when the system is disposed.
  55998. */
  55999. this.onDisposeObservable = new BABYLON.Observable();
  56000. this._particles = new Array();
  56001. this._stockParticles = new Array();
  56002. this._newPartsExcess = 0;
  56003. this._vertexBuffers = {};
  56004. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56005. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56006. this._scaledDirection = BABYLON.Vector3.Zero();
  56007. this._scaledGravity = BABYLON.Vector3.Zero();
  56008. this._currentRenderId = -1;
  56009. this._started = false;
  56010. this._stopped = false;
  56011. this._actualFrame = 0;
  56012. this._vertexBufferSize = 11;
  56013. // start of sub system methods
  56014. /**
  56015. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56016. * Its lifetime will start back at 0.
  56017. */
  56018. this.recycleParticle = function (particle) {
  56019. var lastParticle = _this._particles.pop();
  56020. if (lastParticle !== particle) {
  56021. lastParticle.copyTo(particle);
  56022. }
  56023. _this._stockParticles.push(lastParticle);
  56024. };
  56025. this._createParticle = function () {
  56026. var particle;
  56027. if (_this._stockParticles.length !== 0) {
  56028. particle = _this._stockParticles.pop();
  56029. particle.age = 0;
  56030. particle.cellIndex = _this.startSpriteCellID;
  56031. }
  56032. else {
  56033. particle = new BABYLON.Particle(_this);
  56034. }
  56035. return particle;
  56036. };
  56037. this._emitFromParticle = function (particle) {
  56038. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56039. return;
  56040. }
  56041. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56042. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56043. subSystem._rootParticleSystem = _this;
  56044. _this.activeSubSystems.push(subSystem);
  56045. subSystem.start();
  56046. };
  56047. this._appendParticleVertexes = null;
  56048. this.id = name;
  56049. this.name = name;
  56050. this._capacity = capacity;
  56051. this._epsilon = epsilon;
  56052. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56053. if (isAnimationSheetEnabled) {
  56054. this._vertexBufferSize = 12;
  56055. }
  56056. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56057. this._customEffect = customEffect;
  56058. scene.particleSystems.push(this);
  56059. this._createIndexBuffer();
  56060. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  56061. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  56062. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  56063. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  56064. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  56065. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  56066. if (this._isAnimationSheetEnabled) {
  56067. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  56068. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56069. }
  56070. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56071. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56072. this._vertexBuffers["options"] = options;
  56073. // Default emitter type
  56074. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56075. this.updateFunction = function (particles) {
  56076. for (var index = 0; index < particles.length; index++) {
  56077. var particle = particles[index];
  56078. particle.age += _this._scaledUpdateSpeed;
  56079. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56080. _this._emitFromParticle(particle);
  56081. _this.recycleParticle(particle);
  56082. index--;
  56083. continue;
  56084. }
  56085. else {
  56086. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56087. particle.color.addInPlace(_this._scaledColorStep);
  56088. if (particle.color.a < 0)
  56089. particle.color.a = 0;
  56090. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56091. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56092. particle.position.addInPlace(_this._scaledDirection);
  56093. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56094. particle.direction.addInPlace(_this._scaledGravity);
  56095. if (_this._isAnimationSheetEnabled) {
  56096. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56097. }
  56098. }
  56099. }
  56100. };
  56101. }
  56102. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56103. /**
  56104. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56105. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56106. */
  56107. get: function () {
  56108. if (this.particleEmitterType.direction1) {
  56109. return this.particleEmitterType.direction1;
  56110. }
  56111. return BABYLON.Vector3.Zero();
  56112. },
  56113. set: function (value) {
  56114. if (this.particleEmitterType.direction1) {
  56115. this.particleEmitterType.direction1 = value;
  56116. }
  56117. },
  56118. enumerable: true,
  56119. configurable: true
  56120. });
  56121. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56122. /**
  56123. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56124. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56125. */
  56126. get: function () {
  56127. if (this.particleEmitterType.direction2) {
  56128. return this.particleEmitterType.direction2;
  56129. }
  56130. return BABYLON.Vector3.Zero();
  56131. },
  56132. set: function (value) {
  56133. if (this.particleEmitterType.direction2) {
  56134. this.particleEmitterType.direction2 = value;
  56135. }
  56136. },
  56137. enumerable: true,
  56138. configurable: true
  56139. });
  56140. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56141. /**
  56142. * 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.
  56143. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56144. */
  56145. get: function () {
  56146. if (this.particleEmitterType.minEmitBox) {
  56147. return this.particleEmitterType.minEmitBox;
  56148. }
  56149. return BABYLON.Vector3.Zero();
  56150. },
  56151. set: function (value) {
  56152. if (this.particleEmitterType.minEmitBox) {
  56153. this.particleEmitterType.minEmitBox = value;
  56154. }
  56155. },
  56156. enumerable: true,
  56157. configurable: true
  56158. });
  56159. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56160. /**
  56161. * 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.
  56162. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56163. */
  56164. get: function () {
  56165. if (this.particleEmitterType.maxEmitBox) {
  56166. return this.particleEmitterType.maxEmitBox;
  56167. }
  56168. return BABYLON.Vector3.Zero();
  56169. },
  56170. set: function (value) {
  56171. if (this.particleEmitterType.maxEmitBox) {
  56172. this.particleEmitterType.maxEmitBox = value;
  56173. }
  56174. },
  56175. enumerable: true,
  56176. configurable: true
  56177. });
  56178. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56179. /**
  56180. * Sets a callback that will be triggered when the system is disposed.
  56181. */
  56182. set: function (callback) {
  56183. if (this._onDisposeObserver) {
  56184. this.onDisposeObservable.remove(this._onDisposeObserver);
  56185. }
  56186. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56187. },
  56188. enumerable: true,
  56189. configurable: true
  56190. });
  56191. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56192. /**
  56193. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56194. */
  56195. get: function () {
  56196. return this._isAnimationSheetEnabled;
  56197. },
  56198. enumerable: true,
  56199. configurable: true
  56200. });
  56201. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56202. //end of Sub-emitter
  56203. /**
  56204. * Gets the current list of active particles
  56205. */
  56206. get: function () {
  56207. return this._particles;
  56208. },
  56209. enumerable: true,
  56210. configurable: true
  56211. });
  56212. /**
  56213. * Returns the string "ParticleSystem"
  56214. * @returns a string containing the class name
  56215. */
  56216. ParticleSystem.prototype.getClassName = function () {
  56217. return "ParticleSystem";
  56218. };
  56219. ParticleSystem.prototype._createIndexBuffer = function () {
  56220. var indices = [];
  56221. var index = 0;
  56222. for (var count = 0; count < this._capacity; count++) {
  56223. indices.push(index);
  56224. indices.push(index + 1);
  56225. indices.push(index + 2);
  56226. indices.push(index);
  56227. indices.push(index + 2);
  56228. indices.push(index + 3);
  56229. index += 4;
  56230. }
  56231. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56232. };
  56233. /**
  56234. * Gets the maximum number of particles active at the same time.
  56235. * @returns The max number of active particles.
  56236. */
  56237. ParticleSystem.prototype.getCapacity = function () {
  56238. return this._capacity;
  56239. };
  56240. /**
  56241. * Gets Wether there are still active particles in the system.
  56242. * @returns True if it is alive, otherwise false.
  56243. */
  56244. ParticleSystem.prototype.isAlive = function () {
  56245. return this._alive;
  56246. };
  56247. /**
  56248. * Gets Wether the system has been started.
  56249. * @returns True if it has been started, otherwise false.
  56250. */
  56251. ParticleSystem.prototype.isStarted = function () {
  56252. return this._started;
  56253. };
  56254. /**
  56255. * Starts the particle system and begins to emit.
  56256. */
  56257. ParticleSystem.prototype.start = function () {
  56258. this._started = true;
  56259. this._stopped = false;
  56260. this._actualFrame = 0;
  56261. if (this.subEmitters && this.subEmitters.length != 0) {
  56262. this.activeSubSystems = new Array();
  56263. }
  56264. };
  56265. /**
  56266. * Stops the particle system.
  56267. * @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.
  56268. */
  56269. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56270. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56271. this._stopped = true;
  56272. if (stopSubEmitters) {
  56273. this._stopSubEmitters();
  56274. }
  56275. };
  56276. // animation sheet
  56277. /**
  56278. * Remove all active particles
  56279. */
  56280. ParticleSystem.prototype.reset = function () {
  56281. this._stockParticles = [];
  56282. this._particles = [];
  56283. };
  56284. /**
  56285. * @hidden (for internal use only)
  56286. */
  56287. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56288. var offset = index * this._vertexBufferSize;
  56289. this._vertexData[offset] = particle.position.x;
  56290. this._vertexData[offset + 1] = particle.position.y;
  56291. this._vertexData[offset + 2] = particle.position.z;
  56292. this._vertexData[offset + 3] = particle.color.r;
  56293. this._vertexData[offset + 4] = particle.color.g;
  56294. this._vertexData[offset + 5] = particle.color.b;
  56295. this._vertexData[offset + 6] = particle.color.a;
  56296. this._vertexData[offset + 7] = particle.angle;
  56297. this._vertexData[offset + 8] = particle.size;
  56298. this._vertexData[offset + 9] = offsetX;
  56299. this._vertexData[offset + 10] = offsetY;
  56300. };
  56301. /**
  56302. * @hidden (for internal use only)
  56303. */
  56304. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56305. if (offsetX === 0)
  56306. offsetX = this._epsilon;
  56307. else if (offsetX === 1)
  56308. offsetX = 1 - this._epsilon;
  56309. if (offsetY === 0)
  56310. offsetY = this._epsilon;
  56311. else if (offsetY === 1)
  56312. offsetY = 1 - this._epsilon;
  56313. var offset = index * this._vertexBufferSize;
  56314. this._vertexData[offset] = particle.position.x;
  56315. this._vertexData[offset + 1] = particle.position.y;
  56316. this._vertexData[offset + 2] = particle.position.z;
  56317. this._vertexData[offset + 3] = particle.color.r;
  56318. this._vertexData[offset + 4] = particle.color.g;
  56319. this._vertexData[offset + 5] = particle.color.b;
  56320. this._vertexData[offset + 6] = particle.color.a;
  56321. this._vertexData[offset + 7] = particle.angle;
  56322. this._vertexData[offset + 8] = particle.size;
  56323. this._vertexData[offset + 9] = offsetX;
  56324. this._vertexData[offset + 10] = offsetY;
  56325. this._vertexData[offset + 11] = particle.cellIndex;
  56326. };
  56327. ParticleSystem.prototype._stopSubEmitters = function () {
  56328. if (!this.activeSubSystems) {
  56329. return;
  56330. }
  56331. this.activeSubSystems.forEach(function (subSystem) {
  56332. subSystem.stop(true);
  56333. });
  56334. this.activeSubSystems = new Array();
  56335. };
  56336. ParticleSystem.prototype._removeFromRoot = function () {
  56337. if (!this._rootParticleSystem) {
  56338. return;
  56339. }
  56340. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56341. if (index !== -1) {
  56342. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56343. }
  56344. };
  56345. // end of sub system methods
  56346. ParticleSystem.prototype._update = function (newParticles) {
  56347. // Update current
  56348. this._alive = this._particles.length > 0;
  56349. this.updateFunction(this._particles);
  56350. // Add new ones
  56351. var worldMatrix;
  56352. if (this.emitter.position) {
  56353. var emitterMesh = this.emitter;
  56354. worldMatrix = emitterMesh.getWorldMatrix();
  56355. }
  56356. else {
  56357. var emitterPosition = this.emitter;
  56358. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56359. }
  56360. var particle;
  56361. for (var index = 0; index < newParticles; index++) {
  56362. if (this._particles.length === this._capacity) {
  56363. break;
  56364. }
  56365. particle = this._createParticle();
  56366. this._particles.push(particle);
  56367. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56368. if (this.startPositionFunction) {
  56369. this.startPositionFunction(worldMatrix, particle.position, particle);
  56370. }
  56371. else {
  56372. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56373. }
  56374. if (this.startDirectionFunction) {
  56375. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56376. }
  56377. else {
  56378. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56379. }
  56380. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56381. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56382. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56383. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56384. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56385. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56386. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56387. }
  56388. };
  56389. ParticleSystem.prototype._getEffect = function () {
  56390. if (this._customEffect) {
  56391. return this._customEffect;
  56392. }
  56393. ;
  56394. var defines = [];
  56395. if (this._scene.clipPlane) {
  56396. defines.push("#define CLIPPLANE");
  56397. }
  56398. if (this._isAnimationSheetEnabled) {
  56399. defines.push("#define ANIMATESHEET");
  56400. }
  56401. // Effect
  56402. var join = defines.join("\n");
  56403. if (this._cachedDefines !== join) {
  56404. this._cachedDefines = join;
  56405. var attributesNamesOrOptions;
  56406. var effectCreationOption;
  56407. if (this._isAnimationSheetEnabled) {
  56408. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56409. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56410. }
  56411. else {
  56412. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56413. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56414. }
  56415. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56416. }
  56417. return this._effect;
  56418. };
  56419. /**
  56420. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56421. */
  56422. ParticleSystem.prototype.animate = function () {
  56423. if (!this._started)
  56424. return;
  56425. var effect = this._getEffect();
  56426. // Check
  56427. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56428. return;
  56429. if (this._currentRenderId === this._scene.getRenderId()) {
  56430. return;
  56431. }
  56432. this._currentRenderId = this._scene.getRenderId();
  56433. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56434. // determine the number of particles we need to create
  56435. var newParticles;
  56436. if (this.manualEmitCount > -1) {
  56437. newParticles = this.manualEmitCount;
  56438. this._newPartsExcess = 0;
  56439. this.manualEmitCount = 0;
  56440. }
  56441. else {
  56442. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56443. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56444. }
  56445. if (this._newPartsExcess > 1.0) {
  56446. newParticles += this._newPartsExcess >> 0;
  56447. this._newPartsExcess -= this._newPartsExcess >> 0;
  56448. }
  56449. this._alive = false;
  56450. if (!this._stopped) {
  56451. this._actualFrame += this._scaledUpdateSpeed;
  56452. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56453. this.stop();
  56454. }
  56455. else {
  56456. newParticles = 0;
  56457. }
  56458. this._update(newParticles);
  56459. // Stopped?
  56460. if (this._stopped) {
  56461. if (!this._alive) {
  56462. this._started = false;
  56463. if (this.onAnimationEnd) {
  56464. this.onAnimationEnd();
  56465. }
  56466. if (this.disposeOnStop) {
  56467. this._scene._toBeDisposed.push(this);
  56468. }
  56469. }
  56470. }
  56471. // Animation sheet
  56472. if (this._isAnimationSheetEnabled) {
  56473. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56474. }
  56475. else {
  56476. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56477. }
  56478. // Update VBO
  56479. var offset = 0;
  56480. for (var index = 0; index < this._particles.length; index++) {
  56481. var particle = this._particles[index];
  56482. this._appendParticleVertexes(offset, particle);
  56483. offset += 4;
  56484. }
  56485. if (this._vertexBuffer) {
  56486. this._vertexBuffer.update(this._vertexData);
  56487. }
  56488. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56489. this.stop();
  56490. }
  56491. };
  56492. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56493. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56494. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56495. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56496. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56497. };
  56498. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56499. this._appendParticleVertex(offset++, particle, 0, 0);
  56500. this._appendParticleVertex(offset++, particle, 1, 0);
  56501. this._appendParticleVertex(offset++, particle, 1, 1);
  56502. this._appendParticleVertex(offset++, particle, 0, 1);
  56503. };
  56504. /**
  56505. * Rebuilds the particle system.
  56506. */
  56507. ParticleSystem.prototype.rebuild = function () {
  56508. this._createIndexBuffer();
  56509. if (this._vertexBuffer) {
  56510. this._vertexBuffer._rebuild();
  56511. }
  56512. };
  56513. /**
  56514. * Is this system ready to be used/rendered
  56515. * @return true if the system is ready
  56516. */
  56517. ParticleSystem.prototype.isReady = function () {
  56518. var effect = this._getEffect();
  56519. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56520. return false;
  56521. }
  56522. return true;
  56523. };
  56524. /**
  56525. * Renders the particle system in its current state.
  56526. * @returns the current number of particles
  56527. */
  56528. ParticleSystem.prototype.render = function () {
  56529. var effect = this._getEffect();
  56530. // Check
  56531. if (!this.isReady() || !this._particles.length) {
  56532. return 0;
  56533. }
  56534. var engine = this._scene.getEngine();
  56535. // Render
  56536. engine.enableEffect(effect);
  56537. engine.setState(false);
  56538. var viewMatrix = this._scene.getViewMatrix();
  56539. effect.setTexture("diffuseSampler", this.particleTexture);
  56540. effect.setMatrix("view", viewMatrix);
  56541. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56542. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56543. var baseSize = this.particleTexture.getBaseSize();
  56544. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56545. }
  56546. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56547. if (this._scene.clipPlane) {
  56548. var clipPlane = this._scene.clipPlane;
  56549. var invView = viewMatrix.clone();
  56550. invView.invert();
  56551. effect.setMatrix("invView", invView);
  56552. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56553. }
  56554. // VBOs
  56555. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56556. // Draw order
  56557. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56558. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56559. }
  56560. else {
  56561. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56562. }
  56563. if (this.forceDepthWrite) {
  56564. engine.setDepthWrite(true);
  56565. }
  56566. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56567. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56568. return this._particles.length;
  56569. };
  56570. /**
  56571. * Disposes the particle system and free the associated resources
  56572. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56573. */
  56574. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56575. if (disposeTexture === void 0) { disposeTexture = true; }
  56576. if (this._vertexBuffer) {
  56577. this._vertexBuffer.dispose();
  56578. this._vertexBuffer = null;
  56579. }
  56580. if (this._indexBuffer) {
  56581. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56582. this._indexBuffer = null;
  56583. }
  56584. if (disposeTexture && this.particleTexture) {
  56585. this.particleTexture.dispose();
  56586. this.particleTexture = null;
  56587. }
  56588. this._removeFromRoot();
  56589. // Remove from scene
  56590. var index = this._scene.particleSystems.indexOf(this);
  56591. if (index > -1) {
  56592. this._scene.particleSystems.splice(index, 1);
  56593. }
  56594. // Callback
  56595. this.onDisposeObservable.notifyObservers(this);
  56596. this.onDisposeObservable.clear();
  56597. };
  56598. /**
  56599. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56600. * @param radius The radius of the sphere to emit from
  56601. * @returns the emitter
  56602. */
  56603. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56604. if (radius === void 0) { radius = 1; }
  56605. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56606. this.particleEmitterType = particleEmitter;
  56607. return particleEmitter;
  56608. };
  56609. /**
  56610. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56611. * @param radius The radius of the sphere to emit from
  56612. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56613. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56614. * @returns the emitter
  56615. */
  56616. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56617. if (radius === void 0) { radius = 1; }
  56618. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56619. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56620. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56621. this.particleEmitterType = particleEmitter;
  56622. return particleEmitter;
  56623. };
  56624. /**
  56625. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56626. * @param radius The radius of the cone to emit from
  56627. * @param angle The base angle of the cone
  56628. * @returns the emitter
  56629. */
  56630. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56631. if (radius === void 0) { radius = 1; }
  56632. if (angle === void 0) { angle = Math.PI / 4; }
  56633. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56634. this.particleEmitterType = particleEmitter;
  56635. return particleEmitter;
  56636. };
  56637. // 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.
  56638. /**
  56639. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56640. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56641. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56642. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56643. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56644. * @returns the emitter
  56645. */
  56646. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56647. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56648. this.particleEmitterType = particleEmitter;
  56649. this.direction1 = direction1;
  56650. this.direction2 = direction2;
  56651. this.minEmitBox = minEmitBox;
  56652. this.maxEmitBox = maxEmitBox;
  56653. return particleEmitter;
  56654. };
  56655. // Clone
  56656. /**
  56657. * Clones the particle system.
  56658. * @param name The name of the cloned object
  56659. * @param newEmitter The new emitter to use
  56660. * @returns the cloned particle system
  56661. */
  56662. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56663. var custom = null;
  56664. var program = null;
  56665. if (this.customShader != null) {
  56666. program = this.customShader;
  56667. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56668. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56669. }
  56670. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56671. result.customShader = program;
  56672. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56673. if (newEmitter === undefined) {
  56674. newEmitter = this.emitter;
  56675. }
  56676. result.emitter = newEmitter;
  56677. if (this.particleTexture) {
  56678. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56679. }
  56680. if (!this.preventAutoStart) {
  56681. result.start();
  56682. }
  56683. return result;
  56684. };
  56685. /**
  56686. * Serializes the particle system to a JSON object.
  56687. * @returns the JSON object
  56688. */
  56689. ParticleSystem.prototype.serialize = function () {
  56690. var serializationObject = {};
  56691. serializationObject.name = this.name;
  56692. serializationObject.id = this.id;
  56693. // Emitter
  56694. if (this.emitter.position) {
  56695. var emitterMesh = this.emitter;
  56696. serializationObject.emitterId = emitterMesh.id;
  56697. }
  56698. else {
  56699. var emitterPosition = this.emitter;
  56700. serializationObject.emitter = emitterPosition.asArray();
  56701. }
  56702. serializationObject.capacity = this.getCapacity();
  56703. if (this.particleTexture) {
  56704. serializationObject.textureName = this.particleTexture.name;
  56705. }
  56706. // Animations
  56707. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56708. // Particle system
  56709. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56710. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56711. serializationObject.minSize = this.minSize;
  56712. serializationObject.maxSize = this.maxSize;
  56713. serializationObject.minEmitPower = this.minEmitPower;
  56714. serializationObject.maxEmitPower = this.maxEmitPower;
  56715. serializationObject.minLifeTime = this.minLifeTime;
  56716. serializationObject.maxLifeTime = this.maxLifeTime;
  56717. serializationObject.emitRate = this.emitRate;
  56718. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56719. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56720. serializationObject.gravity = this.gravity.asArray();
  56721. serializationObject.direction1 = this.direction1.asArray();
  56722. serializationObject.direction2 = this.direction2.asArray();
  56723. serializationObject.color1 = this.color1.asArray();
  56724. serializationObject.color2 = this.color2.asArray();
  56725. serializationObject.colorDead = this.colorDead.asArray();
  56726. serializationObject.updateSpeed = this.updateSpeed;
  56727. serializationObject.targetStopDuration = this.targetStopDuration;
  56728. serializationObject.textureMask = this.textureMask.asArray();
  56729. serializationObject.blendMode = this.blendMode;
  56730. serializationObject.customShader = this.customShader;
  56731. serializationObject.preventAutoStart = this.preventAutoStart;
  56732. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56733. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56734. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56735. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56736. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56737. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56738. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56739. // Emitter
  56740. if (this.particleEmitterType) {
  56741. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56742. }
  56743. return serializationObject;
  56744. };
  56745. /**
  56746. * Parses a JSON object to create a particle system.
  56747. * @param parsedParticleSystem The JSON object to parse
  56748. * @param scene The scene to create the particle system in
  56749. * @param rootUrl The root url to use to load external dependencies like texture
  56750. * @returns the Parsed particle system
  56751. */
  56752. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56753. var name = parsedParticleSystem.name;
  56754. var custom = null;
  56755. var program = null;
  56756. if (parsedParticleSystem.customShader) {
  56757. program = parsedParticleSystem.customShader;
  56758. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56759. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56760. }
  56761. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56762. particleSystem.customShader = program;
  56763. if (parsedParticleSystem.id) {
  56764. particleSystem.id = parsedParticleSystem.id;
  56765. }
  56766. // Auto start
  56767. if (parsedParticleSystem.preventAutoStart) {
  56768. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56769. }
  56770. // Texture
  56771. if (parsedParticleSystem.textureName) {
  56772. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56773. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56774. }
  56775. // Emitter
  56776. if (parsedParticleSystem.emitterId) {
  56777. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56778. }
  56779. else {
  56780. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56781. }
  56782. // Animations
  56783. if (parsedParticleSystem.animations) {
  56784. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56785. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56786. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56787. }
  56788. }
  56789. if (parsedParticleSystem.autoAnimate) {
  56790. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56791. }
  56792. // Particle system
  56793. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56794. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56795. particleSystem.minSize = parsedParticleSystem.minSize;
  56796. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56797. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56798. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56799. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56800. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56801. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56802. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56803. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56804. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56805. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56806. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56807. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56808. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56809. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56810. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56811. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56812. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56813. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56814. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56815. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56816. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56817. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56818. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56819. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56820. if (!particleSystem.preventAutoStart) {
  56821. particleSystem.start();
  56822. }
  56823. return particleSystem;
  56824. };
  56825. /**
  56826. * Source color is added to the destination color without alpha affecting the result.
  56827. */
  56828. ParticleSystem.BLENDMODE_ONEONE = 0;
  56829. /**
  56830. * Blend current color and particle color using particle’s alpha.
  56831. */
  56832. ParticleSystem.BLENDMODE_STANDARD = 1;
  56833. return ParticleSystem;
  56834. }());
  56835. BABYLON.ParticleSystem = ParticleSystem;
  56836. })(BABYLON || (BABYLON = {}));
  56837. //# sourceMappingURL=babylon.particleSystem.js.map
  56838. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56839. var BABYLON;
  56840. (function (BABYLON) {
  56841. /**
  56842. * Particle emitter emitting particles from the inside of a box.
  56843. * It emits the particles randomly between 2 given directions.
  56844. */
  56845. var BoxParticleEmitter = /** @class */ (function () {
  56846. /**
  56847. * Creates a new instance BoxParticleEmitter
  56848. */
  56849. function BoxParticleEmitter() {
  56850. /**
  56851. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56852. */
  56853. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56854. /**
  56855. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56856. */
  56857. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56858. /**
  56859. * 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.
  56860. */
  56861. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56862. /**
  56863. * 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.
  56864. */
  56865. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56866. }
  56867. /**
  56868. * Called by the particle System when the direction is computed for the created particle.
  56869. * @param emitPower is the power of the particle (speed)
  56870. * @param worldMatrix is the world matrix of the particle system
  56871. * @param directionToUpdate is the direction vector to update with the result
  56872. * @param particle is the particle we are computed the direction for
  56873. */
  56874. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56875. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56876. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56877. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56878. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56879. };
  56880. /**
  56881. * Called by the particle System when the position is computed for the created particle.
  56882. * @param worldMatrix is the world matrix of the particle system
  56883. * @param positionToUpdate is the position vector to update with the result
  56884. * @param particle is the particle we are computed the position for
  56885. */
  56886. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56887. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56888. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56889. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56890. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56891. };
  56892. /**
  56893. * Clones the current emitter and returns a copy of it
  56894. * @returns the new emitter
  56895. */
  56896. BoxParticleEmitter.prototype.clone = function () {
  56897. var newOne = new BoxParticleEmitter();
  56898. BABYLON.Tools.DeepCopy(this, newOne);
  56899. return newOne;
  56900. };
  56901. /**
  56902. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56903. * @param effect defines the update shader
  56904. */
  56905. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56906. effect.setVector3("direction1", this.direction1);
  56907. effect.setVector3("direction2", this.direction2);
  56908. effect.setVector3("minEmitBox", this.minEmitBox);
  56909. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56910. };
  56911. /**
  56912. * Returns a string to use to update the GPU particles update shader
  56913. * @returns a string containng the defines string
  56914. */
  56915. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56916. return "#define BOXEMITTER";
  56917. };
  56918. /**
  56919. * Returns the string "BoxEmitter"
  56920. * @returns a string containing the class name
  56921. */
  56922. BoxParticleEmitter.prototype.getClassName = function () {
  56923. return "BoxEmitter";
  56924. };
  56925. /**
  56926. * Serializes the particle system to a JSON object.
  56927. * @returns the JSON object
  56928. */
  56929. BoxParticleEmitter.prototype.serialize = function () {
  56930. var serializationObject = {};
  56931. serializationObject.type = this.getClassName();
  56932. serializationObject.direction1 = this.direction1.asArray();
  56933. serializationObject.direction2 = this.direction2.asArray();
  56934. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56935. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56936. return serializationObject;
  56937. };
  56938. /**
  56939. * Parse properties from a JSON object
  56940. * @param serializationObject defines the JSON object
  56941. */
  56942. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56943. this.direction1.copyFrom(serializationObject.direction1);
  56944. this.direction2.copyFrom(serializationObject.direction2);
  56945. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56946. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56947. };
  56948. return BoxParticleEmitter;
  56949. }());
  56950. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56951. })(BABYLON || (BABYLON = {}));
  56952. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56953. var BABYLON;
  56954. (function (BABYLON) {
  56955. /**
  56956. * Particle emitter emitting particles from the inside of a cone.
  56957. * It emits the particles alongside the cone volume from the base to the particle.
  56958. * The emission direction might be randomized.
  56959. */
  56960. var ConeParticleEmitter = /** @class */ (function () {
  56961. /**
  56962. * Creates a new instance ConeParticleEmitter
  56963. * @param radius the radius of the emission cone (1 by default)
  56964. * @param angles the cone base angle (PI by default)
  56965. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56966. */
  56967. function ConeParticleEmitter(radius,
  56968. /**
  56969. * The radius of the emission cone.
  56970. */
  56971. angle,
  56972. /**
  56973. * The cone base angle.
  56974. */
  56975. directionRandomizer) {
  56976. if (radius === void 0) { radius = 1; }
  56977. if (angle === void 0) { angle = Math.PI; }
  56978. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56979. this.angle = angle;
  56980. this.directionRandomizer = directionRandomizer;
  56981. this.radius = radius;
  56982. }
  56983. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56984. /**
  56985. * Gets the radius of the emission cone.
  56986. */
  56987. get: function () {
  56988. return this._radius;
  56989. },
  56990. /**
  56991. * Sets the radius of the emission cone.
  56992. */
  56993. set: function (value) {
  56994. this._radius = value;
  56995. if (this.angle !== 0) {
  56996. this._height = value / Math.tan(this.angle / 2);
  56997. }
  56998. else {
  56999. this._height = 1;
  57000. }
  57001. },
  57002. enumerable: true,
  57003. configurable: true
  57004. });
  57005. /**
  57006. * Called by the particle System when the direction is computed for the created particle.
  57007. * @param emitPower is the power of the particle (speed)
  57008. * @param worldMatrix is the world matrix of the particle system
  57009. * @param directionToUpdate is the direction vector to update with the result
  57010. * @param particle is the particle we are computed the direction for
  57011. */
  57012. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57013. if (this.angle === 0) {
  57014. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  57015. }
  57016. else {
  57017. // measure the direction Vector from the emitter to the particle.
  57018. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57019. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57020. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57021. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57022. direction.x += randX;
  57023. direction.y += randY;
  57024. direction.z += randZ;
  57025. direction.normalize();
  57026. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57027. }
  57028. };
  57029. /**
  57030. * Called by the particle System when the position is computed for the created particle.
  57031. * @param worldMatrix is the world matrix of the particle system
  57032. * @param positionToUpdate is the position vector to update with the result
  57033. * @param particle is the particle we are computed the position for
  57034. */
  57035. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57036. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57037. var h = BABYLON.Scalar.RandomRange(0, 1);
  57038. // Better distribution in a cone at normal angles.
  57039. h = 1 - h * h;
  57040. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  57041. radius = radius * h;
  57042. var randX = radius * Math.sin(s);
  57043. var randZ = radius * Math.cos(s);
  57044. var randY = h * this._height;
  57045. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57046. };
  57047. /**
  57048. * Clones the current emitter and returns a copy of it
  57049. * @returns the new emitter
  57050. */
  57051. ConeParticleEmitter.prototype.clone = function () {
  57052. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  57053. BABYLON.Tools.DeepCopy(this, newOne);
  57054. return newOne;
  57055. };
  57056. /**
  57057. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57058. * @param effect defines the update shader
  57059. */
  57060. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57061. effect.setFloat("radius", this.radius);
  57062. effect.setFloat("angle", this.angle);
  57063. effect.setFloat("height", this._height);
  57064. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57065. };
  57066. /**
  57067. * Returns a string to use to update the GPU particles update shader
  57068. * @returns a string containng the defines string
  57069. */
  57070. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57071. return "#define CONEEMITTER";
  57072. };
  57073. /**
  57074. * Returns the string "BoxEmitter"
  57075. * @returns a string containing the class name
  57076. */
  57077. ConeParticleEmitter.prototype.getClassName = function () {
  57078. return "ConeEmitter";
  57079. };
  57080. /**
  57081. * Serializes the particle system to a JSON object.
  57082. * @returns the JSON object
  57083. */
  57084. ConeParticleEmitter.prototype.serialize = function () {
  57085. var serializationObject = {};
  57086. serializationObject.type = this.getClassName();
  57087. serializationObject.radius = this.radius;
  57088. serializationObject.angle = this.angle;
  57089. serializationObject.directionRandomizer = this.directionRandomizer;
  57090. return serializationObject;
  57091. };
  57092. /**
  57093. * Parse properties from a JSON object
  57094. * @param serializationObject defines the JSON object
  57095. */
  57096. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57097. this.radius = serializationObject.radius;
  57098. this.angle = serializationObject.angle;
  57099. this.directionRandomizer = serializationObject.directionRandomizer;
  57100. };
  57101. return ConeParticleEmitter;
  57102. }());
  57103. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57104. })(BABYLON || (BABYLON = {}));
  57105. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57106. var BABYLON;
  57107. (function (BABYLON) {
  57108. /**
  57109. * Particle emitter emitting particles from the inside of a sphere.
  57110. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57111. */
  57112. var SphereParticleEmitter = /** @class */ (function () {
  57113. /**
  57114. * Creates a new instance SphereParticleEmitter
  57115. * @param radius the radius of the emission sphere (1 by default)
  57116. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57117. */
  57118. function SphereParticleEmitter(
  57119. /**
  57120. * The radius of the emission sphere.
  57121. */
  57122. radius,
  57123. /**
  57124. * How much to randomize the particle direction [0-1].
  57125. */
  57126. directionRandomizer) {
  57127. if (radius === void 0) { radius = 1; }
  57128. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57129. this.radius = radius;
  57130. this.directionRandomizer = directionRandomizer;
  57131. }
  57132. /**
  57133. * Called by the particle System when the direction is computed for the created particle.
  57134. * @param emitPower is the power of the particle (speed)
  57135. * @param worldMatrix is the world matrix of the particle system
  57136. * @param directionToUpdate is the direction vector to update with the result
  57137. * @param particle is the particle we are computed the direction for
  57138. */
  57139. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57140. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57141. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57142. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57143. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57144. direction.x += randX;
  57145. direction.y += randY;
  57146. direction.z += randZ;
  57147. direction.normalize();
  57148. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57149. };
  57150. /**
  57151. * Called by the particle System when the position is computed for the created particle.
  57152. * @param worldMatrix is the world matrix of the particle system
  57153. * @param positionToUpdate is the position vector to update with the result
  57154. * @param particle is the particle we are computed the position for
  57155. */
  57156. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57157. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57158. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57159. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57160. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57161. var randY = randRadius * Math.cos(theta);
  57162. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57163. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57164. };
  57165. /**
  57166. * Clones the current emitter and returns a copy of it
  57167. * @returns the new emitter
  57168. */
  57169. SphereParticleEmitter.prototype.clone = function () {
  57170. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57171. BABYLON.Tools.DeepCopy(this, newOne);
  57172. return newOne;
  57173. };
  57174. /**
  57175. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57176. * @param effect defines the update shader
  57177. */
  57178. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57179. effect.setFloat("radius", this.radius);
  57180. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57181. };
  57182. /**
  57183. * Returns a string to use to update the GPU particles update shader
  57184. * @returns a string containng the defines string
  57185. */
  57186. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57187. return "#define SPHEREEMITTER";
  57188. };
  57189. /**
  57190. * Returns the string "SphereParticleEmitter"
  57191. * @returns a string containing the class name
  57192. */
  57193. SphereParticleEmitter.prototype.getClassName = function () {
  57194. return "SphereParticleEmitter";
  57195. };
  57196. /**
  57197. * Serializes the particle system to a JSON object.
  57198. * @returns the JSON object
  57199. */
  57200. SphereParticleEmitter.prototype.serialize = function () {
  57201. var serializationObject = {};
  57202. serializationObject.type = this.getClassName();
  57203. serializationObject.radius = this.radius;
  57204. serializationObject.directionRandomizer = this.directionRandomizer;
  57205. return serializationObject;
  57206. };
  57207. /**
  57208. * Parse properties from a JSON object
  57209. * @param serializationObject defines the JSON object
  57210. */
  57211. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57212. this.radius = serializationObject.radius;
  57213. this.directionRandomizer = serializationObject.directionRandomizer;
  57214. };
  57215. return SphereParticleEmitter;
  57216. }());
  57217. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57218. /**
  57219. * Particle emitter emitting particles from the inside of a sphere.
  57220. * It emits the particles randomly between two vectors.
  57221. */
  57222. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57223. __extends(SphereDirectedParticleEmitter, _super);
  57224. /**
  57225. * Creates a new instance SphereDirectedParticleEmitter
  57226. * @param radius the radius of the emission sphere (1 by default)
  57227. * @param direction1 the min limit of the emission direction (up vector by default)
  57228. * @param direction2 the max limit of the emission direction (up vector by default)
  57229. */
  57230. function SphereDirectedParticleEmitter(radius,
  57231. /**
  57232. * The min limit of the emission direction.
  57233. */
  57234. direction1,
  57235. /**
  57236. * The max limit of the emission direction.
  57237. */
  57238. direction2) {
  57239. if (radius === void 0) { radius = 1; }
  57240. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57241. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57242. var _this = _super.call(this, radius) || this;
  57243. _this.direction1 = direction1;
  57244. _this.direction2 = direction2;
  57245. return _this;
  57246. }
  57247. /**
  57248. * Called by the particle System when the direction is computed for the created particle.
  57249. * @param emitPower is the power of the particle (speed)
  57250. * @param worldMatrix is the world matrix of the particle system
  57251. * @param directionToUpdate is the direction vector to update with the result
  57252. * @param particle is the particle we are computed the direction for
  57253. */
  57254. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57255. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57256. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57257. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57258. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57259. };
  57260. /**
  57261. * Clones the current emitter and returns a copy of it
  57262. * @returns the new emitter
  57263. */
  57264. SphereDirectedParticleEmitter.prototype.clone = function () {
  57265. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57266. BABYLON.Tools.DeepCopy(this, newOne);
  57267. return newOne;
  57268. };
  57269. /**
  57270. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57271. * @param effect defines the update shader
  57272. */
  57273. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57274. effect.setFloat("radius", this.radius);
  57275. effect.setVector3("direction1", this.direction1);
  57276. effect.setVector3("direction2", this.direction2);
  57277. };
  57278. /**
  57279. * Returns a string to use to update the GPU particles update shader
  57280. * @returns a string containng the defines string
  57281. */
  57282. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57283. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57284. };
  57285. /**
  57286. * Returns the string "SphereDirectedParticleEmitter"
  57287. * @returns a string containing the class name
  57288. */
  57289. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57290. return "SphereDirectedParticleEmitter";
  57291. };
  57292. /**
  57293. * Serializes the particle system to a JSON object.
  57294. * @returns the JSON object
  57295. */
  57296. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57297. var serializationObject = _super.prototype.serialize.call(this);
  57298. serializationObject.direction1 = this.direction1.asArray();
  57299. serializationObject.direction2 = this.direction2.asArray();
  57300. return serializationObject;
  57301. };
  57302. /**
  57303. * Parse properties from a JSON object
  57304. * @param serializationObject defines the JSON object
  57305. */
  57306. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57307. _super.prototype.parse.call(this, serializationObject);
  57308. this.direction1.copyFrom(serializationObject.direction1);
  57309. this.direction2.copyFrom(serializationObject.direction2);
  57310. };
  57311. return SphereDirectedParticleEmitter;
  57312. }(SphereParticleEmitter));
  57313. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57314. })(BABYLON || (BABYLON = {}));
  57315. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57316. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57317. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57318. s = arguments[i];
  57319. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57320. t[p] = s[p];
  57321. }
  57322. return t;
  57323. };
  57324. var BABYLON;
  57325. (function (BABYLON) {
  57326. /**
  57327. * This represents a GPU particle system in Babylon
  57328. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57329. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57330. */
  57331. var GPUParticleSystem = /** @class */ (function () {
  57332. /**
  57333. * Instantiates a GPU particle system.
  57334. * 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.
  57335. * @param name The name of the particle system
  57336. * @param capacity The max number of particles alive at the same time
  57337. * @param scene The scene the particle system belongs to
  57338. */
  57339. function GPUParticleSystem(name, options, scene) {
  57340. /**
  57341. * The emitter represents the Mesh or position we are attaching the particle system to.
  57342. */
  57343. this.emitter = null;
  57344. /**
  57345. * The rendering group used by the Particle system to chose when to render.
  57346. */
  57347. this.renderingGroupId = 0;
  57348. /**
  57349. * The layer mask we are rendering the particles through.
  57350. */
  57351. this.layerMask = 0x0FFFFFFF;
  57352. this._targetIndex = 0;
  57353. this._currentRenderId = -1;
  57354. this._started = false;
  57355. this._stopped = false;
  57356. this._timeDelta = 0;
  57357. this._attributesStrideSize = 14;
  57358. this._actualFrame = 0;
  57359. /**
  57360. * List of animations used by the particle system.
  57361. */
  57362. this.animations = [];
  57363. /**
  57364. * An event triggered when the system is disposed.
  57365. */
  57366. this.onDisposeObservable = new BABYLON.Observable();
  57367. /**
  57368. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57369. */
  57370. this.updateSpeed = 0.01;
  57371. /**
  57372. * The amount of time the particle system is running (depends of the overall update speed).
  57373. */
  57374. this.targetStopDuration = 0;
  57375. /**
  57376. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57377. */
  57378. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57379. /**
  57380. * Minimum life time of emitting particles.
  57381. */
  57382. this.minLifeTime = 1;
  57383. /**
  57384. * Maximum life time of emitting particles.
  57385. */
  57386. this.maxLifeTime = 1;
  57387. /**
  57388. * Minimum Size of emitting particles.
  57389. */
  57390. this.minSize = 1;
  57391. /**
  57392. * Maximum Size of emitting particles.
  57393. */
  57394. this.maxSize = 1;
  57395. /**
  57396. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57397. */
  57398. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57399. /**
  57400. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57401. */
  57402. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57403. /**
  57404. * Color the particle will have at the end of its lifetime.
  57405. */
  57406. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57407. /**
  57408. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57409. */
  57410. this.emitRate = 100;
  57411. /**
  57412. * You can use gravity if you want to give an orientation to your particles.
  57413. */
  57414. this.gravity = BABYLON.Vector3.Zero();
  57415. /**
  57416. * Minimum power of emitting particles.
  57417. */
  57418. this.minEmitPower = 1;
  57419. /**
  57420. * Maximum power of emitting particles.
  57421. */
  57422. this.maxEmitPower = 1;
  57423. /**
  57424. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57425. * to override the particles.
  57426. */
  57427. this.forceDepthWrite = false;
  57428. this.id = name;
  57429. this.name = name;
  57430. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57431. this._engine = this._scene.getEngine();
  57432. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57433. this._capacity = fullOptions.capacity;
  57434. this._activeCount = fullOptions.capacity;
  57435. this._currentActiveCount = 0;
  57436. this._scene.particleSystems.push(this);
  57437. this._updateEffectOptions = {
  57438. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57439. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57440. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57441. uniformBuffersNames: [],
  57442. samplers: ["randomSampler"],
  57443. defines: "",
  57444. fallbacks: null,
  57445. onCompiled: null,
  57446. onError: null,
  57447. indexParameters: null,
  57448. maxSimultaneousLights: 0,
  57449. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57450. };
  57451. // Random data
  57452. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57453. var d = [];
  57454. for (var i = 0; i < maxTextureSize; ++i) {
  57455. d.push(Math.random());
  57456. d.push(Math.random());
  57457. d.push(Math.random());
  57458. d.push(Math.random());
  57459. }
  57460. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57461. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57462. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57463. this._randomTextureSize = maxTextureSize;
  57464. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57465. }
  57466. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57467. /**
  57468. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57469. */
  57470. get: function () {
  57471. if (!BABYLON.Engine.LastCreatedEngine) {
  57472. return false;
  57473. }
  57474. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57475. },
  57476. enumerable: true,
  57477. configurable: true
  57478. });
  57479. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57480. /**
  57481. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57482. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57483. */
  57484. get: function () {
  57485. if (this.particleEmitterType.direction1) {
  57486. return this.particleEmitterType.direction1;
  57487. }
  57488. return BABYLON.Vector3.Zero();
  57489. },
  57490. set: function (value) {
  57491. if (this.particleEmitterType.direction1) {
  57492. this.particleEmitterType.direction1 = value;
  57493. }
  57494. },
  57495. enumerable: true,
  57496. configurable: true
  57497. });
  57498. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57499. /**
  57500. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57501. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57502. */
  57503. get: function () {
  57504. if (this.particleEmitterType.direction2) {
  57505. return this.particleEmitterType.direction2;
  57506. }
  57507. return BABYLON.Vector3.Zero();
  57508. },
  57509. set: function (value) {
  57510. if (this.particleEmitterType.direction2) {
  57511. this.particleEmitterType.direction2 = value;
  57512. }
  57513. },
  57514. enumerable: true,
  57515. configurable: true
  57516. });
  57517. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57518. /**
  57519. * 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.
  57520. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57521. */
  57522. get: function () {
  57523. if (this.particleEmitterType.minEmitBox) {
  57524. return this.particleEmitterType.minEmitBox;
  57525. }
  57526. return BABYLON.Vector3.Zero();
  57527. },
  57528. set: function (value) {
  57529. if (this.particleEmitterType.minEmitBox) {
  57530. this.particleEmitterType.minEmitBox = value;
  57531. }
  57532. },
  57533. enumerable: true,
  57534. configurable: true
  57535. });
  57536. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57537. /**
  57538. * 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.
  57539. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57540. */
  57541. get: function () {
  57542. if (this.particleEmitterType.maxEmitBox) {
  57543. return this.particleEmitterType.maxEmitBox;
  57544. }
  57545. return BABYLON.Vector3.Zero();
  57546. },
  57547. set: function (value) {
  57548. if (this.particleEmitterType.maxEmitBox) {
  57549. this.particleEmitterType.maxEmitBox = value;
  57550. }
  57551. },
  57552. enumerable: true,
  57553. configurable: true
  57554. });
  57555. /**
  57556. * Gets the maximum number of particles active at the same time.
  57557. * @returns The max number of active particles.
  57558. */
  57559. GPUParticleSystem.prototype.getCapacity = function () {
  57560. return this._capacity;
  57561. };
  57562. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57563. /**
  57564. * Gets or set the number of active particles
  57565. */
  57566. get: function () {
  57567. return this._activeCount;
  57568. },
  57569. set: function (value) {
  57570. this._activeCount = Math.min(value, this._capacity);
  57571. },
  57572. enumerable: true,
  57573. configurable: true
  57574. });
  57575. /**
  57576. * Is this system ready to be used/rendered
  57577. * @return true if the system is ready
  57578. */
  57579. GPUParticleSystem.prototype.isReady = function () {
  57580. if (!this._updateEffect) {
  57581. this._recreateUpdateEffect();
  57582. this._recreateRenderEffect();
  57583. return false;
  57584. }
  57585. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57586. return false;
  57587. }
  57588. return true;
  57589. };
  57590. /**
  57591. * Gets Wether the system has been started.
  57592. * @returns True if it has been started, otherwise false.
  57593. */
  57594. GPUParticleSystem.prototype.isStarted = function () {
  57595. return this._started;
  57596. };
  57597. /**
  57598. * Starts the particle system and begins to emit.
  57599. */
  57600. GPUParticleSystem.prototype.start = function () {
  57601. this._started = true;
  57602. this._stopped = false;
  57603. };
  57604. /**
  57605. * Stops the particle system.
  57606. */
  57607. GPUParticleSystem.prototype.stop = function () {
  57608. this._stopped = true;
  57609. };
  57610. /**
  57611. * Remove all active particles
  57612. */
  57613. GPUParticleSystem.prototype.reset = function () {
  57614. this._releaseBuffers();
  57615. this._releaseVAOs();
  57616. this._currentActiveCount = 0;
  57617. this._targetIndex = 0;
  57618. };
  57619. /**
  57620. * Returns the string "GPUParticleSystem"
  57621. * @returns a string containing the class name
  57622. */
  57623. GPUParticleSystem.prototype.getClassName = function () {
  57624. return "GPUParticleSystem";
  57625. };
  57626. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57627. var updateVertexBuffers = {};
  57628. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57629. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57630. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57631. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57632. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57633. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57634. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57635. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57636. this._engine.bindArrayBuffer(null);
  57637. return vao;
  57638. };
  57639. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57640. var renderVertexBuffers = {};
  57641. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57642. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57643. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57644. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57645. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57646. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57647. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57648. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57649. this._engine.bindArrayBuffer(null);
  57650. return vao;
  57651. };
  57652. GPUParticleSystem.prototype._initialize = function (force) {
  57653. if (force === void 0) { force = false; }
  57654. if (this._buffer0 && !force) {
  57655. return;
  57656. }
  57657. var engine = this._scene.getEngine();
  57658. var data = new Array();
  57659. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57660. // position
  57661. data.push(0.0);
  57662. data.push(0.0);
  57663. data.push(0.0);
  57664. // Age and life
  57665. data.push(0.0); // create the particle as a dead one to create a new one at start
  57666. data.push(0.0);
  57667. // Seed
  57668. data.push(Math.random());
  57669. // Size
  57670. data.push(0.0);
  57671. // color
  57672. data.push(0.0);
  57673. data.push(0.0);
  57674. data.push(0.0);
  57675. data.push(0.0);
  57676. // direction
  57677. data.push(0.0);
  57678. data.push(0.0);
  57679. data.push(0.0);
  57680. }
  57681. // Sprite data
  57682. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57683. -0.5, 0.5, 0, 1,
  57684. -0.5, -0.5, 0, 0,
  57685. 0.5, -0.5, 1, 0]);
  57686. // Buffers
  57687. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57688. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57689. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57690. // Update VAO
  57691. this._updateVAO = [];
  57692. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57693. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57694. // Render VAO
  57695. this._renderVAO = [];
  57696. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57697. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57698. // Links
  57699. this._sourceBuffer = this._buffer0;
  57700. this._targetBuffer = this._buffer1;
  57701. };
  57702. /** @hidden */
  57703. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57704. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57705. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57706. return;
  57707. }
  57708. this._updateEffectOptions.defines = defines;
  57709. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57710. };
  57711. /** @hidden */
  57712. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57713. var defines = "";
  57714. if (this._scene.clipPlane) {
  57715. defines = "\n#define CLIPPLANE";
  57716. }
  57717. if (this._renderEffect && this._renderEffect.defines === defines) {
  57718. return;
  57719. }
  57720. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57721. };
  57722. /**
  57723. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57724. */
  57725. GPUParticleSystem.prototype.animate = function () {
  57726. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57727. this._actualFrame += this._timeDelta;
  57728. if (!this._stopped) {
  57729. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57730. this.stop();
  57731. }
  57732. }
  57733. };
  57734. /**
  57735. * Renders the particle system in its current state.
  57736. * @returns the current number of particles
  57737. */
  57738. GPUParticleSystem.prototype.render = function () {
  57739. if (!this._started) {
  57740. return 0;
  57741. }
  57742. this._recreateUpdateEffect();
  57743. this._recreateRenderEffect();
  57744. if (!this.isReady()) {
  57745. return 0;
  57746. }
  57747. if (this._currentRenderId === this._scene.getRenderId()) {
  57748. return 0;
  57749. }
  57750. this._currentRenderId = this._scene.getRenderId();
  57751. // Get everything ready to render
  57752. this._initialize();
  57753. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57754. // Enable update effect
  57755. this._engine.enableEffect(this._updateEffect);
  57756. this._engine.setState(false);
  57757. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57758. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57759. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57760. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57761. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57762. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57763. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57764. this._updateEffect.setDirectColor4("color1", this.color1);
  57765. this._updateEffect.setDirectColor4("color2", this.color2);
  57766. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57767. this._updateEffect.setVector3("gravity", this.gravity);
  57768. if (this.particleEmitterType) {
  57769. this.particleEmitterType.applyToShader(this._updateEffect);
  57770. }
  57771. var emitterWM;
  57772. if (this.emitter.position) {
  57773. var emitterMesh = this.emitter;
  57774. emitterWM = emitterMesh.getWorldMatrix();
  57775. }
  57776. else {
  57777. var emitterPosition = this.emitter;
  57778. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57779. }
  57780. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57781. // Bind source VAO
  57782. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57783. // Update
  57784. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57785. this._engine.setRasterizerState(false);
  57786. this._engine.beginTransformFeedback();
  57787. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57788. this._engine.endTransformFeedback();
  57789. this._engine.setRasterizerState(true);
  57790. this._engine.bindTransformFeedbackBuffer(null);
  57791. // Enable render effect
  57792. this._engine.enableEffect(this._renderEffect);
  57793. var viewMatrix = this._scene.getViewMatrix();
  57794. this._renderEffect.setMatrix("view", viewMatrix);
  57795. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57796. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57797. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57798. if (this._scene.clipPlane) {
  57799. var clipPlane = this._scene.clipPlane;
  57800. var invView = viewMatrix.clone();
  57801. invView.invert();
  57802. this._renderEffect.setMatrix("invView", invView);
  57803. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57804. }
  57805. // Draw order
  57806. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57807. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57808. }
  57809. else {
  57810. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57811. }
  57812. if (this.forceDepthWrite) {
  57813. this._engine.setDepthWrite(true);
  57814. }
  57815. // Bind source VAO
  57816. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57817. // Render
  57818. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57819. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57820. // Switch VAOs
  57821. this._targetIndex++;
  57822. if (this._targetIndex === 2) {
  57823. this._targetIndex = 0;
  57824. }
  57825. // Switch buffers
  57826. var tmpBuffer = this._sourceBuffer;
  57827. this._sourceBuffer = this._targetBuffer;
  57828. this._targetBuffer = tmpBuffer;
  57829. return this._currentActiveCount;
  57830. };
  57831. /**
  57832. * Rebuilds the particle system
  57833. */
  57834. GPUParticleSystem.prototype.rebuild = function () {
  57835. this._initialize(true);
  57836. };
  57837. GPUParticleSystem.prototype._releaseBuffers = function () {
  57838. if (this._buffer0) {
  57839. this._buffer0.dispose();
  57840. this._buffer0 = null;
  57841. }
  57842. if (this._buffer1) {
  57843. this._buffer1.dispose();
  57844. this._buffer1 = null;
  57845. }
  57846. if (this._spriteBuffer) {
  57847. this._spriteBuffer.dispose();
  57848. this._spriteBuffer = null;
  57849. }
  57850. };
  57851. GPUParticleSystem.prototype._releaseVAOs = function () {
  57852. if (!this._updateVAO) {
  57853. return;
  57854. }
  57855. for (var index = 0; index < this._updateVAO.length; index++) {
  57856. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57857. }
  57858. this._updateVAO = [];
  57859. for (var index = 0; index < this._renderVAO.length; index++) {
  57860. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57861. }
  57862. this._renderVAO = [];
  57863. };
  57864. /**
  57865. * Disposes the particle system and free the associated resources
  57866. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57867. */
  57868. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57869. if (disposeTexture === void 0) { disposeTexture = true; }
  57870. var index = this._scene.particleSystems.indexOf(this);
  57871. if (index > -1) {
  57872. this._scene.particleSystems.splice(index, 1);
  57873. }
  57874. this._releaseBuffers();
  57875. this._releaseVAOs();
  57876. if (this._randomTexture) {
  57877. this._randomTexture.dispose();
  57878. this._randomTexture = null;
  57879. }
  57880. if (disposeTexture && this.particleTexture) {
  57881. this.particleTexture.dispose();
  57882. this.particleTexture = null;
  57883. }
  57884. // Callback
  57885. this.onDisposeObservable.notifyObservers(this);
  57886. this.onDisposeObservable.clear();
  57887. };
  57888. /**
  57889. * Clones the particle system.
  57890. * @param name The name of the cloned object
  57891. * @param newEmitter The new emitter to use
  57892. * @returns the cloned particle system
  57893. */
  57894. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57895. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57896. BABYLON.Tools.DeepCopy(this, result);
  57897. if (newEmitter === undefined) {
  57898. newEmitter = this.emitter;
  57899. }
  57900. result.emitter = newEmitter;
  57901. if (this.particleTexture) {
  57902. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57903. }
  57904. return result;
  57905. };
  57906. /**
  57907. * Serializes the particle system to a JSON object.
  57908. * @returns the JSON object
  57909. */
  57910. GPUParticleSystem.prototype.serialize = function () {
  57911. var serializationObject = {};
  57912. serializationObject.name = this.name;
  57913. serializationObject.id = this.id;
  57914. // Emitter
  57915. if (this.emitter.position) {
  57916. var emitterMesh = this.emitter;
  57917. serializationObject.emitterId = emitterMesh.id;
  57918. }
  57919. else {
  57920. var emitterPosition = this.emitter;
  57921. serializationObject.emitter = emitterPosition.asArray();
  57922. }
  57923. serializationObject.capacity = this.getCapacity();
  57924. if (this.particleTexture) {
  57925. serializationObject.textureName = this.particleTexture.name;
  57926. }
  57927. // Animations
  57928. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57929. // Particle system
  57930. serializationObject.activeParticleCount = this.activeParticleCount;
  57931. serializationObject.randomTextureSize = this._randomTextureSize;
  57932. serializationObject.minSize = this.minSize;
  57933. serializationObject.maxSize = this.maxSize;
  57934. serializationObject.minEmitPower = this.minEmitPower;
  57935. serializationObject.maxEmitPower = this.maxEmitPower;
  57936. serializationObject.minLifeTime = this.minLifeTime;
  57937. serializationObject.maxLifeTime = this.maxLifeTime;
  57938. serializationObject.emitRate = this.emitRate;
  57939. serializationObject.gravity = this.gravity.asArray();
  57940. serializationObject.color1 = this.color1.asArray();
  57941. serializationObject.color2 = this.color2.asArray();
  57942. serializationObject.colorDead = this.colorDead.asArray();
  57943. serializationObject.updateSpeed = this.updateSpeed;
  57944. serializationObject.targetStopDuration = this.targetStopDuration;
  57945. serializationObject.blendMode = this.blendMode;
  57946. // Emitter
  57947. if (this.particleEmitterType) {
  57948. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57949. }
  57950. return serializationObject;
  57951. };
  57952. /**
  57953. * Parses a JSON object to create a GPU particle system.
  57954. * @param parsedParticleSystem The JSON object to parse
  57955. * @param scene The scene to create the particle system in
  57956. * @param rootUrl The root url to use to load external dependencies like texture
  57957. * @returns the parsed GPU particle system
  57958. */
  57959. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57960. var name = parsedParticleSystem.name;
  57961. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57962. if (parsedParticleSystem.id) {
  57963. particleSystem.id = parsedParticleSystem.id;
  57964. }
  57965. // Texture
  57966. if (parsedParticleSystem.textureName) {
  57967. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57968. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57969. }
  57970. // Emitter
  57971. if (parsedParticleSystem.emitterId) {
  57972. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57973. }
  57974. else {
  57975. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57976. }
  57977. // Animations
  57978. if (parsedParticleSystem.animations) {
  57979. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57980. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57981. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57982. }
  57983. }
  57984. // Particle system
  57985. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57986. particleSystem.minSize = parsedParticleSystem.minSize;
  57987. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57988. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57989. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57990. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57991. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57992. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57993. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57994. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57995. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57996. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57997. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57998. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57999. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58000. // Emitter
  58001. if (parsedParticleSystem.particleEmitterType) {
  58002. var emitterType = void 0;
  58003. switch (parsedParticleSystem.particleEmitterType.type) {
  58004. case "SphereEmitter":
  58005. emitterType = new BABYLON.SphereParticleEmitter();
  58006. break;
  58007. case "SphereDirectedParticleEmitter":
  58008. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58009. break;
  58010. case "ConeEmitter":
  58011. emitterType = new BABYLON.ConeParticleEmitter();
  58012. break;
  58013. case "BoxEmitter":
  58014. default:
  58015. emitterType = new BABYLON.BoxParticleEmitter();
  58016. break;
  58017. }
  58018. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58019. particleSystem.particleEmitterType = emitterType;
  58020. }
  58021. return particleSystem;
  58022. };
  58023. return GPUParticleSystem;
  58024. }());
  58025. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58026. })(BABYLON || (BABYLON = {}));
  58027. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58028. var BABYLON;
  58029. (function (BABYLON) {
  58030. /**
  58031. * Represents one particle of a solid particle system.
  58032. */
  58033. var SolidParticle = /** @class */ (function () {
  58034. /**
  58035. * Creates a Solid Particle object.
  58036. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58037. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58038. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58039. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58040. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58041. * @param shapeId (integer) is the model shape identifier in the SPS.
  58042. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58043. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58044. */
  58045. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58046. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58047. /**
  58048. * particle global index
  58049. */
  58050. this.idx = 0;
  58051. /**
  58052. * The color of the particle
  58053. */
  58054. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58055. /**
  58056. * The world space position of the particle.
  58057. */
  58058. this.position = BABYLON.Vector3.Zero();
  58059. /**
  58060. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58061. */
  58062. this.rotation = BABYLON.Vector3.Zero();
  58063. /**
  58064. * The scaling of the particle.
  58065. */
  58066. this.scaling = BABYLON.Vector3.One();
  58067. /**
  58068. * The uvs of the particle.
  58069. */
  58070. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58071. /**
  58072. * The current speed of the particle.
  58073. */
  58074. this.velocity = BABYLON.Vector3.Zero();
  58075. /**
  58076. * The pivot point in the particle local space.
  58077. */
  58078. this.pivot = BABYLON.Vector3.Zero();
  58079. /**
  58080. * Must the particle be translated from its pivot point in its local space ?
  58081. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58082. * Default : false
  58083. */
  58084. this.translateFromPivot = false;
  58085. /**
  58086. * Is the particle active or not ?
  58087. */
  58088. this.alive = true;
  58089. /**
  58090. * Is the particle visible or not ?
  58091. */
  58092. this.isVisible = true;
  58093. /**
  58094. * Index of this particle in the global "positions" array (Internal use)
  58095. */
  58096. this._pos = 0;
  58097. /**
  58098. * Index of this particle in the global "indices" array (Internal use)
  58099. */
  58100. this._ind = 0;
  58101. /**
  58102. * ModelShape id of this particle
  58103. */
  58104. this.shapeId = 0;
  58105. /**
  58106. * Index of the particle in its shape id (Internal use)
  58107. */
  58108. this.idxInShape = 0;
  58109. /**
  58110. * Still set as invisible in order to skip useless computations (Internal use)
  58111. */
  58112. this._stillInvisible = false;
  58113. /**
  58114. * Last computed particle rotation matrix
  58115. */
  58116. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58117. /**
  58118. * Parent particle Id, if any.
  58119. * Default null.
  58120. */
  58121. this.parentId = null;
  58122. /**
  58123. * Internal global position in the SPS.
  58124. */
  58125. this._globalPosition = BABYLON.Vector3.Zero();
  58126. this.idx = particleIndex;
  58127. this._pos = positionIndex;
  58128. this._ind = indiceIndex;
  58129. this._model = model;
  58130. this.shapeId = shapeId;
  58131. this.idxInShape = idxInShape;
  58132. this._sps = sps;
  58133. if (modelBoundingInfo) {
  58134. this._modelBoundingInfo = modelBoundingInfo;
  58135. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58136. }
  58137. }
  58138. Object.defineProperty(SolidParticle.prototype, "scale", {
  58139. /**
  58140. * Legacy support, changed scale to scaling
  58141. */
  58142. get: function () {
  58143. return this.scaling;
  58144. },
  58145. /**
  58146. * Legacy support, changed scale to scaling
  58147. */
  58148. set: function (scale) {
  58149. this.scaling = scale;
  58150. },
  58151. enumerable: true,
  58152. configurable: true
  58153. });
  58154. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58155. /**
  58156. * Legacy support, changed quaternion to rotationQuaternion
  58157. */
  58158. get: function () {
  58159. return this.rotationQuaternion;
  58160. },
  58161. /**
  58162. * Legacy support, changed quaternion to rotationQuaternion
  58163. */
  58164. set: function (q) {
  58165. this.rotationQuaternion = q;
  58166. },
  58167. enumerable: true,
  58168. configurable: true
  58169. });
  58170. /**
  58171. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58172. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58173. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58174. * @returns true if it intersects
  58175. */
  58176. SolidParticle.prototype.intersectsMesh = function (target) {
  58177. if (!this._boundingInfo || !target._boundingInfo) {
  58178. return false;
  58179. }
  58180. if (this._sps._bSphereOnly) {
  58181. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58182. }
  58183. return this._boundingInfo.intersects(target._boundingInfo, false);
  58184. };
  58185. return SolidParticle;
  58186. }());
  58187. BABYLON.SolidParticle = SolidParticle;
  58188. /**
  58189. * Represents the shape of the model used by one particle of a solid particle system.
  58190. * SPS internal tool, don't use it manually.
  58191. */
  58192. var ModelShape = /** @class */ (function () {
  58193. /**
  58194. * 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.
  58195. * SPS internal tool, don't use it manually.
  58196. * @hidden
  58197. */
  58198. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58199. /**
  58200. * length of the shape in the model indices array (internal use)
  58201. */
  58202. this._indicesLength = 0;
  58203. this.shapeID = id;
  58204. this._shape = shape;
  58205. this._indicesLength = indicesLength;
  58206. this._shapeUV = shapeUV;
  58207. this._positionFunction = posFunction;
  58208. this._vertexFunction = vtxFunction;
  58209. }
  58210. return ModelShape;
  58211. }());
  58212. BABYLON.ModelShape = ModelShape;
  58213. /**
  58214. * Represents a Depth Sorted Particle in the solid particle system.
  58215. */
  58216. var DepthSortedParticle = /** @class */ (function () {
  58217. function DepthSortedParticle() {
  58218. /**
  58219. * Index of the particle in the "indices" array
  58220. */
  58221. this.ind = 0;
  58222. /**
  58223. * Length of the particle shape in the "indices" array
  58224. */
  58225. this.indicesLength = 0;
  58226. /**
  58227. * Squared distance from the particle to the camera
  58228. */
  58229. this.sqDistance = 0.0;
  58230. }
  58231. return DepthSortedParticle;
  58232. }());
  58233. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58234. })(BABYLON || (BABYLON = {}));
  58235. //# sourceMappingURL=babylon.solidParticle.js.map
  58236. var BABYLON;
  58237. (function (BABYLON) {
  58238. /**
  58239. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58240. *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.
  58241. * The SPS is also a particle system. It provides some methods to manage the particles.
  58242. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58243. *
  58244. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58245. */
  58246. var SolidParticleSystem = /** @class */ (function () {
  58247. /**
  58248. * Creates a SPS (Solid Particle System) object.
  58249. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58250. * @param scene (Scene) is the scene in which the SPS is added.
  58251. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58252. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58253. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58254. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58255. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58256. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58257. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58258. */
  58259. function SolidParticleSystem(name, scene, options) {
  58260. /**
  58261. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58262. * Example : var p = SPS.particles[i];
  58263. */
  58264. this.particles = new Array();
  58265. /**
  58266. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58267. */
  58268. this.nbParticles = 0;
  58269. /**
  58270. * If the particles must ever face the camera (default false). Useful for planar particles.
  58271. */
  58272. this.billboard = false;
  58273. /**
  58274. * Recompute normals when adding a shape
  58275. */
  58276. this.recomputeNormals = true;
  58277. /**
  58278. * This a counter ofr your own usage. It's not set by any SPS functions.
  58279. */
  58280. this.counter = 0;
  58281. /**
  58282. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58283. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58284. */
  58285. this.vars = {};
  58286. /**
  58287. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58288. */
  58289. this._bSphereOnly = false;
  58290. /**
  58291. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58292. */
  58293. this._bSphereRadiusFactor = 1.0;
  58294. this._positions = new Array();
  58295. this._indices = new Array();
  58296. this._normals = new Array();
  58297. this._colors = new Array();
  58298. this._uvs = new Array();
  58299. this._index = 0; // indices index
  58300. this._updatable = true;
  58301. this._pickable = false;
  58302. this._isVisibilityBoxLocked = false;
  58303. this._alwaysVisible = false;
  58304. this._depthSort = false;
  58305. this._shapeCounter = 0;
  58306. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58307. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58308. this._computeParticleColor = true;
  58309. this._computeParticleTexture = true;
  58310. this._computeParticleRotation = true;
  58311. this._computeParticleVertex = false;
  58312. this._computeBoundingBox = false;
  58313. this._depthSortParticles = true;
  58314. this._cam_axisZ = BABYLON.Vector3.Zero();
  58315. this._cam_axisY = BABYLON.Vector3.Zero();
  58316. this._cam_axisX = BABYLON.Vector3.Zero();
  58317. this._axisZ = BABYLON.Axis.Z;
  58318. this._camDir = BABYLON.Vector3.Zero();
  58319. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58320. this._rotMatrix = new BABYLON.Matrix();
  58321. this._invertMatrix = new BABYLON.Matrix();
  58322. this._rotated = BABYLON.Vector3.Zero();
  58323. this._quaternion = new BABYLON.Quaternion();
  58324. this._vertex = BABYLON.Vector3.Zero();
  58325. this._normal = BABYLON.Vector3.Zero();
  58326. this._yaw = 0.0;
  58327. this._pitch = 0.0;
  58328. this._roll = 0.0;
  58329. this._halfroll = 0.0;
  58330. this._halfpitch = 0.0;
  58331. this._halfyaw = 0.0;
  58332. this._sinRoll = 0.0;
  58333. this._cosRoll = 0.0;
  58334. this._sinPitch = 0.0;
  58335. this._cosPitch = 0.0;
  58336. this._sinYaw = 0.0;
  58337. this._cosYaw = 0.0;
  58338. this._mustUnrotateFixedNormals = false;
  58339. this._minimum = BABYLON.Vector3.Zero();
  58340. this._maximum = BABYLON.Vector3.Zero();
  58341. this._minBbox = BABYLON.Vector3.Zero();
  58342. this._maxBbox = BABYLON.Vector3.Zero();
  58343. this._particlesIntersect = false;
  58344. this._depthSortFunction = function (p1, p2) {
  58345. return (p2.sqDistance - p1.sqDistance);
  58346. };
  58347. this._needs32Bits = false;
  58348. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58349. this._scaledPivot = BABYLON.Vector3.Zero();
  58350. this._particleHasParent = false;
  58351. this.name = name;
  58352. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58353. this._camera = scene.activeCamera;
  58354. this._pickable = options ? options.isPickable : false;
  58355. this._depthSort = options ? options.enableDepthSort : false;
  58356. this._particlesIntersect = options ? options.particleIntersection : false;
  58357. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58358. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58359. if (options && options.updatable) {
  58360. this._updatable = options.updatable;
  58361. }
  58362. else {
  58363. this._updatable = true;
  58364. }
  58365. if (this._pickable) {
  58366. this.pickedParticles = [];
  58367. }
  58368. if (this._depthSort) {
  58369. this.depthSortedParticles = [];
  58370. }
  58371. }
  58372. /**
  58373. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58374. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58375. * @returns the created mesh
  58376. */
  58377. SolidParticleSystem.prototype.buildMesh = function () {
  58378. if (this.nbParticles === 0) {
  58379. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58380. this.addShape(triangle, 1);
  58381. triangle.dispose();
  58382. }
  58383. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58384. this._positions32 = new Float32Array(this._positions);
  58385. this._uvs32 = new Float32Array(this._uvs);
  58386. this._colors32 = new Float32Array(this._colors);
  58387. if (this.recomputeNormals) {
  58388. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58389. }
  58390. this._normals32 = new Float32Array(this._normals);
  58391. this._fixedNormal32 = new Float32Array(this._normals);
  58392. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58393. this._unrotateFixedNormals();
  58394. }
  58395. var vertexData = new BABYLON.VertexData();
  58396. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58397. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58398. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58399. if (this._uvs32.length > 0) {
  58400. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58401. }
  58402. if (this._colors32.length > 0) {
  58403. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58404. }
  58405. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58406. vertexData.applyToMesh(mesh, this._updatable);
  58407. this.mesh = mesh;
  58408. this.mesh.isPickable = this._pickable;
  58409. // free memory
  58410. if (!this._depthSort) {
  58411. this._indices = null;
  58412. }
  58413. this._positions = null;
  58414. this._normals = null;
  58415. this._uvs = null;
  58416. this._colors = null;
  58417. if (!this._updatable) {
  58418. this.particles.length = 0;
  58419. }
  58420. return mesh;
  58421. };
  58422. /**
  58423. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58424. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58425. * Thus the particles generated from `digest()` have their property `position` set yet.
  58426. * @param mesh ( Mesh ) is the mesh to be digested
  58427. * @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
  58428. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58429. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58430. * @returns the current SPS
  58431. */
  58432. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58433. var size = (options && options.facetNb) || 1;
  58434. var number = (options && options.number) || 0;
  58435. var delta = (options && options.delta) || 0;
  58436. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58437. var meshInd = mesh.getIndices();
  58438. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58439. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58440. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58441. var f = 0; // facet counter
  58442. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58443. // compute size from number
  58444. if (number) {
  58445. number = (number > totalFacets) ? totalFacets : number;
  58446. size = Math.round(totalFacets / number);
  58447. delta = 0;
  58448. }
  58449. else {
  58450. size = (size > totalFacets) ? totalFacets : size;
  58451. }
  58452. var facetPos = []; // submesh positions
  58453. var facetInd = []; // submesh indices
  58454. var facetUV = []; // submesh UV
  58455. var facetCol = []; // submesh colors
  58456. var barycenter = BABYLON.Vector3.Zero();
  58457. var sizeO = size;
  58458. while (f < totalFacets) {
  58459. size = sizeO + Math.floor((1 + delta) * Math.random());
  58460. if (f > totalFacets - size) {
  58461. size = totalFacets - f;
  58462. }
  58463. // reset temp arrays
  58464. facetPos.length = 0;
  58465. facetInd.length = 0;
  58466. facetUV.length = 0;
  58467. facetCol.length = 0;
  58468. // iterate over "size" facets
  58469. var fi = 0;
  58470. for (var j = f * 3; j < (f + size) * 3; j++) {
  58471. facetInd.push(fi);
  58472. var i = meshInd[j];
  58473. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58474. if (meshUV) {
  58475. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58476. }
  58477. if (meshCol) {
  58478. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58479. }
  58480. fi++;
  58481. }
  58482. // create a model shape for each single particle
  58483. var idx = this.nbParticles;
  58484. var shape = this._posToShape(facetPos);
  58485. var shapeUV = this._uvsToShapeUV(facetUV);
  58486. // compute the barycenter of the shape
  58487. var v;
  58488. for (v = 0; v < shape.length; v++) {
  58489. barycenter.addInPlace(shape[v]);
  58490. }
  58491. barycenter.scaleInPlace(1 / shape.length);
  58492. // shift the shape from its barycenter to the origin
  58493. for (v = 0; v < shape.length; v++) {
  58494. shape[v].subtractInPlace(barycenter);
  58495. }
  58496. var bInfo;
  58497. if (this._particlesIntersect) {
  58498. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58499. }
  58500. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58501. // add the particle in the SPS
  58502. var currentPos = this._positions.length;
  58503. var currentInd = this._indices.length;
  58504. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58505. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58506. // initialize the particle position
  58507. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58508. this._index += shape.length;
  58509. idx++;
  58510. this.nbParticles++;
  58511. this._shapeCounter++;
  58512. f += size;
  58513. }
  58514. return this;
  58515. };
  58516. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58517. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58518. var index = 0;
  58519. var idx = 0;
  58520. for (var p = 0; p < this.particles.length; p++) {
  58521. this._particle = this.particles[p];
  58522. this._shape = this._particle._model._shape;
  58523. if (this._particle.rotationQuaternion) {
  58524. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58525. }
  58526. else {
  58527. this._yaw = this._particle.rotation.y;
  58528. this._pitch = this._particle.rotation.x;
  58529. this._roll = this._particle.rotation.z;
  58530. this._quaternionRotationYPR();
  58531. }
  58532. this._quaternionToRotationMatrix();
  58533. this._rotMatrix.invertToRef(this._invertMatrix);
  58534. for (var pt = 0; pt < this._shape.length; pt++) {
  58535. idx = index + pt * 3;
  58536. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58537. this._fixedNormal32[idx] = this._normal.x;
  58538. this._fixedNormal32[idx + 1] = this._normal.y;
  58539. this._fixedNormal32[idx + 2] = this._normal.z;
  58540. }
  58541. index = idx + 3;
  58542. }
  58543. };
  58544. //reset copy
  58545. SolidParticleSystem.prototype._resetCopy = function () {
  58546. this._copy.position.x = 0;
  58547. this._copy.position.y = 0;
  58548. this._copy.position.z = 0;
  58549. this._copy.rotation.x = 0;
  58550. this._copy.rotation.y = 0;
  58551. this._copy.rotation.z = 0;
  58552. this._copy.rotationQuaternion = null;
  58553. this._copy.scaling.x = 1.0;
  58554. this._copy.scaling.y = 1.0;
  58555. this._copy.scaling.z = 1.0;
  58556. this._copy.uvs.x = 0;
  58557. this._copy.uvs.y = 0;
  58558. this._copy.uvs.z = 1.0;
  58559. this._copy.uvs.w = 1.0;
  58560. this._copy.color = null;
  58561. this._copy.translateFromPivot = false;
  58562. };
  58563. // _meshBuilder : inserts the shape model in the global SPS mesh
  58564. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58565. var i;
  58566. var u = 0;
  58567. var c = 0;
  58568. var n = 0;
  58569. this._resetCopy();
  58570. if (options && options.positionFunction) { // call to custom positionFunction
  58571. options.positionFunction(this._copy, idx, idxInShape);
  58572. this._mustUnrotateFixedNormals = true;
  58573. }
  58574. if (this._copy.rotationQuaternion) {
  58575. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58576. }
  58577. else {
  58578. this._yaw = this._copy.rotation.y;
  58579. this._pitch = this._copy.rotation.x;
  58580. this._roll = this._copy.rotation.z;
  58581. this._quaternionRotationYPR();
  58582. }
  58583. this._quaternionToRotationMatrix();
  58584. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58585. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58586. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58587. if (this._copy.translateFromPivot) {
  58588. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58589. }
  58590. else {
  58591. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58592. }
  58593. for (i = 0; i < shape.length; i++) {
  58594. this._vertex.x = shape[i].x;
  58595. this._vertex.y = shape[i].y;
  58596. this._vertex.z = shape[i].z;
  58597. if (options && options.vertexFunction) {
  58598. options.vertexFunction(this._copy, this._vertex, i);
  58599. }
  58600. this._vertex.x *= this._copy.scaling.x;
  58601. this._vertex.y *= this._copy.scaling.y;
  58602. this._vertex.z *= this._copy.scaling.z;
  58603. this._vertex.x -= this._scaledPivot.x;
  58604. this._vertex.y -= this._scaledPivot.y;
  58605. this._vertex.z -= this._scaledPivot.z;
  58606. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58607. this._rotated.addInPlace(this._pivotBackTranslation);
  58608. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58609. if (meshUV) {
  58610. 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);
  58611. u += 2;
  58612. }
  58613. if (this._copy.color) {
  58614. this._color = this._copy.color;
  58615. }
  58616. else if (meshCol && meshCol[c] !== undefined) {
  58617. this._color.r = meshCol[c];
  58618. this._color.g = meshCol[c + 1];
  58619. this._color.b = meshCol[c + 2];
  58620. this._color.a = meshCol[c + 3];
  58621. }
  58622. else {
  58623. this._color.r = 1.0;
  58624. this._color.g = 1.0;
  58625. this._color.b = 1.0;
  58626. this._color.a = 1.0;
  58627. }
  58628. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58629. c += 4;
  58630. if (!this.recomputeNormals && meshNor) {
  58631. this._normal.x = meshNor[n];
  58632. this._normal.y = meshNor[n + 1];
  58633. this._normal.z = meshNor[n + 2];
  58634. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58635. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58636. n += 3;
  58637. }
  58638. }
  58639. for (i = 0; i < meshInd.length; i++) {
  58640. var current_ind = p + meshInd[i];
  58641. indices.push(current_ind);
  58642. if (current_ind > 65535) {
  58643. this._needs32Bits = true;
  58644. }
  58645. }
  58646. if (this._pickable) {
  58647. var nbfaces = meshInd.length / 3;
  58648. for (i = 0; i < nbfaces; i++) {
  58649. this.pickedParticles.push({ idx: idx, faceId: i });
  58650. }
  58651. }
  58652. if (this._depthSort) {
  58653. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58654. }
  58655. return this._copy;
  58656. };
  58657. // returns a shape array from positions array
  58658. SolidParticleSystem.prototype._posToShape = function (positions) {
  58659. var shape = [];
  58660. for (var i = 0; i < positions.length; i += 3) {
  58661. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58662. }
  58663. return shape;
  58664. };
  58665. // returns a shapeUV array from a Vector4 uvs
  58666. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58667. var shapeUV = [];
  58668. if (uvs) {
  58669. for (var i = 0; i < uvs.length; i++)
  58670. shapeUV.push(uvs[i]);
  58671. }
  58672. return shapeUV;
  58673. };
  58674. // adds a new particle object in the particles array
  58675. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58676. if (bInfo === void 0) { bInfo = null; }
  58677. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58678. this.particles.push(sp);
  58679. return sp;
  58680. };
  58681. /**
  58682. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58683. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58684. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58685. * @param nb (positive integer) the number of particles to be created from this model
  58686. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58687. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58688. * @returns the number of shapes in the system
  58689. */
  58690. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58691. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58692. var meshInd = mesh.getIndices();
  58693. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58694. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58695. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58696. var bbInfo;
  58697. if (this._particlesIntersect) {
  58698. bbInfo = mesh.getBoundingInfo();
  58699. }
  58700. var shape = this._posToShape(meshPos);
  58701. var shapeUV = this._uvsToShapeUV(meshUV);
  58702. var posfunc = options ? options.positionFunction : null;
  58703. var vtxfunc = options ? options.vertexFunction : null;
  58704. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58705. // particles
  58706. var sp;
  58707. var currentCopy;
  58708. var idx = this.nbParticles;
  58709. for (var i = 0; i < nb; i++) {
  58710. var currentPos = this._positions.length;
  58711. var currentInd = this._indices.length;
  58712. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58713. if (this._updatable) {
  58714. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58715. sp.position.copyFrom(currentCopy.position);
  58716. sp.rotation.copyFrom(currentCopy.rotation);
  58717. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58718. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58719. }
  58720. if (currentCopy.color && sp.color) {
  58721. sp.color.copyFrom(currentCopy.color);
  58722. }
  58723. sp.scaling.copyFrom(currentCopy.scaling);
  58724. sp.uvs.copyFrom(currentCopy.uvs);
  58725. }
  58726. this._index += shape.length;
  58727. idx++;
  58728. }
  58729. this.nbParticles += nb;
  58730. this._shapeCounter++;
  58731. return this._shapeCounter - 1;
  58732. };
  58733. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58734. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58735. this._resetCopy();
  58736. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58737. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58738. }
  58739. if (this._copy.rotationQuaternion) {
  58740. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58741. }
  58742. else {
  58743. this._yaw = this._copy.rotation.y;
  58744. this._pitch = this._copy.rotation.x;
  58745. this._roll = this._copy.rotation.z;
  58746. this._quaternionRotationYPR();
  58747. }
  58748. this._quaternionToRotationMatrix();
  58749. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58750. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58751. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58752. if (this._copy.translateFromPivot) {
  58753. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58754. }
  58755. else {
  58756. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58757. }
  58758. this._shape = particle._model._shape;
  58759. for (var pt = 0; pt < this._shape.length; pt++) {
  58760. this._vertex.x = this._shape[pt].x;
  58761. this._vertex.y = this._shape[pt].y;
  58762. this._vertex.z = this._shape[pt].z;
  58763. if (particle._model._vertexFunction) {
  58764. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58765. }
  58766. this._vertex.x *= this._copy.scaling.x;
  58767. this._vertex.y *= this._copy.scaling.y;
  58768. this._vertex.z *= this._copy.scaling.z;
  58769. this._vertex.x -= this._scaledPivot.x;
  58770. this._vertex.y -= this._scaledPivot.y;
  58771. this._vertex.z -= this._scaledPivot.z;
  58772. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58773. this._rotated.addInPlace(this._pivotBackTranslation);
  58774. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58775. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58776. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58777. }
  58778. particle.position.x = 0.0;
  58779. particle.position.y = 0.0;
  58780. particle.position.z = 0.0;
  58781. particle.rotation.x = 0.0;
  58782. particle.rotation.y = 0.0;
  58783. particle.rotation.z = 0.0;
  58784. particle.rotationQuaternion = null;
  58785. particle.scaling.x = 1.0;
  58786. particle.scaling.y = 1.0;
  58787. particle.scaling.z = 1.0;
  58788. particle.uvs.x = 0.0;
  58789. particle.uvs.y = 0.0;
  58790. particle.uvs.z = 1.0;
  58791. particle.uvs.w = 1.0;
  58792. particle.pivot.x = 0.0;
  58793. particle.pivot.y = 0.0;
  58794. particle.pivot.z = 0.0;
  58795. particle.translateFromPivot = false;
  58796. particle.parentId = null;
  58797. };
  58798. /**
  58799. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58800. * @returns the SPS.
  58801. */
  58802. SolidParticleSystem.prototype.rebuildMesh = function () {
  58803. for (var p = 0; p < this.particles.length; p++) {
  58804. this._rebuildParticle(this.particles[p]);
  58805. }
  58806. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58807. return this;
  58808. };
  58809. /**
  58810. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58811. * This method calls `updateParticle()` for each particle of the SPS.
  58812. * For an animated SPS, it is usually called within the render loop.
  58813. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58814. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58815. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58816. * @returns the SPS.
  58817. */
  58818. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58819. if (start === void 0) { start = 0; }
  58820. if (end === void 0) { end = this.nbParticles - 1; }
  58821. if (update === void 0) { update = true; }
  58822. if (!this._updatable) {
  58823. return this;
  58824. }
  58825. // custom beforeUpdate
  58826. this.beforeUpdateParticles(start, end, update);
  58827. this._cam_axisX.x = 1.0;
  58828. this._cam_axisX.y = 0.0;
  58829. this._cam_axisX.z = 0.0;
  58830. this._cam_axisY.x = 0.0;
  58831. this._cam_axisY.y = 1.0;
  58832. this._cam_axisY.z = 0.0;
  58833. this._cam_axisZ.x = 0.0;
  58834. this._cam_axisZ.y = 0.0;
  58835. this._cam_axisZ.z = 1.0;
  58836. // cases when the World Matrix is to be computed first
  58837. if (this.billboard || this._depthSort) {
  58838. this.mesh.computeWorldMatrix(true);
  58839. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58840. }
  58841. // if the particles will always face the camera
  58842. if (this.billboard) {
  58843. // compute the camera position and un-rotate it by the current mesh rotation
  58844. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58845. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58846. this._cam_axisZ.normalize();
  58847. // same for camera up vector extracted from the cam view matrix
  58848. var view = this._camera.getViewMatrix(true);
  58849. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58850. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58851. this._cam_axisY.normalize();
  58852. this._cam_axisX.normalize();
  58853. }
  58854. // if depthSort, compute the camera global position in the mesh local system
  58855. if (this._depthSort) {
  58856. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58857. }
  58858. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58859. var idx = 0; // current position index in the global array positions32
  58860. var index = 0; // position start index in the global array positions32 of the current particle
  58861. var colidx = 0; // current color index in the global array colors32
  58862. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58863. var uvidx = 0; // current uv index in the global array uvs32
  58864. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58865. var pt = 0; // current index in the particle model shape
  58866. if (this.mesh.isFacetDataEnabled) {
  58867. this._computeBoundingBox = true;
  58868. }
  58869. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58870. if (this._computeBoundingBox) {
  58871. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58872. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58873. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58874. }
  58875. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58876. if (this.mesh._boundingInfo) {
  58877. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58878. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58879. }
  58880. }
  58881. }
  58882. // particle loop
  58883. index = this.particles[start]._pos;
  58884. var vpos = (index / 3) | 0;
  58885. colorIndex = vpos * 4;
  58886. uvIndex = vpos * 2;
  58887. for (var p = start; p <= end; p++) {
  58888. this._particle = this.particles[p];
  58889. this._shape = this._particle._model._shape;
  58890. this._shapeUV = this._particle._model._shapeUV;
  58891. // call to custom user function to update the particle properties
  58892. this.updateParticle(this._particle);
  58893. // camera-particle distance for depth sorting
  58894. if (this._depthSort && this._depthSortParticles) {
  58895. var dsp = this.depthSortedParticles[p];
  58896. dsp.ind = this._particle._ind;
  58897. dsp.indicesLength = this._particle._model._indicesLength;
  58898. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58899. }
  58900. // skip the computations for inactive or already invisible particles
  58901. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58902. // increment indexes for the next particle
  58903. pt = this._shape.length;
  58904. index += pt * 3;
  58905. colorIndex += pt * 4;
  58906. uvIndex += pt * 2;
  58907. continue;
  58908. }
  58909. if (this._particle.isVisible) {
  58910. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58911. this._particleHasParent = (this._particle.parentId !== null);
  58912. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58913. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58914. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58915. // particle rotation matrix
  58916. if (this.billboard) {
  58917. this._particle.rotation.x = 0.0;
  58918. this._particle.rotation.y = 0.0;
  58919. }
  58920. if (this._computeParticleRotation || this.billboard) {
  58921. if (this._particle.rotationQuaternion) {
  58922. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58923. }
  58924. else {
  58925. this._yaw = this._particle.rotation.y;
  58926. this._pitch = this._particle.rotation.x;
  58927. this._roll = this._particle.rotation.z;
  58928. this._quaternionRotationYPR();
  58929. }
  58930. this._quaternionToRotationMatrix();
  58931. }
  58932. if (this._particleHasParent) {
  58933. this._parent = this.particles[this._particle.parentId];
  58934. 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];
  58935. 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];
  58936. 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];
  58937. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58938. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58939. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58940. if (this._computeParticleRotation || this.billboard) {
  58941. 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];
  58942. 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];
  58943. 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];
  58944. 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];
  58945. 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];
  58946. 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];
  58947. 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];
  58948. 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];
  58949. 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];
  58950. }
  58951. }
  58952. else {
  58953. this._particle._globalPosition.x = this._particle.position.x;
  58954. this._particle._globalPosition.y = this._particle.position.y;
  58955. this._particle._globalPosition.z = this._particle.position.z;
  58956. if (this._computeParticleRotation || this.billboard) {
  58957. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58958. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58959. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58960. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58961. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58962. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58963. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58964. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58965. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58966. }
  58967. }
  58968. if (this._particle.translateFromPivot) {
  58969. this._pivotBackTranslation.x = 0.0;
  58970. this._pivotBackTranslation.y = 0.0;
  58971. this._pivotBackTranslation.z = 0.0;
  58972. }
  58973. else {
  58974. this._pivotBackTranslation.x = this._scaledPivot.x;
  58975. this._pivotBackTranslation.y = this._scaledPivot.y;
  58976. this._pivotBackTranslation.z = this._scaledPivot.z;
  58977. }
  58978. // particle vertex loop
  58979. for (pt = 0; pt < this._shape.length; pt++) {
  58980. idx = index + pt * 3;
  58981. colidx = colorIndex + pt * 4;
  58982. uvidx = uvIndex + pt * 2;
  58983. this._vertex.x = this._shape[pt].x;
  58984. this._vertex.y = this._shape[pt].y;
  58985. this._vertex.z = this._shape[pt].z;
  58986. if (this._computeParticleVertex) {
  58987. this.updateParticleVertex(this._particle, this._vertex, pt);
  58988. }
  58989. // positions
  58990. this._vertex.x *= this._particle.scaling.x;
  58991. this._vertex.y *= this._particle.scaling.y;
  58992. this._vertex.z *= this._particle.scaling.z;
  58993. this._vertex.x -= this._scaledPivot.x;
  58994. this._vertex.y -= this._scaledPivot.y;
  58995. this._vertex.z -= this._scaledPivot.z;
  58996. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58997. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58998. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58999. this._rotated.x += this._pivotBackTranslation.x;
  59000. this._rotated.y += this._pivotBackTranslation.y;
  59001. this._rotated.z += this._pivotBackTranslation.z;
  59002. 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;
  59003. 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;
  59004. 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;
  59005. if (this._computeBoundingBox) {
  59006. if (this._positions32[idx] < this._minimum.x) {
  59007. this._minimum.x = this._positions32[idx];
  59008. }
  59009. if (this._positions32[idx] > this._maximum.x) {
  59010. this._maximum.x = this._positions32[idx];
  59011. }
  59012. if (this._positions32[idx + 1] < this._minimum.y) {
  59013. this._minimum.y = this._positions32[idx + 1];
  59014. }
  59015. if (this._positions32[idx + 1] > this._maximum.y) {
  59016. this._maximum.y = this._positions32[idx + 1];
  59017. }
  59018. if (this._positions32[idx + 2] < this._minimum.z) {
  59019. this._minimum.z = this._positions32[idx + 2];
  59020. }
  59021. if (this._positions32[idx + 2] > this._maximum.z) {
  59022. this._maximum.z = this._positions32[idx + 2];
  59023. }
  59024. }
  59025. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59026. if (!this._computeParticleVertex) {
  59027. this._normal.x = this._fixedNormal32[idx];
  59028. this._normal.y = this._fixedNormal32[idx + 1];
  59029. this._normal.z = this._fixedNormal32[idx + 2];
  59030. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59031. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59032. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59033. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59034. 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;
  59035. 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;
  59036. }
  59037. if (this._computeParticleColor && this._particle.color) {
  59038. this._colors32[colidx] = this._particle.color.r;
  59039. this._colors32[colidx + 1] = this._particle.color.g;
  59040. this._colors32[colidx + 2] = this._particle.color.b;
  59041. this._colors32[colidx + 3] = this._particle.color.a;
  59042. }
  59043. if (this._computeParticleTexture) {
  59044. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59045. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59046. }
  59047. }
  59048. }
  59049. // particle just set invisible : scaled to zero and positioned at the origin
  59050. else {
  59051. this._particle._stillInvisible = true; // mark the particle as invisible
  59052. for (pt = 0; pt < this._shape.length; pt++) {
  59053. idx = index + pt * 3;
  59054. colidx = colorIndex + pt * 4;
  59055. uvidx = uvIndex + pt * 2;
  59056. this._positions32[idx] = 0.0;
  59057. this._positions32[idx + 1] = 0.0;
  59058. this._positions32[idx + 2] = 0.0;
  59059. this._normals32[idx] = 0.0;
  59060. this._normals32[idx + 1] = 0.0;
  59061. this._normals32[idx + 2] = 0.0;
  59062. if (this._computeParticleColor && this._particle.color) {
  59063. this._colors32[colidx] = this._particle.color.r;
  59064. this._colors32[colidx + 1] = this._particle.color.g;
  59065. this._colors32[colidx + 2] = this._particle.color.b;
  59066. this._colors32[colidx + 3] = this._particle.color.a;
  59067. }
  59068. if (this._computeParticleTexture) {
  59069. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59070. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59071. }
  59072. }
  59073. }
  59074. // if the particle intersections must be computed : update the bbInfo
  59075. if (this._particlesIntersect) {
  59076. var bInfo = this._particle._boundingInfo;
  59077. var bBox = bInfo.boundingBox;
  59078. var bSphere = bInfo.boundingSphere;
  59079. if (!this._bSphereOnly) {
  59080. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59081. for (var b = 0; b < bBox.vectors.length; b++) {
  59082. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59083. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59084. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59085. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59086. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59087. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59088. 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;
  59089. 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;
  59090. 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;
  59091. }
  59092. bBox._update(this.mesh._worldMatrix);
  59093. }
  59094. // place and scale the particle bouding sphere in the SPS local system, then update it
  59095. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59096. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59097. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59098. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59099. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59100. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59101. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59102. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59103. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59104. 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));
  59105. bSphere._update(this.mesh._worldMatrix);
  59106. }
  59107. // increment indexes for the next particle
  59108. index = idx + 3;
  59109. colorIndex = colidx + 4;
  59110. uvIndex = uvidx + 2;
  59111. }
  59112. // if the VBO must be updated
  59113. if (update) {
  59114. if (this._computeParticleColor) {
  59115. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59116. }
  59117. if (this._computeParticleTexture) {
  59118. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59119. }
  59120. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59121. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59122. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59123. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59124. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59125. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59126. for (var i = 0; i < this._normals32.length; i++) {
  59127. this._fixedNormal32[i] = this._normals32[i];
  59128. }
  59129. }
  59130. if (!this.mesh.areNormalsFrozen) {
  59131. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59132. }
  59133. }
  59134. if (this._depthSort && this._depthSortParticles) {
  59135. this.depthSortedParticles.sort(this._depthSortFunction);
  59136. var dspl = this.depthSortedParticles.length;
  59137. var sorted = 0;
  59138. var lind = 0;
  59139. var sind = 0;
  59140. var sid = 0;
  59141. for (sorted = 0; sorted < dspl; sorted++) {
  59142. lind = this.depthSortedParticles[sorted].indicesLength;
  59143. sind = this.depthSortedParticles[sorted].ind;
  59144. for (var i = 0; i < lind; i++) {
  59145. this._indices32[sid] = this._indices[sind + i];
  59146. sid++;
  59147. }
  59148. }
  59149. this.mesh.updateIndices(this._indices32);
  59150. }
  59151. }
  59152. if (this._computeBoundingBox) {
  59153. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59154. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59155. }
  59156. this.afterUpdateParticles(start, end, update);
  59157. return this;
  59158. };
  59159. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59160. this._halfroll = this._roll * 0.5;
  59161. this._halfpitch = this._pitch * 0.5;
  59162. this._halfyaw = this._yaw * 0.5;
  59163. this._sinRoll = Math.sin(this._halfroll);
  59164. this._cosRoll = Math.cos(this._halfroll);
  59165. this._sinPitch = Math.sin(this._halfpitch);
  59166. this._cosPitch = Math.cos(this._halfpitch);
  59167. this._sinYaw = Math.sin(this._halfyaw);
  59168. this._cosYaw = Math.cos(this._halfyaw);
  59169. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59170. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59171. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59172. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59173. };
  59174. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59175. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59176. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59177. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59178. this._rotMatrix.m[3] = 0;
  59179. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59180. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59181. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59182. this._rotMatrix.m[7] = 0;
  59183. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59184. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59185. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59186. this._rotMatrix.m[11] = 0;
  59187. this._rotMatrix.m[12] = 0;
  59188. this._rotMatrix.m[13] = 0;
  59189. this._rotMatrix.m[14] = 0;
  59190. this._rotMatrix.m[15] = 1.0;
  59191. };
  59192. /**
  59193. * Disposes the SPS.
  59194. */
  59195. SolidParticleSystem.prototype.dispose = function () {
  59196. this.mesh.dispose();
  59197. this.vars = null;
  59198. // drop references to internal big arrays for the GC
  59199. this._positions = null;
  59200. this._indices = null;
  59201. this._normals = null;
  59202. this._uvs = null;
  59203. this._colors = null;
  59204. this._indices32 = null;
  59205. this._positions32 = null;
  59206. this._normals32 = null;
  59207. this._fixedNormal32 = null;
  59208. this._uvs32 = null;
  59209. this._colors32 = null;
  59210. this.pickedParticles = null;
  59211. };
  59212. /**
  59213. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59214. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59215. * @returns the SPS.
  59216. */
  59217. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59218. if (!this._isVisibilityBoxLocked) {
  59219. this.mesh.refreshBoundingInfo();
  59220. }
  59221. return this;
  59222. };
  59223. /**
  59224. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59225. * @param size the size (float) of the visibility box
  59226. * note : this doesn't lock the SPS mesh bounding box.
  59227. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59228. */
  59229. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59230. var vis = size / 2;
  59231. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59232. };
  59233. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59234. /**
  59235. * Gets whether the SPS as always visible or not
  59236. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59237. */
  59238. get: function () {
  59239. return this._alwaysVisible;
  59240. },
  59241. /**
  59242. * Sets the SPS as always visible or not
  59243. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59244. */
  59245. set: function (val) {
  59246. this._alwaysVisible = val;
  59247. this.mesh.alwaysSelectAsActiveMesh = val;
  59248. },
  59249. enumerable: true,
  59250. configurable: true
  59251. });
  59252. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59253. /**
  59254. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59255. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59256. */
  59257. get: function () {
  59258. return this._isVisibilityBoxLocked;
  59259. },
  59260. /**
  59261. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59262. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59263. */
  59264. set: function (val) {
  59265. this._isVisibilityBoxLocked = val;
  59266. var boundingInfo = this.mesh.getBoundingInfo();
  59267. boundingInfo.isLocked = val;
  59268. },
  59269. enumerable: true,
  59270. configurable: true
  59271. });
  59272. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59273. /**
  59274. * Gets if `setParticles()` computes the particle rotations or not.
  59275. * Default value : true. The SPS is faster when it's set to false.
  59276. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59277. */
  59278. get: function () {
  59279. return this._computeParticleRotation;
  59280. },
  59281. /**
  59282. * Tells to `setParticles()` to compute the particle rotations or not.
  59283. * Default value : true. The SPS is faster when it's set to false.
  59284. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59285. */
  59286. set: function (val) {
  59287. this._computeParticleRotation = val;
  59288. },
  59289. enumerable: true,
  59290. configurable: true
  59291. });
  59292. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59293. /**
  59294. * Gets if `setParticles()` computes the particle colors or not.
  59295. * Default value : true. The SPS is faster when it's set to false.
  59296. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59297. */
  59298. get: function () {
  59299. return this._computeParticleColor;
  59300. },
  59301. /**
  59302. * Tells to `setParticles()` to compute the particle colors or not.
  59303. * Default value : true. The SPS is faster when it's set to false.
  59304. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59305. */
  59306. set: function (val) {
  59307. this._computeParticleColor = val;
  59308. },
  59309. enumerable: true,
  59310. configurable: true
  59311. });
  59312. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59313. /**
  59314. * Gets if `setParticles()` computes the particle textures or not.
  59315. * Default value : true. The SPS is faster when it's set to false.
  59316. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59317. */
  59318. get: function () {
  59319. return this._computeParticleTexture;
  59320. },
  59321. set: function (val) {
  59322. this._computeParticleTexture = val;
  59323. },
  59324. enumerable: true,
  59325. configurable: true
  59326. });
  59327. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59328. /**
  59329. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59330. * Default value : false. The SPS is faster when it's set to false.
  59331. * Note : the particle custom vertex positions aren't stored values.
  59332. */
  59333. get: function () {
  59334. return this._computeParticleVertex;
  59335. },
  59336. /**
  59337. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59338. * Default value : false. The SPS is faster when it's set to false.
  59339. * Note : the particle custom vertex positions aren't stored values.
  59340. */
  59341. set: function (val) {
  59342. this._computeParticleVertex = val;
  59343. },
  59344. enumerable: true,
  59345. configurable: true
  59346. });
  59347. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59348. /**
  59349. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59350. */
  59351. get: function () {
  59352. return this._computeBoundingBox;
  59353. },
  59354. /**
  59355. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59356. */
  59357. set: function (val) {
  59358. this._computeBoundingBox = val;
  59359. },
  59360. enumerable: true,
  59361. configurable: true
  59362. });
  59363. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59364. /**
  59365. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59366. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59367. * Default : `true`
  59368. */
  59369. get: function () {
  59370. return this._depthSortParticles;
  59371. },
  59372. /**
  59373. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59374. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59375. * Default : `true`
  59376. */
  59377. set: function (val) {
  59378. this._depthSortParticles = val;
  59379. },
  59380. enumerable: true,
  59381. configurable: true
  59382. });
  59383. // =======================================================================
  59384. // Particle behavior logic
  59385. // these following methods may be overwritten by the user to fit his needs
  59386. /**
  59387. * This function does nothing. It may be overwritten to set all the particle first values.
  59388. * The SPS doesn't call this function, you may have to call it by your own.
  59389. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59390. */
  59391. SolidParticleSystem.prototype.initParticles = function () {
  59392. };
  59393. /**
  59394. * This function does nothing. It may be overwritten to recycle a particle.
  59395. * The SPS doesn't call this function, you may have to call it by your own.
  59396. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59397. * @param particle The particle to recycle
  59398. * @returns the recycled particle
  59399. */
  59400. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59401. return particle;
  59402. };
  59403. /**
  59404. * Updates a particle : this function should be overwritten by the user.
  59405. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59406. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59407. * @example : just set a particle position or velocity and recycle conditions
  59408. * @param particle The particle to update
  59409. * @returns the updated particle
  59410. */
  59411. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59412. return particle;
  59413. };
  59414. /**
  59415. * Updates a vertex of a particle : it can be overwritten by the user.
  59416. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59417. * @param particle the current particle
  59418. * @param vertex the current index of the current particle
  59419. * @param pt the index of the current vertex in the particle shape
  59420. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59421. * @example : just set a vertex particle position
  59422. * @returns the updated vertex
  59423. */
  59424. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59425. return vertex;
  59426. };
  59427. /**
  59428. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59429. * This does nothing and may be overwritten by the user.
  59430. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59431. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59432. * @param update the boolean update value actually passed to setParticles()
  59433. */
  59434. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59435. };
  59436. /**
  59437. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59438. * This will be passed three parameters.
  59439. * This does nothing and may be overwritten by the user.
  59440. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59441. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59442. * @param update the boolean update value actually passed to setParticles()
  59443. */
  59444. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59445. };
  59446. return SolidParticleSystem;
  59447. }());
  59448. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59449. })(BABYLON || (BABYLON = {}));
  59450. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59451. var BABYLON;
  59452. (function (BABYLON) {
  59453. var ShaderMaterial = /** @class */ (function (_super) {
  59454. __extends(ShaderMaterial, _super);
  59455. function ShaderMaterial(name, scene, shaderPath, options) {
  59456. var _this = _super.call(this, name, scene) || this;
  59457. _this._textures = {};
  59458. _this._textureArrays = {};
  59459. _this._floats = {};
  59460. _this._ints = {};
  59461. _this._floatsArrays = {};
  59462. _this._colors3 = {};
  59463. _this._colors3Arrays = {};
  59464. _this._colors4 = {};
  59465. _this._vectors2 = {};
  59466. _this._vectors3 = {};
  59467. _this._vectors4 = {};
  59468. _this._matrices = {};
  59469. _this._matrices3x3 = {};
  59470. _this._matrices2x2 = {};
  59471. _this._vectors2Arrays = {};
  59472. _this._vectors3Arrays = {};
  59473. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59474. _this._shaderPath = shaderPath;
  59475. options.needAlphaBlending = options.needAlphaBlending || false;
  59476. options.needAlphaTesting = options.needAlphaTesting || false;
  59477. options.attributes = options.attributes || ["position", "normal", "uv"];
  59478. options.uniforms = options.uniforms || ["worldViewProjection"];
  59479. options.uniformBuffers = options.uniformBuffers || [];
  59480. options.samplers = options.samplers || [];
  59481. options.defines = options.defines || [];
  59482. _this._options = options;
  59483. return _this;
  59484. }
  59485. ShaderMaterial.prototype.getClassName = function () {
  59486. return "ShaderMaterial";
  59487. };
  59488. ShaderMaterial.prototype.needAlphaBlending = function () {
  59489. return this._options.needAlphaBlending;
  59490. };
  59491. ShaderMaterial.prototype.needAlphaTesting = function () {
  59492. return this._options.needAlphaTesting;
  59493. };
  59494. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59495. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59496. this._options.uniforms.push(uniformName);
  59497. }
  59498. };
  59499. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59500. if (this._options.samplers.indexOf(name) === -1) {
  59501. this._options.samplers.push(name);
  59502. }
  59503. this._textures[name] = texture;
  59504. return this;
  59505. };
  59506. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59507. if (this._options.samplers.indexOf(name) === -1) {
  59508. this._options.samplers.push(name);
  59509. }
  59510. this._checkUniform(name);
  59511. this._textureArrays[name] = textures;
  59512. return this;
  59513. };
  59514. ShaderMaterial.prototype.setFloat = function (name, value) {
  59515. this._checkUniform(name);
  59516. this._floats[name] = value;
  59517. return this;
  59518. };
  59519. ShaderMaterial.prototype.setInt = function (name, value) {
  59520. this._checkUniform(name);
  59521. this._ints[name] = value;
  59522. return this;
  59523. };
  59524. ShaderMaterial.prototype.setFloats = function (name, value) {
  59525. this._checkUniform(name);
  59526. this._floatsArrays[name] = value;
  59527. return this;
  59528. };
  59529. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59530. this._checkUniform(name);
  59531. this._colors3[name] = value;
  59532. return this;
  59533. };
  59534. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59535. this._checkUniform(name);
  59536. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59537. color.toArray(arr, arr.length);
  59538. return arr;
  59539. }, []);
  59540. return this;
  59541. };
  59542. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59543. this._checkUniform(name);
  59544. this._colors4[name] = value;
  59545. return this;
  59546. };
  59547. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59548. this._checkUniform(name);
  59549. this._vectors2[name] = value;
  59550. return this;
  59551. };
  59552. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59553. this._checkUniform(name);
  59554. this._vectors3[name] = value;
  59555. return this;
  59556. };
  59557. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59558. this._checkUniform(name);
  59559. this._vectors4[name] = value;
  59560. return this;
  59561. };
  59562. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59563. this._checkUniform(name);
  59564. this._matrices[name] = value;
  59565. return this;
  59566. };
  59567. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59568. this._checkUniform(name);
  59569. this._matrices3x3[name] = value;
  59570. return this;
  59571. };
  59572. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59573. this._checkUniform(name);
  59574. this._matrices2x2[name] = value;
  59575. return this;
  59576. };
  59577. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59578. this._checkUniform(name);
  59579. this._vectors2Arrays[name] = value;
  59580. return this;
  59581. };
  59582. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59583. this._checkUniform(name);
  59584. this._vectors3Arrays[name] = value;
  59585. return this;
  59586. };
  59587. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59588. if (!mesh) {
  59589. return true;
  59590. }
  59591. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59592. return false;
  59593. }
  59594. return false;
  59595. };
  59596. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59597. var scene = this.getScene();
  59598. var engine = scene.getEngine();
  59599. if (!this.checkReadyOnEveryCall) {
  59600. if (this._renderId === scene.getRenderId()) {
  59601. if (this._checkCache(scene, mesh, useInstances)) {
  59602. return true;
  59603. }
  59604. }
  59605. }
  59606. // Instances
  59607. var defines = [];
  59608. var attribs = [];
  59609. var fallbacks = new BABYLON.EffectFallbacks();
  59610. if (useInstances) {
  59611. defines.push("#define INSTANCES");
  59612. }
  59613. for (var index = 0; index < this._options.defines.length; index++) {
  59614. defines.push(this._options.defines[index]);
  59615. }
  59616. for (var index = 0; index < this._options.attributes.length; index++) {
  59617. attribs.push(this._options.attributes[index]);
  59618. }
  59619. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59620. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59621. defines.push("#define VERTEXCOLOR");
  59622. }
  59623. // Bones
  59624. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59625. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59626. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59627. if (mesh.numBoneInfluencers > 4) {
  59628. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59629. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59630. }
  59631. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59632. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59633. fallbacks.addCPUSkinningFallback(0, mesh);
  59634. if (this._options.uniforms.indexOf("mBones") === -1) {
  59635. this._options.uniforms.push("mBones");
  59636. }
  59637. }
  59638. else {
  59639. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59640. }
  59641. // Textures
  59642. for (var name in this._textures) {
  59643. if (!this._textures[name].isReady()) {
  59644. return false;
  59645. }
  59646. }
  59647. // Alpha test
  59648. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59649. defines.push("#define ALPHATEST");
  59650. }
  59651. var previousEffect = this._effect;
  59652. var join = defines.join("\n");
  59653. this._effect = engine.createEffect(this._shaderPath, {
  59654. attributes: attribs,
  59655. uniformsNames: this._options.uniforms,
  59656. uniformBuffersNames: this._options.uniformBuffers,
  59657. samplers: this._options.samplers,
  59658. defines: join,
  59659. fallbacks: fallbacks,
  59660. onCompiled: this.onCompiled,
  59661. onError: this.onError
  59662. }, engine);
  59663. if (!this._effect.isReady()) {
  59664. return false;
  59665. }
  59666. if (previousEffect !== this._effect) {
  59667. scene.resetCachedMaterial();
  59668. }
  59669. this._renderId = scene.getRenderId();
  59670. return true;
  59671. };
  59672. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59673. var scene = this.getScene();
  59674. if (!this._effect) {
  59675. return;
  59676. }
  59677. if (this._options.uniforms.indexOf("world") !== -1) {
  59678. this._effect.setMatrix("world", world);
  59679. }
  59680. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59681. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59682. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59683. }
  59684. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59685. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59686. }
  59687. };
  59688. ShaderMaterial.prototype.bind = function (world, mesh) {
  59689. // Std values
  59690. this.bindOnlyWorldMatrix(world);
  59691. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59692. if (this._options.uniforms.indexOf("view") !== -1) {
  59693. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59694. }
  59695. if (this._options.uniforms.indexOf("projection") !== -1) {
  59696. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59697. }
  59698. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59699. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59700. }
  59701. // Bones
  59702. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59703. var name;
  59704. // Texture
  59705. for (name in this._textures) {
  59706. this._effect.setTexture(name, this._textures[name]);
  59707. }
  59708. // Texture arrays
  59709. for (name in this._textureArrays) {
  59710. this._effect.setTextureArray(name, this._textureArrays[name]);
  59711. }
  59712. // Int
  59713. for (name in this._ints) {
  59714. this._effect.setInt(name, this._ints[name]);
  59715. }
  59716. // Float
  59717. for (name in this._floats) {
  59718. this._effect.setFloat(name, this._floats[name]);
  59719. }
  59720. // Floats
  59721. for (name in this._floatsArrays) {
  59722. this._effect.setArray(name, this._floatsArrays[name]);
  59723. }
  59724. // Color3
  59725. for (name in this._colors3) {
  59726. this._effect.setColor3(name, this._colors3[name]);
  59727. }
  59728. for (name in this._colors3Arrays) {
  59729. this._effect.setArray3(name, this._colors3Arrays[name]);
  59730. }
  59731. // Color4
  59732. for (name in this._colors4) {
  59733. var color = this._colors4[name];
  59734. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59735. }
  59736. // Vector2
  59737. for (name in this._vectors2) {
  59738. this._effect.setVector2(name, this._vectors2[name]);
  59739. }
  59740. // Vector3
  59741. for (name in this._vectors3) {
  59742. this._effect.setVector3(name, this._vectors3[name]);
  59743. }
  59744. // Vector4
  59745. for (name in this._vectors4) {
  59746. this._effect.setVector4(name, this._vectors4[name]);
  59747. }
  59748. // Matrix
  59749. for (name in this._matrices) {
  59750. this._effect.setMatrix(name, this._matrices[name]);
  59751. }
  59752. // Matrix 3x3
  59753. for (name in this._matrices3x3) {
  59754. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59755. }
  59756. // Matrix 2x2
  59757. for (name in this._matrices2x2) {
  59758. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59759. }
  59760. // Vector2Array
  59761. for (name in this._vectors2Arrays) {
  59762. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59763. }
  59764. // Vector3Array
  59765. for (name in this._vectors3Arrays) {
  59766. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59767. }
  59768. }
  59769. this._afterBind(mesh);
  59770. };
  59771. ShaderMaterial.prototype.getActiveTextures = function () {
  59772. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59773. for (var name in this._textures) {
  59774. activeTextures.push(this._textures[name]);
  59775. }
  59776. for (var name in this._textureArrays) {
  59777. var array = this._textureArrays[name];
  59778. for (var index = 0; index < array.length; index++) {
  59779. activeTextures.push(array[index]);
  59780. }
  59781. }
  59782. return activeTextures;
  59783. };
  59784. ShaderMaterial.prototype.hasTexture = function (texture) {
  59785. if (_super.prototype.hasTexture.call(this, texture)) {
  59786. return true;
  59787. }
  59788. for (var name in this._textures) {
  59789. if (this._textures[name] === texture) {
  59790. return true;
  59791. }
  59792. }
  59793. for (var name in this._textureArrays) {
  59794. var array = this._textureArrays[name];
  59795. for (var index = 0; index < array.length; index++) {
  59796. if (array[index] === texture) {
  59797. return true;
  59798. }
  59799. }
  59800. }
  59801. return false;
  59802. };
  59803. ShaderMaterial.prototype.clone = function (name) {
  59804. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59805. return newShaderMaterial;
  59806. };
  59807. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59808. if (forceDisposeTextures) {
  59809. var name;
  59810. for (name in this._textures) {
  59811. this._textures[name].dispose();
  59812. }
  59813. for (name in this._textureArrays) {
  59814. var array = this._textureArrays[name];
  59815. for (var index = 0; index < array.length; index++) {
  59816. array[index].dispose();
  59817. }
  59818. }
  59819. }
  59820. this._textures = {};
  59821. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59822. };
  59823. ShaderMaterial.prototype.serialize = function () {
  59824. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59825. serializationObject.customType = "BABYLON.ShaderMaterial";
  59826. serializationObject.options = this._options;
  59827. serializationObject.shaderPath = this._shaderPath;
  59828. var name;
  59829. // Texture
  59830. serializationObject.textures = {};
  59831. for (name in this._textures) {
  59832. serializationObject.textures[name] = this._textures[name].serialize();
  59833. }
  59834. // Texture arrays
  59835. serializationObject.textureArrays = {};
  59836. for (name in this._textureArrays) {
  59837. serializationObject.textureArrays[name] = [];
  59838. var array = this._textureArrays[name];
  59839. for (var index = 0; index < array.length; index++) {
  59840. serializationObject.textureArrays[name].push(array[index].serialize());
  59841. }
  59842. }
  59843. // Float
  59844. serializationObject.floats = {};
  59845. for (name in this._floats) {
  59846. serializationObject.floats[name] = this._floats[name];
  59847. }
  59848. // Float s
  59849. serializationObject.FloatArrays = {};
  59850. for (name in this._floatsArrays) {
  59851. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59852. }
  59853. // Color3
  59854. serializationObject.colors3 = {};
  59855. for (name in this._colors3) {
  59856. serializationObject.colors3[name] = this._colors3[name].asArray();
  59857. }
  59858. // Color3 array
  59859. serializationObject.colors3Arrays = {};
  59860. for (name in this._colors3Arrays) {
  59861. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59862. }
  59863. // Color4
  59864. serializationObject.colors4 = {};
  59865. for (name in this._colors4) {
  59866. serializationObject.colors4[name] = this._colors4[name].asArray();
  59867. }
  59868. // Vector2
  59869. serializationObject.vectors2 = {};
  59870. for (name in this._vectors2) {
  59871. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59872. }
  59873. // Vector3
  59874. serializationObject.vectors3 = {};
  59875. for (name in this._vectors3) {
  59876. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59877. }
  59878. // Vector4
  59879. serializationObject.vectors4 = {};
  59880. for (name in this._vectors4) {
  59881. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59882. }
  59883. // Matrix
  59884. serializationObject.matrices = {};
  59885. for (name in this._matrices) {
  59886. serializationObject.matrices[name] = this._matrices[name].asArray();
  59887. }
  59888. // Matrix 3x3
  59889. serializationObject.matrices3x3 = {};
  59890. for (name in this._matrices3x3) {
  59891. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59892. }
  59893. // Matrix 2x2
  59894. serializationObject.matrices2x2 = {};
  59895. for (name in this._matrices2x2) {
  59896. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59897. }
  59898. // Vector2Array
  59899. serializationObject.vectors2Arrays = {};
  59900. for (name in this._vectors2Arrays) {
  59901. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59902. }
  59903. // Vector3Array
  59904. serializationObject.vectors3Arrays = {};
  59905. for (name in this._vectors3Arrays) {
  59906. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59907. }
  59908. return serializationObject;
  59909. };
  59910. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59911. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59912. var name;
  59913. // Texture
  59914. for (name in source.textures) {
  59915. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59916. }
  59917. // Texture arrays
  59918. for (name in source.textureArrays) {
  59919. var array = source.textureArrays[name];
  59920. var textureArray = new Array();
  59921. for (var index = 0; index < array.length; index++) {
  59922. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59923. }
  59924. material.setTextureArray(name, textureArray);
  59925. }
  59926. // Float
  59927. for (name in source.floats) {
  59928. material.setFloat(name, source.floats[name]);
  59929. }
  59930. // Float s
  59931. for (name in source.floatsArrays) {
  59932. material.setFloats(name, source.floatsArrays[name]);
  59933. }
  59934. // Color3
  59935. for (name in source.colors3) {
  59936. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59937. }
  59938. // Color3 arrays
  59939. for (name in source.colors3Arrays) {
  59940. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59941. if (i % 3 === 0) {
  59942. arr.push([num]);
  59943. }
  59944. else {
  59945. arr[arr.length - 1].push(num);
  59946. }
  59947. return arr;
  59948. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59949. material.setColor3Array(name, colors);
  59950. }
  59951. // Color4
  59952. for (name in source.colors4) {
  59953. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59954. }
  59955. // Vector2
  59956. for (name in source.vectors2) {
  59957. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59958. }
  59959. // Vector3
  59960. for (name in source.vectors3) {
  59961. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59962. }
  59963. // Vector4
  59964. for (name in source.vectors4) {
  59965. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59966. }
  59967. // Matrix
  59968. for (name in source.matrices) {
  59969. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59970. }
  59971. // Matrix 3x3
  59972. for (name in source.matrices3x3) {
  59973. material.setMatrix3x3(name, source.matrices3x3[name]);
  59974. }
  59975. // Matrix 2x2
  59976. for (name in source.matrices2x2) {
  59977. material.setMatrix2x2(name, source.matrices2x2[name]);
  59978. }
  59979. // Vector2Array
  59980. for (name in source.vectors2Arrays) {
  59981. material.setArray2(name, source.vectors2Arrays[name]);
  59982. }
  59983. // Vector3Array
  59984. for (name in source.vectors3Arrays) {
  59985. material.setArray3(name, source.vectors3Arrays[name]);
  59986. }
  59987. return material;
  59988. };
  59989. return ShaderMaterial;
  59990. }(BABYLON.Material));
  59991. BABYLON.ShaderMaterial = ShaderMaterial;
  59992. })(BABYLON || (BABYLON = {}));
  59993. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59994. var BABYLON;
  59995. (function (BABYLON) {
  59996. var GroundMesh = /** @class */ (function (_super) {
  59997. __extends(GroundMesh, _super);
  59998. function GroundMesh(name, scene) {
  59999. var _this = _super.call(this, name, scene) || this;
  60000. _this.generateOctree = false;
  60001. return _this;
  60002. }
  60003. GroundMesh.prototype.getClassName = function () {
  60004. return "GroundMesh";
  60005. };
  60006. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60007. get: function () {
  60008. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60009. },
  60010. enumerable: true,
  60011. configurable: true
  60012. });
  60013. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60014. get: function () {
  60015. return this._subdivisionsX;
  60016. },
  60017. enumerable: true,
  60018. configurable: true
  60019. });
  60020. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60021. get: function () {
  60022. return this._subdivisionsY;
  60023. },
  60024. enumerable: true,
  60025. configurable: true
  60026. });
  60027. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60028. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60029. this._subdivisionsX = chunksCount;
  60030. this._subdivisionsY = chunksCount;
  60031. this.subdivide(chunksCount);
  60032. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60033. };
  60034. /**
  60035. * Returns a height (y) value in the Worl system :
  60036. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60037. * Returns the ground y position if (x, z) are outside the ground surface.
  60038. */
  60039. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60040. var world = this.getWorldMatrix();
  60041. var invMat = BABYLON.Tmp.Matrix[5];
  60042. world.invertToRef(invMat);
  60043. var tmpVect = BABYLON.Tmp.Vector3[8];
  60044. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60045. x = tmpVect.x;
  60046. z = tmpVect.z;
  60047. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60048. return this.position.y;
  60049. }
  60050. if (!this._heightQuads || this._heightQuads.length == 0) {
  60051. this._initHeightQuads();
  60052. this._computeHeightQuads();
  60053. }
  60054. var facet = this._getFacetAt(x, z);
  60055. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60056. // return y in the World system
  60057. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60058. return tmpVect.y;
  60059. };
  60060. /**
  60061. * Returns a normalized vector (Vector3) orthogonal to the ground
  60062. * at the ground coordinates (x, z) expressed in the World system.
  60063. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60064. */
  60065. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60066. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60067. this.getNormalAtCoordinatesToRef(x, z, normal);
  60068. return normal;
  60069. };
  60070. /**
  60071. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60072. * at the ground coordinates (x, z) expressed in the World system.
  60073. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60074. * Returns the GroundMesh.
  60075. */
  60076. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60077. var world = this.getWorldMatrix();
  60078. var tmpMat = BABYLON.Tmp.Matrix[5];
  60079. world.invertToRef(tmpMat);
  60080. var tmpVect = BABYLON.Tmp.Vector3[8];
  60081. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60082. x = tmpVect.x;
  60083. z = tmpVect.z;
  60084. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60085. return this;
  60086. }
  60087. if (!this._heightQuads || this._heightQuads.length == 0) {
  60088. this._initHeightQuads();
  60089. this._computeHeightQuads();
  60090. }
  60091. var facet = this._getFacetAt(x, z);
  60092. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60093. return this;
  60094. };
  60095. /**
  60096. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60097. * if the ground has been updated.
  60098. * This can be used in the render loop.
  60099. * Returns the GroundMesh.
  60100. */
  60101. GroundMesh.prototype.updateCoordinateHeights = function () {
  60102. if (!this._heightQuads || this._heightQuads.length == 0) {
  60103. this._initHeightQuads();
  60104. }
  60105. this._computeHeightQuads();
  60106. return this;
  60107. };
  60108. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60109. GroundMesh.prototype._getFacetAt = function (x, z) {
  60110. // retrieve col and row from x, z coordinates in the ground local system
  60111. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60112. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60113. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60114. var facet;
  60115. if (z < quad.slope.x * x + quad.slope.y) {
  60116. facet = quad.facet1;
  60117. }
  60118. else {
  60119. facet = quad.facet2;
  60120. }
  60121. return facet;
  60122. };
  60123. // Creates and populates the heightMap array with "facet" elements :
  60124. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60125. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60126. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60127. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60128. // Returns the GroundMesh.
  60129. GroundMesh.prototype._initHeightQuads = function () {
  60130. var subdivisionsX = this._subdivisionsX;
  60131. var subdivisionsY = this._subdivisionsY;
  60132. this._heightQuads = new Array();
  60133. for (var row = 0; row < subdivisionsY; row++) {
  60134. for (var col = 0; col < subdivisionsX; col++) {
  60135. 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) };
  60136. this._heightQuads[row * subdivisionsX + col] = quad;
  60137. }
  60138. }
  60139. return this;
  60140. };
  60141. // Compute each quad element values and update the the heightMap array :
  60142. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60143. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60144. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60145. // Returns the GroundMesh.
  60146. GroundMesh.prototype._computeHeightQuads = function () {
  60147. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60148. if (!positions) {
  60149. return this;
  60150. }
  60151. var v1 = BABYLON.Tmp.Vector3[3];
  60152. var v2 = BABYLON.Tmp.Vector3[2];
  60153. var v3 = BABYLON.Tmp.Vector3[1];
  60154. var v4 = BABYLON.Tmp.Vector3[0];
  60155. var v1v2 = BABYLON.Tmp.Vector3[4];
  60156. var v1v3 = BABYLON.Tmp.Vector3[5];
  60157. var v1v4 = BABYLON.Tmp.Vector3[6];
  60158. var norm1 = BABYLON.Tmp.Vector3[7];
  60159. var norm2 = BABYLON.Tmp.Vector3[8];
  60160. var i = 0;
  60161. var j = 0;
  60162. var k = 0;
  60163. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60164. var h = 0;
  60165. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60166. var d2 = 0;
  60167. var subdivisionsX = this._subdivisionsX;
  60168. var subdivisionsY = this._subdivisionsY;
  60169. for (var row = 0; row < subdivisionsY; row++) {
  60170. for (var col = 0; col < subdivisionsX; col++) {
  60171. i = col * 3;
  60172. j = row * (subdivisionsX + 1) * 3;
  60173. k = (row + 1) * (subdivisionsX + 1) * 3;
  60174. v1.x = positions[j + i];
  60175. v1.y = positions[j + i + 1];
  60176. v1.z = positions[j + i + 2];
  60177. v2.x = positions[j + i + 3];
  60178. v2.y = positions[j + i + 4];
  60179. v2.z = positions[j + i + 5];
  60180. v3.x = positions[k + i];
  60181. v3.y = positions[k + i + 1];
  60182. v3.z = positions[k + i + 2];
  60183. v4.x = positions[k + i + 3];
  60184. v4.y = positions[k + i + 4];
  60185. v4.z = positions[k + i + 5];
  60186. // 2D slope V1V4
  60187. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60188. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60189. // facet equations :
  60190. // we compute each facet normal vector
  60191. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60192. // we compute the value d by applying the equation to v1 which belongs to the plane
  60193. // then we store the facet equation in a Vector4
  60194. v2.subtractToRef(v1, v1v2);
  60195. v3.subtractToRef(v1, v1v3);
  60196. v4.subtractToRef(v1, v1v4);
  60197. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60198. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60199. norm1.normalize();
  60200. norm2.normalize();
  60201. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60202. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60203. var quad = this._heightQuads[row * subdivisionsX + col];
  60204. quad.slope.copyFromFloats(cd, h);
  60205. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60206. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60207. }
  60208. }
  60209. return this;
  60210. };
  60211. GroundMesh.prototype.serialize = function (serializationObject) {
  60212. _super.prototype.serialize.call(this, serializationObject);
  60213. serializationObject.subdivisionsX = this._subdivisionsX;
  60214. serializationObject.subdivisionsY = this._subdivisionsY;
  60215. serializationObject.minX = this._minX;
  60216. serializationObject.maxX = this._maxX;
  60217. serializationObject.minZ = this._minZ;
  60218. serializationObject.maxZ = this._maxZ;
  60219. serializationObject.width = this._width;
  60220. serializationObject.height = this._height;
  60221. };
  60222. GroundMesh.Parse = function (parsedMesh, scene) {
  60223. var result = new GroundMesh(parsedMesh.name, scene);
  60224. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60225. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60226. result._minX = parsedMesh.minX;
  60227. result._maxX = parsedMesh.maxX;
  60228. result._minZ = parsedMesh.minZ;
  60229. result._maxZ = parsedMesh.maxZ;
  60230. result._width = parsedMesh.width;
  60231. result._height = parsedMesh.height;
  60232. return result;
  60233. };
  60234. return GroundMesh;
  60235. }(BABYLON.Mesh));
  60236. BABYLON.GroundMesh = GroundMesh;
  60237. })(BABYLON || (BABYLON = {}));
  60238. //# sourceMappingURL=babylon.groundMesh.js.map
  60239. var BABYLON;
  60240. (function (BABYLON) {
  60241. /**
  60242. * Creates an instance based on a source mesh.
  60243. */
  60244. var InstancedMesh = /** @class */ (function (_super) {
  60245. __extends(InstancedMesh, _super);
  60246. function InstancedMesh(name, source) {
  60247. var _this = _super.call(this, name, source.getScene()) || this;
  60248. source.instances.push(_this);
  60249. _this._sourceMesh = source;
  60250. _this.position.copyFrom(source.position);
  60251. _this.rotation.copyFrom(source.rotation);
  60252. _this.scaling.copyFrom(source.scaling);
  60253. if (source.rotationQuaternion) {
  60254. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60255. }
  60256. _this.infiniteDistance = source.infiniteDistance;
  60257. _this.setPivotMatrix(source.getPivotMatrix());
  60258. _this.refreshBoundingInfo();
  60259. _this._syncSubMeshes();
  60260. return _this;
  60261. }
  60262. /**
  60263. * Returns the string "InstancedMesh".
  60264. */
  60265. InstancedMesh.prototype.getClassName = function () {
  60266. return "InstancedMesh";
  60267. };
  60268. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60269. // Methods
  60270. get: function () {
  60271. return this._sourceMesh.receiveShadows;
  60272. },
  60273. enumerable: true,
  60274. configurable: true
  60275. });
  60276. Object.defineProperty(InstancedMesh.prototype, "material", {
  60277. get: function () {
  60278. return this._sourceMesh.material;
  60279. },
  60280. enumerable: true,
  60281. configurable: true
  60282. });
  60283. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60284. get: function () {
  60285. return this._sourceMesh.visibility;
  60286. },
  60287. enumerable: true,
  60288. configurable: true
  60289. });
  60290. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60291. get: function () {
  60292. return this._sourceMesh.skeleton;
  60293. },
  60294. enumerable: true,
  60295. configurable: true
  60296. });
  60297. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60298. get: function () {
  60299. return this._sourceMesh.renderingGroupId;
  60300. },
  60301. set: function (value) {
  60302. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60303. return;
  60304. }
  60305. //no-op with warning
  60306. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60307. },
  60308. enumerable: true,
  60309. configurable: true
  60310. });
  60311. /**
  60312. * Returns the total number of vertices (integer).
  60313. */
  60314. InstancedMesh.prototype.getTotalVertices = function () {
  60315. return this._sourceMesh.getTotalVertices();
  60316. };
  60317. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60318. get: function () {
  60319. return this._sourceMesh;
  60320. },
  60321. enumerable: true,
  60322. configurable: true
  60323. });
  60324. /**
  60325. * Is this node ready to be used/rendered
  60326. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60327. * @return {boolean} is it ready
  60328. */
  60329. InstancedMesh.prototype.isReady = function (completeCheck) {
  60330. if (completeCheck === void 0) { completeCheck = false; }
  60331. return this._sourceMesh.isReady(completeCheck, true);
  60332. };
  60333. /**
  60334. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60335. */
  60336. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60337. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60338. };
  60339. /**
  60340. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60341. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60342. * The `data` are either a numeric array either a Float32Array.
  60343. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60344. * 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).
  60345. * Note that a new underlying VertexBuffer object is created each call.
  60346. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60347. *
  60348. * Possible `kind` values :
  60349. * - BABYLON.VertexBuffer.PositionKind
  60350. * - BABYLON.VertexBuffer.UVKind
  60351. * - BABYLON.VertexBuffer.UV2Kind
  60352. * - BABYLON.VertexBuffer.UV3Kind
  60353. * - BABYLON.VertexBuffer.UV4Kind
  60354. * - BABYLON.VertexBuffer.UV5Kind
  60355. * - BABYLON.VertexBuffer.UV6Kind
  60356. * - BABYLON.VertexBuffer.ColorKind
  60357. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60358. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60359. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60360. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60361. *
  60362. * Returns the Mesh.
  60363. */
  60364. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60365. if (this.sourceMesh) {
  60366. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60367. }
  60368. return this.sourceMesh;
  60369. };
  60370. /**
  60371. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60372. * If the mesh has no geometry, it is simply returned as it is.
  60373. * The `data` are either a numeric array either a Float32Array.
  60374. * No new underlying VertexBuffer object is created.
  60375. * 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.
  60376. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60377. *
  60378. * Possible `kind` values :
  60379. * - BABYLON.VertexBuffer.PositionKind
  60380. * - BABYLON.VertexBuffer.UVKind
  60381. * - BABYLON.VertexBuffer.UV2Kind
  60382. * - BABYLON.VertexBuffer.UV3Kind
  60383. * - BABYLON.VertexBuffer.UV4Kind
  60384. * - BABYLON.VertexBuffer.UV5Kind
  60385. * - BABYLON.VertexBuffer.UV6Kind
  60386. * - BABYLON.VertexBuffer.ColorKind
  60387. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60388. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60389. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60390. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60391. *
  60392. * Returns the Mesh.
  60393. */
  60394. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60395. if (this.sourceMesh) {
  60396. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60397. }
  60398. return this.sourceMesh;
  60399. };
  60400. /**
  60401. * Sets the mesh indices.
  60402. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60403. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60404. * This method creates a new index buffer each call.
  60405. * Returns the Mesh.
  60406. */
  60407. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60408. if (totalVertices === void 0) { totalVertices = null; }
  60409. if (this.sourceMesh) {
  60410. this.sourceMesh.setIndices(indices, totalVertices);
  60411. }
  60412. return this.sourceMesh;
  60413. };
  60414. /**
  60415. * Boolean : True if the mesh owns the requested kind of data.
  60416. */
  60417. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60418. return this._sourceMesh.isVerticesDataPresent(kind);
  60419. };
  60420. /**
  60421. * Returns an array of indices (IndicesArray).
  60422. */
  60423. InstancedMesh.prototype.getIndices = function () {
  60424. return this._sourceMesh.getIndices();
  60425. };
  60426. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60427. get: function () {
  60428. return this._sourceMesh._positions;
  60429. },
  60430. enumerable: true,
  60431. configurable: true
  60432. });
  60433. /**
  60434. * Sets a new updated BoundingInfo to the mesh.
  60435. * Returns the mesh.
  60436. */
  60437. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60438. var meshBB = this._sourceMesh.getBoundingInfo();
  60439. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60440. this._updateBoundingInfo();
  60441. return this;
  60442. };
  60443. InstancedMesh.prototype._preActivate = function () {
  60444. if (this._currentLOD) {
  60445. this._currentLOD._preActivate();
  60446. }
  60447. return this;
  60448. };
  60449. InstancedMesh.prototype._activate = function (renderId) {
  60450. if (this._currentLOD) {
  60451. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60452. }
  60453. return this;
  60454. };
  60455. /**
  60456. * Returns the current associated LOD AbstractMesh.
  60457. */
  60458. InstancedMesh.prototype.getLOD = function (camera) {
  60459. if (!camera) {
  60460. return this;
  60461. }
  60462. var boundingInfo = this.getBoundingInfo();
  60463. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60464. if (this._currentLOD === this.sourceMesh) {
  60465. return this;
  60466. }
  60467. return this._currentLOD;
  60468. };
  60469. InstancedMesh.prototype._syncSubMeshes = function () {
  60470. this.releaseSubMeshes();
  60471. if (this._sourceMesh.subMeshes) {
  60472. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60473. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60474. }
  60475. }
  60476. return this;
  60477. };
  60478. InstancedMesh.prototype._generatePointsArray = function () {
  60479. return this._sourceMesh._generatePointsArray();
  60480. };
  60481. /**
  60482. * Creates a new InstancedMesh from the current mesh.
  60483. * - name (string) : the cloned mesh name
  60484. * - newParent (optional Node) : the optional Node to parent the clone to.
  60485. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60486. *
  60487. * Returns the clone.
  60488. */
  60489. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60490. var result = this._sourceMesh.createInstance(name);
  60491. // Deep copy
  60492. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60493. // Bounding info
  60494. this.refreshBoundingInfo();
  60495. // Parent
  60496. if (newParent) {
  60497. result.parent = newParent;
  60498. }
  60499. if (!doNotCloneChildren) {
  60500. // Children
  60501. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60502. var mesh = this.getScene().meshes[index];
  60503. if (mesh.parent === this) {
  60504. mesh.clone(mesh.name, result);
  60505. }
  60506. }
  60507. }
  60508. result.computeWorldMatrix(true);
  60509. return result;
  60510. };
  60511. /**
  60512. * Disposes the InstancedMesh.
  60513. * Returns nothing.
  60514. */
  60515. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60516. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60517. // Remove from mesh
  60518. var index = this._sourceMesh.instances.indexOf(this);
  60519. this._sourceMesh.instances.splice(index, 1);
  60520. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60521. };
  60522. return InstancedMesh;
  60523. }(BABYLON.AbstractMesh));
  60524. BABYLON.InstancedMesh = InstancedMesh;
  60525. })(BABYLON || (BABYLON = {}));
  60526. //# sourceMappingURL=babylon.instancedMesh.js.map
  60527. var BABYLON;
  60528. (function (BABYLON) {
  60529. var LinesMesh = /** @class */ (function (_super) {
  60530. __extends(LinesMesh, _super);
  60531. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60532. if (scene === void 0) { scene = null; }
  60533. if (parent === void 0) { parent = null; }
  60534. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60535. _this.useVertexColor = useVertexColor;
  60536. _this.useVertexAlpha = useVertexAlpha;
  60537. _this.color = new BABYLON.Color3(1, 1, 1);
  60538. _this.alpha = 1;
  60539. if (source) {
  60540. _this.color = source.color.clone();
  60541. _this.alpha = source.alpha;
  60542. _this.useVertexColor = source.useVertexColor;
  60543. _this.useVertexAlpha = source.useVertexAlpha;
  60544. }
  60545. _this._intersectionThreshold = 0.1;
  60546. var defines = [];
  60547. var options = {
  60548. attributes: [BABYLON.VertexBuffer.PositionKind],
  60549. uniforms: ["world", "viewProjection"],
  60550. needAlphaBlending: true,
  60551. defines: defines
  60552. };
  60553. if (useVertexAlpha === false) {
  60554. options.needAlphaBlending = false;
  60555. }
  60556. if (!useVertexColor) {
  60557. options.uniforms.push("color");
  60558. }
  60559. else {
  60560. options.defines.push("#define VERTEXCOLOR");
  60561. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60562. }
  60563. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60564. return _this;
  60565. }
  60566. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60567. /**
  60568. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60569. * This margin is expressed in world space coordinates, so its value may vary.
  60570. * Default value is 0.1
  60571. * @returns the intersection Threshold value.
  60572. */
  60573. get: function () {
  60574. return this._intersectionThreshold;
  60575. },
  60576. /**
  60577. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60578. * This margin is expressed in world space coordinates, so its value may vary.
  60579. * @param value the new threshold to apply
  60580. */
  60581. set: function (value) {
  60582. if (this._intersectionThreshold === value) {
  60583. return;
  60584. }
  60585. this._intersectionThreshold = value;
  60586. if (this.geometry) {
  60587. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60588. }
  60589. },
  60590. enumerable: true,
  60591. configurable: true
  60592. });
  60593. /**
  60594. * Returns the string "LineMesh"
  60595. */
  60596. LinesMesh.prototype.getClassName = function () {
  60597. return "LinesMesh";
  60598. };
  60599. Object.defineProperty(LinesMesh.prototype, "material", {
  60600. get: function () {
  60601. return this._colorShader;
  60602. },
  60603. set: function (value) {
  60604. // Do nothing
  60605. },
  60606. enumerable: true,
  60607. configurable: true
  60608. });
  60609. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60610. get: function () {
  60611. return false;
  60612. },
  60613. enumerable: true,
  60614. configurable: true
  60615. });
  60616. LinesMesh.prototype.createInstance = function (name) {
  60617. throw new Error("LinesMeshes do not support createInstance.");
  60618. };
  60619. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60620. if (!this._geometry) {
  60621. return this;
  60622. }
  60623. // VBOs
  60624. this._geometry._bind(this._colorShader.getEffect());
  60625. // Color
  60626. if (!this.useVertexColor) {
  60627. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60628. }
  60629. return this;
  60630. };
  60631. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60632. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60633. return this;
  60634. }
  60635. var engine = this.getScene().getEngine();
  60636. // Draw order
  60637. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60638. return this;
  60639. };
  60640. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60641. this._colorShader.dispose();
  60642. _super.prototype.dispose.call(this, doNotRecurse);
  60643. };
  60644. /**
  60645. * Returns a new LineMesh object cloned from the current one.
  60646. */
  60647. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60648. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60649. };
  60650. return LinesMesh;
  60651. }(BABYLON.Mesh));
  60652. BABYLON.LinesMesh = LinesMesh;
  60653. })(BABYLON || (BABYLON = {}));
  60654. //# sourceMappingURL=babylon.linesMesh.js.map
  60655. var BABYLON;
  60656. (function (BABYLON) {
  60657. /**
  60658. * Class containing static functions to help procedurally build meshes
  60659. */
  60660. var MeshBuilder = /** @class */ (function () {
  60661. function MeshBuilder() {
  60662. }
  60663. MeshBuilder.updateSideOrientation = function (orientation) {
  60664. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60665. return BABYLON.Mesh.DOUBLESIDE;
  60666. }
  60667. if (orientation === undefined || orientation === null) {
  60668. return BABYLON.Mesh.FRONTSIDE;
  60669. }
  60670. return orientation;
  60671. };
  60672. /**
  60673. * Creates a box mesh
  60674. * * The parameter `size` sets the size (float) of each box side (default 1)
  60675. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60676. * * 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)
  60677. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60678. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60679. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60680. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60681. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60682. * @param name defines the name of the mesh
  60683. * @param options defines the options used to create the mesh
  60684. * @param scene defines the hosting scene
  60685. * @returns the box mesh
  60686. */
  60687. MeshBuilder.CreateBox = function (name, options, scene) {
  60688. if (scene === void 0) { scene = null; }
  60689. var box = new BABYLON.Mesh(name, scene);
  60690. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60691. box._originalBuilderSideOrientation = options.sideOrientation;
  60692. var vertexData = BABYLON.VertexData.CreateBox(options);
  60693. vertexData.applyToMesh(box, options.updatable);
  60694. return box;
  60695. };
  60696. /**
  60697. * Creates a sphere mesh
  60698. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60699. * * 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`)
  60700. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60701. * * 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
  60702. * * 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)
  60703. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60704. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60705. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60706. * @param name defines the name of the mesh
  60707. * @param options defines the options used to create the mesh
  60708. * @param scene defines the hosting scene
  60709. * @returns the sphere mesh
  60710. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60711. */
  60712. MeshBuilder.CreateSphere = function (name, options, scene) {
  60713. var sphere = new BABYLON.Mesh(name, scene);
  60714. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60715. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60716. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60717. vertexData.applyToMesh(sphere, options.updatable);
  60718. return sphere;
  60719. };
  60720. /**
  60721. * Creates a plane polygonal mesh. By default, this is a disc
  60722. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60723. * * 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
  60724. * * 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
  60725. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60726. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60727. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60728. * @param name defines the name of the mesh
  60729. * @param options defines the options used to create the mesh
  60730. * @param scene defines the hosting scene
  60731. * @returns the plane polygonal mesh
  60732. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60733. */
  60734. MeshBuilder.CreateDisc = function (name, options, scene) {
  60735. if (scene === void 0) { scene = null; }
  60736. var disc = new BABYLON.Mesh(name, scene);
  60737. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60738. disc._originalBuilderSideOrientation = options.sideOrientation;
  60739. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60740. vertexData.applyToMesh(disc, options.updatable);
  60741. return disc;
  60742. };
  60743. /**
  60744. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60745. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60746. * * 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`)
  60747. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60748. * * 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
  60749. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60750. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60751. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60752. * @param name defines the name of the mesh
  60753. * @param options defines the options used to create the mesh
  60754. * @param scene defines the hosting scene
  60755. * @returns the icosahedron mesh
  60756. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60757. */
  60758. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60759. var sphere = new BABYLON.Mesh(name, scene);
  60760. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60761. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60762. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60763. vertexData.applyToMesh(sphere, options.updatable);
  60764. return sphere;
  60765. };
  60766. ;
  60767. /**
  60768. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60769. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60770. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60771. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60772. * * 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
  60773. * * 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
  60774. * * 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
  60775. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60776. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60777. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60778. * * 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
  60779. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60780. * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  60781. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60782. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60783. * @param name defines the name of the mesh
  60784. * @param options defines the options used to create the mesh
  60785. * @param scene defines the hosting scene
  60786. * @returns the ribbon mesh
  60787. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60788. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60789. */
  60790. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60791. if (scene === void 0) { scene = null; }
  60792. var pathArray = options.pathArray;
  60793. var closeArray = options.closeArray;
  60794. var closePath = options.closePath;
  60795. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60796. var instance = options.instance;
  60797. var updatable = options.updatable;
  60798. if (instance) { // existing ribbon instance update
  60799. // positionFunction : ribbon case
  60800. // only pathArray and sideOrientation parameters are taken into account for positions update
  60801. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60802. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60803. var positionFunction = function (positions) {
  60804. var minlg = pathArray[0].length;
  60805. var i = 0;
  60806. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60807. for (var si = 1; si <= ns; si++) {
  60808. for (var p = 0; p < pathArray.length; p++) {
  60809. var path = pathArray[p];
  60810. var l = path.length;
  60811. minlg = (minlg < l) ? minlg : l;
  60812. var j = 0;
  60813. while (j < minlg) {
  60814. positions[i] = path[j].x;
  60815. positions[i + 1] = path[j].y;
  60816. positions[i + 2] = path[j].z;
  60817. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60818. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60819. }
  60820. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60821. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60822. }
  60823. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60824. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60825. }
  60826. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60827. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60828. }
  60829. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60830. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60831. }
  60832. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60833. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60834. }
  60835. j++;
  60836. i += 3;
  60837. }
  60838. if (instance._closePath) {
  60839. positions[i] = path[0].x;
  60840. positions[i + 1] = path[0].y;
  60841. positions[i + 2] = path[0].z;
  60842. i += 3;
  60843. }
  60844. }
  60845. }
  60846. };
  60847. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60848. positionFunction(positions);
  60849. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60850. instance._boundingInfo.update(instance._worldMatrix);
  60851. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60852. if (options.colors) {
  60853. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60854. for (var c = 0; c < options.colors.length; c++) {
  60855. colors[c * 4] = options.colors[c].r;
  60856. colors[c * 4 + 1] = options.colors[c].g;
  60857. colors[c * 4 + 2] = options.colors[c].b;
  60858. colors[c * 4 + 3] = options.colors[c].a;
  60859. }
  60860. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60861. }
  60862. if (options.uvs) {
  60863. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60864. for (var i = 0; i < options.uvs.length; i++) {
  60865. uvs[i * 2] = options.uvs[i].x;
  60866. uvs[i * 2 + 1] = options.uvs[i].y;
  60867. }
  60868. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60869. }
  60870. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60871. var indices = instance.getIndices();
  60872. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60873. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60874. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60875. if (instance._closePath) {
  60876. var indexFirst = 0;
  60877. var indexLast = 0;
  60878. for (var p = 0; p < pathArray.length; p++) {
  60879. indexFirst = instance._idx[p] * 3;
  60880. if (p + 1 < pathArray.length) {
  60881. indexLast = (instance._idx[p + 1] - 1) * 3;
  60882. }
  60883. else {
  60884. indexLast = normals.length - 3;
  60885. }
  60886. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60887. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60888. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60889. normals[indexLast] = normals[indexFirst];
  60890. normals[indexLast + 1] = normals[indexFirst + 1];
  60891. normals[indexLast + 2] = normals[indexFirst + 2];
  60892. }
  60893. }
  60894. if (!(instance.areNormalsFrozen)) {
  60895. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60896. }
  60897. }
  60898. return instance;
  60899. }
  60900. else { // new ribbon creation
  60901. var ribbon = new BABYLON.Mesh(name, scene);
  60902. ribbon._originalBuilderSideOrientation = sideOrientation;
  60903. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60904. if (closePath) {
  60905. ribbon._idx = vertexData._idx;
  60906. }
  60907. ribbon._closePath = closePath;
  60908. ribbon._closeArray = closeArray;
  60909. vertexData.applyToMesh(ribbon, updatable);
  60910. return ribbon;
  60911. }
  60912. };
  60913. /**
  60914. * Creates a cylinder or a cone mesh
  60915. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60916. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60917. * * 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.
  60918. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60919. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60920. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60921. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60922. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60923. * * 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).
  60924. * * 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
  60925. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60926. * * 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
  60927. * * 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.
  60928. * * If `enclose` is false, a ring surface is one element.
  60929. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60930. * * 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
  60931. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60932. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60933. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60934. * @param name defines the name of the mesh
  60935. * @param options defines the options used to create the mesh
  60936. * @param scene defines the hosting scene
  60937. * @returns the cylinder mesh
  60938. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60939. */
  60940. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60941. var cylinder = new BABYLON.Mesh(name, scene);
  60942. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60943. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60944. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60945. vertexData.applyToMesh(cylinder, options.updatable);
  60946. return cylinder;
  60947. };
  60948. /**
  60949. * Creates a torus mesh
  60950. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60951. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60952. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60953. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60954. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60955. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60956. * @param name defines the name of the mesh
  60957. * @param options defines the options used to create the mesh
  60958. * @param scene defines the hosting scene
  60959. * @returns the torus mesh
  60960. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60961. */
  60962. MeshBuilder.CreateTorus = function (name, options, scene) {
  60963. var torus = new BABYLON.Mesh(name, scene);
  60964. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60965. torus._originalBuilderSideOrientation = options.sideOrientation;
  60966. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60967. vertexData.applyToMesh(torus, options.updatable);
  60968. return torus;
  60969. };
  60970. /**
  60971. * Creates a torus knot mesh
  60972. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60973. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60974. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60975. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60976. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60977. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60978. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60979. * @param name defines the name of the mesh
  60980. * @param options defines the options used to create the mesh
  60981. * @param scene defines the hosting scene
  60982. * @returns the torus knot mesh
  60983. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60984. */
  60985. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60986. var torusKnot = new BABYLON.Mesh(name, scene);
  60987. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60988. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60989. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60990. vertexData.applyToMesh(torusKnot, options.updatable);
  60991. return torusKnot;
  60992. };
  60993. /**
  60994. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60995. * * 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
  60996. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60997. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60998. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60999. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61000. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61001. * * 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
  61002. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61003. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61004. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61005. * @param name defines the name of the new line system
  61006. * @param options defines the options used to create the line system
  61007. * @param scene defines the hosting scene
  61008. * @returns a new line system mesh
  61009. */
  61010. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61011. var instance = options.instance;
  61012. var lines = options.lines;
  61013. var colors = options.colors;
  61014. if (instance) { // lines update
  61015. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61016. var vertexColor;
  61017. var lineColors;
  61018. if (colors) {
  61019. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61020. }
  61021. var i = 0;
  61022. var c = 0;
  61023. for (var l = 0; l < lines.length; l++) {
  61024. var points = lines[l];
  61025. for (var p = 0; p < points.length; p++) {
  61026. positions[i] = points[p].x;
  61027. positions[i + 1] = points[p].y;
  61028. positions[i + 2] = points[p].z;
  61029. if (colors && vertexColor) {
  61030. lineColors = colors[l];
  61031. vertexColor[c] = lineColors[p].r;
  61032. vertexColor[c + 1] = lineColors[p].g;
  61033. vertexColor[c + 2] = lineColors[p].b;
  61034. vertexColor[c + 3] = lineColors[p].a;
  61035. c += 4;
  61036. }
  61037. i += 3;
  61038. }
  61039. }
  61040. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61041. if (colors && vertexColor) {
  61042. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61043. }
  61044. return instance;
  61045. }
  61046. // line system creation
  61047. var useVertexColor = (colors) ? true : false;
  61048. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61049. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61050. vertexData.applyToMesh(lineSystem, options.updatable);
  61051. return lineSystem;
  61052. };
  61053. /**
  61054. * Creates a line mesh
  61055. * 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
  61056. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61057. * * The parameter `points` is an array successive Vector3
  61058. * * 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
  61059. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61060. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61061. * * When updating an instance, remember that only point positions can change, not the number of points
  61062. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61063. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61064. * @param name defines the name of the new line system
  61065. * @param options defines the options used to create the line system
  61066. * @param scene defines the hosting scene
  61067. * @returns a new line mesh
  61068. */
  61069. MeshBuilder.CreateLines = function (name, options, scene) {
  61070. if (scene === void 0) { scene = null; }
  61071. var colors = (options.colors) ? [options.colors] : null;
  61072. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61073. return lines;
  61074. };
  61075. /**
  61076. * Creates a dashed line mesh
  61077. * * 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
  61078. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61079. * * The parameter `points` is an array successive Vector3
  61080. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61081. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61082. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61083. * * 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
  61084. * * When updating an instance, remember that only point positions can change, not the number of points
  61085. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61086. * @param name defines the name of the mesh
  61087. * @param options defines the options used to create the mesh
  61088. * @param scene defines the hosting scene
  61089. * @returns the dashed line mesh
  61090. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61091. */
  61092. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61093. if (scene === void 0) { scene = null; }
  61094. var points = options.points;
  61095. var instance = options.instance;
  61096. var gapSize = options.gapSize || 1;
  61097. var dashSize = options.dashSize || 3;
  61098. if (instance) { // dashed lines update
  61099. var positionFunction = function (positions) {
  61100. var curvect = BABYLON.Vector3.Zero();
  61101. var nbSeg = positions.length / 6;
  61102. var lg = 0;
  61103. var nb = 0;
  61104. var shft = 0;
  61105. var dashshft = 0;
  61106. var curshft = 0;
  61107. var p = 0;
  61108. var i = 0;
  61109. var j = 0;
  61110. for (i = 0; i < points.length - 1; i++) {
  61111. points[i + 1].subtractToRef(points[i], curvect);
  61112. lg += curvect.length();
  61113. }
  61114. shft = lg / nbSeg;
  61115. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61116. for (i = 0; i < points.length - 1; i++) {
  61117. points[i + 1].subtractToRef(points[i], curvect);
  61118. nb = Math.floor(curvect.length() / shft);
  61119. curvect.normalize();
  61120. j = 0;
  61121. while (j < nb && p < positions.length) {
  61122. curshft = shft * j;
  61123. positions[p] = points[i].x + curshft * curvect.x;
  61124. positions[p + 1] = points[i].y + curshft * curvect.y;
  61125. positions[p + 2] = points[i].z + curshft * curvect.z;
  61126. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61127. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61128. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61129. p += 6;
  61130. j++;
  61131. }
  61132. }
  61133. while (p < positions.length) {
  61134. positions[p] = points[i].x;
  61135. positions[p + 1] = points[i].y;
  61136. positions[p + 2] = points[i].z;
  61137. p += 3;
  61138. }
  61139. };
  61140. instance.updateMeshPositions(positionFunction, false);
  61141. return instance;
  61142. }
  61143. // dashed lines creation
  61144. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61145. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61146. vertexData.applyToMesh(dashedLines, options.updatable);
  61147. dashedLines.dashSize = dashSize;
  61148. dashedLines.gapSize = gapSize;
  61149. return dashedLines;
  61150. };
  61151. /**
  61152. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61153. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  61154. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61155. * * 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.
  61156. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61157. * * 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
  61158. * * 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
  61159. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61160. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61161. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61162. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61163. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61164. * @param name defines the name of the mesh
  61165. * @param options defines the options used to create the mesh
  61166. * @param scene defines the hosting scene
  61167. * @returns the extruded shape mesh
  61168. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61169. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61170. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61171. */
  61172. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61173. if (scene === void 0) { scene = null; }
  61174. var path = options.path;
  61175. var shape = options.shape;
  61176. var scale = options.scale || 1;
  61177. var rotation = options.rotation || 0;
  61178. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61179. var updatable = options.updatable;
  61180. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61181. var instance = options.instance || null;
  61182. var invertUV = options.invertUV || false;
  61183. 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);
  61184. };
  61185. /**
  61186. * Creates an custom extruded shape mesh.
  61187. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61188. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  61189. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61190. * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  61191. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61192. * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  61193. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61194. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61195. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61196. * * 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
  61197. * * 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
  61198. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61199. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61200. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61201. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61202. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61203. * @param name defines the name of the mesh
  61204. * @param options defines the options used to create the mesh
  61205. * @param scene defines the hosting scene
  61206. * @returns the custom extruded shape mesh
  61207. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61208. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61209. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61210. */
  61211. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61212. var path = options.path;
  61213. var shape = options.shape;
  61214. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61215. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61216. var ribbonCloseArray = options.ribbonCloseArray || false;
  61217. var ribbonClosePath = options.ribbonClosePath || false;
  61218. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61219. var updatable = options.updatable;
  61220. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61221. var instance = options.instance;
  61222. var invertUV = options.invertUV || false;
  61223. 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);
  61224. };
  61225. /**
  61226. * Creates lathe mesh.
  61227. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61228. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  61229. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61230. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61231. * * 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
  61232. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61233. * * 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
  61234. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61235. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61236. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61237. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61238. * @param name defines the name of the mesh
  61239. * @param options defines the options used to create the mesh
  61240. * @param scene defines the hosting scene
  61241. * @returns the lathe mesh
  61242. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61243. */
  61244. MeshBuilder.CreateLathe = function (name, options, scene) {
  61245. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61246. var closed = (options.closed === undefined) ? true : options.closed;
  61247. var shape = options.shape;
  61248. var radius = options.radius || 1;
  61249. var tessellation = options.tessellation || 64;
  61250. var updatable = options.updatable;
  61251. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61252. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61253. var pi2 = Math.PI * 2;
  61254. var paths = new Array();
  61255. var invertUV = options.invertUV || false;
  61256. var i = 0;
  61257. var p = 0;
  61258. var step = pi2 / tessellation * arc;
  61259. var rotated;
  61260. var path = new Array();
  61261. for (i = 0; i <= tessellation; i++) {
  61262. var path = [];
  61263. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61264. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61265. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61266. }
  61267. for (p = 0; p < shape.length; p++) {
  61268. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61269. path.push(rotated);
  61270. }
  61271. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61272. 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));
  61273. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61274. }
  61275. paths.push(path);
  61276. }
  61277. // lathe ribbon
  61278. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61279. return lathe;
  61280. };
  61281. /**
  61282. * Creates a plane mesh
  61283. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61284. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61285. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61286. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61287. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61288. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61289. * @param name defines the name of the mesh
  61290. * @param options defines the options used to create the mesh
  61291. * @param scene defines the hosting scene
  61292. * @returns the plane mesh
  61293. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61294. */
  61295. MeshBuilder.CreatePlane = function (name, options, scene) {
  61296. var plane = new BABYLON.Mesh(name, scene);
  61297. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61298. plane._originalBuilderSideOrientation = options.sideOrientation;
  61299. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61300. vertexData.applyToMesh(plane, options.updatable);
  61301. if (options.sourcePlane) {
  61302. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61303. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61304. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61305. plane.rotate(vectorProduct, product);
  61306. }
  61307. return plane;
  61308. };
  61309. /**
  61310. * Creates a ground mesh
  61311. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61312. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61313. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61314. * @param name defines the name of the mesh
  61315. * @param options defines the options used to create the mesh
  61316. * @param scene defines the hosting scene
  61317. * @returns the ground mesh
  61318. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61319. */
  61320. MeshBuilder.CreateGround = function (name, options, scene) {
  61321. var ground = new BABYLON.GroundMesh(name, scene);
  61322. ground._setReady(false);
  61323. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61324. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61325. ground._width = options.width || 1;
  61326. ground._height = options.height || 1;
  61327. ground._maxX = ground._width / 2;
  61328. ground._maxZ = ground._height / 2;
  61329. ground._minX = -ground._maxX;
  61330. ground._minZ = -ground._maxZ;
  61331. var vertexData = BABYLON.VertexData.CreateGround(options);
  61332. vertexData.applyToMesh(ground, options.updatable);
  61333. ground._setReady(true);
  61334. return ground;
  61335. };
  61336. /**
  61337. * Creates a tiled ground mesh
  61338. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61339. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61340. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  61341. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  61342. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61343. * @param name defines the name of the mesh
  61344. * @param options defines the options used to create the mesh
  61345. * @param scene defines the hosting scene
  61346. * @returns the tiled ground mesh
  61347. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61348. */
  61349. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61350. var tiledGround = new BABYLON.Mesh(name, scene);
  61351. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61352. vertexData.applyToMesh(tiledGround, options.updatable);
  61353. return tiledGround;
  61354. };
  61355. /**
  61356. * Creates a ground mesh from a height map
  61357. * * The parameter `url` sets the URL of the height map image resource.
  61358. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61359. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61360. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61361. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61362. * * 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.
  61363. * * 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).
  61364. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61365. * @param name defines the name of the mesh
  61366. * @param url defines the url to the height map
  61367. * @param options defines the options used to create the mesh
  61368. * @param scene defines the hosting scene
  61369. * @returns the ground mesh
  61370. * @see http://doc.babylonjs.com/babylon101/height_map
  61371. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61372. */
  61373. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61374. var width = options.width || 10.0;
  61375. var height = options.height || 10.0;
  61376. var subdivisions = options.subdivisions || 1 | 0;
  61377. var minHeight = options.minHeight || 0.0;
  61378. var maxHeight = options.maxHeight || 1.0;
  61379. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61380. var updatable = options.updatable;
  61381. var onReady = options.onReady;
  61382. var ground = new BABYLON.GroundMesh(name, scene);
  61383. ground._subdivisionsX = subdivisions;
  61384. ground._subdivisionsY = subdivisions;
  61385. ground._width = width;
  61386. ground._height = height;
  61387. ground._maxX = ground._width / 2.0;
  61388. ground._maxZ = ground._height / 2.0;
  61389. ground._minX = -ground._maxX;
  61390. ground._minZ = -ground._maxZ;
  61391. ground._setReady(false);
  61392. var onload = function (img) {
  61393. // Getting height map data
  61394. var canvas = document.createElement("canvas");
  61395. var context = canvas.getContext("2d");
  61396. if (!context) {
  61397. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61398. }
  61399. if (scene.isDisposed) {
  61400. return;
  61401. }
  61402. var bufferWidth = img.width;
  61403. var bufferHeight = img.height;
  61404. canvas.width = bufferWidth;
  61405. canvas.height = bufferHeight;
  61406. context.drawImage(img, 0, 0);
  61407. // Create VertexData from map data
  61408. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61409. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61410. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61411. width: width, height: height,
  61412. subdivisions: subdivisions,
  61413. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61414. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61415. });
  61416. vertexData.applyToMesh(ground, updatable);
  61417. //execute ready callback, if set
  61418. if (onReady) {
  61419. onReady(ground);
  61420. }
  61421. ground._setReady(true);
  61422. };
  61423. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61424. return ground;
  61425. };
  61426. /**
  61427. * Creates a polygon mesh
  61428. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61429. * * 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
  61430. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61431. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61432. * * 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)
  61433. * * Remember you can only change the shape positions, not their number when updating a polygon
  61434. * @param name defines the name of the mesh
  61435. * @param options defines the options used to create the mesh
  61436. * @param scene defines the hosting scene
  61437. * @returns the polygon mesh
  61438. */
  61439. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61440. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61441. var shape = options.shape;
  61442. var holes = options.holes || [];
  61443. var depth = options.depth || 0;
  61444. var contours = [];
  61445. var hole = [];
  61446. for (var i = 0; i < shape.length; i++) {
  61447. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61448. }
  61449. var epsilon = 0.00000001;
  61450. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61451. contours.pop();
  61452. }
  61453. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61454. for (var hNb = 0; hNb < holes.length; hNb++) {
  61455. hole = [];
  61456. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61457. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61458. }
  61459. polygonTriangulation.addHole(hole);
  61460. }
  61461. var polygon = polygonTriangulation.build(options.updatable, depth);
  61462. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61463. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61464. vertexData.applyToMesh(polygon, options.updatable);
  61465. return polygon;
  61466. };
  61467. ;
  61468. /**
  61469. * Creates an extruded polygon mesh, with depth in the Y direction.
  61470. * * 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)
  61471. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61472. * @param name defines the name of the mesh
  61473. * @param options defines the options used to create the mesh
  61474. * @param scene defines the hosting scene
  61475. * @returns the polygon mesh
  61476. */
  61477. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61478. return MeshBuilder.CreatePolygon(name, options, scene);
  61479. };
  61480. ;
  61481. /**
  61482. * Creates a tube mesh.
  61483. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61484. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61485. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61486. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61487. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61488. * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float)
  61489. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61490. * * 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
  61491. * * 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
  61492. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61493. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61494. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61495. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61496. * @param name defines the name of the mesh
  61497. * @param options defines the options used to create the mesh
  61498. * @param scene defines the hosting scene
  61499. * @returns the tube mesh
  61500. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61501. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61502. */
  61503. MeshBuilder.CreateTube = function (name, options, scene) {
  61504. var path = options.path;
  61505. var instance = options.instance;
  61506. var radius = 1.0;
  61507. if (instance) {
  61508. radius = instance.radius;
  61509. }
  61510. if (options.radius !== undefined) {
  61511. radius = options.radius;
  61512. }
  61513. ;
  61514. var tessellation = options.tessellation || 64 | 0;
  61515. var radiusFunction = options.radiusFunction || null;
  61516. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61517. var invertUV = options.invertUV || false;
  61518. var updatable = options.updatable;
  61519. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61520. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61521. // tube geometry
  61522. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61523. var tangents = path3D.getTangents();
  61524. var normals = path3D.getNormals();
  61525. var distances = path3D.getDistances();
  61526. var pi2 = Math.PI * 2;
  61527. var step = pi2 / tessellation * arc;
  61528. var returnRadius = function () { return radius; };
  61529. var radiusFunctionFinal = radiusFunction || returnRadius;
  61530. var circlePath;
  61531. var rad;
  61532. var normal;
  61533. var rotated;
  61534. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61535. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61536. for (var i = 0; i < path.length; i++) {
  61537. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61538. circlePath = Array(); // current circle array
  61539. normal = normals[i]; // current normal
  61540. for (var t = 0; t < tessellation; t++) {
  61541. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61542. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61543. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61544. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61545. circlePath[t] = rotated;
  61546. }
  61547. circlePaths[index] = circlePath;
  61548. index++;
  61549. }
  61550. // cap
  61551. var capPath = function (nbPoints, pathIndex) {
  61552. var pointCap = Array();
  61553. for (var i = 0; i < nbPoints; i++) {
  61554. pointCap.push(path[pathIndex]);
  61555. }
  61556. return pointCap;
  61557. };
  61558. switch (cap) {
  61559. case BABYLON.Mesh.NO_CAP:
  61560. break;
  61561. case BABYLON.Mesh.CAP_START:
  61562. circlePaths[0] = capPath(tessellation, 0);
  61563. circlePaths[1] = circlePaths[2].slice(0);
  61564. break;
  61565. case BABYLON.Mesh.CAP_END:
  61566. circlePaths[index] = circlePaths[index - 1].slice(0);
  61567. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61568. break;
  61569. case BABYLON.Mesh.CAP_ALL:
  61570. circlePaths[0] = capPath(tessellation, 0);
  61571. circlePaths[1] = circlePaths[2].slice(0);
  61572. circlePaths[index] = circlePaths[index - 1].slice(0);
  61573. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61574. break;
  61575. default:
  61576. break;
  61577. }
  61578. return circlePaths;
  61579. };
  61580. var path3D;
  61581. var pathArray;
  61582. if (instance) { // tube update
  61583. var arc = options.arc || instance.arc;
  61584. path3D = (instance.path3D).update(path);
  61585. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61586. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61587. instance.path3D = path3D;
  61588. instance.pathArray = pathArray;
  61589. instance.arc = arc;
  61590. instance.radius = radius;
  61591. return instance;
  61592. }
  61593. // tube creation
  61594. path3D = new BABYLON.Path3D(path);
  61595. var newPathArray = new Array();
  61596. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61597. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61598. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61599. tube.pathArray = pathArray;
  61600. tube.path3D = path3D;
  61601. tube.tessellation = tessellation;
  61602. tube.cap = cap;
  61603. tube.arc = options.arc;
  61604. tube.radius = radius;
  61605. return tube;
  61606. };
  61607. /**
  61608. * Creates a polyhedron mesh
  61609. * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
  61610. * * The parameter `size` (positive float, default 1) sets the polygon size
  61611. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61612. * * 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`
  61613. * * 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
  61614. * * 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)`)
  61615. * * 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
  61616. * * 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
  61617. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61618. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61619. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61620. * @param name defines the name of the mesh
  61621. * @param options defines the options used to create the mesh
  61622. * @param scene defines the hosting scene
  61623. * @returns the polyhedron mesh
  61624. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61625. */
  61626. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61627. var polyhedron = new BABYLON.Mesh(name, scene);
  61628. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61629. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61630. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61631. vertexData.applyToMesh(polyhedron, options.updatable);
  61632. return polyhedron;
  61633. };
  61634. /**
  61635. * Creates a decal mesh.
  61636. * 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
  61637. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61638. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61639. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61640. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61641. * @param name defines the name of the mesh
  61642. * @param sourceMesh defines the mesh where the decal must be applied
  61643. * @param options defines the options used to create the mesh
  61644. * @param scene defines the hosting scene
  61645. * @returns the decal mesh
  61646. * @see http://doc.babylonjs.com/how_to/decals
  61647. */
  61648. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61649. var indices = sourceMesh.getIndices();
  61650. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61651. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61652. var position = options.position || BABYLON.Vector3.Zero();
  61653. var normal = options.normal || BABYLON.Vector3.Up();
  61654. var size = options.size || BABYLON.Vector3.One();
  61655. var angle = options.angle || 0;
  61656. // Getting correct rotation
  61657. if (!normal) {
  61658. var target = new BABYLON.Vector3(0, 0, 1);
  61659. var camera = sourceMesh.getScene().activeCamera;
  61660. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61661. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61662. }
  61663. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61664. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61665. var pitch = Math.atan2(normal.y, len);
  61666. // Matrix
  61667. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61668. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61669. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61670. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61671. var vertexData = new BABYLON.VertexData();
  61672. vertexData.indices = [];
  61673. vertexData.positions = [];
  61674. vertexData.normals = [];
  61675. vertexData.uvs = [];
  61676. var currentVertexDataIndex = 0;
  61677. var extractDecalVector3 = function (indexId) {
  61678. var result = new BABYLON.PositionNormalVertex();
  61679. if (!indices || !positions || !normals) {
  61680. return result;
  61681. }
  61682. var vertexId = indices[indexId];
  61683. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61684. // Send vector to decal local world
  61685. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61686. // Get normal
  61687. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61688. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61689. return result;
  61690. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61691. var clip = function (vertices, axis) {
  61692. if (vertices.length === 0) {
  61693. return vertices;
  61694. }
  61695. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61696. var clipVertices = function (v0, v1) {
  61697. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61698. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61699. };
  61700. var result = new Array();
  61701. for (var index = 0; index < vertices.length; index += 3) {
  61702. var v1Out;
  61703. var v2Out;
  61704. var v3Out;
  61705. var total = 0;
  61706. var nV1 = null;
  61707. var nV2 = null;
  61708. var nV3 = null;
  61709. var nV4 = null;
  61710. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61711. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61712. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61713. v1Out = d1 > 0;
  61714. v2Out = d2 > 0;
  61715. v3Out = d3 > 0;
  61716. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61717. switch (total) {
  61718. case 0:
  61719. result.push(vertices[index]);
  61720. result.push(vertices[index + 1]);
  61721. result.push(vertices[index + 2]);
  61722. break;
  61723. case 1:
  61724. if (v1Out) {
  61725. nV1 = vertices[index + 1];
  61726. nV2 = vertices[index + 2];
  61727. nV3 = clipVertices(vertices[index], nV1);
  61728. nV4 = clipVertices(vertices[index], nV2);
  61729. }
  61730. if (v2Out) {
  61731. nV1 = vertices[index];
  61732. nV2 = vertices[index + 2];
  61733. nV3 = clipVertices(vertices[index + 1], nV1);
  61734. nV4 = clipVertices(vertices[index + 1], nV2);
  61735. result.push(nV3);
  61736. result.push(nV2.clone());
  61737. result.push(nV1.clone());
  61738. result.push(nV2.clone());
  61739. result.push(nV3.clone());
  61740. result.push(nV4);
  61741. break;
  61742. }
  61743. if (v3Out) {
  61744. nV1 = vertices[index];
  61745. nV2 = vertices[index + 1];
  61746. nV3 = clipVertices(vertices[index + 2], nV1);
  61747. nV4 = clipVertices(vertices[index + 2], nV2);
  61748. }
  61749. if (nV1 && nV2 && nV3 && nV4) {
  61750. result.push(nV1.clone());
  61751. result.push(nV2.clone());
  61752. result.push(nV3);
  61753. result.push(nV4);
  61754. result.push(nV3.clone());
  61755. result.push(nV2.clone());
  61756. }
  61757. break;
  61758. case 2:
  61759. if (!v1Out) {
  61760. nV1 = vertices[index].clone();
  61761. nV2 = clipVertices(nV1, vertices[index + 1]);
  61762. nV3 = clipVertices(nV1, vertices[index + 2]);
  61763. result.push(nV1);
  61764. result.push(nV2);
  61765. result.push(nV3);
  61766. }
  61767. if (!v2Out) {
  61768. nV1 = vertices[index + 1].clone();
  61769. nV2 = clipVertices(nV1, vertices[index + 2]);
  61770. nV3 = clipVertices(nV1, vertices[index]);
  61771. result.push(nV1);
  61772. result.push(nV2);
  61773. result.push(nV3);
  61774. }
  61775. if (!v3Out) {
  61776. nV1 = vertices[index + 2].clone();
  61777. nV2 = clipVertices(nV1, vertices[index]);
  61778. nV3 = clipVertices(nV1, vertices[index + 1]);
  61779. result.push(nV1);
  61780. result.push(nV2);
  61781. result.push(nV3);
  61782. }
  61783. break;
  61784. case 3:
  61785. break;
  61786. }
  61787. }
  61788. return result;
  61789. };
  61790. for (var index = 0; index < indices.length; index += 3) {
  61791. var faceVertices = new Array();
  61792. faceVertices.push(extractDecalVector3(index));
  61793. faceVertices.push(extractDecalVector3(index + 1));
  61794. faceVertices.push(extractDecalVector3(index + 2));
  61795. // Clip
  61796. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61797. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61798. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61799. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61800. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61801. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61802. if (faceVertices.length === 0) {
  61803. continue;
  61804. }
  61805. // Add UVs and get back to world
  61806. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61807. var vertex = faceVertices[vIndex];
  61808. //TODO check for Int32Array | Uint32Array | Uint16Array
  61809. vertexData.indices.push(currentVertexDataIndex);
  61810. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61811. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61812. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61813. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61814. currentVertexDataIndex++;
  61815. }
  61816. }
  61817. // Return mesh
  61818. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61819. vertexData.applyToMesh(decal);
  61820. decal.position = position.clone();
  61821. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61822. return decal;
  61823. };
  61824. // Privates
  61825. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61826. // extrusion geometry
  61827. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61828. var tangents = path3D.getTangents();
  61829. var normals = path3D.getNormals();
  61830. var binormals = path3D.getBinormals();
  61831. var distances = path3D.getDistances();
  61832. var angle = 0;
  61833. var returnScale = function () { return scale !== null ? scale : 1; };
  61834. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61835. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61836. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61837. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61838. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61839. for (var i = 0; i < curve.length; i++) {
  61840. var shapePath = new Array();
  61841. var angleStep = rotate(i, distances[i]);
  61842. var scaleRatio = scl(i, distances[i]);
  61843. for (var p = 0; p < shape.length; p++) {
  61844. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61845. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61846. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61847. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61848. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61849. shapePath[p] = rotated;
  61850. }
  61851. shapePaths[index] = shapePath;
  61852. angle += angleStep;
  61853. index++;
  61854. }
  61855. // cap
  61856. var capPath = function (shapePath) {
  61857. var pointCap = Array();
  61858. var barycenter = BABYLON.Vector3.Zero();
  61859. var i;
  61860. for (i = 0; i < shapePath.length; i++) {
  61861. barycenter.addInPlace(shapePath[i]);
  61862. }
  61863. barycenter.scaleInPlace(1.0 / shapePath.length);
  61864. for (i = 0; i < shapePath.length; i++) {
  61865. pointCap.push(barycenter);
  61866. }
  61867. return pointCap;
  61868. };
  61869. switch (cap) {
  61870. case BABYLON.Mesh.NO_CAP:
  61871. break;
  61872. case BABYLON.Mesh.CAP_START:
  61873. shapePaths[0] = capPath(shapePaths[2]);
  61874. shapePaths[1] = shapePaths[2];
  61875. break;
  61876. case BABYLON.Mesh.CAP_END:
  61877. shapePaths[index] = shapePaths[index - 1];
  61878. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61879. break;
  61880. case BABYLON.Mesh.CAP_ALL:
  61881. shapePaths[0] = capPath(shapePaths[2]);
  61882. shapePaths[1] = shapePaths[2];
  61883. shapePaths[index] = shapePaths[index - 1];
  61884. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61885. break;
  61886. default:
  61887. break;
  61888. }
  61889. return shapePaths;
  61890. };
  61891. var path3D;
  61892. var pathArray;
  61893. if (instance) { // instance update
  61894. path3D = (instance.path3D).update(curve);
  61895. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61896. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61897. return instance;
  61898. }
  61899. // extruded shape creation
  61900. path3D = new BABYLON.Path3D(curve);
  61901. var newShapePaths = new Array();
  61902. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61903. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61904. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61905. extrudedGeneric.pathArray = pathArray;
  61906. extrudedGeneric.path3D = path3D;
  61907. extrudedGeneric.cap = cap;
  61908. return extrudedGeneric;
  61909. };
  61910. return MeshBuilder;
  61911. }());
  61912. BABYLON.MeshBuilder = MeshBuilder;
  61913. })(BABYLON || (BABYLON = {}));
  61914. //# sourceMappingURL=babylon.meshBuilder.js.map
  61915. var BABYLON;
  61916. (function (BABYLON) {
  61917. /**
  61918. * Draco compression (https://google.github.io/draco/)
  61919. */
  61920. var DracoCompression = /** @class */ (function () {
  61921. /**
  61922. * Constructor
  61923. */
  61924. function DracoCompression() {
  61925. }
  61926. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61927. /**
  61928. * Returns true if the decoder is available.
  61929. */
  61930. get: function () {
  61931. if (typeof DracoDecoderModule !== "undefined") {
  61932. return true;
  61933. }
  61934. var decoder = DracoCompression.Configuration.decoder;
  61935. if (decoder) {
  61936. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61937. return true;
  61938. }
  61939. if (decoder.fallbackUrl) {
  61940. return true;
  61941. }
  61942. }
  61943. return false;
  61944. },
  61945. enumerable: true,
  61946. configurable: true
  61947. });
  61948. /**
  61949. * Stop all async operations and release resources.
  61950. */
  61951. DracoCompression.prototype.dispose = function () {
  61952. };
  61953. /**
  61954. * Decode Draco compressed mesh data to vertex data.
  61955. * @param data The array buffer view for the Draco compression data
  61956. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61957. * @returns A promise that resolves with the decoded vertex data
  61958. */
  61959. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61960. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61961. var module = wrappedModule.module;
  61962. var vertexData = new BABYLON.VertexData();
  61963. var buffer = new module.DecoderBuffer();
  61964. buffer.Init(data, data.byteLength);
  61965. var decoder = new module.Decoder();
  61966. var geometry;
  61967. var status;
  61968. try {
  61969. var type = decoder.GetEncodedGeometryType(buffer);
  61970. switch (type) {
  61971. case module.TRIANGULAR_MESH:
  61972. geometry = new module.Mesh();
  61973. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61974. break;
  61975. case module.POINT_CLOUD:
  61976. geometry = new module.PointCloud();
  61977. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61978. break;
  61979. default:
  61980. throw new Error("Invalid geometry type " + type);
  61981. }
  61982. if (!status.ok() || !geometry.ptr) {
  61983. throw new Error(status.error_msg());
  61984. }
  61985. var numPoints = geometry.num_points();
  61986. if (type === module.TRIANGULAR_MESH) {
  61987. var numFaces = geometry.num_faces();
  61988. var faceIndices = new module.DracoInt32Array();
  61989. try {
  61990. var indices = new Uint32Array(numFaces * 3);
  61991. for (var i = 0; i < numFaces; i++) {
  61992. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61993. var offset = i * 3;
  61994. indices[offset + 0] = faceIndices.GetValue(0);
  61995. indices[offset + 1] = faceIndices.GetValue(1);
  61996. indices[offset + 2] = faceIndices.GetValue(2);
  61997. }
  61998. vertexData.indices = indices;
  61999. }
  62000. finally {
  62001. module.destroy(faceIndices);
  62002. }
  62003. }
  62004. for (var kind in attributes) {
  62005. var uniqueId = attributes[kind];
  62006. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62007. var dracoData = new module.DracoFloat32Array();
  62008. try {
  62009. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62010. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62011. for (var i = 0; i < babylonData.length; i++) {
  62012. babylonData[i] = dracoData.GetValue(i);
  62013. }
  62014. vertexData.set(babylonData, kind);
  62015. }
  62016. finally {
  62017. module.destroy(dracoData);
  62018. }
  62019. }
  62020. }
  62021. finally {
  62022. if (geometry) {
  62023. module.destroy(geometry);
  62024. }
  62025. module.destroy(decoder);
  62026. module.destroy(buffer);
  62027. }
  62028. return vertexData;
  62029. });
  62030. };
  62031. DracoCompression._GetDecoderModule = function () {
  62032. if (!DracoCompression._DecoderModulePromise) {
  62033. var promise = null;
  62034. var config_1 = {};
  62035. if (typeof DracoDecoderModule !== "undefined") {
  62036. promise = Promise.resolve();
  62037. }
  62038. else {
  62039. var decoder = DracoCompression.Configuration.decoder;
  62040. if (decoder) {
  62041. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62042. promise = Promise.all([
  62043. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62044. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62045. config_1.wasmBinary = data;
  62046. })
  62047. ]);
  62048. }
  62049. else if (decoder.fallbackUrl) {
  62050. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62051. }
  62052. }
  62053. }
  62054. if (!promise) {
  62055. throw new Error("Draco decoder module is not available");
  62056. }
  62057. DracoCompression._DecoderModulePromise = promise.then(function () {
  62058. return new Promise(function (resolve) {
  62059. config_1.onModuleLoaded = function (decoderModule) {
  62060. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62061. resolve({ module: decoderModule });
  62062. };
  62063. DracoDecoderModule(config_1);
  62064. });
  62065. });
  62066. }
  62067. return DracoCompression._DecoderModulePromise;
  62068. };
  62069. DracoCompression._LoadScriptAsync = function (url) {
  62070. return new Promise(function (resolve, reject) {
  62071. BABYLON.Tools.LoadScript(url, function () {
  62072. resolve();
  62073. }, function (message) {
  62074. reject(new Error(message));
  62075. });
  62076. });
  62077. };
  62078. DracoCompression._LoadFileAsync = function (url) {
  62079. return new Promise(function (resolve, reject) {
  62080. BABYLON.Tools.LoadFile(url, function (data) {
  62081. resolve(data);
  62082. }, undefined, undefined, true, function (request, exception) {
  62083. reject(exception);
  62084. });
  62085. });
  62086. };
  62087. /**
  62088. * The configuration.
  62089. */
  62090. DracoCompression.Configuration = {
  62091. decoder: {
  62092. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62093. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62094. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62095. }
  62096. };
  62097. return DracoCompression;
  62098. }());
  62099. BABYLON.DracoCompression = DracoCompression;
  62100. })(BABYLON || (BABYLON = {}));
  62101. //# sourceMappingURL=babylon.dracoCompression.js.map
  62102. var BABYLON;
  62103. (function (BABYLON) {
  62104. var AudioEngine = /** @class */ (function () {
  62105. function AudioEngine() {
  62106. this._audioContext = null;
  62107. this._audioContextInitialized = false;
  62108. this.canUseWebAudio = false;
  62109. this.WarnedWebAudioUnsupported = false;
  62110. this.unlocked = false;
  62111. this.isMP3supported = false;
  62112. this.isOGGsupported = false;
  62113. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62114. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62115. this.canUseWebAudio = true;
  62116. }
  62117. var audioElem = document.createElement('audio');
  62118. try {
  62119. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62120. this.isMP3supported = true;
  62121. }
  62122. }
  62123. catch (e) {
  62124. // protect error during capability check.
  62125. }
  62126. try {
  62127. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62128. this.isOGGsupported = true;
  62129. }
  62130. }
  62131. catch (e) {
  62132. // protect error during capability check.
  62133. }
  62134. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62135. this._unlockiOSaudio();
  62136. }
  62137. else {
  62138. this.unlocked = true;
  62139. }
  62140. }
  62141. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62142. get: function () {
  62143. if (!this._audioContextInitialized) {
  62144. this._initializeAudioContext();
  62145. }
  62146. return this._audioContext;
  62147. },
  62148. enumerable: true,
  62149. configurable: true
  62150. });
  62151. AudioEngine.prototype._unlockiOSaudio = function () {
  62152. var _this = this;
  62153. var unlockaudio = function () {
  62154. if (!_this.audioContext) {
  62155. return;
  62156. }
  62157. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62158. var source = _this.audioContext.createBufferSource();
  62159. source.buffer = buffer;
  62160. source.connect(_this.audioContext.destination);
  62161. source.start(0);
  62162. setTimeout(function () {
  62163. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62164. _this.unlocked = true;
  62165. window.removeEventListener('touchend', unlockaudio, false);
  62166. if (_this.onAudioUnlocked) {
  62167. _this.onAudioUnlocked();
  62168. }
  62169. }
  62170. }, 0);
  62171. };
  62172. window.addEventListener('touchend', unlockaudio, false);
  62173. };
  62174. AudioEngine.prototype._initializeAudioContext = function () {
  62175. try {
  62176. if (this.canUseWebAudio) {
  62177. this._audioContext = new AudioContext();
  62178. // create a global volume gain node
  62179. this.masterGain = this._audioContext.createGain();
  62180. this.masterGain.gain.value = 1;
  62181. this.masterGain.connect(this._audioContext.destination);
  62182. this._audioContextInitialized = true;
  62183. }
  62184. }
  62185. catch (e) {
  62186. this.canUseWebAudio = false;
  62187. BABYLON.Tools.Error("Web Audio: " + e.message);
  62188. }
  62189. };
  62190. AudioEngine.prototype.dispose = function () {
  62191. if (this.canUseWebAudio && this._audioContextInitialized) {
  62192. if (this._connectedAnalyser && this._audioContext) {
  62193. this._connectedAnalyser.stopDebugCanvas();
  62194. this._connectedAnalyser.dispose();
  62195. this.masterGain.disconnect();
  62196. this.masterGain.connect(this._audioContext.destination);
  62197. this._connectedAnalyser = null;
  62198. }
  62199. this.masterGain.gain.value = 1;
  62200. }
  62201. this.WarnedWebAudioUnsupported = false;
  62202. };
  62203. AudioEngine.prototype.getGlobalVolume = function () {
  62204. if (this.canUseWebAudio && this._audioContextInitialized) {
  62205. return this.masterGain.gain.value;
  62206. }
  62207. else {
  62208. return -1;
  62209. }
  62210. };
  62211. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62212. if (this.canUseWebAudio && this._audioContextInitialized) {
  62213. this.masterGain.gain.value = newVolume;
  62214. }
  62215. };
  62216. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62217. if (this._connectedAnalyser) {
  62218. this._connectedAnalyser.stopDebugCanvas();
  62219. }
  62220. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62221. this._connectedAnalyser = analyser;
  62222. this.masterGain.disconnect();
  62223. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62224. }
  62225. };
  62226. return AudioEngine;
  62227. }());
  62228. BABYLON.AudioEngine = AudioEngine;
  62229. })(BABYLON || (BABYLON = {}));
  62230. //# sourceMappingURL=babylon.audioEngine.js.map
  62231. var BABYLON;
  62232. (function (BABYLON) {
  62233. var Sound = /** @class */ (function () {
  62234. /**
  62235. * Create a sound and attach it to a scene
  62236. * @param name Name of your sound
  62237. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62238. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62239. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62240. */
  62241. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62242. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62243. var _this = this;
  62244. this.autoplay = false;
  62245. this.loop = false;
  62246. this.useCustomAttenuation = false;
  62247. this.spatialSound = false;
  62248. this.refDistance = 1;
  62249. this.rolloffFactor = 1;
  62250. this.maxDistance = 100;
  62251. this.distanceModel = "linear";
  62252. this._panningModel = "equalpower";
  62253. this._playbackRate = 1;
  62254. this._streaming = false;
  62255. this._startTime = 0;
  62256. this._startOffset = 0;
  62257. this._position = BABYLON.Vector3.Zero();
  62258. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62259. this._volume = 1;
  62260. this._isReadyToPlay = false;
  62261. this.isPlaying = false;
  62262. this.isPaused = false;
  62263. this._isDirectional = false;
  62264. // Used if you'd like to create a directional sound.
  62265. // If not set, the sound will be omnidirectional
  62266. this._coneInnerAngle = 360;
  62267. this._coneOuterAngle = 360;
  62268. this._coneOuterGain = 0;
  62269. this._isOutputConnected = false;
  62270. this._urlType = "Unknown";
  62271. this.name = name;
  62272. this._scene = scene;
  62273. this._readyToPlayCallback = readyToPlayCallback;
  62274. // Default custom attenuation function is a linear attenuation
  62275. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62276. if (currentDistance < maxDistance) {
  62277. return currentVolume * (1 - currentDistance / maxDistance);
  62278. }
  62279. else {
  62280. return 0;
  62281. }
  62282. };
  62283. if (options) {
  62284. this.autoplay = options.autoplay || false;
  62285. this.loop = options.loop || false;
  62286. // if volume === 0, we need another way to check this option
  62287. if (options.volume !== undefined) {
  62288. this._volume = options.volume;
  62289. }
  62290. this.spatialSound = options.spatialSound || false;
  62291. this.maxDistance = options.maxDistance || 100;
  62292. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62293. this.rolloffFactor = options.rolloffFactor || 1;
  62294. this.refDistance = options.refDistance || 1;
  62295. this.distanceModel = options.distanceModel || "linear";
  62296. this._playbackRate = options.playbackRate || 1;
  62297. this._streaming = options.streaming || false;
  62298. }
  62299. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62300. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62301. this._soundGain.gain.value = this._volume;
  62302. this._inputAudioNode = this._soundGain;
  62303. this._ouputAudioNode = this._soundGain;
  62304. if (this.spatialSound) {
  62305. this._createSpatialParameters();
  62306. }
  62307. this._scene.mainSoundTrack.AddSound(this);
  62308. var validParameter = true;
  62309. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62310. if (urlOrArrayBuffer) {
  62311. try {
  62312. if (typeof (urlOrArrayBuffer) === "string")
  62313. this._urlType = "String";
  62314. if (Array.isArray(urlOrArrayBuffer))
  62315. this._urlType = "Array";
  62316. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62317. this._urlType = "ArrayBuffer";
  62318. var urls = [];
  62319. var codecSupportedFound = false;
  62320. switch (this._urlType) {
  62321. case "ArrayBuffer":
  62322. if (urlOrArrayBuffer.byteLength > 0) {
  62323. codecSupportedFound = true;
  62324. this._soundLoaded(urlOrArrayBuffer);
  62325. }
  62326. break;
  62327. case "String":
  62328. urls.push(urlOrArrayBuffer);
  62329. case "Array":
  62330. if (urls.length === 0)
  62331. urls = urlOrArrayBuffer;
  62332. // If we found a supported format, we load it immediately and stop the loop
  62333. for (var i = 0; i < urls.length; i++) {
  62334. var url = urls[i];
  62335. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62336. codecSupportedFound = true;
  62337. }
  62338. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62339. codecSupportedFound = true;
  62340. }
  62341. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62342. codecSupportedFound = true;
  62343. }
  62344. if (url.indexOf("blob:") !== -1) {
  62345. codecSupportedFound = true;
  62346. }
  62347. if (codecSupportedFound) {
  62348. // Loading sound using XHR2
  62349. if (!this._streaming) {
  62350. this._scene._loadFile(url, function (data) {
  62351. _this._soundLoaded(data);
  62352. }, undefined, true, true, function (exception) {
  62353. if (exception) {
  62354. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62355. }
  62356. BABYLON.Tools.Error("Sound creation aborted.");
  62357. _this._scene.mainSoundTrack.RemoveSound(_this);
  62358. });
  62359. }
  62360. // Streaming sound using HTML5 Audio tag
  62361. else {
  62362. this._htmlAudioElement = new Audio(url);
  62363. this._htmlAudioElement.controls = false;
  62364. this._htmlAudioElement.loop = this.loop;
  62365. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62366. this._htmlAudioElement.preload = "auto";
  62367. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62368. _this._isReadyToPlay = true;
  62369. if (_this.autoplay) {
  62370. _this.play();
  62371. }
  62372. if (_this._readyToPlayCallback) {
  62373. _this._readyToPlayCallback();
  62374. }
  62375. });
  62376. document.body.appendChild(this._htmlAudioElement);
  62377. }
  62378. break;
  62379. }
  62380. }
  62381. break;
  62382. default:
  62383. validParameter = false;
  62384. break;
  62385. }
  62386. if (!validParameter) {
  62387. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62388. }
  62389. else {
  62390. if (!codecSupportedFound) {
  62391. this._isReadyToPlay = true;
  62392. // Simulating a ready to play event to avoid breaking code path
  62393. if (this._readyToPlayCallback) {
  62394. window.setTimeout(function () {
  62395. if (_this._readyToPlayCallback) {
  62396. _this._readyToPlayCallback();
  62397. }
  62398. }, 1000);
  62399. }
  62400. }
  62401. }
  62402. }
  62403. catch (ex) {
  62404. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62405. this._scene.mainSoundTrack.RemoveSound(this);
  62406. }
  62407. }
  62408. }
  62409. else {
  62410. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62411. this._scene.mainSoundTrack.AddSound(this);
  62412. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62413. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62414. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62415. }
  62416. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62417. if (this._readyToPlayCallback) {
  62418. window.setTimeout(function () {
  62419. if (_this._readyToPlayCallback) {
  62420. _this._readyToPlayCallback();
  62421. }
  62422. }, 1000);
  62423. }
  62424. }
  62425. }
  62426. Sound.prototype.dispose = function () {
  62427. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62428. if (this.isPlaying) {
  62429. this.stop();
  62430. }
  62431. this._isReadyToPlay = false;
  62432. if (this.soundTrackId === -1) {
  62433. this._scene.mainSoundTrack.RemoveSound(this);
  62434. }
  62435. else {
  62436. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62437. }
  62438. if (this._soundGain) {
  62439. this._soundGain.disconnect();
  62440. this._soundGain = null;
  62441. }
  62442. if (this._soundPanner) {
  62443. this._soundPanner.disconnect();
  62444. this._soundPanner = null;
  62445. }
  62446. if (this._soundSource) {
  62447. this._soundSource.disconnect();
  62448. this._soundSource = null;
  62449. }
  62450. this._audioBuffer = null;
  62451. if (this._htmlAudioElement) {
  62452. this._htmlAudioElement.pause();
  62453. this._htmlAudioElement.src = "";
  62454. document.body.removeChild(this._htmlAudioElement);
  62455. }
  62456. if (this._connectedMesh && this._registerFunc) {
  62457. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62458. this._connectedMesh = null;
  62459. }
  62460. }
  62461. };
  62462. Sound.prototype.isReady = function () {
  62463. return this._isReadyToPlay;
  62464. };
  62465. Sound.prototype._soundLoaded = function (audioData) {
  62466. var _this = this;
  62467. if (!BABYLON.Engine.audioEngine.audioContext) {
  62468. return;
  62469. }
  62470. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62471. _this._audioBuffer = buffer;
  62472. _this._isReadyToPlay = true;
  62473. if (_this.autoplay) {
  62474. _this.play();
  62475. }
  62476. if (_this._readyToPlayCallback) {
  62477. _this._readyToPlayCallback();
  62478. }
  62479. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62480. };
  62481. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62482. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62483. this._audioBuffer = audioBuffer;
  62484. this._isReadyToPlay = true;
  62485. }
  62486. };
  62487. Sound.prototype.updateOptions = function (options) {
  62488. if (options) {
  62489. this.loop = options.loop || this.loop;
  62490. this.maxDistance = options.maxDistance || this.maxDistance;
  62491. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62492. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62493. this.refDistance = options.refDistance || this.refDistance;
  62494. this.distanceModel = options.distanceModel || this.distanceModel;
  62495. this._playbackRate = options.playbackRate || this._playbackRate;
  62496. this._updateSpatialParameters();
  62497. if (this.isPlaying) {
  62498. if (this._streaming) {
  62499. this._htmlAudioElement.playbackRate = this._playbackRate;
  62500. }
  62501. else {
  62502. if (this._soundSource) {
  62503. this._soundSource.playbackRate.value = this._playbackRate;
  62504. }
  62505. }
  62506. }
  62507. }
  62508. };
  62509. Sound.prototype._createSpatialParameters = function () {
  62510. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62511. if (this._scene.headphone) {
  62512. this._panningModel = "HRTF";
  62513. }
  62514. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62515. this._updateSpatialParameters();
  62516. this._soundPanner.connect(this._ouputAudioNode);
  62517. this._inputAudioNode = this._soundPanner;
  62518. }
  62519. };
  62520. Sound.prototype._updateSpatialParameters = function () {
  62521. if (this.spatialSound && this._soundPanner) {
  62522. if (this.useCustomAttenuation) {
  62523. // Tricks to disable in a way embedded Web Audio attenuation
  62524. this._soundPanner.distanceModel = "linear";
  62525. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62526. this._soundPanner.refDistance = 1;
  62527. this._soundPanner.rolloffFactor = 1;
  62528. this._soundPanner.panningModel = this._panningModel;
  62529. }
  62530. else {
  62531. this._soundPanner.distanceModel = this.distanceModel;
  62532. this._soundPanner.maxDistance = this.maxDistance;
  62533. this._soundPanner.refDistance = this.refDistance;
  62534. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62535. this._soundPanner.panningModel = this._panningModel;
  62536. }
  62537. }
  62538. };
  62539. Sound.prototype.switchPanningModelToHRTF = function () {
  62540. this._panningModel = "HRTF";
  62541. this._switchPanningModel();
  62542. };
  62543. Sound.prototype.switchPanningModelToEqualPower = function () {
  62544. this._panningModel = "equalpower";
  62545. this._switchPanningModel();
  62546. };
  62547. Sound.prototype._switchPanningModel = function () {
  62548. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62549. this._soundPanner.panningModel = this._panningModel;
  62550. }
  62551. };
  62552. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62553. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62554. if (this._isOutputConnected) {
  62555. this._ouputAudioNode.disconnect();
  62556. }
  62557. this._ouputAudioNode.connect(soundTrackAudioNode);
  62558. this._isOutputConnected = true;
  62559. }
  62560. };
  62561. /**
  62562. * Transform this sound into a directional source
  62563. * @param coneInnerAngle Size of the inner cone in degree
  62564. * @param coneOuterAngle Size of the outer cone in degree
  62565. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62566. */
  62567. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62568. if (coneOuterAngle < coneInnerAngle) {
  62569. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62570. return;
  62571. }
  62572. this._coneInnerAngle = coneInnerAngle;
  62573. this._coneOuterAngle = coneOuterAngle;
  62574. this._coneOuterGain = coneOuterGain;
  62575. this._isDirectional = true;
  62576. if (this.isPlaying && this.loop) {
  62577. this.stop();
  62578. this.play();
  62579. }
  62580. };
  62581. Sound.prototype.setPosition = function (newPosition) {
  62582. this._position = newPosition;
  62583. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62584. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62585. }
  62586. };
  62587. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62588. this._localDirection = newLocalDirection;
  62589. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62590. this._updateDirection();
  62591. }
  62592. };
  62593. Sound.prototype._updateDirection = function () {
  62594. if (!this._connectedMesh || !this._soundPanner) {
  62595. return;
  62596. }
  62597. var mat = this._connectedMesh.getWorldMatrix();
  62598. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62599. direction.normalize();
  62600. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62601. };
  62602. Sound.prototype.updateDistanceFromListener = function () {
  62603. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62604. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62605. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62606. }
  62607. };
  62608. Sound.prototype.setAttenuationFunction = function (callback) {
  62609. this._customAttenuationFunction = callback;
  62610. };
  62611. /**
  62612. * Play the sound
  62613. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62614. * @param offset (optional) Start the sound setting it at a specific time
  62615. */
  62616. Sound.prototype.play = function (time, offset) {
  62617. var _this = this;
  62618. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62619. try {
  62620. if (this._startOffset < 0) {
  62621. time = -this._startOffset;
  62622. this._startOffset = 0;
  62623. }
  62624. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62625. if (!this._soundSource || !this._streamingSource) {
  62626. if (this.spatialSound && this._soundPanner) {
  62627. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62628. if (this._isDirectional) {
  62629. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62630. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62631. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62632. if (this._connectedMesh) {
  62633. this._updateDirection();
  62634. }
  62635. else {
  62636. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62637. }
  62638. }
  62639. }
  62640. }
  62641. if (this._streaming) {
  62642. if (!this._streamingSource) {
  62643. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62644. this._htmlAudioElement.onended = function () { _this._onended(); };
  62645. this._htmlAudioElement.playbackRate = this._playbackRate;
  62646. }
  62647. this._streamingSource.disconnect();
  62648. this._streamingSource.connect(this._inputAudioNode);
  62649. this._htmlAudioElement.play();
  62650. }
  62651. else {
  62652. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62653. this._soundSource.buffer = this._audioBuffer;
  62654. this._soundSource.connect(this._inputAudioNode);
  62655. this._soundSource.loop = this.loop;
  62656. this._soundSource.playbackRate.value = this._playbackRate;
  62657. this._soundSource.onended = function () { _this._onended(); };
  62658. if (this._soundSource.buffer) {
  62659. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62660. }
  62661. }
  62662. this._startTime = startTime;
  62663. this.isPlaying = true;
  62664. this.isPaused = false;
  62665. }
  62666. catch (ex) {
  62667. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62668. }
  62669. }
  62670. };
  62671. Sound.prototype._onended = function () {
  62672. this.isPlaying = false;
  62673. if (this.onended) {
  62674. this.onended();
  62675. }
  62676. };
  62677. /**
  62678. * Stop the sound
  62679. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62680. */
  62681. Sound.prototype.stop = function (time) {
  62682. if (this.isPlaying) {
  62683. if (this._streaming) {
  62684. this._htmlAudioElement.pause();
  62685. // Test needed for Firefox or it will generate an Invalid State Error
  62686. if (this._htmlAudioElement.currentTime > 0) {
  62687. this._htmlAudioElement.currentTime = 0;
  62688. }
  62689. }
  62690. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62691. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62692. this._soundSource.stop(stopTime);
  62693. this._soundSource.onended = function () { };
  62694. if (!this.isPaused) {
  62695. this._startOffset = 0;
  62696. }
  62697. }
  62698. this.isPlaying = false;
  62699. }
  62700. };
  62701. Sound.prototype.pause = function () {
  62702. if (this.isPlaying) {
  62703. this.isPaused = true;
  62704. if (this._streaming) {
  62705. this._htmlAudioElement.pause();
  62706. }
  62707. else if (BABYLON.Engine.audioEngine.audioContext) {
  62708. this.stop(0);
  62709. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62710. }
  62711. }
  62712. };
  62713. Sound.prototype.setVolume = function (newVolume, time) {
  62714. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62715. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62716. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62717. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62718. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62719. }
  62720. else {
  62721. this._soundGain.gain.value = newVolume;
  62722. }
  62723. }
  62724. this._volume = newVolume;
  62725. };
  62726. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62727. this._playbackRate = newPlaybackRate;
  62728. if (this.isPlaying) {
  62729. if (this._streaming) {
  62730. this._htmlAudioElement.playbackRate = this._playbackRate;
  62731. }
  62732. else if (this._soundSource) {
  62733. this._soundSource.playbackRate.value = this._playbackRate;
  62734. }
  62735. }
  62736. };
  62737. Sound.prototype.getVolume = function () {
  62738. return this._volume;
  62739. };
  62740. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62741. var _this = this;
  62742. if (this._connectedMesh && this._registerFunc) {
  62743. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62744. this._registerFunc = null;
  62745. }
  62746. this._connectedMesh = meshToConnectTo;
  62747. if (!this.spatialSound) {
  62748. this.spatialSound = true;
  62749. this._createSpatialParameters();
  62750. if (this.isPlaying && this.loop) {
  62751. this.stop();
  62752. this.play();
  62753. }
  62754. }
  62755. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62756. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62757. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62758. };
  62759. Sound.prototype.detachFromMesh = function () {
  62760. if (this._connectedMesh && this._registerFunc) {
  62761. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62762. this._registerFunc = null;
  62763. this._connectedMesh = null;
  62764. }
  62765. };
  62766. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62767. if (!node.getBoundingInfo) {
  62768. return;
  62769. }
  62770. var mesh = node;
  62771. var boundingInfo = mesh.getBoundingInfo();
  62772. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62773. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62774. this._updateDirection();
  62775. }
  62776. };
  62777. Sound.prototype.clone = function () {
  62778. var _this = this;
  62779. if (!this._streaming) {
  62780. var setBufferAndRun = function () {
  62781. if (_this._isReadyToPlay) {
  62782. clonedSound._audioBuffer = _this.getAudioBuffer();
  62783. clonedSound._isReadyToPlay = true;
  62784. if (clonedSound.autoplay) {
  62785. clonedSound.play();
  62786. }
  62787. }
  62788. else {
  62789. window.setTimeout(setBufferAndRun, 300);
  62790. }
  62791. };
  62792. var currentOptions = {
  62793. autoplay: this.autoplay, loop: this.loop,
  62794. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62795. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62796. refDistance: this.refDistance, distanceModel: this.distanceModel
  62797. };
  62798. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62799. if (this.useCustomAttenuation) {
  62800. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62801. }
  62802. clonedSound.setPosition(this._position);
  62803. clonedSound.setPlaybackRate(this._playbackRate);
  62804. setBufferAndRun();
  62805. return clonedSound;
  62806. }
  62807. // Can't clone a streaming sound
  62808. else {
  62809. return null;
  62810. }
  62811. };
  62812. Sound.prototype.getAudioBuffer = function () {
  62813. return this._audioBuffer;
  62814. };
  62815. Sound.prototype.serialize = function () {
  62816. var serializationObject = {
  62817. name: this.name,
  62818. url: this.name,
  62819. autoplay: this.autoplay,
  62820. loop: this.loop,
  62821. volume: this._volume,
  62822. spatialSound: this.spatialSound,
  62823. maxDistance: this.maxDistance,
  62824. rolloffFactor: this.rolloffFactor,
  62825. refDistance: this.refDistance,
  62826. distanceModel: this.distanceModel,
  62827. playbackRate: this._playbackRate,
  62828. panningModel: this._panningModel,
  62829. soundTrackId: this.soundTrackId
  62830. };
  62831. if (this.spatialSound) {
  62832. if (this._connectedMesh)
  62833. serializationObject.connectedMeshId = this._connectedMesh.id;
  62834. serializationObject.position = this._position.asArray();
  62835. serializationObject.refDistance = this.refDistance;
  62836. serializationObject.distanceModel = this.distanceModel;
  62837. serializationObject.isDirectional = this._isDirectional;
  62838. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62839. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62840. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62841. serializationObject.coneOuterGain = this._coneOuterGain;
  62842. }
  62843. return serializationObject;
  62844. };
  62845. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62846. var soundName = parsedSound.name;
  62847. var soundUrl;
  62848. if (parsedSound.url) {
  62849. soundUrl = rootUrl + parsedSound.url;
  62850. }
  62851. else {
  62852. soundUrl = rootUrl + soundName;
  62853. }
  62854. var options = {
  62855. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62856. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62857. rolloffFactor: parsedSound.rolloffFactor,
  62858. refDistance: parsedSound.refDistance,
  62859. distanceModel: parsedSound.distanceModel,
  62860. playbackRate: parsedSound.playbackRate
  62861. };
  62862. var newSound;
  62863. if (!sourceSound) {
  62864. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62865. scene._addPendingData(newSound);
  62866. }
  62867. else {
  62868. var setBufferAndRun = function () {
  62869. if (sourceSound._isReadyToPlay) {
  62870. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62871. newSound._isReadyToPlay = true;
  62872. if (newSound.autoplay) {
  62873. newSound.play();
  62874. }
  62875. }
  62876. else {
  62877. window.setTimeout(setBufferAndRun, 300);
  62878. }
  62879. };
  62880. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62881. setBufferAndRun();
  62882. }
  62883. if (parsedSound.position) {
  62884. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62885. newSound.setPosition(soundPosition);
  62886. }
  62887. if (parsedSound.isDirectional) {
  62888. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62889. if (parsedSound.localDirectionToMesh) {
  62890. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62891. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62892. }
  62893. }
  62894. if (parsedSound.connectedMeshId) {
  62895. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62896. if (connectedMesh) {
  62897. newSound.attachToMesh(connectedMesh);
  62898. }
  62899. }
  62900. return newSound;
  62901. };
  62902. return Sound;
  62903. }());
  62904. BABYLON.Sound = Sound;
  62905. })(BABYLON || (BABYLON = {}));
  62906. //# sourceMappingURL=babylon.sound.js.map
  62907. var BABYLON;
  62908. (function (BABYLON) {
  62909. var SoundTrack = /** @class */ (function () {
  62910. function SoundTrack(scene, options) {
  62911. this.id = -1;
  62912. this._isMainTrack = false;
  62913. this._isInitialized = false;
  62914. this._scene = scene;
  62915. this.soundCollection = new Array();
  62916. this._options = options;
  62917. if (!this._isMainTrack) {
  62918. this._scene.soundTracks.push(this);
  62919. this.id = this._scene.soundTracks.length - 1;
  62920. }
  62921. }
  62922. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62923. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62924. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62925. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62926. if (this._options) {
  62927. if (this._options.volume) {
  62928. this._outputAudioNode.gain.value = this._options.volume;
  62929. }
  62930. if (this._options.mainTrack) {
  62931. this._isMainTrack = this._options.mainTrack;
  62932. }
  62933. }
  62934. this._isInitialized = true;
  62935. }
  62936. };
  62937. SoundTrack.prototype.dispose = function () {
  62938. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62939. if (this._connectedAnalyser) {
  62940. this._connectedAnalyser.stopDebugCanvas();
  62941. }
  62942. while (this.soundCollection.length) {
  62943. this.soundCollection[0].dispose();
  62944. }
  62945. if (this._outputAudioNode) {
  62946. this._outputAudioNode.disconnect();
  62947. }
  62948. this._outputAudioNode = null;
  62949. }
  62950. };
  62951. SoundTrack.prototype.AddSound = function (sound) {
  62952. if (!this._isInitialized) {
  62953. this._initializeSoundTrackAudioGraph();
  62954. }
  62955. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62956. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62957. }
  62958. if (sound.soundTrackId) {
  62959. if (sound.soundTrackId === -1) {
  62960. this._scene.mainSoundTrack.RemoveSound(sound);
  62961. }
  62962. else {
  62963. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62964. }
  62965. }
  62966. this.soundCollection.push(sound);
  62967. sound.soundTrackId = this.id;
  62968. };
  62969. SoundTrack.prototype.RemoveSound = function (sound) {
  62970. var index = this.soundCollection.indexOf(sound);
  62971. if (index !== -1) {
  62972. this.soundCollection.splice(index, 1);
  62973. }
  62974. };
  62975. SoundTrack.prototype.setVolume = function (newVolume) {
  62976. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62977. this._outputAudioNode.gain.value = newVolume;
  62978. }
  62979. };
  62980. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62981. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62982. for (var i = 0; i < this.soundCollection.length; i++) {
  62983. this.soundCollection[i].switchPanningModelToHRTF();
  62984. }
  62985. }
  62986. };
  62987. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62988. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62989. for (var i = 0; i < this.soundCollection.length; i++) {
  62990. this.soundCollection[i].switchPanningModelToEqualPower();
  62991. }
  62992. }
  62993. };
  62994. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62995. if (this._connectedAnalyser) {
  62996. this._connectedAnalyser.stopDebugCanvas();
  62997. }
  62998. this._connectedAnalyser = analyser;
  62999. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63000. this._outputAudioNode.disconnect();
  63001. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63002. }
  63003. };
  63004. return SoundTrack;
  63005. }());
  63006. BABYLON.SoundTrack = SoundTrack;
  63007. })(BABYLON || (BABYLON = {}));
  63008. //# sourceMappingURL=babylon.soundtrack.js.map
  63009. var BABYLON;
  63010. (function (BABYLON) {
  63011. /**
  63012. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63013. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63014. */
  63015. var Analyser = /** @class */ (function () {
  63016. /**
  63017. * Creates a new analyser
  63018. * @param scene defines hosting scene
  63019. */
  63020. function Analyser(scene) {
  63021. /**
  63022. * Gets or sets the smoothing
  63023. * @ignorenaming
  63024. */
  63025. this.SMOOTHING = 0.75;
  63026. /**
  63027. * Gets or sets the FFT table size
  63028. * @ignorenaming
  63029. */
  63030. this.FFT_SIZE = 512;
  63031. /**
  63032. * Gets or sets the bar graph amplitude
  63033. * @ignorenaming
  63034. */
  63035. this.BARGRAPHAMPLITUDE = 256;
  63036. /**
  63037. * Gets or sets the position of the debug canvas
  63038. * @ignorenaming
  63039. */
  63040. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63041. /**
  63042. * Gets or sets the debug canvas size
  63043. * @ignorenaming
  63044. */
  63045. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63046. this._scene = scene;
  63047. this._audioEngine = BABYLON.Engine.audioEngine;
  63048. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63049. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63050. this._webAudioAnalyser.minDecibels = -140;
  63051. this._webAudioAnalyser.maxDecibels = 0;
  63052. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63053. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63054. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63055. }
  63056. }
  63057. /**
  63058. * Get the number of data values you will have to play with for the visualization
  63059. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63060. * @returns a number
  63061. */
  63062. Analyser.prototype.getFrequencyBinCount = function () {
  63063. if (this._audioEngine.canUseWebAudio) {
  63064. return this._webAudioAnalyser.frequencyBinCount;
  63065. }
  63066. else {
  63067. return 0;
  63068. }
  63069. };
  63070. /**
  63071. * Gets the current frequency data as a byte array
  63072. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63073. * @returns a Uint8Array
  63074. */
  63075. Analyser.prototype.getByteFrequencyData = function () {
  63076. if (this._audioEngine.canUseWebAudio) {
  63077. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63078. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63079. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63080. }
  63081. return this._byteFreqs;
  63082. };
  63083. /**
  63084. * Gets the current waveform as a byte array
  63085. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63086. * @returns a Uint8Array
  63087. */
  63088. Analyser.prototype.getByteTimeDomainData = function () {
  63089. if (this._audioEngine.canUseWebAudio) {
  63090. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63091. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63092. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63093. }
  63094. return this._byteTime;
  63095. };
  63096. /**
  63097. * Gets the current frequency data as a float array
  63098. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63099. * @returns a Float32Array
  63100. */
  63101. Analyser.prototype.getFloatFrequencyData = function () {
  63102. if (this._audioEngine.canUseWebAudio) {
  63103. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63104. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63105. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63106. }
  63107. return this._floatFreqs;
  63108. };
  63109. /**
  63110. * Renders the debug canvas
  63111. */
  63112. Analyser.prototype.drawDebugCanvas = function () {
  63113. var _this = this;
  63114. if (this._audioEngine.canUseWebAudio) {
  63115. if (!this._debugCanvas) {
  63116. this._debugCanvas = document.createElement("canvas");
  63117. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63118. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63119. this._debugCanvas.style.position = "absolute";
  63120. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63121. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63122. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63123. document.body.appendChild(this._debugCanvas);
  63124. this._registerFunc = function () {
  63125. _this.drawDebugCanvas();
  63126. };
  63127. this._scene.registerBeforeRender(this._registerFunc);
  63128. }
  63129. if (this._registerFunc && this._debugCanvasContext) {
  63130. var workingArray = this.getByteFrequencyData();
  63131. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63132. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63133. // Draw the frequency domain chart.
  63134. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63135. var value = workingArray[i];
  63136. var percent = value / this.BARGRAPHAMPLITUDE;
  63137. var height = this.DEBUGCANVASSIZE.height * percent;
  63138. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63139. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63140. var hue = i / this.getFrequencyBinCount() * 360;
  63141. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63142. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63143. }
  63144. }
  63145. }
  63146. };
  63147. /**
  63148. * Stops rendering the debug canvas and removes it
  63149. */
  63150. Analyser.prototype.stopDebugCanvas = function () {
  63151. if (this._debugCanvas) {
  63152. if (this._registerFunc) {
  63153. this._scene.unregisterBeforeRender(this._registerFunc);
  63154. this._registerFunc = null;
  63155. }
  63156. document.body.removeChild(this._debugCanvas);
  63157. this._debugCanvas = null;
  63158. this._debugCanvasContext = null;
  63159. }
  63160. };
  63161. /**
  63162. * Connects two audio nodes
  63163. * @param inputAudioNode defines first node to connect
  63164. * @param outputAudioNode defines second node to connect
  63165. */
  63166. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63167. if (this._audioEngine.canUseWebAudio) {
  63168. inputAudioNode.connect(this._webAudioAnalyser);
  63169. this._webAudioAnalyser.connect(outputAudioNode);
  63170. }
  63171. };
  63172. /**
  63173. * Releases all associated resources
  63174. */
  63175. Analyser.prototype.dispose = function () {
  63176. if (this._audioEngine.canUseWebAudio) {
  63177. this._webAudioAnalyser.disconnect();
  63178. }
  63179. };
  63180. return Analyser;
  63181. }());
  63182. BABYLON.Analyser = Analyser;
  63183. })(BABYLON || (BABYLON = {}));
  63184. //# sourceMappingURL=babylon.analyser.js.map
  63185. var BABYLON;
  63186. (function (BABYLON) {
  63187. var CubeTexture = /** @class */ (function (_super) {
  63188. __extends(CubeTexture, _super);
  63189. /**
  63190. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63191. * as prefiltered data.
  63192. * @param rootUrl defines the url of the texture or the root name of the six images
  63193. * @param scene defines the scene the texture is attached to
  63194. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63195. * @param noMipmap defines if mipmaps should be created or not
  63196. * @param files defines the six files to load for the different faces
  63197. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63198. * @param onError defines a callback triggered in case of error during load
  63199. * @param format defines the internal format to use for the texture once loaded
  63200. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63201. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63202. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63203. * @return the cube texture
  63204. */
  63205. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials) {
  63206. if (extensions === void 0) { extensions = null; }
  63207. if (noMipmap === void 0) { noMipmap = false; }
  63208. if (files === void 0) { files = null; }
  63209. if (onLoad === void 0) { onLoad = null; }
  63210. if (onError === void 0) { onError = null; }
  63211. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63212. if (prefiltered === void 0) { prefiltered = false; }
  63213. if (forcedExtension === void 0) { forcedExtension = null; }
  63214. if (createPolynomials === void 0) { createPolynomials = false; }
  63215. var _this = _super.call(this, scene) || this;
  63216. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63217. /**
  63218. * Gets or sets the center of the bounding box associated with the cube texture
  63219. * It must define where the camera used to render the texture was set
  63220. */
  63221. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63222. _this._rotationY = 0;
  63223. _this.name = rootUrl;
  63224. _this.url = rootUrl;
  63225. _this._noMipmap = noMipmap;
  63226. _this.hasAlpha = false;
  63227. _this._format = format;
  63228. _this._prefiltered = prefiltered;
  63229. _this.isCube = true;
  63230. _this._textureMatrix = BABYLON.Matrix.Identity();
  63231. _this._createPolynomials = createPolynomials;
  63232. if (prefiltered) {
  63233. _this.gammaSpace = false;
  63234. }
  63235. if (!rootUrl && !files) {
  63236. return _this;
  63237. }
  63238. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63239. var lastDot = rootUrl.lastIndexOf(".");
  63240. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63241. var isDDS = (extension === ".dds");
  63242. if (!files) {
  63243. if (!isDDS && !extensions) {
  63244. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63245. }
  63246. files = [];
  63247. if (extensions) {
  63248. for (var index = 0; index < extensions.length; index++) {
  63249. files.push(rootUrl + extensions[index]);
  63250. }
  63251. }
  63252. }
  63253. _this._files = files;
  63254. if (!_this._texture) {
  63255. if (!scene.useDelayedTextureLoading) {
  63256. if (prefiltered) {
  63257. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63258. }
  63259. else {
  63260. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63261. }
  63262. }
  63263. else {
  63264. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63265. }
  63266. }
  63267. else if (onLoad) {
  63268. if (_this._texture.isReady) {
  63269. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63270. }
  63271. else {
  63272. _this._texture.onLoadedObservable.add(onLoad);
  63273. }
  63274. }
  63275. return _this;
  63276. }
  63277. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63278. get: function () {
  63279. return this._boundingBoxSize;
  63280. },
  63281. /**
  63282. * Gets or sets the size of the bounding box associated with the cube texture
  63283. * When defined, the cubemap will switch to local mode
  63284. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63285. * @example https://www.babylonjs-playground.com/#RNASML
  63286. */
  63287. set: function (value) {
  63288. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63289. return;
  63290. }
  63291. this._boundingBoxSize = value;
  63292. var scene = this.getScene();
  63293. if (scene) {
  63294. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63295. }
  63296. },
  63297. enumerable: true,
  63298. configurable: true
  63299. });
  63300. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63301. /**
  63302. * Gets texture matrix rotation angle around Y axis radians.
  63303. */
  63304. get: function () {
  63305. return this._rotationY;
  63306. },
  63307. /**
  63308. * Sets texture matrix rotation angle around Y axis in radians.
  63309. */
  63310. set: function (value) {
  63311. this._rotationY = value;
  63312. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63313. },
  63314. enumerable: true,
  63315. configurable: true
  63316. });
  63317. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63318. var rootUrlKey = "";
  63319. files.forEach(function (url) { return rootUrlKey += url; });
  63320. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63321. };
  63322. /**
  63323. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63324. * @param url defines the url of the prefiltered texture
  63325. * @param scene defines the scene the texture is attached to
  63326. * @param forcedExtension defines the extension of the file if different from the url
  63327. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63328. * @return the prefiltered texture
  63329. */
  63330. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63331. if (forcedExtension === void 0) { forcedExtension = null; }
  63332. if (createPolynomials === void 0) { createPolynomials = true; }
  63333. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63334. };
  63335. // Methods
  63336. CubeTexture.prototype.delayLoad = function () {
  63337. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63338. return;
  63339. }
  63340. var scene = this.getScene();
  63341. if (!scene) {
  63342. return;
  63343. }
  63344. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63345. this._texture = this._getFromCache(this.url, this._noMipmap);
  63346. if (!this._texture) {
  63347. if (this._prefiltered) {
  63348. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63349. }
  63350. else {
  63351. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63352. }
  63353. }
  63354. };
  63355. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63356. return this._textureMatrix;
  63357. };
  63358. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63359. this._textureMatrix = value;
  63360. };
  63361. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63362. var texture = BABYLON.SerializationHelper.Parse(function () {
  63363. var prefiltered = false;
  63364. if (parsedTexture.prefiltered) {
  63365. prefiltered = parsedTexture.prefiltered;
  63366. }
  63367. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63368. }, parsedTexture, scene);
  63369. // Local Cubemaps
  63370. if (parsedTexture.boundingBoxPosition) {
  63371. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63372. }
  63373. if (parsedTexture.boundingBoxSize) {
  63374. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63375. }
  63376. // Animations
  63377. if (parsedTexture.animations) {
  63378. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63379. var parsedAnimation = parsedTexture.animations[animationIndex];
  63380. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63381. }
  63382. }
  63383. return texture;
  63384. };
  63385. CubeTexture.prototype.clone = function () {
  63386. var _this = this;
  63387. return BABYLON.SerializationHelper.Clone(function () {
  63388. var scene = _this.getScene();
  63389. if (!scene) {
  63390. return _this;
  63391. }
  63392. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63393. }, this);
  63394. };
  63395. __decorate([
  63396. BABYLON.serialize("rotationY")
  63397. ], CubeTexture.prototype, "_rotationY", void 0);
  63398. return CubeTexture;
  63399. }(BABYLON.BaseTexture));
  63400. BABYLON.CubeTexture = CubeTexture;
  63401. })(BABYLON || (BABYLON = {}));
  63402. //# sourceMappingURL=babylon.cubeTexture.js.map
  63403. var BABYLON;
  63404. (function (BABYLON) {
  63405. var RenderTargetTexture = /** @class */ (function (_super) {
  63406. __extends(RenderTargetTexture, _super);
  63407. /**
  63408. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63409. * or used a shadow, depth texture...
  63410. * @param name The friendly name of the texture
  63411. * @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)
  63412. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63413. * @param generateMipMaps True if mip maps need to be generated after render.
  63414. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63415. * @param type The type of the buffer in the RTT (int, half float, float...)
  63416. * @param isCube True if a cube texture needs to be created
  63417. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63418. * @param generateDepthBuffer True to generate a depth buffer
  63419. * @param generateStencilBuffer True to generate a stencil buffer
  63420. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63421. */
  63422. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63423. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63424. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63425. if (isCube === void 0) { isCube = false; }
  63426. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63427. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63428. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63429. if (isMulti === void 0) { isMulti = false; }
  63430. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63431. _this.isCube = isCube;
  63432. /**
  63433. * Use this list to define the list of mesh you want to render.
  63434. */
  63435. _this.renderList = new Array();
  63436. _this.renderParticles = true;
  63437. _this.renderSprites = false;
  63438. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63439. _this.ignoreCameraViewport = false;
  63440. // Events
  63441. /**
  63442. * An event triggered when the texture is unbind.
  63443. */
  63444. _this.onBeforeBindObservable = new BABYLON.Observable();
  63445. /**
  63446. * An event triggered when the texture is unbind.
  63447. */
  63448. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63449. /**
  63450. * An event triggered before rendering the texture
  63451. */
  63452. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63453. /**
  63454. * An event triggered after rendering the texture
  63455. */
  63456. _this.onAfterRenderObservable = new BABYLON.Observable();
  63457. /**
  63458. * An event triggered after the texture clear
  63459. */
  63460. _this.onClearObservable = new BABYLON.Observable();
  63461. _this._currentRefreshId = -1;
  63462. _this._refreshRate = 1;
  63463. _this._samples = 1;
  63464. /**
  63465. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63466. * It must define where the camera used to render the texture is set
  63467. */
  63468. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63469. scene = _this.getScene();
  63470. if (!scene) {
  63471. return _this;
  63472. }
  63473. _this._engine = scene.getEngine();
  63474. _this.name = name;
  63475. _this.isRenderTarget = true;
  63476. _this._initialSizeParameter = size;
  63477. _this._processSizeParameter(size);
  63478. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63479. });
  63480. _this._generateMipMaps = generateMipMaps ? true : false;
  63481. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63482. // Rendering groups
  63483. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63484. if (isMulti) {
  63485. return _this;
  63486. }
  63487. _this._renderTargetOptions = {
  63488. generateMipMaps: generateMipMaps,
  63489. type: type,
  63490. samplingMode: samplingMode,
  63491. generateDepthBuffer: generateDepthBuffer,
  63492. generateStencilBuffer: generateStencilBuffer
  63493. };
  63494. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63495. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63496. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63497. }
  63498. if (isCube) {
  63499. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63500. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63501. _this._textureMatrix = BABYLON.Matrix.Identity();
  63502. }
  63503. else {
  63504. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63505. }
  63506. return _this;
  63507. }
  63508. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63509. get: function () {
  63510. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63511. },
  63512. enumerable: true,
  63513. configurable: true
  63514. });
  63515. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63516. get: function () {
  63517. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63518. },
  63519. enumerable: true,
  63520. configurable: true
  63521. });
  63522. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63523. get: function () {
  63524. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63525. },
  63526. enumerable: true,
  63527. configurable: true
  63528. });
  63529. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63530. set: function (callback) {
  63531. if (this._onAfterUnbindObserver) {
  63532. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63533. }
  63534. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63535. },
  63536. enumerable: true,
  63537. configurable: true
  63538. });
  63539. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63540. set: function (callback) {
  63541. if (this._onBeforeRenderObserver) {
  63542. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63543. }
  63544. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63545. },
  63546. enumerable: true,
  63547. configurable: true
  63548. });
  63549. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63550. set: function (callback) {
  63551. if (this._onAfterRenderObserver) {
  63552. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63553. }
  63554. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63555. },
  63556. enumerable: true,
  63557. configurable: true
  63558. });
  63559. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63560. set: function (callback) {
  63561. if (this._onClearObserver) {
  63562. this.onClearObservable.remove(this._onClearObserver);
  63563. }
  63564. this._onClearObserver = this.onClearObservable.add(callback);
  63565. },
  63566. enumerable: true,
  63567. configurable: true
  63568. });
  63569. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63570. get: function () {
  63571. return this._renderTargetOptions;
  63572. },
  63573. enumerable: true,
  63574. configurable: true
  63575. });
  63576. RenderTargetTexture.prototype._onRatioRescale = function () {
  63577. if (this._sizeRatio) {
  63578. this.resize(this._initialSizeParameter);
  63579. }
  63580. };
  63581. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63582. get: function () {
  63583. return this._boundingBoxSize;
  63584. },
  63585. /**
  63586. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63587. * When defined, the cubemap will switch to local mode
  63588. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63589. * @example https://www.babylonjs-playground.com/#RNASML
  63590. */
  63591. set: function (value) {
  63592. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63593. return;
  63594. }
  63595. this._boundingBoxSize = value;
  63596. var scene = this.getScene();
  63597. if (scene) {
  63598. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63599. }
  63600. },
  63601. enumerable: true,
  63602. configurable: true
  63603. });
  63604. /**
  63605. * Creates a depth stencil texture.
  63606. * This is only available in WebGL 2 or with the depth texture extension available.
  63607. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63608. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63609. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63610. */
  63611. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63612. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63613. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63614. if (generateStencil === void 0) { generateStencil = false; }
  63615. if (!this.getScene()) {
  63616. return;
  63617. }
  63618. var engine = this.getScene().getEngine();
  63619. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63620. bilinearFiltering: bilinearFiltering,
  63621. comparisonFunction: comparisonFunction,
  63622. generateStencil: generateStencil,
  63623. isCube: this.isCube
  63624. });
  63625. engine.setFrameBufferDepthStencilTexture(this);
  63626. };
  63627. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63628. if (size.ratio) {
  63629. this._sizeRatio = size.ratio;
  63630. this._size = {
  63631. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63632. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63633. };
  63634. }
  63635. else {
  63636. this._size = size;
  63637. }
  63638. };
  63639. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63640. get: function () {
  63641. return this._samples;
  63642. },
  63643. set: function (value) {
  63644. if (this._samples === value) {
  63645. return;
  63646. }
  63647. var scene = this.getScene();
  63648. if (!scene) {
  63649. return;
  63650. }
  63651. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63652. },
  63653. enumerable: true,
  63654. configurable: true
  63655. });
  63656. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63657. this._currentRefreshId = -1;
  63658. };
  63659. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63660. get: function () {
  63661. return this._refreshRate;
  63662. },
  63663. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63664. set: function (value) {
  63665. this._refreshRate = value;
  63666. this.resetRefreshCounter();
  63667. },
  63668. enumerable: true,
  63669. configurable: true
  63670. });
  63671. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63672. if (!this._postProcessManager) {
  63673. var scene = this.getScene();
  63674. if (!scene) {
  63675. return;
  63676. }
  63677. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63678. this._postProcesses = new Array();
  63679. }
  63680. this._postProcesses.push(postProcess);
  63681. this._postProcesses[0].autoClear = false;
  63682. };
  63683. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63684. if (!this._postProcesses) {
  63685. return;
  63686. }
  63687. if (dispose) {
  63688. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63689. var postProcess = _a[_i];
  63690. postProcess.dispose();
  63691. }
  63692. }
  63693. this._postProcesses = [];
  63694. };
  63695. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63696. if (!this._postProcesses) {
  63697. return;
  63698. }
  63699. var index = this._postProcesses.indexOf(postProcess);
  63700. if (index === -1) {
  63701. return;
  63702. }
  63703. this._postProcesses.splice(index, 1);
  63704. if (this._postProcesses.length > 0) {
  63705. this._postProcesses[0].autoClear = false;
  63706. }
  63707. };
  63708. RenderTargetTexture.prototype._shouldRender = function () {
  63709. if (this._currentRefreshId === -1) { // At least render once
  63710. this._currentRefreshId = 1;
  63711. return true;
  63712. }
  63713. if (this.refreshRate === this._currentRefreshId) {
  63714. this._currentRefreshId = 1;
  63715. return true;
  63716. }
  63717. this._currentRefreshId++;
  63718. return false;
  63719. };
  63720. RenderTargetTexture.prototype.getRenderSize = function () {
  63721. if (this._size.width) {
  63722. return this._size.width;
  63723. }
  63724. return this._size;
  63725. };
  63726. RenderTargetTexture.prototype.getRenderWidth = function () {
  63727. if (this._size.width) {
  63728. return this._size.width;
  63729. }
  63730. return this._size;
  63731. };
  63732. RenderTargetTexture.prototype.getRenderHeight = function () {
  63733. if (this._size.width) {
  63734. return this._size.height;
  63735. }
  63736. return this._size;
  63737. };
  63738. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63739. get: function () {
  63740. return true;
  63741. },
  63742. enumerable: true,
  63743. configurable: true
  63744. });
  63745. RenderTargetTexture.prototype.scale = function (ratio) {
  63746. var newSize = this.getRenderSize() * ratio;
  63747. this.resize(newSize);
  63748. };
  63749. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63750. if (this.isCube) {
  63751. return this._textureMatrix;
  63752. }
  63753. return _super.prototype.getReflectionTextureMatrix.call(this);
  63754. };
  63755. RenderTargetTexture.prototype.resize = function (size) {
  63756. this.releaseInternalTexture();
  63757. var scene = this.getScene();
  63758. if (!scene) {
  63759. return;
  63760. }
  63761. this._processSizeParameter(size);
  63762. if (this.isCube) {
  63763. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63764. }
  63765. else {
  63766. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63767. }
  63768. };
  63769. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63770. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63771. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63772. var scene = this.getScene();
  63773. if (!scene) {
  63774. return;
  63775. }
  63776. var engine = scene.getEngine();
  63777. if (this.useCameraPostProcesses !== undefined) {
  63778. useCameraPostProcess = this.useCameraPostProcesses;
  63779. }
  63780. if (this._waitingRenderList) {
  63781. this.renderList = [];
  63782. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63783. var id = this._waitingRenderList[index];
  63784. var mesh_1 = scene.getMeshByID(id);
  63785. if (mesh_1) {
  63786. this.renderList.push(mesh_1);
  63787. }
  63788. }
  63789. delete this._waitingRenderList;
  63790. }
  63791. // Is predicate defined?
  63792. if (this.renderListPredicate) {
  63793. if (this.renderList) {
  63794. this.renderList.splice(0); // Clear previous renderList
  63795. }
  63796. else {
  63797. this.renderList = [];
  63798. }
  63799. var scene = this.getScene();
  63800. if (!scene) {
  63801. return;
  63802. }
  63803. var sceneMeshes = scene.meshes;
  63804. for (var index = 0; index < sceneMeshes.length; index++) {
  63805. var mesh = sceneMeshes[index];
  63806. if (this.renderListPredicate(mesh)) {
  63807. this.renderList.push(mesh);
  63808. }
  63809. }
  63810. }
  63811. this.onBeforeBindObservable.notifyObservers(this);
  63812. // Set custom projection.
  63813. // Needs to be before binding to prevent changing the aspect ratio.
  63814. var camera;
  63815. if (this.activeCamera) {
  63816. camera = this.activeCamera;
  63817. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63818. if (this.activeCamera !== scene.activeCamera) {
  63819. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63820. }
  63821. }
  63822. else {
  63823. camera = scene.activeCamera;
  63824. if (camera) {
  63825. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63826. }
  63827. }
  63828. // Prepare renderingManager
  63829. this._renderingManager.reset();
  63830. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63831. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63832. var sceneRenderId = scene.getRenderId();
  63833. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63834. var mesh = currentRenderList[meshIndex];
  63835. if (mesh) {
  63836. if (!mesh.isReady(this.refreshRate === 0)) {
  63837. this.resetRefreshCounter();
  63838. continue;
  63839. }
  63840. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63841. var isMasked = void 0;
  63842. if (!this.renderList && camera) {
  63843. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63844. }
  63845. else {
  63846. isMasked = false;
  63847. }
  63848. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63849. mesh._activate(sceneRenderId);
  63850. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63851. var subMesh = mesh.subMeshes[subIndex];
  63852. scene._activeIndices.addCount(subMesh.indexCount, false);
  63853. this._renderingManager.dispatch(subMesh, mesh);
  63854. }
  63855. }
  63856. }
  63857. }
  63858. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63859. var particleSystem = scene.particleSystems[particleIndex];
  63860. var emitter = particleSystem.emitter;
  63861. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63862. continue;
  63863. }
  63864. if (currentRenderList.indexOf(emitter) >= 0) {
  63865. this._renderingManager.dispatchParticles(particleSystem);
  63866. }
  63867. }
  63868. if (this.isCube) {
  63869. for (var face = 0; face < 6; face++) {
  63870. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63871. scene.incrementRenderId();
  63872. scene.resetCachedMaterial();
  63873. }
  63874. }
  63875. else {
  63876. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63877. }
  63878. this.onAfterUnbindObservable.notifyObservers(this);
  63879. if (scene.activeCamera) {
  63880. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63881. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63882. }
  63883. engine.setViewport(scene.activeCamera.viewport);
  63884. }
  63885. scene.resetCachedMaterial();
  63886. };
  63887. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63888. var minimum = 128;
  63889. var x = renderDimension * scale;
  63890. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63891. // Ensure we don't exceed the render dimension (while staying POT)
  63892. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63893. };
  63894. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63895. var _this = this;
  63896. if (!this._texture) {
  63897. return;
  63898. }
  63899. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63900. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63901. });
  63902. };
  63903. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63904. var scene = this.getScene();
  63905. if (!scene) {
  63906. return;
  63907. }
  63908. var engine = scene.getEngine();
  63909. if (!this._texture) {
  63910. return;
  63911. }
  63912. // Bind
  63913. if (this._postProcessManager) {
  63914. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63915. }
  63916. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63917. if (this._texture) {
  63918. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63919. }
  63920. }
  63921. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63922. // Clear
  63923. if (this.onClearObservable.hasObservers()) {
  63924. this.onClearObservable.notifyObservers(engine);
  63925. }
  63926. else {
  63927. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63928. }
  63929. if (!this._doNotChangeAspectRatio) {
  63930. scene.updateTransformMatrix(true);
  63931. }
  63932. // Render
  63933. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63934. if (this._postProcessManager) {
  63935. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63936. }
  63937. else if (useCameraPostProcess) {
  63938. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63939. }
  63940. if (!this._doNotChangeAspectRatio) {
  63941. scene.updateTransformMatrix(true);
  63942. }
  63943. // Dump ?
  63944. if (dumpForDebug) {
  63945. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63946. }
  63947. // Unbind
  63948. if (!this.isCube || faceIndex === 5) {
  63949. if (this.isCube) {
  63950. if (faceIndex === 5) {
  63951. engine.generateMipMapsForCubemap(this._texture);
  63952. }
  63953. }
  63954. this.unbindFrameBuffer(engine, faceIndex);
  63955. }
  63956. else {
  63957. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63958. }
  63959. };
  63960. /**
  63961. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63962. * This allowed control for front to back rendering or reversly depending of the special needs.
  63963. *
  63964. * @param renderingGroupId The rendering group id corresponding to its index
  63965. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63966. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63967. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63968. */
  63969. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63970. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63971. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63972. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63973. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63974. };
  63975. /**
  63976. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63977. *
  63978. * @param renderingGroupId The rendering group id corresponding to its index
  63979. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63980. */
  63981. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63982. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63983. };
  63984. RenderTargetTexture.prototype.clone = function () {
  63985. var textureSize = this.getSize();
  63986. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  63987. // Base texture
  63988. newTexture.hasAlpha = this.hasAlpha;
  63989. newTexture.level = this.level;
  63990. // RenderTarget Texture
  63991. newTexture.coordinatesMode = this.coordinatesMode;
  63992. if (this.renderList) {
  63993. newTexture.renderList = this.renderList.slice(0);
  63994. }
  63995. return newTexture;
  63996. };
  63997. RenderTargetTexture.prototype.serialize = function () {
  63998. if (!this.name) {
  63999. return null;
  64000. }
  64001. var serializationObject = _super.prototype.serialize.call(this);
  64002. serializationObject.renderTargetSize = this.getRenderSize();
  64003. serializationObject.renderList = [];
  64004. if (this.renderList) {
  64005. for (var index = 0; index < this.renderList.length; index++) {
  64006. serializationObject.renderList.push(this.renderList[index].id);
  64007. }
  64008. }
  64009. return serializationObject;
  64010. };
  64011. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64012. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64013. var objBuffer = this.getInternalTexture();
  64014. var scene = this.getScene();
  64015. if (objBuffer && scene) {
  64016. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64017. }
  64018. };
  64019. RenderTargetTexture.prototype.dispose = function () {
  64020. if (this._postProcessManager) {
  64021. this._postProcessManager.dispose();
  64022. this._postProcessManager = null;
  64023. }
  64024. this.clearPostProcesses(true);
  64025. if (this._resizeObserver) {
  64026. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64027. this._resizeObserver = null;
  64028. }
  64029. this.renderList = null;
  64030. // Remove from custom render targets
  64031. var scene = this.getScene();
  64032. if (!scene) {
  64033. return;
  64034. }
  64035. var index = scene.customRenderTargets.indexOf(this);
  64036. if (index >= 0) {
  64037. scene.customRenderTargets.splice(index, 1);
  64038. }
  64039. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64040. var camera = _a[_i];
  64041. index = camera.customRenderTargets.indexOf(this);
  64042. if (index >= 0) {
  64043. camera.customRenderTargets.splice(index, 1);
  64044. }
  64045. }
  64046. _super.prototype.dispose.call(this);
  64047. };
  64048. RenderTargetTexture.prototype._rebuild = function () {
  64049. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64050. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64051. }
  64052. if (this._postProcessManager) {
  64053. this._postProcessManager._rebuild();
  64054. }
  64055. };
  64056. /**
  64057. * Clear the info related to rendering groups preventing retention point in material dispose.
  64058. */
  64059. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64060. if (this._renderingManager) {
  64061. this._renderingManager.freeRenderingGroups();
  64062. }
  64063. };
  64064. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64065. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64066. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64067. return RenderTargetTexture;
  64068. }(BABYLON.Texture));
  64069. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64070. })(BABYLON || (BABYLON = {}));
  64071. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64072. var BABYLON;
  64073. (function (BABYLON) {
  64074. ;
  64075. var MultiRenderTarget = /** @class */ (function (_super) {
  64076. __extends(MultiRenderTarget, _super);
  64077. function MultiRenderTarget(name, size, count, scene, options) {
  64078. var _this = this;
  64079. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64080. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64081. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64082. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64083. _this._engine = scene.getEngine();
  64084. if (!_this.isSupported) {
  64085. _this.dispose();
  64086. return;
  64087. }
  64088. var types = [];
  64089. var samplingModes = [];
  64090. for (var i = 0; i < count; i++) {
  64091. if (options && options.types && options.types[i] !== undefined) {
  64092. types.push(options.types[i]);
  64093. }
  64094. else {
  64095. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64096. }
  64097. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64098. samplingModes.push(options.samplingModes[i]);
  64099. }
  64100. else {
  64101. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64102. }
  64103. }
  64104. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64105. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64106. _this._size = size;
  64107. _this._multiRenderTargetOptions = {
  64108. samplingModes: samplingModes,
  64109. generateMipMaps: generateMipMaps,
  64110. generateDepthBuffer: generateDepthBuffer,
  64111. generateStencilBuffer: generateStencilBuffer,
  64112. generateDepthTexture: generateDepthTexture,
  64113. types: types,
  64114. textureCount: count
  64115. };
  64116. _this._createInternalTextures();
  64117. _this._createTextures();
  64118. return _this;
  64119. }
  64120. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64121. get: function () {
  64122. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64123. },
  64124. enumerable: true,
  64125. configurable: true
  64126. });
  64127. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64128. get: function () {
  64129. return this._textures;
  64130. },
  64131. enumerable: true,
  64132. configurable: true
  64133. });
  64134. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64135. get: function () {
  64136. return this._textures[this._textures.length - 1];
  64137. },
  64138. enumerable: true,
  64139. configurable: true
  64140. });
  64141. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64142. set: function (wrap) {
  64143. if (this._textures) {
  64144. for (var i = 0; i < this._textures.length; i++) {
  64145. this._textures[i].wrapU = wrap;
  64146. }
  64147. }
  64148. },
  64149. enumerable: true,
  64150. configurable: true
  64151. });
  64152. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64153. set: function (wrap) {
  64154. if (this._textures) {
  64155. for (var i = 0; i < this._textures.length; i++) {
  64156. this._textures[i].wrapV = wrap;
  64157. }
  64158. }
  64159. },
  64160. enumerable: true,
  64161. configurable: true
  64162. });
  64163. MultiRenderTarget.prototype._rebuild = function () {
  64164. this.releaseInternalTextures();
  64165. this._createInternalTextures();
  64166. for (var i = 0; i < this._internalTextures.length; i++) {
  64167. var texture = this._textures[i];
  64168. texture._texture = this._internalTextures[i];
  64169. }
  64170. // Keeps references to frame buffer and stencil/depth buffer
  64171. this._texture = this._internalTextures[0];
  64172. };
  64173. MultiRenderTarget.prototype._createInternalTextures = function () {
  64174. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64175. };
  64176. MultiRenderTarget.prototype._createTextures = function () {
  64177. this._textures = [];
  64178. for (var i = 0; i < this._internalTextures.length; i++) {
  64179. var texture = new BABYLON.Texture(null, this.getScene());
  64180. texture._texture = this._internalTextures[i];
  64181. this._textures.push(texture);
  64182. }
  64183. // Keeps references to frame buffer and stencil/depth buffer
  64184. this._texture = this._internalTextures[0];
  64185. };
  64186. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64187. get: function () {
  64188. return this._samples;
  64189. },
  64190. set: function (value) {
  64191. if (this._samples === value) {
  64192. return;
  64193. }
  64194. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64195. },
  64196. enumerable: true,
  64197. configurable: true
  64198. });
  64199. MultiRenderTarget.prototype.resize = function (size) {
  64200. this.releaseInternalTextures();
  64201. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64202. this._createInternalTextures();
  64203. };
  64204. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64205. var _this = this;
  64206. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64207. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64208. });
  64209. };
  64210. MultiRenderTarget.prototype.dispose = function () {
  64211. this.releaseInternalTextures();
  64212. _super.prototype.dispose.call(this);
  64213. };
  64214. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64215. if (!this._internalTextures) {
  64216. return;
  64217. }
  64218. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64219. if (this._internalTextures[i] !== undefined) {
  64220. this._internalTextures[i].dispose();
  64221. this._internalTextures.splice(i, 1);
  64222. }
  64223. }
  64224. };
  64225. return MultiRenderTarget;
  64226. }(BABYLON.RenderTargetTexture));
  64227. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64228. })(BABYLON || (BABYLON = {}));
  64229. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64230. var BABYLON;
  64231. (function (BABYLON) {
  64232. var MirrorTexture = /** @class */ (function (_super) {
  64233. __extends(MirrorTexture, _super);
  64234. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64235. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64236. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64237. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64238. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64239. _this.scene = scene;
  64240. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64241. _this._transformMatrix = BABYLON.Matrix.Zero();
  64242. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64243. _this._adaptiveBlurKernel = 0;
  64244. _this._blurKernelX = 0;
  64245. _this._blurKernelY = 0;
  64246. _this._blurRatio = 1.0;
  64247. _this.ignoreCameraViewport = true;
  64248. _this._updateGammaSpace();
  64249. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64250. _this._updateGammaSpace;
  64251. });
  64252. _this.onBeforeRenderObservable.add(function () {
  64253. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64254. _this._savedViewMatrix = scene.getViewMatrix();
  64255. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64256. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64257. scene.clipPlane = _this.mirrorPlane;
  64258. scene.getEngine().cullBackFaces = false;
  64259. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64260. });
  64261. _this.onAfterRenderObservable.add(function () {
  64262. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64263. scene.getEngine().cullBackFaces = true;
  64264. scene._mirroredCameraPosition = null;
  64265. delete scene.clipPlane;
  64266. });
  64267. return _this;
  64268. }
  64269. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64270. get: function () {
  64271. return this._blurRatio;
  64272. },
  64273. set: function (value) {
  64274. if (this._blurRatio === value) {
  64275. return;
  64276. }
  64277. this._blurRatio = value;
  64278. this._preparePostProcesses();
  64279. },
  64280. enumerable: true,
  64281. configurable: true
  64282. });
  64283. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64284. set: function (value) {
  64285. this._adaptiveBlurKernel = value;
  64286. this._autoComputeBlurKernel();
  64287. },
  64288. enumerable: true,
  64289. configurable: true
  64290. });
  64291. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64292. set: function (value) {
  64293. this.blurKernelX = value;
  64294. this.blurKernelY = value;
  64295. },
  64296. enumerable: true,
  64297. configurable: true
  64298. });
  64299. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64300. get: function () {
  64301. return this._blurKernelX;
  64302. },
  64303. set: function (value) {
  64304. if (this._blurKernelX === value) {
  64305. return;
  64306. }
  64307. this._blurKernelX = value;
  64308. this._preparePostProcesses();
  64309. },
  64310. enumerable: true,
  64311. configurable: true
  64312. });
  64313. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64314. get: function () {
  64315. return this._blurKernelY;
  64316. },
  64317. set: function (value) {
  64318. if (this._blurKernelY === value) {
  64319. return;
  64320. }
  64321. this._blurKernelY = value;
  64322. this._preparePostProcesses();
  64323. },
  64324. enumerable: true,
  64325. configurable: true
  64326. });
  64327. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64328. var engine = this.getScene().getEngine();
  64329. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64330. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64331. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64332. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64333. };
  64334. MirrorTexture.prototype._onRatioRescale = function () {
  64335. if (this._sizeRatio) {
  64336. this.resize(this._initialSizeParameter);
  64337. if (!this._adaptiveBlurKernel) {
  64338. this._preparePostProcesses();
  64339. }
  64340. }
  64341. if (this._adaptiveBlurKernel) {
  64342. this._autoComputeBlurKernel();
  64343. }
  64344. };
  64345. MirrorTexture.prototype._updateGammaSpace = function () {
  64346. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64347. };
  64348. MirrorTexture.prototype._preparePostProcesses = function () {
  64349. this.clearPostProcesses(true);
  64350. if (this._blurKernelX && this._blurKernelY) {
  64351. var engine = this.getScene().getEngine();
  64352. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64353. 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);
  64354. this._blurX.autoClear = false;
  64355. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64356. this._blurX.inputTexture = this._texture;
  64357. }
  64358. else {
  64359. this._blurX.alwaysForcePOT = true;
  64360. }
  64361. 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);
  64362. this._blurY.autoClear = false;
  64363. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64364. this.addPostProcess(this._blurX);
  64365. this.addPostProcess(this._blurY);
  64366. }
  64367. else {
  64368. if (this._blurY) {
  64369. this.removePostProcess(this._blurY);
  64370. this._blurY.dispose();
  64371. this._blurY = null;
  64372. }
  64373. if (this._blurX) {
  64374. this.removePostProcess(this._blurX);
  64375. this._blurX.dispose();
  64376. this._blurX = null;
  64377. }
  64378. }
  64379. };
  64380. MirrorTexture.prototype.clone = function () {
  64381. var scene = this.getScene();
  64382. if (!scene) {
  64383. return this;
  64384. }
  64385. var textureSize = this.getSize();
  64386. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64387. // Base texture
  64388. newTexture.hasAlpha = this.hasAlpha;
  64389. newTexture.level = this.level;
  64390. // Mirror Texture
  64391. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64392. if (this.renderList) {
  64393. newTexture.renderList = this.renderList.slice(0);
  64394. }
  64395. return newTexture;
  64396. };
  64397. MirrorTexture.prototype.serialize = function () {
  64398. if (!this.name) {
  64399. return null;
  64400. }
  64401. var serializationObject = _super.prototype.serialize.call(this);
  64402. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64403. return serializationObject;
  64404. };
  64405. MirrorTexture.prototype.dispose = function () {
  64406. _super.prototype.dispose.call(this);
  64407. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64408. };
  64409. return MirrorTexture;
  64410. }(BABYLON.RenderTargetTexture));
  64411. BABYLON.MirrorTexture = MirrorTexture;
  64412. })(BABYLON || (BABYLON = {}));
  64413. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64414. var BABYLON;
  64415. (function (BABYLON) {
  64416. /**
  64417. * Creates a refraction texture used by refraction channel of the standard material.
  64418. * @param name the texture name
  64419. * @param size size of the underlying texture
  64420. * @param scene root scene
  64421. */
  64422. var RefractionTexture = /** @class */ (function (_super) {
  64423. __extends(RefractionTexture, _super);
  64424. function RefractionTexture(name, size, scene, generateMipMaps) {
  64425. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64426. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64427. _this.depth = 2.0;
  64428. _this.onBeforeRenderObservable.add(function () {
  64429. scene.clipPlane = _this.refractionPlane;
  64430. });
  64431. _this.onAfterRenderObservable.add(function () {
  64432. delete scene.clipPlane;
  64433. });
  64434. return _this;
  64435. }
  64436. RefractionTexture.prototype.clone = function () {
  64437. var scene = this.getScene();
  64438. if (!scene) {
  64439. return this;
  64440. }
  64441. var textureSize = this.getSize();
  64442. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64443. // Base texture
  64444. newTexture.hasAlpha = this.hasAlpha;
  64445. newTexture.level = this.level;
  64446. // Refraction Texture
  64447. newTexture.refractionPlane = this.refractionPlane.clone();
  64448. if (this.renderList) {
  64449. newTexture.renderList = this.renderList.slice(0);
  64450. }
  64451. newTexture.depth = this.depth;
  64452. return newTexture;
  64453. };
  64454. RefractionTexture.prototype.serialize = function () {
  64455. if (!this.name) {
  64456. return null;
  64457. }
  64458. var serializationObject = _super.prototype.serialize.call(this);
  64459. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64460. serializationObject.depth = this.depth;
  64461. return serializationObject;
  64462. };
  64463. return RefractionTexture;
  64464. }(BABYLON.RenderTargetTexture));
  64465. BABYLON.RefractionTexture = RefractionTexture;
  64466. })(BABYLON || (BABYLON = {}));
  64467. //# sourceMappingURL=babylon.refractionTexture.js.map
  64468. var BABYLON;
  64469. (function (BABYLON) {
  64470. /**
  64471. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64472. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64473. */
  64474. var DynamicTexture = /** @class */ (function (_super) {
  64475. __extends(DynamicTexture, _super);
  64476. /**
  64477. * Creates a {BABYLON.DynamicTexture}
  64478. * @param name defines the name of the texture
  64479. * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height
  64480. * @param scene defines the scene where you want the texture
  64481. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64482. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64483. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64484. */
  64485. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64486. if (scene === void 0) { scene = null; }
  64487. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64488. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64489. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64490. _this.name = name;
  64491. _this._engine = _this.getScene().getEngine();
  64492. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64493. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64494. _this._generateMipMaps = generateMipMaps;
  64495. if (options.getContext) {
  64496. _this._canvas = options;
  64497. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64498. }
  64499. else {
  64500. _this._canvas = document.createElement("canvas");
  64501. if (options.width || options.width === 0) {
  64502. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64503. }
  64504. else {
  64505. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64506. }
  64507. }
  64508. var textureSize = _this.getSize();
  64509. _this._canvas.width = textureSize.width;
  64510. _this._canvas.height = textureSize.height;
  64511. _this._context = _this._canvas.getContext("2d");
  64512. return _this;
  64513. }
  64514. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64515. /**
  64516. * Gets the current state of canRescale
  64517. */
  64518. get: function () {
  64519. return true;
  64520. },
  64521. enumerable: true,
  64522. configurable: true
  64523. });
  64524. DynamicTexture.prototype._recreate = function (textureSize) {
  64525. this._canvas.width = textureSize.width;
  64526. this._canvas.height = textureSize.height;
  64527. this.releaseInternalTexture();
  64528. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64529. };
  64530. /**
  64531. * Scales the texture
  64532. * @param ratio the scale factor to apply to both width and height
  64533. */
  64534. DynamicTexture.prototype.scale = function (ratio) {
  64535. var textureSize = this.getSize();
  64536. textureSize.width *= ratio;
  64537. textureSize.height *= ratio;
  64538. this._recreate(textureSize);
  64539. };
  64540. /**
  64541. * Resizes the texture
  64542. * @param width the new width
  64543. * @param height the new height
  64544. */
  64545. DynamicTexture.prototype.scaleTo = function (width, height) {
  64546. var textureSize = this.getSize();
  64547. textureSize.width = width;
  64548. textureSize.height = height;
  64549. this._recreate(textureSize);
  64550. };
  64551. /**
  64552. * Gets the context of the canvas used by the texture
  64553. * @returns the canvas context of the dynamic texture
  64554. */
  64555. DynamicTexture.prototype.getContext = function () {
  64556. return this._context;
  64557. };
  64558. /**
  64559. * Clears the texture
  64560. */
  64561. DynamicTexture.prototype.clear = function () {
  64562. var size = this.getSize();
  64563. this._context.fillRect(0, 0, size.width, size.height);
  64564. };
  64565. /**
  64566. * Updates the texture
  64567. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64568. */
  64569. DynamicTexture.prototype.update = function (invertY) {
  64570. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64571. };
  64572. /**
  64573. * Draws text onto the texture
  64574. * @param text defines the text to be drawn
  64575. * @param x defines the placement of the text from the left
  64576. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64577. * @param font defines the font to be used with font-style, font-size, font-name
  64578. * @param color defines the color used for the text
  64579. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64580. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64581. * @param update defines whether texture is immediately update (default is true)
  64582. */
  64583. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64584. if (update === void 0) { update = true; }
  64585. var size = this.getSize();
  64586. if (clearColor) {
  64587. this._context.fillStyle = clearColor;
  64588. this._context.fillRect(0, 0, size.width, size.height);
  64589. }
  64590. this._context.font = font;
  64591. if (x === null || x === undefined) {
  64592. var textSize = this._context.measureText(text);
  64593. x = (size.width - textSize.width) / 2;
  64594. }
  64595. if (y === null || y === undefined) {
  64596. var fontSize = parseInt((font.replace(/\D/g, '')));
  64597. y = (size.height / 2) + (fontSize / 3.65);
  64598. }
  64599. this._context.fillStyle = color;
  64600. this._context.fillText(text, x, y);
  64601. if (update) {
  64602. this.update(invertY);
  64603. }
  64604. };
  64605. /**
  64606. * Clones the texture
  64607. * @returns the clone of the texture.
  64608. */
  64609. DynamicTexture.prototype.clone = function () {
  64610. var scene = this.getScene();
  64611. if (!scene) {
  64612. return this;
  64613. }
  64614. var textureSize = this.getSize();
  64615. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64616. // Base texture
  64617. newTexture.hasAlpha = this.hasAlpha;
  64618. newTexture.level = this.level;
  64619. // Dynamic Texture
  64620. newTexture.wrapU = this.wrapU;
  64621. newTexture.wrapV = this.wrapV;
  64622. return newTexture;
  64623. };
  64624. /** @hidden */
  64625. DynamicTexture.prototype._rebuild = function () {
  64626. this.update();
  64627. };
  64628. return DynamicTexture;
  64629. }(BABYLON.Texture));
  64630. BABYLON.DynamicTexture = DynamicTexture;
  64631. })(BABYLON || (BABYLON = {}));
  64632. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64633. var BABYLON;
  64634. (function (BABYLON) {
  64635. var VideoTexture = /** @class */ (function (_super) {
  64636. __extends(VideoTexture, _super);
  64637. /**
  64638. * Creates a video texture.
  64639. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64640. * @param {string | null} name optional name, will detect from video source, if not defined
  64641. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64642. * @param {BABYLON.Scene} scene is obviously the current scene.
  64643. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64644. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64645. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64646. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64647. */
  64648. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64649. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64650. if (invertY === void 0) { invertY = false; }
  64651. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64652. if (settings === void 0) { settings = {
  64653. autoPlay: true,
  64654. loop: true,
  64655. autoUpdateTexture: true,
  64656. }; }
  64657. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64658. _this._stillImageCaptured = false;
  64659. _this._createInternalTexture = function () {
  64660. if (_this._texture != null) {
  64661. return;
  64662. }
  64663. if (!_this._engine.needPOTTextures ||
  64664. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64665. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64666. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64667. }
  64668. else {
  64669. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64670. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64671. _this._generateMipMaps = false;
  64672. }
  64673. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64674. if (!_this.video.autoplay) {
  64675. var oldHandler_1 = _this.video.onplaying;
  64676. _this.video.onplaying = function () {
  64677. _this.video.onplaying = oldHandler_1;
  64678. _this._texture.isReady = true;
  64679. _this._updateInternalTexture();
  64680. _this.video.pause();
  64681. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64682. _this.onLoadObservable.notifyObservers(_this);
  64683. }
  64684. };
  64685. _this.video.play();
  64686. }
  64687. else {
  64688. _this._texture.isReady = true;
  64689. _this._updateInternalTexture();
  64690. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64691. _this.onLoadObservable.notifyObservers(_this);
  64692. }
  64693. }
  64694. };
  64695. _this.reset = function () {
  64696. if (_this._texture == null) {
  64697. return;
  64698. }
  64699. _this._texture.dispose();
  64700. _this._texture = null;
  64701. };
  64702. _this._updateInternalTexture = function (e) {
  64703. if (_this._texture == null || !_this._texture.isReady) {
  64704. return;
  64705. }
  64706. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64707. return;
  64708. }
  64709. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64710. };
  64711. _this._engine = _this.getScene().getEngine();
  64712. _this._generateMipMaps = generateMipMaps;
  64713. _this._samplingMode = samplingMode;
  64714. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64715. _this.name = name || _this._getName(src);
  64716. _this.video = _this._getVideo(src);
  64717. if (settings.autoPlay !== undefined) {
  64718. _this.video.autoplay = settings.autoPlay;
  64719. }
  64720. if (settings.loop !== undefined) {
  64721. _this.video.loop = settings.loop;
  64722. }
  64723. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64724. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64725. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64726. _this.video.addEventListener("emptied", _this.reset);
  64727. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64728. _this._createInternalTexture();
  64729. }
  64730. return _this;
  64731. }
  64732. VideoTexture.prototype._getName = function (src) {
  64733. if (src instanceof HTMLVideoElement) {
  64734. return src.currentSrc;
  64735. }
  64736. if (typeof src === "object") {
  64737. return src.toString();
  64738. }
  64739. return src;
  64740. };
  64741. ;
  64742. VideoTexture.prototype._getVideo = function (src) {
  64743. if (src instanceof HTMLVideoElement) {
  64744. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64745. return src;
  64746. }
  64747. var video = document.createElement("video");
  64748. if (typeof src === "string") {
  64749. BABYLON.Tools.SetCorsBehavior(src, video);
  64750. video.src = src;
  64751. }
  64752. else {
  64753. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64754. src.forEach(function (url) {
  64755. var source = document.createElement("source");
  64756. source.src = url;
  64757. video.appendChild(source);
  64758. });
  64759. }
  64760. return video;
  64761. };
  64762. ;
  64763. /**
  64764. * Internal method to initiate `update`.
  64765. */
  64766. VideoTexture.prototype._rebuild = function () {
  64767. this.update();
  64768. };
  64769. /**
  64770. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64771. */
  64772. VideoTexture.prototype.update = function () {
  64773. if (!this.autoUpdateTexture) {
  64774. // Expecting user to call `updateTexture` manually
  64775. return;
  64776. }
  64777. this.updateTexture(true);
  64778. };
  64779. /**
  64780. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64781. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64782. */
  64783. VideoTexture.prototype.updateTexture = function (isVisible) {
  64784. if (!isVisible) {
  64785. return;
  64786. }
  64787. if (this.video.paused && this._stillImageCaptured) {
  64788. return;
  64789. }
  64790. this._stillImageCaptured = true;
  64791. this._updateInternalTexture();
  64792. };
  64793. /**
  64794. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64795. * @param url New url.
  64796. */
  64797. VideoTexture.prototype.updateURL = function (url) {
  64798. this.video.src = url;
  64799. };
  64800. VideoTexture.prototype.dispose = function () {
  64801. _super.prototype.dispose.call(this);
  64802. this.video.removeEventListener("canplay", this._createInternalTexture);
  64803. this.video.removeEventListener("paused", this._updateInternalTexture);
  64804. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64805. this.video.removeEventListener("emptied", this.reset);
  64806. this.video.pause();
  64807. };
  64808. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64809. var video = document.createElement("video");
  64810. var constraintsDeviceId;
  64811. if (constraints && constraints.deviceId) {
  64812. constraintsDeviceId = {
  64813. exact: constraints.deviceId,
  64814. };
  64815. }
  64816. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64817. if (navigator.mediaDevices) {
  64818. navigator.mediaDevices.getUserMedia({ video: constraints })
  64819. .then(function (stream) {
  64820. if (video.mozSrcObject !== undefined) {
  64821. // hack for Firefox < 19
  64822. video.mozSrcObject = stream;
  64823. }
  64824. else {
  64825. video.srcObject = stream;
  64826. }
  64827. var onPlaying = function () {
  64828. if (onReady) {
  64829. onReady(new VideoTexture("video", video, scene, true, true));
  64830. }
  64831. video.removeEventListener("playing", onPlaying);
  64832. };
  64833. video.addEventListener("playing", onPlaying);
  64834. video.play();
  64835. })
  64836. .catch(function (err) {
  64837. BABYLON.Tools.Error(err.name);
  64838. });
  64839. }
  64840. else {
  64841. navigator.getUserMedia =
  64842. navigator.getUserMedia ||
  64843. navigator.webkitGetUserMedia ||
  64844. navigator.mozGetUserMedia ||
  64845. navigator.msGetUserMedia;
  64846. if (navigator.getUserMedia) {
  64847. navigator.getUserMedia({
  64848. video: {
  64849. deviceId: constraintsDeviceId,
  64850. width: {
  64851. min: (constraints && constraints.minWidth) || 256,
  64852. max: (constraints && constraints.maxWidth) || 640,
  64853. },
  64854. height: {
  64855. min: (constraints && constraints.minHeight) || 256,
  64856. max: (constraints && constraints.maxHeight) || 480,
  64857. },
  64858. },
  64859. }, function (stream) {
  64860. if (video.mozSrcObject !== undefined) {
  64861. // hack for Firefox < 19
  64862. video.mozSrcObject = stream;
  64863. }
  64864. else {
  64865. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64866. }
  64867. video.play();
  64868. if (onReady) {
  64869. onReady(new VideoTexture("video", video, scene, true, true));
  64870. }
  64871. }, function (e) {
  64872. BABYLON.Tools.Error(e.name);
  64873. });
  64874. }
  64875. }
  64876. };
  64877. return VideoTexture;
  64878. }(BABYLON.Texture));
  64879. BABYLON.VideoTexture = VideoTexture;
  64880. })(BABYLON || (BABYLON = {}));
  64881. //# sourceMappingURL=babylon.videoTexture.js.map
  64882. var BABYLON;
  64883. (function (BABYLON) {
  64884. var RawTexture = /** @class */ (function (_super) {
  64885. __extends(RawTexture, _super);
  64886. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64887. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64888. if (invertY === void 0) { invertY = false; }
  64889. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64890. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64891. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64892. _this.format = format;
  64893. _this._engine = scene.getEngine();
  64894. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64895. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64896. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64897. return _this;
  64898. }
  64899. RawTexture.prototype.update = function (data) {
  64900. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64901. };
  64902. // Statics
  64903. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64904. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64905. if (invertY === void 0) { invertY = false; }
  64906. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64907. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64908. };
  64909. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64910. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64911. if (invertY === void 0) { invertY = false; }
  64912. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64913. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64914. };
  64915. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64916. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64917. if (invertY === void 0) { invertY = false; }
  64918. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64919. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64920. };
  64921. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64922. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64923. if (invertY === void 0) { invertY = false; }
  64924. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64925. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64926. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64927. };
  64928. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64929. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64930. if (invertY === void 0) { invertY = false; }
  64931. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64932. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64933. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64934. };
  64935. return RawTexture;
  64936. }(BABYLON.Texture));
  64937. BABYLON.RawTexture = RawTexture;
  64938. })(BABYLON || (BABYLON = {}));
  64939. //# sourceMappingURL=babylon.rawTexture.js.map
  64940. var BABYLON;
  64941. (function (BABYLON) {
  64942. /**
  64943. * Class used to store 3D textures containing user data
  64944. */
  64945. var RawTexture3D = /** @class */ (function (_super) {
  64946. __extends(RawTexture3D, _super);
  64947. /**
  64948. * Create a new RawTexture3D
  64949. * @param data defines the data of the texture
  64950. * @param width defines the width of the texture
  64951. * @param height defines the height of the texture
  64952. * @param depth defines the depth of the texture
  64953. * @param format defines the texture format to use
  64954. * @param scene defines the hosting scene
  64955. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64956. * @param invertY defines if texture must be stored with Y axis inverted
  64957. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64958. */
  64959. function RawTexture3D(data, width, height, depth,
  64960. /** Gets or sets the texture format to use*/
  64961. format, scene, generateMipMaps, invertY, samplingMode) {
  64962. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64963. if (invertY === void 0) { invertY = false; }
  64964. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64965. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64966. _this.format = format;
  64967. _this._engine = scene.getEngine();
  64968. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64969. _this.is3D = true;
  64970. return _this;
  64971. }
  64972. /**
  64973. * Update the texture with new data
  64974. * @param data defines the data to store in the texture
  64975. */
  64976. RawTexture3D.prototype.update = function (data) {
  64977. if (!this._texture) {
  64978. return;
  64979. }
  64980. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64981. };
  64982. return RawTexture3D;
  64983. }(BABYLON.Texture));
  64984. BABYLON.RawTexture3D = RawTexture3D;
  64985. })(BABYLON || (BABYLON = {}));
  64986. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64987. var BABYLON;
  64988. (function (BABYLON) {
  64989. /**
  64990. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64991. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64992. */
  64993. var PostProcess = /** @class */ (function () {
  64994. /**
  64995. * Creates a new instance PostProcess
  64996. * @param name The name of the PostProcess.
  64997. * @param fragmentUrl The url of the fragment shader to be used.
  64998. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64999. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65000. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65001. * @param camera The camera to apply the render pass to.
  65002. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65003. * @param engine The engine which the post process will be applied. (default: current engine)
  65004. * @param reusable If the post process can be reused on the same frame. (default: false)
  65005. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65006. * @param textureType Type of textures used when performing the post process. (default: 0)
  65007. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65008. * @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
  65009. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65010. */
  65011. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65012. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65013. if (defines === void 0) { defines = null; }
  65014. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65015. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65016. if (blockCompilation === void 0) { blockCompilation = false; }
  65017. this.name = name;
  65018. /**
  65019. * Width of the texture to apply the post process on
  65020. */
  65021. this.width = -1;
  65022. /**
  65023. * Height of the texture to apply the post process on
  65024. */
  65025. this.height = -1;
  65026. /**
  65027. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65028. */
  65029. this._outputTexture = null;
  65030. /**
  65031. * If the buffer needs to be cleared before applying the post process. (default: true)
  65032. * Should be set to false if shader will overwrite all previous pixels.
  65033. */
  65034. this.autoClear = true;
  65035. /**
  65036. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65037. */
  65038. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65039. /**
  65040. * Animations to be used for the post processing
  65041. */
  65042. this.animations = new Array();
  65043. /**
  65044. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65045. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65046. */
  65047. this.enablePixelPerfectMode = false;
  65048. /**
  65049. * Force the postprocess to be applied without taking in account viewport
  65050. */
  65051. this.forceFullscreenViewport = true;
  65052. /**
  65053. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65054. */
  65055. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65056. /**
  65057. * Force textures to be a power of two (default: false)
  65058. */
  65059. this.alwaysForcePOT = false;
  65060. /**
  65061. * Number of sample textures (default: 1)
  65062. */
  65063. this.samples = 1;
  65064. /**
  65065. * Modify the scale of the post process to be the same as the viewport (default: false)
  65066. */
  65067. this.adaptScaleToCurrentViewport = false;
  65068. this._reusable = false;
  65069. /**
  65070. * Smart array of input and output textures for the post process.
  65071. */
  65072. this._textures = new BABYLON.SmartArray(2);
  65073. /**
  65074. * The index in _textures that corresponds to the output texture.
  65075. */
  65076. this._currentRenderTextureInd = 0;
  65077. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65078. this._texelSize = BABYLON.Vector2.Zero();
  65079. // Events
  65080. /**
  65081. * An event triggered when the postprocess is activated.
  65082. */
  65083. this.onActivateObservable = new BABYLON.Observable();
  65084. /**
  65085. * An event triggered when the postprocess changes its size.
  65086. */
  65087. this.onSizeChangedObservable = new BABYLON.Observable();
  65088. /**
  65089. * An event triggered when the postprocess applies its effect.
  65090. */
  65091. this.onApplyObservable = new BABYLON.Observable();
  65092. /**
  65093. * An event triggered before rendering the postprocess
  65094. */
  65095. this.onBeforeRenderObservable = new BABYLON.Observable();
  65096. /**
  65097. * An event triggered after rendering the postprocess
  65098. */
  65099. this.onAfterRenderObservable = new BABYLON.Observable();
  65100. if (camera != null) {
  65101. this._camera = camera;
  65102. this._scene = camera.getScene();
  65103. camera.attachPostProcess(this);
  65104. this._engine = this._scene.getEngine();
  65105. this._scene.postProcesses.push(this);
  65106. }
  65107. else if (engine) {
  65108. this._engine = engine;
  65109. this._engine.postProcesses.push(this);
  65110. }
  65111. this._options = options;
  65112. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65113. this._reusable = reusable || false;
  65114. this._textureType = textureType;
  65115. this._samplers = samplers || [];
  65116. this._samplers.push("textureSampler");
  65117. this._fragmentUrl = fragmentUrl;
  65118. this._vertexUrl = vertexUrl;
  65119. this._parameters = parameters || [];
  65120. this._parameters.push("scale");
  65121. this._indexParameters = indexParameters;
  65122. if (!blockCompilation) {
  65123. this.updateEffect(defines);
  65124. }
  65125. }
  65126. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65127. /**
  65128. * A function that is added to the onActivateObservable
  65129. */
  65130. set: function (callback) {
  65131. if (this._onActivateObserver) {
  65132. this.onActivateObservable.remove(this._onActivateObserver);
  65133. }
  65134. if (callback) {
  65135. this._onActivateObserver = this.onActivateObservable.add(callback);
  65136. }
  65137. },
  65138. enumerable: true,
  65139. configurable: true
  65140. });
  65141. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65142. /**
  65143. * A function that is added to the onSizeChangedObservable
  65144. */
  65145. set: function (callback) {
  65146. if (this._onSizeChangedObserver) {
  65147. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65148. }
  65149. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65150. },
  65151. enumerable: true,
  65152. configurable: true
  65153. });
  65154. Object.defineProperty(PostProcess.prototype, "onApply", {
  65155. /**
  65156. * A function that is added to the onApplyObservable
  65157. */
  65158. set: function (callback) {
  65159. if (this._onApplyObserver) {
  65160. this.onApplyObservable.remove(this._onApplyObserver);
  65161. }
  65162. this._onApplyObserver = this.onApplyObservable.add(callback);
  65163. },
  65164. enumerable: true,
  65165. configurable: true
  65166. });
  65167. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65168. /**
  65169. * A function that is added to the onBeforeRenderObservable
  65170. */
  65171. set: function (callback) {
  65172. if (this._onBeforeRenderObserver) {
  65173. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65174. }
  65175. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65176. },
  65177. enumerable: true,
  65178. configurable: true
  65179. });
  65180. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65181. /**
  65182. * A function that is added to the onAfterRenderObservable
  65183. */
  65184. set: function (callback) {
  65185. if (this._onAfterRenderObserver) {
  65186. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65187. }
  65188. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65189. },
  65190. enumerable: true,
  65191. configurable: true
  65192. });
  65193. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65194. /**
  65195. * 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
  65196. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65197. */
  65198. get: function () {
  65199. return this._textures.data[this._currentRenderTextureInd];
  65200. },
  65201. set: function (value) {
  65202. this._forcedOutputTexture = value;
  65203. },
  65204. enumerable: true,
  65205. configurable: true
  65206. });
  65207. /**
  65208. * Gets the camera which post process is applied to.
  65209. * @returns The camera the post process is applied to.
  65210. */
  65211. PostProcess.prototype.getCamera = function () {
  65212. return this._camera;
  65213. };
  65214. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65215. /**
  65216. * Gets the texel size of the postprocess.
  65217. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65218. */
  65219. get: function () {
  65220. if (this._shareOutputWithPostProcess) {
  65221. return this._shareOutputWithPostProcess.texelSize;
  65222. }
  65223. if (this._forcedOutputTexture) {
  65224. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65225. }
  65226. return this._texelSize;
  65227. },
  65228. enumerable: true,
  65229. configurable: true
  65230. });
  65231. /**
  65232. * Gets the engine which this post process belongs to.
  65233. * @returns The engine the post process was enabled with.
  65234. */
  65235. PostProcess.prototype.getEngine = function () {
  65236. return this._engine;
  65237. };
  65238. /**
  65239. * The effect that is created when initializing the post process.
  65240. * @returns The created effect corrisponding the the postprocess.
  65241. */
  65242. PostProcess.prototype.getEffect = function () {
  65243. return this._effect;
  65244. };
  65245. /**
  65246. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65247. * @param postProcess The post process to share the output with.
  65248. * @returns This post process.
  65249. */
  65250. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65251. this._disposeTextures();
  65252. this._shareOutputWithPostProcess = postProcess;
  65253. return this;
  65254. };
  65255. /**
  65256. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65257. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65258. */
  65259. PostProcess.prototype.useOwnOutput = function () {
  65260. if (this._textures.length == 0) {
  65261. this._textures = new BABYLON.SmartArray(2);
  65262. }
  65263. this._shareOutputWithPostProcess = null;
  65264. };
  65265. /**
  65266. * Updates the effect with the current post process compile time values and recompiles the shader.
  65267. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65268. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65269. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65270. * @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
  65271. * @param onCompiled Called when the shader has been compiled.
  65272. * @param onError Called if there is an error when compiling a shader.
  65273. */
  65274. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65275. if (defines === void 0) { defines = null; }
  65276. if (uniforms === void 0) { uniforms = null; }
  65277. if (samplers === void 0) { samplers = null; }
  65278. 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);
  65279. };
  65280. /**
  65281. * The post process is reusable if it can be used multiple times within one frame.
  65282. * @returns If the post process is reusable
  65283. */
  65284. PostProcess.prototype.isReusable = function () {
  65285. return this._reusable;
  65286. };
  65287. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65288. PostProcess.prototype.markTextureDirty = function () {
  65289. this.width = -1;
  65290. };
  65291. /**
  65292. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65293. * 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.
  65294. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65295. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65296. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65297. * @returns The target texture that was bound to be written to.
  65298. */
  65299. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65300. var _this = this;
  65301. if (sourceTexture === void 0) { sourceTexture = null; }
  65302. camera = camera || this._camera;
  65303. var scene = camera.getScene();
  65304. var engine = scene.getEngine();
  65305. var maxSize = engine.getCaps().maxTextureSize;
  65306. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65307. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65308. // 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
  65309. var webVRCamera = camera.parent;
  65310. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65311. requiredWidth /= 2;
  65312. }
  65313. var desiredWidth = (this._options.width || requiredWidth);
  65314. var desiredHeight = this._options.height || requiredHeight;
  65315. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65316. if (this.adaptScaleToCurrentViewport) {
  65317. var currentViewport = engine.currentViewport;
  65318. if (currentViewport) {
  65319. desiredWidth *= currentViewport.width;
  65320. desiredHeight *= currentViewport.height;
  65321. }
  65322. }
  65323. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65324. if (!this._options.width) {
  65325. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65326. }
  65327. if (!this._options.height) {
  65328. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65329. }
  65330. }
  65331. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65332. if (this._textures.length > 0) {
  65333. for (var i = 0; i < this._textures.length; i++) {
  65334. this._engine._releaseTexture(this._textures.data[i]);
  65335. }
  65336. this._textures.reset();
  65337. }
  65338. this.width = desiredWidth;
  65339. this.height = desiredHeight;
  65340. var textureSize = { width: this.width, height: this.height };
  65341. var textureOptions = {
  65342. generateMipMaps: false,
  65343. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65344. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65345. samplingMode: this.renderTargetSamplingMode,
  65346. type: this._textureType
  65347. };
  65348. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65349. if (this._reusable) {
  65350. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65351. }
  65352. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65353. this.onSizeChangedObservable.notifyObservers(this);
  65354. }
  65355. this._textures.forEach(function (texture) {
  65356. if (texture.samples !== _this.samples) {
  65357. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65358. }
  65359. });
  65360. }
  65361. var target;
  65362. if (this._shareOutputWithPostProcess) {
  65363. target = this._shareOutputWithPostProcess.inputTexture;
  65364. }
  65365. else if (this._forcedOutputTexture) {
  65366. target = this._forcedOutputTexture;
  65367. this.width = this._forcedOutputTexture.width;
  65368. this.height = this._forcedOutputTexture.height;
  65369. }
  65370. else {
  65371. target = this.inputTexture;
  65372. }
  65373. // Bind the input of this post process to be used as the output of the previous post process.
  65374. if (this.enablePixelPerfectMode) {
  65375. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65376. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65377. }
  65378. else {
  65379. this._scaleRatio.copyFromFloats(1, 1);
  65380. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65381. }
  65382. this.onActivateObservable.notifyObservers(camera);
  65383. // Clear
  65384. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65385. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65386. }
  65387. if (this._reusable) {
  65388. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65389. }
  65390. return target;
  65391. };
  65392. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65393. /**
  65394. * If the post process is supported.
  65395. */
  65396. get: function () {
  65397. return this._effect.isSupported;
  65398. },
  65399. enumerable: true,
  65400. configurable: true
  65401. });
  65402. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65403. /**
  65404. * The aspect ratio of the output texture.
  65405. */
  65406. get: function () {
  65407. if (this._shareOutputWithPostProcess) {
  65408. return this._shareOutputWithPostProcess.aspectRatio;
  65409. }
  65410. if (this._forcedOutputTexture) {
  65411. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65412. }
  65413. return this.width / this.height;
  65414. },
  65415. enumerable: true,
  65416. configurable: true
  65417. });
  65418. /**
  65419. * Get a value indicating if the post-process is ready to be used
  65420. * @returns true if the post-process is ready (shader is compiled)
  65421. */
  65422. PostProcess.prototype.isReady = function () {
  65423. return this._effect && this._effect.isReady();
  65424. };
  65425. /**
  65426. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65427. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65428. */
  65429. PostProcess.prototype.apply = function () {
  65430. // Check
  65431. if (!this._effect || !this._effect.isReady())
  65432. return null;
  65433. // States
  65434. this._engine.enableEffect(this._effect);
  65435. this._engine.setState(false);
  65436. this._engine.setDepthBuffer(false);
  65437. this._engine.setDepthWrite(false);
  65438. // Alpha
  65439. this._engine.setAlphaMode(this.alphaMode);
  65440. if (this.alphaConstants) {
  65441. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65442. }
  65443. // Bind the output texture of the preivous post process as the input to this post process.
  65444. var source;
  65445. if (this._shareOutputWithPostProcess) {
  65446. source = this._shareOutputWithPostProcess.inputTexture;
  65447. }
  65448. else if (this._forcedOutputTexture) {
  65449. source = this._forcedOutputTexture;
  65450. }
  65451. else {
  65452. source = this.inputTexture;
  65453. }
  65454. this._effect._bindTexture("textureSampler", source);
  65455. // Parameters
  65456. this._effect.setVector2("scale", this._scaleRatio);
  65457. this.onApplyObservable.notifyObservers(this._effect);
  65458. return this._effect;
  65459. };
  65460. PostProcess.prototype._disposeTextures = function () {
  65461. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65462. return;
  65463. }
  65464. if (this._textures.length > 0) {
  65465. for (var i = 0; i < this._textures.length; i++) {
  65466. this._engine._releaseTexture(this._textures.data[i]);
  65467. }
  65468. }
  65469. this._textures.dispose();
  65470. };
  65471. /**
  65472. * Disposes the post process.
  65473. * @param camera The camera to dispose the post process on.
  65474. */
  65475. PostProcess.prototype.dispose = function (camera) {
  65476. camera = camera || this._camera;
  65477. this._disposeTextures();
  65478. if (this._scene) {
  65479. var index_1 = this._scene.postProcesses.indexOf(this);
  65480. if (index_1 !== -1) {
  65481. this._scene.postProcesses.splice(index_1, 1);
  65482. }
  65483. }
  65484. else {
  65485. var index_2 = this._engine.postProcesses.indexOf(this);
  65486. if (index_2 !== -1) {
  65487. this._engine.postProcesses.splice(index_2, 1);
  65488. }
  65489. }
  65490. if (!camera) {
  65491. return;
  65492. }
  65493. camera.detachPostProcess(this);
  65494. var index = camera._postProcesses.indexOf(this);
  65495. if (index === 0 && camera._postProcesses.length > 0) {
  65496. var firstPostProcess = this._camera._getFirstPostProcess();
  65497. if (firstPostProcess) {
  65498. firstPostProcess.markTextureDirty();
  65499. }
  65500. }
  65501. this.onActivateObservable.clear();
  65502. this.onAfterRenderObservable.clear();
  65503. this.onApplyObservable.clear();
  65504. this.onBeforeRenderObservable.clear();
  65505. this.onSizeChangedObservable.clear();
  65506. };
  65507. return PostProcess;
  65508. }());
  65509. BABYLON.PostProcess = PostProcess;
  65510. })(BABYLON || (BABYLON = {}));
  65511. //# sourceMappingURL=babylon.postProcess.js.map
  65512. var BABYLON;
  65513. (function (BABYLON) {
  65514. var PassPostProcess = /** @class */ (function (_super) {
  65515. __extends(PassPostProcess, _super);
  65516. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65517. if (camera === void 0) { camera = null; }
  65518. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65519. if (blockCompilation === void 0) { blockCompilation = false; }
  65520. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65521. }
  65522. return PassPostProcess;
  65523. }(BABYLON.PostProcess));
  65524. BABYLON.PassPostProcess = PassPostProcess;
  65525. })(BABYLON || (BABYLON = {}));
  65526. //# sourceMappingURL=babylon.passPostProcess.js.map
  65527. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65528. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65529. s = arguments[i];
  65530. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65531. t[p] = s[p];
  65532. }
  65533. return t;
  65534. };
  65535. var BABYLON;
  65536. (function (BABYLON) {
  65537. /**
  65538. * Default implementation IShadowGenerator.
  65539. * This is the main object responsible of generating shadows in the framework.
  65540. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65541. */
  65542. var ShadowGenerator = /** @class */ (function () {
  65543. /**
  65544. * Creates a ShadowGenerator object.
  65545. * A ShadowGenerator is the required tool to use the shadows.
  65546. * Each light casting shadows needs to use its own ShadowGenerator.
  65547. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65548. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65549. * @param light The light object generating the shadows.
  65550. * @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.
  65551. */
  65552. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65553. this._bias = 0.00005;
  65554. this._normalBias = 0;
  65555. this._blurBoxOffset = 1;
  65556. this._blurScale = 2;
  65557. this._blurKernel = 1;
  65558. this._useKernelBlur = false;
  65559. this._filter = ShadowGenerator.FILTER_NONE;
  65560. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65561. this._contactHardeningLightSizeUVRatio = 0.1;
  65562. this._darkness = 0;
  65563. this._transparencyShadow = false;
  65564. /**
  65565. * Controls the extent to which the shadows fade out at the edge of the frustum
  65566. * Used only by directionals and spots
  65567. */
  65568. this.frustumEdgeFalloff = 0;
  65569. /**
  65570. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65571. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65572. * It might on the other hand introduce peter panning.
  65573. */
  65574. this.forceBackFacesOnly = false;
  65575. this._lightDirection = BABYLON.Vector3.Zero();
  65576. this._viewMatrix = BABYLON.Matrix.Zero();
  65577. this._projectionMatrix = BABYLON.Matrix.Zero();
  65578. this._transformMatrix = BABYLON.Matrix.Zero();
  65579. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65580. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65581. this._currentFaceIndex = 0;
  65582. this._currentFaceIndexCache = 0;
  65583. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65584. this._mapSize = mapSize;
  65585. this._light = light;
  65586. this._scene = light.getScene();
  65587. light._shadowGenerator = this;
  65588. // Texture type fallback from float to int if not supported.
  65589. var caps = this._scene.getEngine().getCaps();
  65590. if (!useFullFloatFirst) {
  65591. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65592. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65593. }
  65594. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65595. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65596. }
  65597. else {
  65598. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65599. }
  65600. }
  65601. else {
  65602. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65603. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65604. }
  65605. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65606. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65607. }
  65608. else {
  65609. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65610. }
  65611. }
  65612. this._initializeGenerator();
  65613. this._applyFilterValues();
  65614. }
  65615. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65616. /**
  65617. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65618. */
  65619. get: function () {
  65620. return this._bias;
  65621. },
  65622. /**
  65623. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65624. */
  65625. set: function (bias) {
  65626. this._bias = bias;
  65627. },
  65628. enumerable: true,
  65629. configurable: true
  65630. });
  65631. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65632. /**
  65633. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65634. */
  65635. get: function () {
  65636. return this._normalBias;
  65637. },
  65638. /**
  65639. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65640. */
  65641. set: function (normalBias) {
  65642. this._normalBias = normalBias;
  65643. },
  65644. enumerable: true,
  65645. configurable: true
  65646. });
  65647. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65648. /**
  65649. * Gets the blur box offset: offset applied during the blur pass.
  65650. * Only usefull if useKernelBlur = false
  65651. */
  65652. get: function () {
  65653. return this._blurBoxOffset;
  65654. },
  65655. /**
  65656. * Sets the blur box offset: offset applied during the blur pass.
  65657. * Only usefull if useKernelBlur = false
  65658. */
  65659. set: function (value) {
  65660. if (this._blurBoxOffset === value) {
  65661. return;
  65662. }
  65663. this._blurBoxOffset = value;
  65664. this._disposeBlurPostProcesses();
  65665. },
  65666. enumerable: true,
  65667. configurable: true
  65668. });
  65669. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65670. /**
  65671. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65672. * 2 means half of the size.
  65673. */
  65674. get: function () {
  65675. return this._blurScale;
  65676. },
  65677. /**
  65678. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65679. * 2 means half of the size.
  65680. */
  65681. set: function (value) {
  65682. if (this._blurScale === value) {
  65683. return;
  65684. }
  65685. this._blurScale = value;
  65686. this._disposeBlurPostProcesses();
  65687. },
  65688. enumerable: true,
  65689. configurable: true
  65690. });
  65691. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65692. /**
  65693. * Gets the blur kernel: kernel size of the blur pass.
  65694. * Only usefull if useKernelBlur = true
  65695. */
  65696. get: function () {
  65697. return this._blurKernel;
  65698. },
  65699. /**
  65700. * Sets the blur kernel: kernel size of the blur pass.
  65701. * Only usefull if useKernelBlur = true
  65702. */
  65703. set: function (value) {
  65704. if (this._blurKernel === value) {
  65705. return;
  65706. }
  65707. this._blurKernel = value;
  65708. this._disposeBlurPostProcesses();
  65709. },
  65710. enumerable: true,
  65711. configurable: true
  65712. });
  65713. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65714. /**
  65715. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65716. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65717. */
  65718. get: function () {
  65719. return this._useKernelBlur;
  65720. },
  65721. /**
  65722. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65723. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65724. */
  65725. set: function (value) {
  65726. if (this._useKernelBlur === value) {
  65727. return;
  65728. }
  65729. this._useKernelBlur = value;
  65730. this._disposeBlurPostProcesses();
  65731. },
  65732. enumerable: true,
  65733. configurable: true
  65734. });
  65735. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65736. /**
  65737. * Gets the depth scale used in ESM mode.
  65738. */
  65739. get: function () {
  65740. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65741. },
  65742. /**
  65743. * Sets the depth scale used in ESM mode.
  65744. * This can override the scale stored on the light.
  65745. */
  65746. set: function (value) {
  65747. this._depthScale = value;
  65748. },
  65749. enumerable: true,
  65750. configurable: true
  65751. });
  65752. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65753. /**
  65754. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65755. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65756. */
  65757. get: function () {
  65758. return this._filter;
  65759. },
  65760. /**
  65761. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65762. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65763. */
  65764. set: function (value) {
  65765. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65766. if (this._light.needCube()) {
  65767. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65768. this.useExponentialShadowMap = true;
  65769. return;
  65770. }
  65771. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65772. this.useCloseExponentialShadowMap = true;
  65773. return;
  65774. }
  65775. // PCF on cubemap would also be expensive
  65776. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65777. this.usePoissonSampling = true;
  65778. return;
  65779. }
  65780. }
  65781. // Weblg1 fallback for PCF.
  65782. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65783. if (this._scene.getEngine().webGLVersion === 1) {
  65784. this.usePoissonSampling = true;
  65785. return;
  65786. }
  65787. }
  65788. if (this._filter === value) {
  65789. return;
  65790. }
  65791. this._filter = value;
  65792. this._disposeBlurPostProcesses();
  65793. this._applyFilterValues();
  65794. this._light._markMeshesAsLightDirty();
  65795. },
  65796. enumerable: true,
  65797. configurable: true
  65798. });
  65799. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65800. /**
  65801. * Gets if the current filter is set to Poisson Sampling.
  65802. */
  65803. get: function () {
  65804. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65805. },
  65806. /**
  65807. * Sets the current filter to Poisson Sampling.
  65808. */
  65809. set: function (value) {
  65810. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65811. return;
  65812. }
  65813. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65814. },
  65815. enumerable: true,
  65816. configurable: true
  65817. });
  65818. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65819. /**
  65820. * Gets if the current filter is set to VSM.
  65821. * DEPRECATED. Should use useExponentialShadowMap instead.
  65822. */
  65823. get: function () {
  65824. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65825. return this.useExponentialShadowMap;
  65826. },
  65827. /**
  65828. * Sets the current filter is to VSM.
  65829. * DEPRECATED. Should use useExponentialShadowMap instead.
  65830. */
  65831. set: function (value) {
  65832. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65833. this.useExponentialShadowMap = value;
  65834. },
  65835. enumerable: true,
  65836. configurable: true
  65837. });
  65838. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65839. /**
  65840. * Gets if the current filter is set to blurred VSM.
  65841. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65842. */
  65843. get: function () {
  65844. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65845. return this.useBlurExponentialShadowMap;
  65846. },
  65847. /**
  65848. * Sets the current filter is to blurred VSM.
  65849. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65850. */
  65851. set: function (value) {
  65852. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65853. this.useBlurExponentialShadowMap = value;
  65854. },
  65855. enumerable: true,
  65856. configurable: true
  65857. });
  65858. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65859. /**
  65860. * Gets if the current filter is set to ESM.
  65861. */
  65862. get: function () {
  65863. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65864. },
  65865. /**
  65866. * Sets the current filter is to ESM.
  65867. */
  65868. set: function (value) {
  65869. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65870. return;
  65871. }
  65872. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65873. },
  65874. enumerable: true,
  65875. configurable: true
  65876. });
  65877. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65878. /**
  65879. * Gets if the current filter is set to filtered ESM.
  65880. */
  65881. get: function () {
  65882. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65883. },
  65884. /**
  65885. * Gets if the current filter is set to filtered ESM.
  65886. */
  65887. set: function (value) {
  65888. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65889. return;
  65890. }
  65891. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65892. },
  65893. enumerable: true,
  65894. configurable: true
  65895. });
  65896. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65897. /**
  65898. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65899. * exponential to prevent steep falloff artifacts).
  65900. */
  65901. get: function () {
  65902. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65903. },
  65904. /**
  65905. * Sets the current filter to "close ESM" (using the inverse of the
  65906. * exponential to prevent steep falloff artifacts).
  65907. */
  65908. set: function (value) {
  65909. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65910. return;
  65911. }
  65912. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65913. },
  65914. enumerable: true,
  65915. configurable: true
  65916. });
  65917. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65918. /**
  65919. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65920. * exponential to prevent steep falloff artifacts).
  65921. */
  65922. get: function () {
  65923. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65924. },
  65925. /**
  65926. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65927. * exponential to prevent steep falloff artifacts).
  65928. */
  65929. set: function (value) {
  65930. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65931. return;
  65932. }
  65933. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65934. },
  65935. enumerable: true,
  65936. configurable: true
  65937. });
  65938. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65939. /**
  65940. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65941. */
  65942. get: function () {
  65943. return this.filter === ShadowGenerator.FILTER_PCF;
  65944. },
  65945. /**
  65946. * Sets the current filter to "PCF" (percentage closer filtering).
  65947. */
  65948. set: function (value) {
  65949. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65950. return;
  65951. }
  65952. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65953. },
  65954. enumerable: true,
  65955. configurable: true
  65956. });
  65957. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65958. /**
  65959. * Gets the PCF or PCSS Quality.
  65960. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65961. */
  65962. get: function () {
  65963. return this._filteringQuality;
  65964. },
  65965. /**
  65966. * Sets the PCF or PCSS Quality.
  65967. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65968. */
  65969. set: function (filteringQuality) {
  65970. this._filteringQuality = filteringQuality;
  65971. },
  65972. enumerable: true,
  65973. configurable: true
  65974. });
  65975. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65976. /**
  65977. * Gets if the current filter is set to "PCSS" (contact hardening).
  65978. */
  65979. get: function () {
  65980. return this.filter === ShadowGenerator.FILTER_PCSS;
  65981. },
  65982. /**
  65983. * Sets the current filter to "PCSS" (contact hardening).
  65984. */
  65985. set: function (value) {
  65986. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65987. return;
  65988. }
  65989. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65990. },
  65991. enumerable: true,
  65992. configurable: true
  65993. });
  65994. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65995. /**
  65996. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65997. * Using a ratio helps keeping shape stability independently of the map size.
  65998. *
  65999. * It does not account for the light projection as it was having too much
  66000. * instability during the light setup or during light position changes.
  66001. *
  66002. * Only valid if useContactHardeningShadow is true.
  66003. */
  66004. get: function () {
  66005. return this._contactHardeningLightSizeUVRatio;
  66006. },
  66007. /**
  66008. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66009. * Using a ratio helps keeping shape stability independently of the map size.
  66010. *
  66011. * It does not account for the light projection as it was having too much
  66012. * instability during the light setup or during light position changes.
  66013. *
  66014. * Only valid if useContactHardeningShadow is true.
  66015. */
  66016. set: function (contactHardeningLightSizeUVRatio) {
  66017. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66018. },
  66019. enumerable: true,
  66020. configurable: true
  66021. });
  66022. /**
  66023. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66024. * 0 means strongest and 1 would means no shadow.
  66025. * @returns the darkness.
  66026. */
  66027. ShadowGenerator.prototype.getDarkness = function () {
  66028. return this._darkness;
  66029. };
  66030. /**
  66031. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66032. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66033. * @returns the shadow generator allowing fluent coding.
  66034. */
  66035. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66036. if (darkness >= 1.0)
  66037. this._darkness = 1.0;
  66038. else if (darkness <= 0.0)
  66039. this._darkness = 0.0;
  66040. else
  66041. this._darkness = darkness;
  66042. return this;
  66043. };
  66044. /**
  66045. * Sets the ability to have transparent shadow (boolean).
  66046. * @param transparent True if transparent else False
  66047. * @returns the shadow generator allowing fluent coding
  66048. */
  66049. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66050. this._transparencyShadow = transparent;
  66051. return this;
  66052. };
  66053. /**
  66054. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66055. * @returns The render target texture if present otherwise, null
  66056. */
  66057. ShadowGenerator.prototype.getShadowMap = function () {
  66058. return this._shadowMap;
  66059. };
  66060. /**
  66061. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66062. * @returns The render target texture if the shadow map is present otherwise, null
  66063. */
  66064. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66065. if (this._shadowMap2) {
  66066. return this._shadowMap2;
  66067. }
  66068. return this._shadowMap;
  66069. };
  66070. /**
  66071. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66072. * @param mesh Mesh to add
  66073. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66074. * @returns the Shadow Generator itself
  66075. */
  66076. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66077. if (includeDescendants === void 0) { includeDescendants = true; }
  66078. if (!this._shadowMap) {
  66079. return this;
  66080. }
  66081. if (!this._shadowMap.renderList) {
  66082. this._shadowMap.renderList = [];
  66083. }
  66084. this._shadowMap.renderList.push(mesh);
  66085. if (includeDescendants) {
  66086. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66087. }
  66088. return this;
  66089. var _a;
  66090. };
  66091. /**
  66092. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66093. * @param mesh Mesh to remove
  66094. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66095. * @returns the Shadow Generator itself
  66096. */
  66097. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66098. if (includeDescendants === void 0) { includeDescendants = true; }
  66099. if (!this._shadowMap || !this._shadowMap.renderList) {
  66100. return this;
  66101. }
  66102. var index = this._shadowMap.renderList.indexOf(mesh);
  66103. if (index !== -1) {
  66104. this._shadowMap.renderList.splice(index, 1);
  66105. }
  66106. if (includeDescendants) {
  66107. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66108. var child = _a[_i];
  66109. this.removeShadowCaster(child);
  66110. }
  66111. }
  66112. return this;
  66113. };
  66114. /**
  66115. * Returns the associated light object.
  66116. * @returns the light generating the shadow
  66117. */
  66118. ShadowGenerator.prototype.getLight = function () {
  66119. return this._light;
  66120. };
  66121. ShadowGenerator.prototype._initializeGenerator = function () {
  66122. this._light._markMeshesAsLightDirty();
  66123. this._initializeShadowMap();
  66124. };
  66125. ShadowGenerator.prototype._initializeShadowMap = function () {
  66126. var _this = this;
  66127. // Render target
  66128. var engine = this._scene.getEngine();
  66129. if (engine.webGLVersion > 1) {
  66130. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66131. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66132. }
  66133. else {
  66134. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66135. }
  66136. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66137. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66138. this._shadowMap.anisotropicFilteringLevel = 1;
  66139. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66140. this._shadowMap.renderParticles = false;
  66141. this._shadowMap.ignoreCameraViewport = true;
  66142. // Record Face Index before render.
  66143. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66144. _this._currentFaceIndex = faceIndex;
  66145. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66146. engine.setColorWrite(false);
  66147. }
  66148. });
  66149. // Custom render function.
  66150. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66151. // Blur if required afer render.
  66152. this._shadowMap.onAfterUnbindObservable.add(function () {
  66153. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66154. engine.setColorWrite(true);
  66155. }
  66156. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66157. return;
  66158. }
  66159. var shadowMap = _this.getShadowMapForRendering();
  66160. if (shadowMap) {
  66161. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66162. }
  66163. });
  66164. // Clear according to the chosen filter.
  66165. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66166. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66167. this._shadowMap.onClearObservable.add(function (engine) {
  66168. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66169. engine.clear(clearOne, false, true, false);
  66170. }
  66171. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66172. engine.clear(clearZero, true, true, false);
  66173. }
  66174. else {
  66175. engine.clear(clearOne, true, true, false);
  66176. }
  66177. });
  66178. };
  66179. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66180. var _this = this;
  66181. var engine = this._scene.getEngine();
  66182. var targetSize = this._mapSize / this.blurScale;
  66183. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66184. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66185. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66186. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66187. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66188. }
  66189. if (this.useKernelBlur) {
  66190. 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);
  66191. this._kernelBlurXPostprocess.width = targetSize;
  66192. this._kernelBlurXPostprocess.height = targetSize;
  66193. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66194. effect.setTexture("textureSampler", _this._shadowMap);
  66195. });
  66196. 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);
  66197. this._kernelBlurXPostprocess.autoClear = false;
  66198. this._kernelBlurYPostprocess.autoClear = false;
  66199. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66200. this._kernelBlurXPostprocess.packedFloat = true;
  66201. this._kernelBlurYPostprocess.packedFloat = true;
  66202. }
  66203. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66204. }
  66205. else {
  66206. 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);
  66207. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66208. effect.setFloat2("screenSize", targetSize, targetSize);
  66209. effect.setTexture("textureSampler", _this._shadowMap);
  66210. });
  66211. this._boxBlurPostprocess.autoClear = false;
  66212. this._blurPostProcesses = [this._boxBlurPostprocess];
  66213. }
  66214. };
  66215. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66216. var index;
  66217. var engine = this._scene.getEngine();
  66218. if (depthOnlySubMeshes.length) {
  66219. engine.setColorWrite(false);
  66220. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66221. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66222. }
  66223. engine.setColorWrite(true);
  66224. }
  66225. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66226. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66227. }
  66228. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66229. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66230. }
  66231. if (this._transparencyShadow) {
  66232. for (index = 0; index < transparentSubMeshes.length; index++) {
  66233. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66234. }
  66235. }
  66236. };
  66237. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66238. var _this = this;
  66239. var mesh = subMesh.getRenderingMesh();
  66240. var scene = this._scene;
  66241. var engine = scene.getEngine();
  66242. var material = subMesh.getMaterial();
  66243. if (!material) {
  66244. return;
  66245. }
  66246. // Culling
  66247. engine.setState(material.backFaceCulling);
  66248. // Managing instances
  66249. var batch = mesh._getInstancesRenderList(subMesh._id);
  66250. if (batch.mustReturn) {
  66251. return;
  66252. }
  66253. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66254. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66255. engine.enableEffect(this._effect);
  66256. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66257. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66258. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66259. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66260. this._effect.setVector3("lightData", this._cachedDirection);
  66261. }
  66262. else {
  66263. this._effect.setVector3("lightData", this._cachedPosition);
  66264. }
  66265. if (scene.activeCamera) {
  66266. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66267. }
  66268. // Alpha test
  66269. if (material && material.needAlphaTesting()) {
  66270. var alphaTexture = material.getAlphaTestTexture();
  66271. if (alphaTexture) {
  66272. this._effect.setTexture("diffuseSampler", alphaTexture);
  66273. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66274. }
  66275. }
  66276. // Bones
  66277. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66278. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66279. }
  66280. // Morph targets
  66281. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66282. if (this.forceBackFacesOnly) {
  66283. engine.setState(true, 0, false, true);
  66284. }
  66285. // Draw
  66286. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66287. if (this.forceBackFacesOnly) {
  66288. engine.setState(true, 0, false, false);
  66289. }
  66290. }
  66291. else {
  66292. // Need to reset refresh rate of the shadowMap
  66293. if (this._shadowMap) {
  66294. this._shadowMap.resetRefreshCounter();
  66295. }
  66296. }
  66297. };
  66298. ShadowGenerator.prototype._applyFilterValues = function () {
  66299. if (!this._shadowMap) {
  66300. return;
  66301. }
  66302. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66303. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66304. }
  66305. else {
  66306. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66307. }
  66308. };
  66309. /**
  66310. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66311. * @param onCompiled Callback triggered at the and of the effects compilation
  66312. * @param options Sets of optional options forcing the compilation with different modes
  66313. */
  66314. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66315. var _this = this;
  66316. var localOptions = __assign({ useInstances: false }, options);
  66317. var shadowMap = this.getShadowMap();
  66318. if (!shadowMap) {
  66319. if (onCompiled) {
  66320. onCompiled(this);
  66321. }
  66322. return;
  66323. }
  66324. var renderList = shadowMap.renderList;
  66325. if (!renderList) {
  66326. if (onCompiled) {
  66327. onCompiled(this);
  66328. }
  66329. return;
  66330. }
  66331. var subMeshes = new Array();
  66332. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66333. var mesh = renderList_1[_i];
  66334. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66335. }
  66336. if (subMeshes.length === 0) {
  66337. if (onCompiled) {
  66338. onCompiled(this);
  66339. }
  66340. return;
  66341. }
  66342. var currentIndex = 0;
  66343. var checkReady = function () {
  66344. if (!_this._scene || !_this._scene.getEngine()) {
  66345. return;
  66346. }
  66347. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66348. currentIndex++;
  66349. if (currentIndex >= subMeshes.length) {
  66350. if (onCompiled) {
  66351. onCompiled(_this);
  66352. }
  66353. return;
  66354. }
  66355. }
  66356. setTimeout(checkReady, 16);
  66357. };
  66358. checkReady();
  66359. };
  66360. /**
  66361. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66362. * @param options Sets of optional options forcing the compilation with different modes
  66363. * @returns A promise that resolves when the compilation completes
  66364. */
  66365. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66366. var _this = this;
  66367. return new Promise(function (resolve) {
  66368. _this.forceCompilation(function () {
  66369. resolve();
  66370. }, options);
  66371. });
  66372. };
  66373. /**
  66374. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66375. * @param subMesh The submesh we want to render in the shadow map
  66376. * @param useInstances Defines wether will draw in the map using instances
  66377. * @returns true if ready otherwise, false
  66378. */
  66379. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66380. var defines = [];
  66381. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66382. defines.push("#define FLOAT");
  66383. }
  66384. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66385. defines.push("#define ESM");
  66386. }
  66387. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66388. defines.push("#define DEPTHTEXTURE");
  66389. }
  66390. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66391. var mesh = subMesh.getMesh();
  66392. var material = subMesh.getMaterial();
  66393. // Normal bias.
  66394. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66395. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66396. defines.push("#define NORMAL");
  66397. if (mesh.nonUniformScaling) {
  66398. defines.push("#define NONUNIFORMSCALING");
  66399. }
  66400. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66401. defines.push("#define DIRECTIONINLIGHTDATA");
  66402. }
  66403. }
  66404. // Alpha test
  66405. if (material && material.needAlphaTesting()) {
  66406. var alphaTexture = material.getAlphaTestTexture();
  66407. if (alphaTexture) {
  66408. defines.push("#define ALPHATEST");
  66409. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66410. attribs.push(BABYLON.VertexBuffer.UVKind);
  66411. defines.push("#define UV1");
  66412. }
  66413. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66414. if (alphaTexture.coordinatesIndex === 1) {
  66415. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66416. defines.push("#define UV2");
  66417. }
  66418. }
  66419. }
  66420. }
  66421. // Bones
  66422. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66423. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66424. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66425. if (mesh.numBoneInfluencers > 4) {
  66426. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66427. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66428. }
  66429. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66430. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66431. }
  66432. else {
  66433. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66434. }
  66435. // Morph targets
  66436. var manager = mesh.morphTargetManager;
  66437. var morphInfluencers = 0;
  66438. if (manager) {
  66439. if (manager.numInfluencers > 0) {
  66440. defines.push("#define MORPHTARGETS");
  66441. morphInfluencers = manager.numInfluencers;
  66442. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66443. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66444. }
  66445. }
  66446. // Instances
  66447. if (useInstances) {
  66448. defines.push("#define INSTANCES");
  66449. attribs.push("world0");
  66450. attribs.push("world1");
  66451. attribs.push("world2");
  66452. attribs.push("world3");
  66453. }
  66454. // Get correct effect
  66455. var join = defines.join("\n");
  66456. if (this._cachedDefines !== join) {
  66457. this._cachedDefines = join;
  66458. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66459. }
  66460. if (!this._effect.isReady()) {
  66461. return false;
  66462. }
  66463. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66464. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66465. this._initializeBlurRTTAndPostProcesses();
  66466. }
  66467. }
  66468. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66469. return false;
  66470. }
  66471. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66472. return false;
  66473. }
  66474. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66475. return false;
  66476. }
  66477. return true;
  66478. };
  66479. /**
  66480. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66481. * @param defines Defines of the material we want to update
  66482. * @param lightIndex Index of the light in the enabled light list of the material
  66483. */
  66484. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66485. var scene = this._scene;
  66486. var light = this._light;
  66487. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66488. return;
  66489. }
  66490. defines["SHADOW" + lightIndex] = true;
  66491. if (this.useContactHardeningShadow) {
  66492. defines["SHADOWPCSS" + lightIndex] = true;
  66493. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66494. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66495. }
  66496. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66497. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66498. }
  66499. // else default to high.
  66500. }
  66501. if (this.usePercentageCloserFiltering) {
  66502. defines["SHADOWPCF" + lightIndex] = true;
  66503. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66504. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66505. }
  66506. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66507. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66508. }
  66509. // else default to high.
  66510. }
  66511. else if (this.usePoissonSampling) {
  66512. defines["SHADOWPOISSON" + lightIndex] = true;
  66513. }
  66514. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66515. defines["SHADOWESM" + lightIndex] = true;
  66516. }
  66517. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66518. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66519. }
  66520. if (light.needCube()) {
  66521. defines["SHADOWCUBE" + lightIndex] = true;
  66522. }
  66523. };
  66524. /**
  66525. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66526. * defined in the generator but impacting the effect).
  66527. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66528. * @param effect The effect we are binfing the information for
  66529. */
  66530. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66531. var light = this._light;
  66532. var scene = this._scene;
  66533. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66534. return;
  66535. }
  66536. var camera = scene.activeCamera;
  66537. if (!camera) {
  66538. return;
  66539. }
  66540. var shadowMap = this.getShadowMap();
  66541. if (!shadowMap) {
  66542. return;
  66543. }
  66544. if (!light.needCube()) {
  66545. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66546. }
  66547. // Only PCF uses depth stencil texture.
  66548. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66549. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66550. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66551. }
  66552. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66553. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66554. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66555. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66556. }
  66557. else {
  66558. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66559. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66560. }
  66561. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66562. };
  66563. /**
  66564. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66565. * (eq to shadow prjection matrix * light transform matrix)
  66566. * @returns The transform matrix used to create the shadow map
  66567. */
  66568. ShadowGenerator.prototype.getTransformMatrix = function () {
  66569. var scene = this._scene;
  66570. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66571. return this._transformMatrix;
  66572. }
  66573. this._currentRenderID = scene.getRenderId();
  66574. this._currentFaceIndexCache = this._currentFaceIndex;
  66575. var lightPosition = this._light.position;
  66576. if (this._light.computeTransformedInformation()) {
  66577. lightPosition = this._light.transformedPosition;
  66578. }
  66579. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66580. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66581. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66582. }
  66583. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66584. this._cachedPosition.copyFrom(lightPosition);
  66585. this._cachedDirection.copyFrom(this._lightDirection);
  66586. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66587. var shadowMap = this.getShadowMap();
  66588. if (shadowMap) {
  66589. var renderList = shadowMap.renderList;
  66590. if (renderList) {
  66591. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66592. }
  66593. }
  66594. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66595. }
  66596. return this._transformMatrix;
  66597. };
  66598. /**
  66599. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66600. * Cube and 2D textures for instance.
  66601. */
  66602. ShadowGenerator.prototype.recreateShadowMap = function () {
  66603. var shadowMap = this._shadowMap;
  66604. if (!shadowMap) {
  66605. return;
  66606. }
  66607. // Track render list.
  66608. var renderList = shadowMap.renderList;
  66609. // Clean up existing data.
  66610. this._disposeRTTandPostProcesses();
  66611. // Reinitializes.
  66612. this._initializeGenerator();
  66613. // Reaffect the filter to ensure a correct fallback if necessary.
  66614. this.filter = this.filter;
  66615. // Reaffect the filter.
  66616. this._applyFilterValues();
  66617. // Reaffect Render List.
  66618. this._shadowMap.renderList = renderList;
  66619. };
  66620. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66621. if (this._shadowMap2) {
  66622. this._shadowMap2.dispose();
  66623. this._shadowMap2 = null;
  66624. }
  66625. if (this._boxBlurPostprocess) {
  66626. this._boxBlurPostprocess.dispose();
  66627. this._boxBlurPostprocess = null;
  66628. }
  66629. if (this._kernelBlurXPostprocess) {
  66630. this._kernelBlurXPostprocess.dispose();
  66631. this._kernelBlurXPostprocess = null;
  66632. }
  66633. if (this._kernelBlurYPostprocess) {
  66634. this._kernelBlurYPostprocess.dispose();
  66635. this._kernelBlurYPostprocess = null;
  66636. }
  66637. this._blurPostProcesses = [];
  66638. };
  66639. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66640. if (this._shadowMap) {
  66641. this._shadowMap.dispose();
  66642. this._shadowMap = null;
  66643. }
  66644. this._disposeBlurPostProcesses();
  66645. };
  66646. /**
  66647. * Disposes the ShadowGenerator.
  66648. * Returns nothing.
  66649. */
  66650. ShadowGenerator.prototype.dispose = function () {
  66651. this._disposeRTTandPostProcesses();
  66652. if (this._light) {
  66653. this._light._shadowGenerator = null;
  66654. this._light._markMeshesAsLightDirty();
  66655. }
  66656. };
  66657. /**
  66658. * Serializes the shadow generator setup to a json object.
  66659. * @returns The serialized JSON object
  66660. */
  66661. ShadowGenerator.prototype.serialize = function () {
  66662. var serializationObject = {};
  66663. var shadowMap = this.getShadowMap();
  66664. if (!shadowMap) {
  66665. return serializationObject;
  66666. }
  66667. serializationObject.lightId = this._light.id;
  66668. serializationObject.mapSize = shadowMap.getRenderSize();
  66669. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66670. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66671. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66672. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66673. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66674. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66675. serializationObject.depthScale = this.depthScale;
  66676. serializationObject.darkness = this.getDarkness();
  66677. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66678. serializationObject.blurKernel = this.blurKernel;
  66679. serializationObject.blurScale = this.blurScale;
  66680. serializationObject.useKernelBlur = this.useKernelBlur;
  66681. serializationObject.transparencyShadow = this._transparencyShadow;
  66682. serializationObject.bias = this.bias;
  66683. serializationObject.normalBias = this.normalBias;
  66684. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66685. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66686. serializationObject.filteringQuality = this.filteringQuality;
  66687. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66688. serializationObject.renderList = [];
  66689. if (shadowMap.renderList) {
  66690. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66691. var mesh = shadowMap.renderList[meshIndex];
  66692. serializationObject.renderList.push(mesh.id);
  66693. }
  66694. }
  66695. return serializationObject;
  66696. };
  66697. /**
  66698. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66699. * @param parsedShadowGenerator The JSON object to parse
  66700. * @param scene The scene to create the shadow map for
  66701. * @returns The parsed shadow generator
  66702. */
  66703. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66704. //casting to point light, as light is missing the position attr and typescript complains.
  66705. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66706. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66707. var shadowMap = shadowGenerator.getShadowMap();
  66708. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66709. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66710. meshes.forEach(function (mesh) {
  66711. if (!shadowMap) {
  66712. return;
  66713. }
  66714. if (!shadowMap.renderList) {
  66715. shadowMap.renderList = [];
  66716. }
  66717. shadowMap.renderList.push(mesh);
  66718. });
  66719. }
  66720. if (parsedShadowGenerator.usePoissonSampling) {
  66721. shadowGenerator.usePoissonSampling = true;
  66722. }
  66723. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66724. shadowGenerator.useExponentialShadowMap = true;
  66725. }
  66726. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66727. shadowGenerator.useBlurExponentialShadowMap = true;
  66728. }
  66729. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66730. shadowGenerator.useCloseExponentialShadowMap = true;
  66731. }
  66732. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66733. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66734. }
  66735. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66736. shadowGenerator.usePercentageCloserFiltering = true;
  66737. }
  66738. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66739. shadowGenerator.useContactHardeningShadow = true;
  66740. }
  66741. if (parsedShadowGenerator.filteringQuality) {
  66742. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66743. }
  66744. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66745. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66746. }
  66747. // Backward compat
  66748. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66749. shadowGenerator.useExponentialShadowMap = true;
  66750. }
  66751. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66752. shadowGenerator.useBlurExponentialShadowMap = true;
  66753. }
  66754. if (parsedShadowGenerator.depthScale) {
  66755. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66756. }
  66757. if (parsedShadowGenerator.blurScale) {
  66758. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66759. }
  66760. if (parsedShadowGenerator.blurBoxOffset) {
  66761. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66762. }
  66763. if (parsedShadowGenerator.useKernelBlur) {
  66764. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66765. }
  66766. if (parsedShadowGenerator.blurKernel) {
  66767. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66768. }
  66769. if (parsedShadowGenerator.bias !== undefined) {
  66770. shadowGenerator.bias = parsedShadowGenerator.bias;
  66771. }
  66772. if (parsedShadowGenerator.normalBias !== undefined) {
  66773. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66774. }
  66775. if (parsedShadowGenerator.darkness) {
  66776. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66777. }
  66778. if (parsedShadowGenerator.transparencyShadow) {
  66779. shadowGenerator.setTransparencyShadow(true);
  66780. }
  66781. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66782. return shadowGenerator;
  66783. };
  66784. /**
  66785. * Shadow generator mode None: no filtering applied.
  66786. */
  66787. ShadowGenerator.FILTER_NONE = 0;
  66788. /**
  66789. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66790. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66791. */
  66792. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66793. /**
  66794. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66795. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66796. */
  66797. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66798. /**
  66799. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66800. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66801. */
  66802. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66803. /**
  66804. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66805. * edge artifacts on steep falloff.
  66806. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66807. */
  66808. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66809. /**
  66810. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66811. * edge artifacts on steep falloff.
  66812. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66813. */
  66814. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66815. /**
  66816. * Shadow generator mode PCF: Percentage Closer Filtering
  66817. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66818. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66819. */
  66820. ShadowGenerator.FILTER_PCF = 6;
  66821. /**
  66822. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66823. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66824. * Contact Hardening
  66825. */
  66826. ShadowGenerator.FILTER_PCSS = 7;
  66827. /**
  66828. * Reserved for PCF and PCSS
  66829. * Highest Quality.
  66830. *
  66831. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66832. *
  66833. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66834. */
  66835. ShadowGenerator.QUALITY_HIGH = 0;
  66836. /**
  66837. * Reserved for PCF and PCSS
  66838. * Good tradeoff for quality/perf cross devices
  66839. *
  66840. * Execute PCF on a 3*3 kernel.
  66841. *
  66842. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66843. */
  66844. ShadowGenerator.QUALITY_MEDIUM = 1;
  66845. /**
  66846. * Reserved for PCF and PCSS
  66847. * The lowest quality but the fastest.
  66848. *
  66849. * Execute PCF on a 1*1 kernel.
  66850. *
  66851. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66852. */
  66853. ShadowGenerator.QUALITY_LOW = 2;
  66854. return ShadowGenerator;
  66855. }());
  66856. BABYLON.ShadowGenerator = ShadowGenerator;
  66857. })(BABYLON || (BABYLON = {}));
  66858. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66859. var BABYLON;
  66860. (function (BABYLON) {
  66861. var DefaultLoadingScreen = /** @class */ (function () {
  66862. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66863. if (_loadingText === void 0) { _loadingText = ""; }
  66864. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66865. var _this = this;
  66866. this._renderingCanvas = _renderingCanvas;
  66867. this._loadingText = _loadingText;
  66868. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66869. // Resize
  66870. this._resizeLoadingUI = function () {
  66871. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66872. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66873. if (!_this._loadingDiv) {
  66874. return;
  66875. }
  66876. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66877. _this._loadingDiv.style.left = canvasRect.left + "px";
  66878. _this._loadingDiv.style.top = canvasRect.top + "px";
  66879. _this._loadingDiv.style.width = canvasRect.width + "px";
  66880. _this._loadingDiv.style.height = canvasRect.height + "px";
  66881. };
  66882. }
  66883. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66884. if (this._loadingDiv) {
  66885. // Do not add a loading screen if there is already one
  66886. return;
  66887. }
  66888. this._loadingDiv = document.createElement("div");
  66889. this._loadingDiv.id = "babylonjsLoadingDiv";
  66890. this._loadingDiv.style.opacity = "0";
  66891. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66892. this._loadingDiv.style.pointerEvents = "none";
  66893. // Loading text
  66894. this._loadingTextDiv = document.createElement("div");
  66895. this._loadingTextDiv.style.position = "absolute";
  66896. this._loadingTextDiv.style.left = "0";
  66897. this._loadingTextDiv.style.top = "50%";
  66898. this._loadingTextDiv.style.marginTop = "80px";
  66899. this._loadingTextDiv.style.width = "100%";
  66900. this._loadingTextDiv.style.height = "20px";
  66901. this._loadingTextDiv.style.fontFamily = "Arial";
  66902. this._loadingTextDiv.style.fontSize = "14px";
  66903. this._loadingTextDiv.style.color = "white";
  66904. this._loadingTextDiv.style.textAlign = "center";
  66905. this._loadingTextDiv.innerHTML = "Loading";
  66906. this._loadingDiv.appendChild(this._loadingTextDiv);
  66907. //set the predefined text
  66908. this._loadingTextDiv.innerHTML = this._loadingText;
  66909. // Generating keyframes
  66910. var style = document.createElement('style');
  66911. style.type = 'text/css';
  66912. 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 }";
  66913. style.innerHTML = keyFrames;
  66914. document.getElementsByTagName('head')[0].appendChild(style);
  66915. // Loading img
  66916. var imgBack = new Image();
  66917. 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";
  66918. imgBack.style.position = "absolute";
  66919. imgBack.style.left = "50%";
  66920. imgBack.style.top = "50%";
  66921. imgBack.style.marginLeft = "-60px";
  66922. imgBack.style.marginTop = "-60px";
  66923. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66924. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66925. imgBack.style.transformOrigin = "50% 50%";
  66926. imgBack.style.webkitTransformOrigin = "50% 50%";
  66927. this._loadingDiv.appendChild(imgBack);
  66928. this._resizeLoadingUI();
  66929. window.addEventListener("resize", this._resizeLoadingUI);
  66930. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66931. document.body.appendChild(this._loadingDiv);
  66932. this._loadingDiv.style.opacity = "1";
  66933. };
  66934. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66935. var _this = this;
  66936. if (!this._loadingDiv) {
  66937. return;
  66938. }
  66939. var onTransitionEnd = function () {
  66940. if (!_this._loadingDiv) {
  66941. return;
  66942. }
  66943. document.body.removeChild(_this._loadingDiv);
  66944. window.removeEventListener("resize", _this._resizeLoadingUI);
  66945. _this._loadingDiv = null;
  66946. };
  66947. this._loadingDiv.style.opacity = "0";
  66948. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66949. };
  66950. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66951. set: function (text) {
  66952. this._loadingText = text;
  66953. if (this._loadingTextDiv) {
  66954. this._loadingTextDiv.innerHTML = this._loadingText;
  66955. }
  66956. },
  66957. enumerable: true,
  66958. configurable: true
  66959. });
  66960. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66961. get: function () {
  66962. return this._loadingDivBackgroundColor;
  66963. },
  66964. set: function (color) {
  66965. this._loadingDivBackgroundColor = color;
  66966. if (!this._loadingDiv) {
  66967. return;
  66968. }
  66969. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66970. },
  66971. enumerable: true,
  66972. configurable: true
  66973. });
  66974. return DefaultLoadingScreen;
  66975. }());
  66976. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66977. })(BABYLON || (BABYLON = {}));
  66978. //# sourceMappingURL=babylon.loadingScreen.js.map
  66979. var BABYLON;
  66980. (function (BABYLON) {
  66981. var SceneLoaderProgressEvent = /** @class */ (function () {
  66982. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66983. this.lengthComputable = lengthComputable;
  66984. this.loaded = loaded;
  66985. this.total = total;
  66986. }
  66987. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66988. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66989. };
  66990. return SceneLoaderProgressEvent;
  66991. }());
  66992. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66993. var SceneLoader = /** @class */ (function () {
  66994. function SceneLoader() {
  66995. }
  66996. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66997. get: function () {
  66998. return 0;
  66999. },
  67000. enumerable: true,
  67001. configurable: true
  67002. });
  67003. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67004. get: function () {
  67005. return 1;
  67006. },
  67007. enumerable: true,
  67008. configurable: true
  67009. });
  67010. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67011. get: function () {
  67012. return 2;
  67013. },
  67014. enumerable: true,
  67015. configurable: true
  67016. });
  67017. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67018. get: function () {
  67019. return 3;
  67020. },
  67021. enumerable: true,
  67022. configurable: true
  67023. });
  67024. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67025. get: function () {
  67026. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67027. },
  67028. set: function (value) {
  67029. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67030. },
  67031. enumerable: true,
  67032. configurable: true
  67033. });
  67034. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67035. get: function () {
  67036. return SceneLoader._ShowLoadingScreen;
  67037. },
  67038. set: function (value) {
  67039. SceneLoader._ShowLoadingScreen = value;
  67040. },
  67041. enumerable: true,
  67042. configurable: true
  67043. });
  67044. Object.defineProperty(SceneLoader, "loggingLevel", {
  67045. get: function () {
  67046. return SceneLoader._loggingLevel;
  67047. },
  67048. set: function (value) {
  67049. SceneLoader._loggingLevel = value;
  67050. },
  67051. enumerable: true,
  67052. configurable: true
  67053. });
  67054. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67055. get: function () {
  67056. return SceneLoader._CleanBoneMatrixWeights;
  67057. },
  67058. set: function (value) {
  67059. SceneLoader._CleanBoneMatrixWeights = value;
  67060. },
  67061. enumerable: true,
  67062. configurable: true
  67063. });
  67064. SceneLoader._getDefaultPlugin = function () {
  67065. return SceneLoader._registeredPlugins[".babylon"];
  67066. };
  67067. SceneLoader._getPluginForExtension = function (extension) {
  67068. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67069. if (registeredPlugin) {
  67070. return registeredPlugin;
  67071. }
  67072. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  67073. return SceneLoader._getDefaultPlugin();
  67074. };
  67075. SceneLoader._getPluginForDirectLoad = function (data) {
  67076. for (var extension in SceneLoader._registeredPlugins) {
  67077. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67078. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67079. return SceneLoader._registeredPlugins[extension];
  67080. }
  67081. }
  67082. return SceneLoader._getDefaultPlugin();
  67083. };
  67084. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67085. if (sceneFilename.name) {
  67086. sceneFilename = sceneFilename.name;
  67087. }
  67088. var queryStringPosition = sceneFilename.indexOf("?");
  67089. if (queryStringPosition !== -1) {
  67090. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67091. }
  67092. var dotPosition = sceneFilename.lastIndexOf(".");
  67093. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67094. return SceneLoader._getPluginForExtension(extension);
  67095. };
  67096. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67097. SceneLoader._getDirectLoad = function (sceneFilename) {
  67098. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67099. return sceneFilename.substr(5);
  67100. }
  67101. return null;
  67102. };
  67103. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67104. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67105. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67106. var plugin;
  67107. if (registeredPlugin.plugin.createPlugin) {
  67108. plugin = registeredPlugin.plugin.createPlugin();
  67109. }
  67110. else {
  67111. plugin = registeredPlugin.plugin;
  67112. }
  67113. var useArrayBuffer = registeredPlugin.isBinary;
  67114. var database;
  67115. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67116. var dataCallback = function (data, responseURL) {
  67117. if (scene.isDisposed) {
  67118. onError("Scene has been disposed");
  67119. return;
  67120. }
  67121. scene.database = database;
  67122. onSuccess(plugin, data, responseURL);
  67123. };
  67124. var request = null;
  67125. var pluginDisposed = false;
  67126. var onDisposeObservable = plugin.onDisposeObservable;
  67127. if (onDisposeObservable) {
  67128. onDisposeObservable.add(function () {
  67129. pluginDisposed = true;
  67130. if (request) {
  67131. request.abort();
  67132. request = null;
  67133. }
  67134. onDispose();
  67135. });
  67136. }
  67137. var manifestChecked = function () {
  67138. if (pluginDisposed) {
  67139. return;
  67140. }
  67141. var url = rootUrl + sceneFilename;
  67142. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67143. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67144. } : undefined, database, useArrayBuffer, function (request, exception) {
  67145. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67146. });
  67147. };
  67148. if (directLoad) {
  67149. dataCallback(directLoad);
  67150. return plugin;
  67151. }
  67152. if (rootUrl.indexOf("file:") === -1) {
  67153. var engine = scene.getEngine();
  67154. var canUseOfflineSupport = engine.enableOfflineSupport;
  67155. if (canUseOfflineSupport) {
  67156. // Also check for exceptions
  67157. var exceptionFound = false;
  67158. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67159. var regex = _a[_i];
  67160. if (regex.test(rootUrl + sceneFilename)) {
  67161. exceptionFound = true;
  67162. break;
  67163. }
  67164. }
  67165. canUseOfflineSupport = !exceptionFound;
  67166. }
  67167. if (canUseOfflineSupport) {
  67168. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67169. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67170. }
  67171. else {
  67172. manifestChecked();
  67173. }
  67174. }
  67175. // Loading file from disk via input file or drag'n'drop
  67176. else {
  67177. var fileOrString = sceneFilename;
  67178. if (fileOrString.name) { // File
  67179. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67180. }
  67181. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67182. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67183. }
  67184. else {
  67185. onError("Unable to find file named " + sceneFilename);
  67186. }
  67187. }
  67188. return plugin;
  67189. };
  67190. // Public functions
  67191. SceneLoader.GetPluginForExtension = function (extension) {
  67192. return SceneLoader._getPluginForExtension(extension).plugin;
  67193. };
  67194. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67195. return !!SceneLoader._registeredPlugins[extension];
  67196. };
  67197. SceneLoader.RegisterPlugin = function (plugin) {
  67198. if (typeof plugin.extensions === "string") {
  67199. var extension = plugin.extensions;
  67200. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67201. plugin: plugin,
  67202. isBinary: false
  67203. };
  67204. }
  67205. else {
  67206. var extensions = plugin.extensions;
  67207. Object.keys(extensions).forEach(function (extension) {
  67208. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67209. plugin: plugin,
  67210. isBinary: extensions[extension].isBinary
  67211. };
  67212. });
  67213. }
  67214. };
  67215. /**
  67216. * Import meshes into a scene
  67217. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67218. * @param rootUrl a string that defines the root url for scene and resources
  67219. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67220. * @param scene the instance of BABYLON.Scene to append to
  67221. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67222. * @param onProgress a callback with a progress event for each file being loaded
  67223. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67224. * @param pluginExtension the extension used to determine the plugin
  67225. * @returns The loaded plugin
  67226. */
  67227. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67228. if (onSuccess === void 0) { onSuccess = null; }
  67229. if (onProgress === void 0) { onProgress = null; }
  67230. if (onError === void 0) { onError = null; }
  67231. if (pluginExtension === void 0) { pluginExtension = null; }
  67232. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67233. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67234. return null;
  67235. }
  67236. var loadingToken = {};
  67237. scene._addPendingData(loadingToken);
  67238. var disposeHandler = function () {
  67239. scene._removePendingData(loadingToken);
  67240. };
  67241. var errorHandler = function (message, exception) {
  67242. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67243. if (onError) {
  67244. onError(scene, errorMessage, exception);
  67245. }
  67246. else {
  67247. BABYLON.Tools.Error(errorMessage);
  67248. // should the exception be thrown?
  67249. }
  67250. disposeHandler();
  67251. };
  67252. var progressHandler = onProgress ? function (event) {
  67253. try {
  67254. onProgress(event);
  67255. }
  67256. catch (e) {
  67257. errorHandler("Error in onProgress callback", e);
  67258. }
  67259. } : undefined;
  67260. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67261. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67262. if (onSuccess) {
  67263. try {
  67264. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67265. }
  67266. catch (e) {
  67267. errorHandler("Error in onSuccess callback", e);
  67268. }
  67269. }
  67270. scene._removePendingData(loadingToken);
  67271. };
  67272. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67273. if (plugin.rewriteRootURL) {
  67274. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67275. }
  67276. if (sceneFilename === "") {
  67277. if (sceneFilename === "") {
  67278. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67279. }
  67280. }
  67281. if (plugin.importMesh) {
  67282. var syncedPlugin = plugin;
  67283. var meshes = new Array();
  67284. var particleSystems = new Array();
  67285. var skeletons = new Array();
  67286. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67287. return;
  67288. }
  67289. scene.loadingPluginName = plugin.name;
  67290. successHandler(meshes, particleSystems, skeletons, []);
  67291. }
  67292. else {
  67293. var asyncedPlugin = plugin;
  67294. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67295. scene.loadingPluginName = plugin.name;
  67296. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67297. }).catch(function (error) {
  67298. errorHandler(error.message, error);
  67299. });
  67300. }
  67301. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67302. };
  67303. /**
  67304. * Import meshes into a scene
  67305. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67306. * @param rootUrl a string that defines the root url for scene and resources
  67307. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67308. * @param scene the instance of BABYLON.Scene to append to
  67309. * @param onProgress a callback with a progress event for each file being loaded
  67310. * @param pluginExtension the extension used to determine the plugin
  67311. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67312. */
  67313. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67314. if (onProgress === void 0) { onProgress = null; }
  67315. if (pluginExtension === void 0) { pluginExtension = null; }
  67316. return new Promise(function (resolve, reject) {
  67317. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67318. resolve({
  67319. meshes: meshes,
  67320. particleSystems: particleSystems,
  67321. skeletons: skeletons,
  67322. animationGroups: animationGroups
  67323. });
  67324. }, onProgress, function (scene, message, exception) {
  67325. reject(exception || new Error(message));
  67326. }, pluginExtension);
  67327. });
  67328. };
  67329. /**
  67330. * Load a scene
  67331. * @param rootUrl a string that defines the root url for scene and resources
  67332. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67333. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67334. * @param onSuccess a callback with the scene when import succeeds
  67335. * @param onProgress a callback with a progress event for each file being loaded
  67336. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67337. * @param pluginExtension the extension used to determine the plugin
  67338. * @returns The loaded plugin
  67339. */
  67340. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67341. if (onSuccess === void 0) { onSuccess = null; }
  67342. if (onProgress === void 0) { onProgress = null; }
  67343. if (onError === void 0) { onError = null; }
  67344. if (pluginExtension === void 0) { pluginExtension = null; }
  67345. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67346. };
  67347. /**
  67348. * Load a scene
  67349. * @param rootUrl a string that defines the root url for scene and resources
  67350. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67351. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67352. * @param onProgress a callback with a progress event for each file being loaded
  67353. * @param pluginExtension the extension used to determine the plugin
  67354. * @returns The loaded scene
  67355. */
  67356. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67357. if (onProgress === void 0) { onProgress = null; }
  67358. if (pluginExtension === void 0) { pluginExtension = null; }
  67359. return new Promise(function (resolve, reject) {
  67360. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67361. resolve(scene);
  67362. }, onProgress, function (scene, message, exception) {
  67363. reject(exception || new Error(message));
  67364. }, pluginExtension);
  67365. });
  67366. };
  67367. /**
  67368. * Append a scene
  67369. * @param rootUrl a string that defines the root url for scene and resources
  67370. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67371. * @param scene is the instance of BABYLON.Scene to append to
  67372. * @param onSuccess a callback with the scene when import succeeds
  67373. * @param onProgress a callback with a progress event for each file being loaded
  67374. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67375. * @param pluginExtension the extension used to determine the plugin
  67376. * @returns The loaded plugin
  67377. */
  67378. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67379. if (onSuccess === void 0) { onSuccess = null; }
  67380. if (onProgress === void 0) { onProgress = null; }
  67381. if (onError === void 0) { onError = null; }
  67382. if (pluginExtension === void 0) { pluginExtension = null; }
  67383. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67384. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67385. return null;
  67386. }
  67387. if (SceneLoader.ShowLoadingScreen) {
  67388. scene.getEngine().displayLoadingUI();
  67389. }
  67390. var loadingToken = {};
  67391. scene._addPendingData(loadingToken);
  67392. var disposeHandler = function () {
  67393. scene._removePendingData(loadingToken);
  67394. scene.getEngine().hideLoadingUI();
  67395. };
  67396. var errorHandler = function (message, exception) {
  67397. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67398. if (onError) {
  67399. onError(scene, errorMessage, exception);
  67400. }
  67401. else {
  67402. BABYLON.Tools.Error(errorMessage);
  67403. // should the exception be thrown?
  67404. }
  67405. disposeHandler();
  67406. };
  67407. var progressHandler = onProgress ? function (event) {
  67408. try {
  67409. onProgress(event);
  67410. }
  67411. catch (e) {
  67412. errorHandler("Error in onProgress callback", e);
  67413. }
  67414. } : undefined;
  67415. var successHandler = function () {
  67416. if (onSuccess) {
  67417. try {
  67418. onSuccess(scene);
  67419. }
  67420. catch (e) {
  67421. errorHandler("Error in onSuccess callback", e);
  67422. }
  67423. }
  67424. scene._removePendingData(loadingToken);
  67425. };
  67426. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67427. if (sceneFilename === "") {
  67428. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67429. }
  67430. if (plugin.load) {
  67431. var syncedPlugin = plugin;
  67432. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67433. return;
  67434. }
  67435. scene.loadingPluginName = plugin.name;
  67436. successHandler();
  67437. }
  67438. else {
  67439. var asyncedPlugin = plugin;
  67440. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67441. scene.loadingPluginName = plugin.name;
  67442. successHandler();
  67443. }).catch(function (error) {
  67444. errorHandler(error.message, error);
  67445. });
  67446. }
  67447. if (SceneLoader.ShowLoadingScreen) {
  67448. scene.executeWhenReady(function () {
  67449. scene.getEngine().hideLoadingUI();
  67450. });
  67451. }
  67452. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67453. };
  67454. /**
  67455. * Append a scene
  67456. * @param rootUrl a string that defines the root url for scene and resources
  67457. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67458. * @param scene is the instance of BABYLON.Scene to append to
  67459. * @param onProgress a callback with a progress event for each file being loaded
  67460. * @param pluginExtension the extension used to determine the plugin
  67461. * @returns The given scene
  67462. */
  67463. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67464. if (onProgress === void 0) { onProgress = null; }
  67465. if (pluginExtension === void 0) { pluginExtension = null; }
  67466. return new Promise(function (resolve, reject) {
  67467. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67468. resolve(scene);
  67469. }, onProgress, function (scene, message, exception) {
  67470. reject(exception || new Error(message));
  67471. }, pluginExtension);
  67472. });
  67473. };
  67474. /**
  67475. * Load a scene into an asset container
  67476. * @param rootUrl a string that defines the root url for scene and resources
  67477. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67478. * @param scene is the instance of BABYLON.Scene to append to
  67479. * @param onSuccess a callback with the scene when import succeeds
  67480. * @param onProgress a callback with a progress event for each file being loaded
  67481. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67482. * @param pluginExtension the extension used to determine the plugin
  67483. * @returns The loaded plugin
  67484. */
  67485. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67486. if (onSuccess === void 0) { onSuccess = null; }
  67487. if (onProgress === void 0) { onProgress = null; }
  67488. if (onError === void 0) { onError = null; }
  67489. if (pluginExtension === void 0) { pluginExtension = null; }
  67490. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67491. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67492. return null;
  67493. }
  67494. var loadingToken = {};
  67495. scene._addPendingData(loadingToken);
  67496. var disposeHandler = function () {
  67497. scene._removePendingData(loadingToken);
  67498. };
  67499. var errorHandler = function (message, exception) {
  67500. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67501. if (onError) {
  67502. onError(scene, errorMessage, exception);
  67503. }
  67504. else {
  67505. BABYLON.Tools.Error(errorMessage);
  67506. // should the exception be thrown?
  67507. }
  67508. disposeHandler();
  67509. };
  67510. var progressHandler = onProgress ? function (event) {
  67511. try {
  67512. onProgress(event);
  67513. }
  67514. catch (e) {
  67515. errorHandler("Error in onProgress callback", e);
  67516. }
  67517. } : undefined;
  67518. var successHandler = function (assets) {
  67519. if (onSuccess) {
  67520. try {
  67521. onSuccess(assets);
  67522. }
  67523. catch (e) {
  67524. errorHandler("Error in onSuccess callback", e);
  67525. }
  67526. }
  67527. scene._removePendingData(loadingToken);
  67528. };
  67529. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67530. if (plugin.loadAssetContainer) {
  67531. var syncedPlugin = plugin;
  67532. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67533. if (!assetContainer) {
  67534. return;
  67535. }
  67536. scene.loadingPluginName = plugin.name;
  67537. successHandler(assetContainer);
  67538. }
  67539. else if (plugin.loadAssetContainerAsync) {
  67540. var asyncedPlugin = plugin;
  67541. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67542. scene.loadingPluginName = plugin.name;
  67543. successHandler(assetContainer);
  67544. }).catch(function (error) {
  67545. errorHandler(error.message, error);
  67546. });
  67547. }
  67548. else {
  67549. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67550. }
  67551. if (SceneLoader.ShowLoadingScreen) {
  67552. scene.executeWhenReady(function () {
  67553. scene.getEngine().hideLoadingUI();
  67554. });
  67555. }
  67556. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67557. };
  67558. /**
  67559. * Load a scene into an asset container
  67560. * @param rootUrl a string that defines the root url for scene and resources
  67561. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67562. * @param scene is the instance of BABYLON.Scene to append to
  67563. * @param onProgress a callback with a progress event for each file being loaded
  67564. * @param pluginExtension the extension used to determine the plugin
  67565. * @returns The loaded asset container
  67566. */
  67567. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67568. if (onProgress === void 0) { onProgress = null; }
  67569. if (pluginExtension === void 0) { pluginExtension = null; }
  67570. return new Promise(function (resolve, reject) {
  67571. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67572. resolve(assetContainer);
  67573. }, onProgress, function (scene, message, exception) {
  67574. reject(exception || new Error(message));
  67575. }, pluginExtension);
  67576. });
  67577. };
  67578. // Flags
  67579. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67580. SceneLoader._ShowLoadingScreen = true;
  67581. SceneLoader._CleanBoneMatrixWeights = false;
  67582. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67583. // Members
  67584. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67585. SceneLoader._registeredPlugins = {};
  67586. return SceneLoader;
  67587. }());
  67588. BABYLON.SceneLoader = SceneLoader;
  67589. ;
  67590. })(BABYLON || (BABYLON = {}));
  67591. //# sourceMappingURL=babylon.sceneLoader.js.map
  67592. var BABYLON;
  67593. (function (BABYLON) {
  67594. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67595. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67596. var parsedMaterial = parsedData.materials[index];
  67597. if (parsedMaterial.id === id) {
  67598. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67599. }
  67600. }
  67601. return null;
  67602. };
  67603. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67604. for (var i in names) {
  67605. if (mesh.name === names[i]) {
  67606. hierarchyIds.push(mesh.id);
  67607. return true;
  67608. }
  67609. }
  67610. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67611. hierarchyIds.push(mesh.id);
  67612. return true;
  67613. }
  67614. return false;
  67615. };
  67616. var logOperation = function (operation, producer) {
  67617. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67618. };
  67619. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67620. if (addToScene === void 0) { addToScene = false; }
  67621. var container = new BABYLON.AssetContainer(scene);
  67622. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67623. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67624. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67625. // and avoid problems with multiple concurrent .babylon loads.
  67626. var log = "importScene has failed JSON parse";
  67627. try {
  67628. var parsedData = JSON.parse(data);
  67629. log = "";
  67630. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67631. var index;
  67632. var cache;
  67633. // Lights
  67634. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67635. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67636. var parsedLight = parsedData.lights[index];
  67637. var light = BABYLON.Light.Parse(parsedLight, scene);
  67638. if (light) {
  67639. container.lights.push(light);
  67640. log += (index === 0 ? "\n\tLights:" : "");
  67641. log += "\n\t\t" + light.toString(fullDetails);
  67642. }
  67643. }
  67644. }
  67645. // Animations
  67646. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67647. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67648. var parsedAnimation = parsedData.animations[index];
  67649. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67650. scene.animations.push(animation);
  67651. container.animations.push(animation);
  67652. log += (index === 0 ? "\n\tAnimations:" : "");
  67653. log += "\n\t\t" + animation.toString(fullDetails);
  67654. }
  67655. }
  67656. // Materials
  67657. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67658. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67659. var parsedMaterial = parsedData.materials[index];
  67660. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67661. container.materials.push(mat);
  67662. log += (index === 0 ? "\n\tMaterials:" : "");
  67663. log += "\n\t\t" + mat.toString(fullDetails);
  67664. }
  67665. }
  67666. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67667. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67668. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67669. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67670. container.multiMaterials.push(mmat);
  67671. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67672. log += "\n\t\t" + mmat.toString(fullDetails);
  67673. }
  67674. }
  67675. // Morph targets
  67676. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67677. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67678. var managerData = _a[_i];
  67679. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67680. }
  67681. }
  67682. // Skeletons
  67683. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67684. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67685. var parsedSkeleton = parsedData.skeletons[index];
  67686. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67687. container.skeletons.push(skeleton);
  67688. log += (index === 0 ? "\n\tSkeletons:" : "");
  67689. log += "\n\t\t" + skeleton.toString(fullDetails);
  67690. }
  67691. }
  67692. // Geometries
  67693. var geometries = parsedData.geometries;
  67694. if (geometries !== undefined && geometries !== null) {
  67695. var addedGeometry = new Array();
  67696. // Boxes
  67697. var boxes = geometries.boxes;
  67698. if (boxes !== undefined && boxes !== null) {
  67699. for (index = 0, cache = boxes.length; index < cache; index++) {
  67700. var parsedBox = boxes[index];
  67701. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67702. }
  67703. }
  67704. // Spheres
  67705. var spheres = geometries.spheres;
  67706. if (spheres !== undefined && spheres !== null) {
  67707. for (index = 0, cache = spheres.length; index < cache; index++) {
  67708. var parsedSphere = spheres[index];
  67709. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67710. }
  67711. }
  67712. // Cylinders
  67713. var cylinders = geometries.cylinders;
  67714. if (cylinders !== undefined && cylinders !== null) {
  67715. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67716. var parsedCylinder = cylinders[index];
  67717. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67718. }
  67719. }
  67720. // Toruses
  67721. var toruses = geometries.toruses;
  67722. if (toruses !== undefined && toruses !== null) {
  67723. for (index = 0, cache = toruses.length; index < cache; index++) {
  67724. var parsedTorus = toruses[index];
  67725. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67726. }
  67727. }
  67728. // Grounds
  67729. var grounds = geometries.grounds;
  67730. if (grounds !== undefined && grounds !== null) {
  67731. for (index = 0, cache = grounds.length; index < cache; index++) {
  67732. var parsedGround = grounds[index];
  67733. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67734. }
  67735. }
  67736. // Planes
  67737. var planes = geometries.planes;
  67738. if (planes !== undefined && planes !== null) {
  67739. for (index = 0, cache = planes.length; index < cache; index++) {
  67740. var parsedPlane = planes[index];
  67741. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67742. }
  67743. }
  67744. // TorusKnots
  67745. var torusKnots = geometries.torusKnots;
  67746. if (torusKnots !== undefined && torusKnots !== null) {
  67747. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67748. var parsedTorusKnot = torusKnots[index];
  67749. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67750. }
  67751. }
  67752. // VertexData
  67753. var vertexData = geometries.vertexData;
  67754. if (vertexData !== undefined && vertexData !== null) {
  67755. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67756. var parsedVertexData = vertexData[index];
  67757. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67758. }
  67759. }
  67760. addedGeometry.forEach(function (g) {
  67761. if (g) {
  67762. container.geometries.push(g);
  67763. }
  67764. });
  67765. }
  67766. // Transform nodes
  67767. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67768. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67769. var parsedTransformNode = parsedData.transformNodes[index];
  67770. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67771. container.transformNodes.push(node);
  67772. }
  67773. }
  67774. // Meshes
  67775. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67776. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67777. var parsedMesh = parsedData.meshes[index];
  67778. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67779. container.meshes.push(mesh);
  67780. log += (index === 0 ? "\n\tMeshes:" : "");
  67781. log += "\n\t\t" + mesh.toString(fullDetails);
  67782. }
  67783. }
  67784. // Cameras
  67785. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67786. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67787. var parsedCamera = parsedData.cameras[index];
  67788. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67789. container.cameras.push(camera);
  67790. log += (index === 0 ? "\n\tCameras:" : "");
  67791. log += "\n\t\t" + camera.toString(fullDetails);
  67792. }
  67793. }
  67794. // Browsing all the graph to connect the dots
  67795. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67796. var camera = scene.cameras[index];
  67797. if (camera._waitingParentId) {
  67798. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67799. camera._waitingParentId = null;
  67800. }
  67801. }
  67802. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67803. var light_1 = scene.lights[index];
  67804. if (light_1 && light_1._waitingParentId) {
  67805. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67806. light_1._waitingParentId = null;
  67807. }
  67808. }
  67809. // Sounds
  67810. // TODO: add sound
  67811. var loadedSounds = [];
  67812. var loadedSound;
  67813. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67814. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67815. var parsedSound = parsedData.sounds[index];
  67816. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67817. if (!parsedSound.url)
  67818. parsedSound.url = parsedSound.name;
  67819. if (!loadedSounds[parsedSound.url]) {
  67820. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67821. loadedSounds[parsedSound.url] = loadedSound;
  67822. container.sounds.push(loadedSound);
  67823. }
  67824. else {
  67825. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67826. }
  67827. }
  67828. else {
  67829. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67830. }
  67831. }
  67832. }
  67833. loadedSounds = [];
  67834. // Connect parents & children and parse actions
  67835. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67836. var transformNode = scene.transformNodes[index];
  67837. if (transformNode._waitingParentId) {
  67838. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67839. transformNode._waitingParentId = null;
  67840. }
  67841. }
  67842. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67843. var mesh = scene.meshes[index];
  67844. if (mesh._waitingParentId) {
  67845. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67846. mesh._waitingParentId = null;
  67847. }
  67848. if (mesh._waitingActions) {
  67849. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67850. mesh._waitingActions = null;
  67851. }
  67852. }
  67853. // freeze world matrix application
  67854. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67855. var currentMesh = scene.meshes[index];
  67856. if (currentMesh._waitingFreezeWorldMatrix) {
  67857. currentMesh.freezeWorldMatrix();
  67858. currentMesh._waitingFreezeWorldMatrix = null;
  67859. }
  67860. else {
  67861. currentMesh.computeWorldMatrix(true);
  67862. }
  67863. }
  67864. // Particles Systems
  67865. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67866. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67867. var parsedParticleSystem = parsedData.particleSystems[index];
  67868. if (parsedParticleSystem.activeParticleCount) {
  67869. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67870. container.particleSystems.push(ps);
  67871. }
  67872. else {
  67873. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67874. container.particleSystems.push(ps);
  67875. }
  67876. }
  67877. }
  67878. // Lens flares
  67879. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67880. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67881. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67882. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67883. container.lensFlareSystems.push(lf);
  67884. }
  67885. }
  67886. // Shadows
  67887. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67888. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67889. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67890. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67891. container.shadowGenerators.push(sg);
  67892. }
  67893. }
  67894. // Lights exclusions / inclusions
  67895. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67896. var light_2 = scene.lights[index];
  67897. // Excluded check
  67898. if (light_2._excludedMeshesIds.length > 0) {
  67899. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67900. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67901. if (excludedMesh) {
  67902. light_2.excludedMeshes.push(excludedMesh);
  67903. }
  67904. }
  67905. light_2._excludedMeshesIds = [];
  67906. }
  67907. // Included check
  67908. if (light_2._includedOnlyMeshesIds.length > 0) {
  67909. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67910. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67911. if (includedOnlyMesh) {
  67912. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67913. }
  67914. }
  67915. light_2._includedOnlyMeshesIds = [];
  67916. }
  67917. }
  67918. // Effect layers
  67919. if (parsedData.effectLayers) {
  67920. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67921. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67922. container.effectLayers.push(effectLayer);
  67923. }
  67924. }
  67925. // Actions (scene)
  67926. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67927. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67928. }
  67929. if (!addToScene) {
  67930. container.removeAllFromScene();
  67931. }
  67932. }
  67933. catch (err) {
  67934. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67935. if (onError) {
  67936. onError(msg, err);
  67937. }
  67938. else {
  67939. BABYLON.Tools.Log(msg);
  67940. throw err;
  67941. }
  67942. }
  67943. finally {
  67944. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67945. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67946. }
  67947. }
  67948. return container;
  67949. };
  67950. BABYLON.SceneLoader.RegisterPlugin({
  67951. name: "babylon.js",
  67952. extensions: ".babylon",
  67953. canDirectLoad: function (data) {
  67954. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67955. return true;
  67956. }
  67957. return false;
  67958. },
  67959. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67960. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67961. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67962. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67963. // and avoid problems with multiple concurrent .babylon loads.
  67964. var log = "importMesh has failed JSON parse";
  67965. try {
  67966. var parsedData = JSON.parse(data);
  67967. log = "";
  67968. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67969. if (!meshesNames) {
  67970. meshesNames = null;
  67971. }
  67972. else if (!Array.isArray(meshesNames)) {
  67973. meshesNames = [meshesNames];
  67974. }
  67975. var hierarchyIds = new Array();
  67976. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67977. var loadedSkeletonsIds = [];
  67978. var loadedMaterialsIds = [];
  67979. var index;
  67980. var cache;
  67981. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67982. var parsedMesh = parsedData.meshes[index];
  67983. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67984. if (meshesNames !== null) {
  67985. // Remove found mesh name from list.
  67986. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67987. }
  67988. //Geometry?
  67989. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67990. //does the file contain geometries?
  67991. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67992. //find the correct geometry and add it to the scene
  67993. var found = false;
  67994. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67995. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67996. return;
  67997. }
  67998. else {
  67999. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68000. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68001. switch (geometryType) {
  68002. case "boxes":
  68003. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68004. break;
  68005. case "spheres":
  68006. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68007. break;
  68008. case "cylinders":
  68009. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68010. break;
  68011. case "toruses":
  68012. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68013. break;
  68014. case "grounds":
  68015. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68016. break;
  68017. case "planes":
  68018. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68019. break;
  68020. case "torusKnots":
  68021. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68022. break;
  68023. case "vertexData":
  68024. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68025. break;
  68026. }
  68027. found = true;
  68028. }
  68029. });
  68030. }
  68031. });
  68032. if (found === false) {
  68033. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68034. }
  68035. }
  68036. }
  68037. // Material ?
  68038. if (parsedMesh.materialId) {
  68039. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68040. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68041. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68042. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68043. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68044. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68045. var subMatId = parsedMultiMaterial.materials[matIndex];
  68046. loadedMaterialsIds.push(subMatId);
  68047. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68048. if (mat) {
  68049. log += "\n\tMaterial " + mat.toString(fullDetails);
  68050. }
  68051. }
  68052. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68053. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68054. if (mmat) {
  68055. materialFound = true;
  68056. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68057. }
  68058. break;
  68059. }
  68060. }
  68061. }
  68062. if (materialFound === false) {
  68063. loadedMaterialsIds.push(parsedMesh.materialId);
  68064. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68065. if (!mat) {
  68066. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68067. }
  68068. else {
  68069. log += "\n\tMaterial " + mat.toString(fullDetails);
  68070. }
  68071. }
  68072. }
  68073. // Skeleton ?
  68074. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68075. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68076. if (skeletonAlreadyLoaded === false) {
  68077. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68078. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68079. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68080. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68081. skeletons.push(skeleton);
  68082. loadedSkeletonsIds.push(parsedSkeleton.id);
  68083. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68084. }
  68085. }
  68086. }
  68087. }
  68088. // Morph targets ?
  68089. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68090. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68091. var managerData = _a[_i];
  68092. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68093. }
  68094. }
  68095. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68096. meshes.push(mesh);
  68097. log += "\n\tMesh " + mesh.toString(fullDetails);
  68098. }
  68099. }
  68100. // Connecting parents
  68101. var currentMesh;
  68102. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68103. currentMesh = scene.meshes[index];
  68104. if (currentMesh._waitingParentId) {
  68105. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68106. currentMesh._waitingParentId = null;
  68107. }
  68108. }
  68109. // freeze and compute world matrix application
  68110. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68111. currentMesh = scene.meshes[index];
  68112. if (currentMesh._waitingFreezeWorldMatrix) {
  68113. currentMesh.freezeWorldMatrix();
  68114. currentMesh._waitingFreezeWorldMatrix = null;
  68115. }
  68116. else {
  68117. currentMesh.computeWorldMatrix(true);
  68118. }
  68119. }
  68120. }
  68121. // Particles
  68122. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68123. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68124. var parsedParticleSystem = parsedData.particleSystems[index];
  68125. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68126. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68127. }
  68128. }
  68129. }
  68130. return true;
  68131. }
  68132. catch (err) {
  68133. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68134. if (onError) {
  68135. onError(msg, err);
  68136. }
  68137. else {
  68138. BABYLON.Tools.Log(msg);
  68139. throw err;
  68140. }
  68141. }
  68142. finally {
  68143. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68144. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68145. }
  68146. }
  68147. return false;
  68148. },
  68149. load: function (scene, data, rootUrl, onError) {
  68150. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68151. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68152. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68153. // and avoid problems with multiple concurrent .babylon loads.
  68154. var log = "importScene has failed JSON parse";
  68155. try {
  68156. var parsedData = JSON.parse(data);
  68157. log = "";
  68158. // Scene
  68159. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68160. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68161. }
  68162. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68163. scene.autoClear = parsedData.autoClear;
  68164. }
  68165. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68166. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68167. }
  68168. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68169. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68170. }
  68171. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68172. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68173. }
  68174. // Fog
  68175. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68176. scene.fogMode = parsedData.fogMode;
  68177. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68178. scene.fogStart = parsedData.fogStart;
  68179. scene.fogEnd = parsedData.fogEnd;
  68180. scene.fogDensity = parsedData.fogDensity;
  68181. log += "\tFog mode for scene: ";
  68182. switch (scene.fogMode) {
  68183. // getters not compiling, so using hardcoded
  68184. case 1:
  68185. log += "exp\n";
  68186. break;
  68187. case 2:
  68188. log += "exp2\n";
  68189. break;
  68190. case 3:
  68191. log += "linear\n";
  68192. break;
  68193. }
  68194. }
  68195. //Physics
  68196. if (parsedData.physicsEnabled) {
  68197. var physicsPlugin;
  68198. if (parsedData.physicsEngine === "cannon") {
  68199. physicsPlugin = new BABYLON.CannonJSPlugin();
  68200. }
  68201. else if (parsedData.physicsEngine === "oimo") {
  68202. physicsPlugin = new BABYLON.OimoJSPlugin();
  68203. }
  68204. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68205. //else - default engine, which is currently oimo
  68206. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68207. scene.enablePhysics(physicsGravity, physicsPlugin);
  68208. }
  68209. // Metadata
  68210. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68211. scene.metadata = parsedData.metadata;
  68212. }
  68213. //collisions, if defined. otherwise, default is true
  68214. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68215. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68216. }
  68217. scene.workerCollisions = !!parsedData.workerCollisions;
  68218. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68219. if (!container) {
  68220. return false;
  68221. }
  68222. if (parsedData.autoAnimate) {
  68223. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68224. }
  68225. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68226. scene.setActiveCameraByID(parsedData.activeCameraID);
  68227. }
  68228. // Environment texture
  68229. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68230. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68231. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68232. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68233. if (parsedData.environmentTextureRotationY) {
  68234. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68235. }
  68236. scene.environmentTexture = hdrTexture;
  68237. }
  68238. else {
  68239. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68240. if (parsedData.environmentTextureRotationY) {
  68241. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68242. }
  68243. scene.environmentTexture = cubeTexture;
  68244. }
  68245. if (parsedData.createDefaultSkybox === true) {
  68246. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68247. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68248. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68249. }
  68250. }
  68251. // Finish
  68252. return true;
  68253. }
  68254. catch (err) {
  68255. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68256. if (onError) {
  68257. onError(msg, err);
  68258. }
  68259. else {
  68260. BABYLON.Tools.Log(msg);
  68261. throw err;
  68262. }
  68263. }
  68264. finally {
  68265. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68266. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68267. }
  68268. }
  68269. return false;
  68270. },
  68271. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68272. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68273. return container;
  68274. }
  68275. });
  68276. })(BABYLON || (BABYLON = {}));
  68277. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68278. var BABYLON;
  68279. (function (BABYLON) {
  68280. var FilesInput = /** @class */ (function () {
  68281. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68282. this.onProcessFileCallback = function () { return true; };
  68283. this._engine = engine;
  68284. this._currentScene = scene;
  68285. this._sceneLoadedCallback = sceneLoadedCallback;
  68286. this._progressCallback = progressCallback;
  68287. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68288. this._textureLoadingCallback = textureLoadingCallback;
  68289. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68290. this._onReloadCallback = onReloadCallback;
  68291. this._errorCallback = errorCallback;
  68292. }
  68293. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68294. var _this = this;
  68295. if (elementToMonitor) {
  68296. this._elementToMonitor = elementToMonitor;
  68297. this._dragEnterHandler = function (e) { _this.drag(e); };
  68298. this._dragOverHandler = function (e) { _this.drag(e); };
  68299. this._dropHandler = function (e) { _this.drop(e); };
  68300. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68301. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68302. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68303. }
  68304. };
  68305. FilesInput.prototype.dispose = function () {
  68306. if (!this._elementToMonitor) {
  68307. return;
  68308. }
  68309. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68310. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68311. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68312. };
  68313. FilesInput.prototype.renderFunction = function () {
  68314. if (this._additionalRenderLoopLogicCallback) {
  68315. this._additionalRenderLoopLogicCallback();
  68316. }
  68317. if (this._currentScene) {
  68318. if (this._textureLoadingCallback) {
  68319. var remaining = this._currentScene.getWaitingItemsCount();
  68320. if (remaining > 0) {
  68321. this._textureLoadingCallback(remaining);
  68322. }
  68323. }
  68324. this._currentScene.render();
  68325. }
  68326. };
  68327. FilesInput.prototype.drag = function (e) {
  68328. e.stopPropagation();
  68329. e.preventDefault();
  68330. };
  68331. FilesInput.prototype.drop = function (eventDrop) {
  68332. eventDrop.stopPropagation();
  68333. eventDrop.preventDefault();
  68334. this.loadFiles(eventDrop);
  68335. };
  68336. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68337. var _this = this;
  68338. var reader = folder.createReader();
  68339. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68340. reader.readEntries(function (entries) {
  68341. remaining.count += entries.length;
  68342. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68343. var entry = entries_1[_i];
  68344. if (entry.isFile) {
  68345. entry.file(function (file) {
  68346. file.correctName = relativePath + file.name;
  68347. files.push(file);
  68348. if (--remaining.count === 0) {
  68349. callback();
  68350. }
  68351. });
  68352. }
  68353. else if (entry.isDirectory) {
  68354. _this._traverseFolder(entry, files, remaining, callback);
  68355. }
  68356. }
  68357. if (--remaining.count) {
  68358. callback();
  68359. }
  68360. });
  68361. };
  68362. FilesInput.prototype._processFiles = function (files) {
  68363. for (var i = 0; i < files.length; i++) {
  68364. var name = files[i].correctName.toLowerCase();
  68365. var extension = name.split('.').pop();
  68366. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68367. continue;
  68368. }
  68369. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68370. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68371. this._sceneFileToLoad = files[i];
  68372. }
  68373. else {
  68374. FilesInput.FilesToLoad[name] = files[i];
  68375. }
  68376. }
  68377. };
  68378. FilesInput.prototype.loadFiles = function (event) {
  68379. var _this = this;
  68380. if (this._startingProcessingFilesCallback)
  68381. this._startingProcessingFilesCallback();
  68382. // Handling data transfer via drag'n'drop
  68383. if (event && event.dataTransfer && event.dataTransfer.files) {
  68384. this._filesToLoad = event.dataTransfer.files;
  68385. }
  68386. // Handling files from input files
  68387. if (event && event.target && event.target.files) {
  68388. this._filesToLoad = event.target.files;
  68389. }
  68390. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68391. var files_1 = new Array();
  68392. var folders = [];
  68393. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68394. for (var i = 0; i < this._filesToLoad.length; i++) {
  68395. var fileToLoad = this._filesToLoad[i];
  68396. var name_1 = fileToLoad.name.toLowerCase();
  68397. var entry = void 0;
  68398. fileToLoad.correctName = name_1;
  68399. if (items) {
  68400. var item = items[i];
  68401. if (item.getAsEntry) {
  68402. entry = item.getAsEntry();
  68403. }
  68404. else if (item.webkitGetAsEntry) {
  68405. entry = item.webkitGetAsEntry();
  68406. }
  68407. }
  68408. if (!entry) {
  68409. files_1.push(fileToLoad);
  68410. }
  68411. else {
  68412. if (entry.isDirectory) {
  68413. folders.push(entry);
  68414. }
  68415. else {
  68416. files_1.push(fileToLoad);
  68417. }
  68418. }
  68419. }
  68420. if (folders.length === 0) {
  68421. this._processFiles(files_1);
  68422. this._processReload();
  68423. }
  68424. else {
  68425. var remaining = { count: folders.length };
  68426. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68427. var folder = folders_1[_i];
  68428. this._traverseFolder(folder, files_1, remaining, function () {
  68429. _this._processFiles(files_1);
  68430. if (remaining.count === 0) {
  68431. _this._processReload();
  68432. }
  68433. });
  68434. }
  68435. }
  68436. }
  68437. };
  68438. FilesInput.prototype._processReload = function () {
  68439. if (this._onReloadCallback) {
  68440. this._onReloadCallback(this._sceneFileToLoad);
  68441. }
  68442. else {
  68443. this.reload();
  68444. }
  68445. };
  68446. FilesInput.prototype.reload = function () {
  68447. var _this = this;
  68448. // If a scene file has been provided
  68449. if (this._sceneFileToLoad) {
  68450. if (this._currentScene) {
  68451. if (BABYLON.Tools.errorsCount > 0) {
  68452. BABYLON.Tools.ClearLogCache();
  68453. }
  68454. this._engine.stopRenderLoop();
  68455. this._currentScene.dispose();
  68456. }
  68457. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68458. if (_this._progressCallback) {
  68459. _this._progressCallback(progress);
  68460. }
  68461. }).then(function (scene) {
  68462. _this._currentScene = scene;
  68463. if (_this._sceneLoadedCallback) {
  68464. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68465. }
  68466. // Wait for textures and shaders to be ready
  68467. _this._currentScene.executeWhenReady(function () {
  68468. _this._engine.runRenderLoop(function () {
  68469. _this.renderFunction();
  68470. });
  68471. });
  68472. }).catch(function (error) {
  68473. if (_this._errorCallback) {
  68474. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68475. }
  68476. });
  68477. }
  68478. else {
  68479. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68480. }
  68481. };
  68482. FilesInput.FilesToLoad = {};
  68483. return FilesInput;
  68484. }());
  68485. BABYLON.FilesInput = FilesInput;
  68486. })(BABYLON || (BABYLON = {}));
  68487. //# sourceMappingURL=babylon.filesInput.js.map
  68488. var BABYLON;
  68489. (function (BABYLON) {
  68490. /**
  68491. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68492. * The underlying implementation relies on an associative array to ensure the best performances.
  68493. * The value can be anything including 'null' but except 'undefined'
  68494. */
  68495. var StringDictionary = /** @class */ (function () {
  68496. function StringDictionary() {
  68497. this._count = 0;
  68498. this._data = {};
  68499. }
  68500. /**
  68501. * This will clear this dictionary and copy the content from the 'source' one.
  68502. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68503. * @param source the dictionary to take the content from and copy to this dictionary
  68504. */
  68505. StringDictionary.prototype.copyFrom = function (source) {
  68506. var _this = this;
  68507. this.clear();
  68508. source.forEach(function (t, v) { return _this.add(t, v); });
  68509. };
  68510. /**
  68511. * Get a value based from its key
  68512. * @param key the given key to get the matching value from
  68513. * @return the value if found, otherwise undefined is returned
  68514. */
  68515. StringDictionary.prototype.get = function (key) {
  68516. var val = this._data[key];
  68517. if (val !== undefined) {
  68518. return val;
  68519. }
  68520. return undefined;
  68521. };
  68522. /**
  68523. * Get a value from its key or add it if it doesn't exist.
  68524. * This method will ensure you that a given key/data will be present in the dictionary.
  68525. * @param key the given key to get the matching value from
  68526. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68527. * The factory will only be invoked if there's no data for the given key.
  68528. * @return the value corresponding to the key.
  68529. */
  68530. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68531. var val = this.get(key);
  68532. if (val !== undefined) {
  68533. return val;
  68534. }
  68535. val = factory(key);
  68536. if (val) {
  68537. this.add(key, val);
  68538. }
  68539. return val;
  68540. };
  68541. /**
  68542. * Get a value from its key if present in the dictionary otherwise add it
  68543. * @param key the key to get the value from
  68544. * @param val if there's no such key/value pair in the dictionary add it with this value
  68545. * @return the value corresponding to the key
  68546. */
  68547. StringDictionary.prototype.getOrAdd = function (key, val) {
  68548. var curVal = this.get(key);
  68549. if (curVal !== undefined) {
  68550. return curVal;
  68551. }
  68552. this.add(key, val);
  68553. return val;
  68554. };
  68555. /**
  68556. * Check if there's a given key in the dictionary
  68557. * @param key the key to check for
  68558. * @return true if the key is present, false otherwise
  68559. */
  68560. StringDictionary.prototype.contains = function (key) {
  68561. return this._data[key] !== undefined;
  68562. };
  68563. /**
  68564. * Add a new key and its corresponding value
  68565. * @param key the key to add
  68566. * @param value the value corresponding to the key
  68567. * @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
  68568. */
  68569. StringDictionary.prototype.add = function (key, value) {
  68570. if (this._data[key] !== undefined) {
  68571. return false;
  68572. }
  68573. this._data[key] = value;
  68574. ++this._count;
  68575. return true;
  68576. };
  68577. StringDictionary.prototype.set = function (key, value) {
  68578. if (this._data[key] === undefined) {
  68579. return false;
  68580. }
  68581. this._data[key] = value;
  68582. return true;
  68583. };
  68584. /**
  68585. * Get the element of the given key and remove it from the dictionary
  68586. * @param key
  68587. */
  68588. StringDictionary.prototype.getAndRemove = function (key) {
  68589. var val = this.get(key);
  68590. if (val !== undefined) {
  68591. delete this._data[key];
  68592. --this._count;
  68593. return val;
  68594. }
  68595. return null;
  68596. };
  68597. /**
  68598. * Remove a key/value from the dictionary.
  68599. * @param key the key to remove
  68600. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68601. */
  68602. StringDictionary.prototype.remove = function (key) {
  68603. if (this.contains(key)) {
  68604. delete this._data[key];
  68605. --this._count;
  68606. return true;
  68607. }
  68608. return false;
  68609. };
  68610. /**
  68611. * Clear the whole content of the dictionary
  68612. */
  68613. StringDictionary.prototype.clear = function () {
  68614. this._data = {};
  68615. this._count = 0;
  68616. };
  68617. Object.defineProperty(StringDictionary.prototype, "count", {
  68618. get: function () {
  68619. return this._count;
  68620. },
  68621. enumerable: true,
  68622. configurable: true
  68623. });
  68624. /**
  68625. * Execute a callback on each key/val of the dictionary.
  68626. * Note that you can remove any element in this dictionary in the callback implementation
  68627. * @param callback the callback to execute on a given key/value pair
  68628. */
  68629. StringDictionary.prototype.forEach = function (callback) {
  68630. for (var cur in this._data) {
  68631. var val = this._data[cur];
  68632. callback(cur, val);
  68633. }
  68634. };
  68635. /**
  68636. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68637. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68638. * Note that you can remove any element in this dictionary in the callback implementation
  68639. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68640. */
  68641. StringDictionary.prototype.first = function (callback) {
  68642. for (var cur in this._data) {
  68643. var val = this._data[cur];
  68644. var res = callback(cur, val);
  68645. if (res) {
  68646. return res;
  68647. }
  68648. }
  68649. return null;
  68650. };
  68651. return StringDictionary;
  68652. }());
  68653. BABYLON.StringDictionary = StringDictionary;
  68654. })(BABYLON || (BABYLON = {}));
  68655. //# sourceMappingURL=babylon.stringDictionary.js.map
  68656. var BABYLON;
  68657. (function (BABYLON) {
  68658. var Tags = /** @class */ (function () {
  68659. function Tags() {
  68660. }
  68661. Tags.EnableFor = function (obj) {
  68662. obj._tags = obj._tags || {};
  68663. obj.hasTags = function () {
  68664. return Tags.HasTags(obj);
  68665. };
  68666. obj.addTags = function (tagsString) {
  68667. return Tags.AddTagsTo(obj, tagsString);
  68668. };
  68669. obj.removeTags = function (tagsString) {
  68670. return Tags.RemoveTagsFrom(obj, tagsString);
  68671. };
  68672. obj.matchesTagsQuery = function (tagsQuery) {
  68673. return Tags.MatchesQuery(obj, tagsQuery);
  68674. };
  68675. };
  68676. Tags.DisableFor = function (obj) {
  68677. delete obj._tags;
  68678. delete obj.hasTags;
  68679. delete obj.addTags;
  68680. delete obj.removeTags;
  68681. delete obj.matchesTagsQuery;
  68682. };
  68683. Tags.HasTags = function (obj) {
  68684. if (!obj._tags) {
  68685. return false;
  68686. }
  68687. return !BABYLON.Tools.IsEmpty(obj._tags);
  68688. };
  68689. Tags.GetTags = function (obj, asString) {
  68690. if (asString === void 0) { asString = true; }
  68691. if (!obj._tags) {
  68692. return null;
  68693. }
  68694. if (asString) {
  68695. var tagsArray = [];
  68696. for (var tag in obj._tags) {
  68697. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68698. tagsArray.push(tag);
  68699. }
  68700. }
  68701. return tagsArray.join(" ");
  68702. }
  68703. else {
  68704. return obj._tags;
  68705. }
  68706. };
  68707. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68708. // a tag cannot start with '||', '&&', and '!'
  68709. // it cannot contain whitespaces
  68710. Tags.AddTagsTo = function (obj, tagsString) {
  68711. if (!tagsString) {
  68712. return;
  68713. }
  68714. if (typeof tagsString !== "string") {
  68715. return;
  68716. }
  68717. var tags = tagsString.split(" ");
  68718. tags.forEach(function (tag, index, array) {
  68719. Tags._AddTagTo(obj, tag);
  68720. });
  68721. };
  68722. Tags._AddTagTo = function (obj, tag) {
  68723. tag = tag.trim();
  68724. if (tag === "" || tag === "true" || tag === "false") {
  68725. return;
  68726. }
  68727. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68728. return;
  68729. }
  68730. Tags.EnableFor(obj);
  68731. obj._tags[tag] = true;
  68732. };
  68733. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68734. if (!Tags.HasTags(obj)) {
  68735. return;
  68736. }
  68737. var tags = tagsString.split(" ");
  68738. for (var t in tags) {
  68739. Tags._RemoveTagFrom(obj, tags[t]);
  68740. }
  68741. };
  68742. Tags._RemoveTagFrom = function (obj, tag) {
  68743. delete obj._tags[tag];
  68744. };
  68745. Tags.MatchesQuery = function (obj, tagsQuery) {
  68746. if (tagsQuery === undefined) {
  68747. return true;
  68748. }
  68749. if (tagsQuery === "") {
  68750. return Tags.HasTags(obj);
  68751. }
  68752. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68753. };
  68754. return Tags;
  68755. }());
  68756. BABYLON.Tags = Tags;
  68757. })(BABYLON || (BABYLON = {}));
  68758. //# sourceMappingURL=babylon.tags.js.map
  68759. var BABYLON;
  68760. (function (BABYLON) {
  68761. /**
  68762. * Class used to evalaute queries containing `and` and `or` operators
  68763. */
  68764. var AndOrNotEvaluator = /** @class */ (function () {
  68765. function AndOrNotEvaluator() {
  68766. }
  68767. /**
  68768. * Evaluate a query
  68769. * @param query defines the query to evaluate
  68770. * @param evaluateCallback defines the callback used to filter result
  68771. * @returns true if the query matches
  68772. */
  68773. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68774. if (!query.match(/\([^\(\)]*\)/g)) {
  68775. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68776. }
  68777. else {
  68778. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68779. // remove parenthesis
  68780. r = r.slice(1, r.length - 1);
  68781. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68782. });
  68783. }
  68784. if (query === "true") {
  68785. return true;
  68786. }
  68787. if (query === "false") {
  68788. return false;
  68789. }
  68790. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68791. };
  68792. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68793. evaluateCallback = evaluateCallback || (function (r) {
  68794. return r === "true" ? true : false;
  68795. });
  68796. var result;
  68797. var or = parenthesisContent.split("||");
  68798. for (var i in or) {
  68799. if (or.hasOwnProperty(i)) {
  68800. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68801. var and = ori.split("&&");
  68802. if (and.length > 1) {
  68803. for (var j = 0; j < and.length; ++j) {
  68804. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68805. if (andj !== "true" && andj !== "false") {
  68806. if (andj[0] === "!") {
  68807. result = !evaluateCallback(andj.substring(1));
  68808. }
  68809. else {
  68810. result = evaluateCallback(andj);
  68811. }
  68812. }
  68813. else {
  68814. result = andj === "true" ? true : false;
  68815. }
  68816. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68817. ori = "false";
  68818. break;
  68819. }
  68820. }
  68821. }
  68822. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68823. result = true;
  68824. break;
  68825. }
  68826. // result equals false (or undefined)
  68827. if (ori !== "true" && ori !== "false") {
  68828. if (ori[0] === "!") {
  68829. result = !evaluateCallback(ori.substring(1));
  68830. }
  68831. else {
  68832. result = evaluateCallback(ori);
  68833. }
  68834. }
  68835. else {
  68836. result = ori === "true" ? true : false;
  68837. }
  68838. }
  68839. }
  68840. // the whole parenthesis scope is replaced by 'true' or 'false'
  68841. return result ? "true" : "false";
  68842. };
  68843. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68844. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68845. // remove whitespaces
  68846. r = r.replace(/[\s]/g, function () { return ""; });
  68847. return r.length % 2 ? "!" : "";
  68848. });
  68849. booleanString = booleanString.trim();
  68850. if (booleanString === "!true") {
  68851. booleanString = "false";
  68852. }
  68853. else if (booleanString === "!false") {
  68854. booleanString = "true";
  68855. }
  68856. return booleanString;
  68857. };
  68858. return AndOrNotEvaluator;
  68859. }());
  68860. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68861. })(BABYLON || (BABYLON = {}));
  68862. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68863. var BABYLON;
  68864. (function (BABYLON) {
  68865. /**
  68866. * Class used to enable access to IndexedDB
  68867. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68868. */
  68869. var Database = /** @class */ (function () {
  68870. /**
  68871. * Creates a new Database
  68872. * @param urlToScene defines the url to load the scene
  68873. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68874. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68875. */
  68876. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68877. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68878. var _this = this;
  68879. // Handling various flavors of prefixed version of IndexedDB
  68880. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68881. this.callbackManifestChecked = callbackManifestChecked;
  68882. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68883. this.db = null;
  68884. this._enableSceneOffline = false;
  68885. this._enableTexturesOffline = false;
  68886. this.manifestVersionFound = 0;
  68887. this.mustUpdateRessources = false;
  68888. this.hasReachedQuota = false;
  68889. if (!Database.IDBStorageEnabled) {
  68890. this.callbackManifestChecked(true);
  68891. }
  68892. else {
  68893. if (disableManifestCheck) {
  68894. this._enableSceneOffline = true;
  68895. this._enableTexturesOffline = true;
  68896. this.manifestVersionFound = 1;
  68897. BABYLON.Tools.SetImmediate(function () {
  68898. _this.callbackManifestChecked(true);
  68899. });
  68900. }
  68901. else {
  68902. this._checkManifestFile();
  68903. }
  68904. }
  68905. }
  68906. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68907. /**
  68908. * Gets a boolean indicating if scene must be saved in the database
  68909. */
  68910. get: function () {
  68911. return this._enableSceneOffline;
  68912. },
  68913. enumerable: true,
  68914. configurable: true
  68915. });
  68916. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68917. /**
  68918. * Gets a boolean indicating if textures must be saved in the database
  68919. */
  68920. get: function () {
  68921. return this._enableTexturesOffline;
  68922. },
  68923. enumerable: true,
  68924. configurable: true
  68925. });
  68926. Database.prototype._checkManifestFile = function () {
  68927. var _this = this;
  68928. var noManifestFile = function () {
  68929. _this._enableSceneOffline = false;
  68930. _this._enableTexturesOffline = false;
  68931. _this.callbackManifestChecked(false);
  68932. };
  68933. var timeStampUsed = false;
  68934. var manifestURL = this.currentSceneUrl + ".manifest";
  68935. var xhr = new XMLHttpRequest();
  68936. if (navigator.onLine) {
  68937. // Adding a timestamp to by-pass browsers' cache
  68938. timeStampUsed = true;
  68939. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68940. }
  68941. xhr.open("GET", manifestURL, true);
  68942. xhr.addEventListener("load", function () {
  68943. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68944. try {
  68945. var manifestFile = JSON.parse(xhr.response);
  68946. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68947. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68948. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68949. _this.manifestVersionFound = manifestFile.version;
  68950. }
  68951. if (_this.callbackManifestChecked) {
  68952. _this.callbackManifestChecked(true);
  68953. }
  68954. }
  68955. catch (ex) {
  68956. noManifestFile();
  68957. }
  68958. }
  68959. else {
  68960. noManifestFile();
  68961. }
  68962. }, false);
  68963. xhr.addEventListener("error", function (event) {
  68964. if (timeStampUsed) {
  68965. timeStampUsed = false;
  68966. // Let's retry without the timeStamp
  68967. // It could fail when coupled with HTML5 Offline API
  68968. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68969. xhr.open("GET", retryManifestURL, true);
  68970. xhr.send();
  68971. }
  68972. else {
  68973. noManifestFile();
  68974. }
  68975. }, false);
  68976. try {
  68977. xhr.send();
  68978. }
  68979. catch (ex) {
  68980. BABYLON.Tools.Error("Error on XHR send request.");
  68981. this.callbackManifestChecked(false);
  68982. }
  68983. };
  68984. /**
  68985. * Open the database and make it available
  68986. * @param successCallback defines the callback to call on success
  68987. * @param errorCallback defines the callback to call on error
  68988. */
  68989. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68990. var _this = this;
  68991. var handleError = function () {
  68992. _this.isSupported = false;
  68993. if (errorCallback)
  68994. errorCallback();
  68995. };
  68996. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68997. // Your browser doesn't support IndexedDB
  68998. this.isSupported = false;
  68999. if (errorCallback)
  69000. errorCallback();
  69001. }
  69002. else {
  69003. // If the DB hasn't been opened or created yet
  69004. if (!this.db) {
  69005. this.hasReachedQuota = false;
  69006. this.isSupported = true;
  69007. var request = this.idbFactory.open("babylonjs", 1);
  69008. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69009. request.onerror = function (event) {
  69010. handleError();
  69011. };
  69012. // executes when a version change transaction cannot complete due to other active transactions
  69013. request.onblocked = function (event) {
  69014. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69015. handleError();
  69016. };
  69017. // DB has been opened successfully
  69018. request.onsuccess = function (event) {
  69019. _this.db = request.result;
  69020. successCallback();
  69021. };
  69022. // Initialization of the DB. Creating Scenes & Textures stores
  69023. request.onupgradeneeded = function (event) {
  69024. _this.db = (event.target).result;
  69025. if (_this.db) {
  69026. try {
  69027. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69028. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69029. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69030. }
  69031. catch (ex) {
  69032. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69033. handleError();
  69034. }
  69035. }
  69036. };
  69037. }
  69038. // DB has already been created and opened
  69039. else {
  69040. if (successCallback)
  69041. successCallback();
  69042. }
  69043. }
  69044. };
  69045. /**
  69046. * Loads an image from the database
  69047. * @param url defines the url to load from
  69048. * @param image defines the target DOM image
  69049. */
  69050. Database.prototype.loadImageFromDB = function (url, image) {
  69051. var _this = this;
  69052. var completeURL = Database._ReturnFullUrlLocation(url);
  69053. var saveAndLoadImage = function () {
  69054. if (!_this.hasReachedQuota && _this.db !== null) {
  69055. // the texture is not yet in the DB, let's try to save it
  69056. _this._saveImageIntoDBAsync(completeURL, image);
  69057. }
  69058. // If the texture is not in the DB and we've reached the DB quota limit
  69059. // let's load it directly from the web
  69060. else {
  69061. image.src = url;
  69062. }
  69063. };
  69064. if (!this.mustUpdateRessources) {
  69065. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69066. }
  69067. // First time we're download the images or update requested in the manifest file by a version change
  69068. else {
  69069. saveAndLoadImage();
  69070. }
  69071. };
  69072. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69073. if (this.isSupported && this.db !== null) {
  69074. var texture;
  69075. var transaction = this.db.transaction(["textures"]);
  69076. transaction.onabort = function (event) {
  69077. image.src = url;
  69078. };
  69079. transaction.oncomplete = function (event) {
  69080. var blobTextureURL;
  69081. if (texture) {
  69082. var URL = window.URL || window.webkitURL;
  69083. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69084. image.onerror = function () {
  69085. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69086. image.src = url;
  69087. };
  69088. image.src = blobTextureURL;
  69089. }
  69090. else {
  69091. notInDBCallback();
  69092. }
  69093. };
  69094. var getRequest = transaction.objectStore("textures").get(url);
  69095. getRequest.onsuccess = function (event) {
  69096. texture = (event.target).result;
  69097. };
  69098. getRequest.onerror = function (event) {
  69099. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69100. image.src = url;
  69101. };
  69102. }
  69103. else {
  69104. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69105. image.src = url;
  69106. }
  69107. };
  69108. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69109. var _this = this;
  69110. if (this.isSupported) {
  69111. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69112. var generateBlobUrl = function () {
  69113. var blobTextureURL;
  69114. if (blob) {
  69115. var URL = window.URL || window.webkitURL;
  69116. try {
  69117. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69118. }
  69119. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69120. catch (ex) {
  69121. blobTextureURL = URL.createObjectURL(blob);
  69122. }
  69123. }
  69124. if (blobTextureURL) {
  69125. image.src = blobTextureURL;
  69126. }
  69127. };
  69128. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69129. var xhr = new XMLHttpRequest(), blob;
  69130. xhr.open("GET", url, true);
  69131. xhr.responseType = "blob";
  69132. xhr.addEventListener("load", function () {
  69133. if (xhr.status === 200 && _this.db) {
  69134. // Blob as response (XHR2)
  69135. blob = xhr.response;
  69136. var transaction = _this.db.transaction(["textures"], "readwrite");
  69137. // the transaction could abort because of a QuotaExceededError error
  69138. transaction.onabort = function (event) {
  69139. try {
  69140. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69141. var srcElement = (event.srcElement || event.target);
  69142. var error = srcElement.error;
  69143. if (error && error.name === "QuotaExceededError") {
  69144. _this.hasReachedQuota = true;
  69145. }
  69146. }
  69147. catch (ex) { }
  69148. generateBlobUrl();
  69149. };
  69150. transaction.oncomplete = function (event) {
  69151. generateBlobUrl();
  69152. };
  69153. var newTexture = { textureUrl: url, data: blob };
  69154. try {
  69155. // Put the blob into the dabase
  69156. var addRequest = transaction.objectStore("textures").put(newTexture);
  69157. addRequest.onsuccess = function (event) {
  69158. };
  69159. addRequest.onerror = function (event) {
  69160. generateBlobUrl();
  69161. };
  69162. }
  69163. catch (ex) {
  69164. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69165. if (ex.code === 25) {
  69166. Database.IsUASupportingBlobStorage = false;
  69167. }
  69168. image.src = url;
  69169. }
  69170. }
  69171. else {
  69172. image.src = url;
  69173. }
  69174. }, false);
  69175. xhr.addEventListener("error", function (event) {
  69176. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69177. image.src = url;
  69178. }, false);
  69179. xhr.send();
  69180. }
  69181. else {
  69182. image.src = url;
  69183. }
  69184. }
  69185. else {
  69186. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69187. image.src = url;
  69188. }
  69189. };
  69190. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69191. var _this = this;
  69192. var updateVersion = function () {
  69193. // the version is not yet in the DB or we need to update it
  69194. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69195. };
  69196. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69197. };
  69198. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69199. var _this = this;
  69200. if (this.isSupported && this.db) {
  69201. var version;
  69202. try {
  69203. var transaction = this.db.transaction(["versions"]);
  69204. transaction.oncomplete = function (event) {
  69205. if (version) {
  69206. // If the version in the JSON file is different from the version in DB
  69207. if (_this.manifestVersionFound !== version.data) {
  69208. _this.mustUpdateRessources = true;
  69209. updateInDBCallback();
  69210. }
  69211. else {
  69212. callback(version.data);
  69213. }
  69214. }
  69215. // version was not found in DB
  69216. else {
  69217. _this.mustUpdateRessources = true;
  69218. updateInDBCallback();
  69219. }
  69220. };
  69221. transaction.onabort = function (event) {
  69222. callback(-1);
  69223. };
  69224. var getRequest = transaction.objectStore("versions").get(url);
  69225. getRequest.onsuccess = function (event) {
  69226. version = (event.target).result;
  69227. };
  69228. getRequest.onerror = function (event) {
  69229. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69230. callback(-1);
  69231. };
  69232. }
  69233. catch (ex) {
  69234. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69235. callback(-1);
  69236. }
  69237. }
  69238. else {
  69239. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69240. callback(-1);
  69241. }
  69242. };
  69243. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69244. var _this = this;
  69245. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69246. try {
  69247. // Open a transaction to the database
  69248. var transaction = this.db.transaction(["versions"], "readwrite");
  69249. // the transaction could abort because of a QuotaExceededError error
  69250. transaction.onabort = function (event) {
  69251. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69252. var error = event.srcElement['error'];
  69253. if (error && error.name === "QuotaExceededError") {
  69254. _this.hasReachedQuota = true;
  69255. }
  69256. }
  69257. catch (ex) { }
  69258. callback(-1);
  69259. };
  69260. transaction.oncomplete = function (event) {
  69261. callback(_this.manifestVersionFound);
  69262. };
  69263. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69264. // Put the scene into the database
  69265. var addRequest = transaction.objectStore("versions").put(newVersion);
  69266. addRequest.onsuccess = function (event) {
  69267. };
  69268. addRequest.onerror = function (event) {
  69269. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69270. };
  69271. }
  69272. catch (ex) {
  69273. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69274. callback(-1);
  69275. }
  69276. }
  69277. else {
  69278. callback(-1);
  69279. }
  69280. };
  69281. /**
  69282. * Loads a file from database
  69283. * @param url defines the URL to load from
  69284. * @param sceneLoaded defines a callback to call on success
  69285. * @param progressCallBack defines a callback to call when progress changed
  69286. * @param errorCallback defines a callback to call on error
  69287. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69288. */
  69289. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69290. var _this = this;
  69291. var completeUrl = Database._ReturnFullUrlLocation(url);
  69292. var saveAndLoadFile = function () {
  69293. // the scene is not yet in the DB, let's try to save it
  69294. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69295. };
  69296. this._checkVersionFromDB(completeUrl, function (version) {
  69297. if (version !== -1) {
  69298. if (!_this.mustUpdateRessources) {
  69299. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69300. }
  69301. else {
  69302. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69303. }
  69304. }
  69305. else {
  69306. if (errorCallback) {
  69307. errorCallback();
  69308. }
  69309. }
  69310. });
  69311. };
  69312. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69313. if (this.isSupported && this.db) {
  69314. var targetStore;
  69315. if (url.indexOf(".babylon") !== -1) {
  69316. targetStore = "scenes";
  69317. }
  69318. else {
  69319. targetStore = "textures";
  69320. }
  69321. var file;
  69322. var transaction = this.db.transaction([targetStore]);
  69323. transaction.oncomplete = function (event) {
  69324. if (file) {
  69325. callback(file.data);
  69326. }
  69327. // file was not found in DB
  69328. else {
  69329. notInDBCallback();
  69330. }
  69331. };
  69332. transaction.onabort = function (event) {
  69333. notInDBCallback();
  69334. };
  69335. var getRequest = transaction.objectStore(targetStore).get(url);
  69336. getRequest.onsuccess = function (event) {
  69337. file = (event.target).result;
  69338. };
  69339. getRequest.onerror = function (event) {
  69340. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69341. notInDBCallback();
  69342. };
  69343. }
  69344. else {
  69345. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69346. callback();
  69347. }
  69348. };
  69349. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69350. var _this = this;
  69351. if (this.isSupported) {
  69352. var targetStore;
  69353. if (url.indexOf(".babylon") !== -1) {
  69354. targetStore = "scenes";
  69355. }
  69356. else {
  69357. targetStore = "textures";
  69358. }
  69359. // Create XHR
  69360. var xhr = new XMLHttpRequest();
  69361. var fileData;
  69362. xhr.open("GET", url, true);
  69363. if (useArrayBuffer) {
  69364. xhr.responseType = "arraybuffer";
  69365. }
  69366. if (progressCallback) {
  69367. xhr.onprogress = progressCallback;
  69368. }
  69369. xhr.addEventListener("load", function () {
  69370. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69371. // Blob as response (XHR2)
  69372. //fileData = xhr.responseText;
  69373. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69374. if (!_this.hasReachedQuota && _this.db) {
  69375. // Open a transaction to the database
  69376. var transaction = _this.db.transaction([targetStore], "readwrite");
  69377. // the transaction could abort because of a QuotaExceededError error
  69378. transaction.onabort = function (event) {
  69379. try {
  69380. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69381. var error = event.srcElement['error'];
  69382. if (error && error.name === "QuotaExceededError") {
  69383. _this.hasReachedQuota = true;
  69384. }
  69385. }
  69386. catch (ex) { }
  69387. callback(fileData);
  69388. };
  69389. transaction.oncomplete = function (event) {
  69390. callback(fileData);
  69391. };
  69392. var newFile;
  69393. if (targetStore === "scenes") {
  69394. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69395. }
  69396. else {
  69397. newFile = { textureUrl: url, data: fileData };
  69398. }
  69399. try {
  69400. // Put the scene into the database
  69401. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69402. addRequest.onsuccess = function (event) {
  69403. };
  69404. addRequest.onerror = function (event) {
  69405. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69406. };
  69407. }
  69408. catch (ex) {
  69409. callback(fileData);
  69410. }
  69411. }
  69412. else {
  69413. callback(fileData);
  69414. }
  69415. }
  69416. else {
  69417. callback();
  69418. }
  69419. }, false);
  69420. xhr.addEventListener("error", function (event) {
  69421. BABYLON.Tools.Error("error on XHR request.");
  69422. callback();
  69423. }, false);
  69424. xhr.send();
  69425. }
  69426. else {
  69427. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69428. callback();
  69429. }
  69430. };
  69431. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69432. Database.IsUASupportingBlobStorage = true;
  69433. /** Gets a boolean indicating if Database storate is enabled */
  69434. Database.IDBStorageEnabled = true;
  69435. Database._ParseURL = function (url) {
  69436. var a = document.createElement('a');
  69437. a.href = url;
  69438. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69439. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69440. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69441. return absLocation;
  69442. };
  69443. Database._ReturnFullUrlLocation = function (url) {
  69444. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69445. return (Database._ParseURL(window.location.href) + url);
  69446. }
  69447. else {
  69448. return url;
  69449. }
  69450. };
  69451. return Database;
  69452. }());
  69453. BABYLON.Database = Database;
  69454. })(BABYLON || (BABYLON = {}));
  69455. //# sourceMappingURL=babylon.database.js.map
  69456. var BABYLON;
  69457. (function (BABYLON) {
  69458. var FresnelParameters = /** @class */ (function () {
  69459. function FresnelParameters() {
  69460. this._isEnabled = true;
  69461. this.leftColor = BABYLON.Color3.White();
  69462. this.rightColor = BABYLON.Color3.Black();
  69463. this.bias = 0;
  69464. this.power = 1;
  69465. }
  69466. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69467. get: function () {
  69468. return this._isEnabled;
  69469. },
  69470. set: function (value) {
  69471. if (this._isEnabled === value) {
  69472. return;
  69473. }
  69474. this._isEnabled = value;
  69475. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69476. },
  69477. enumerable: true,
  69478. configurable: true
  69479. });
  69480. FresnelParameters.prototype.clone = function () {
  69481. var newFresnelParameters = new FresnelParameters();
  69482. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69483. return newFresnelParameters;
  69484. };
  69485. FresnelParameters.prototype.serialize = function () {
  69486. var serializationObject = {};
  69487. serializationObject.isEnabled = this.isEnabled;
  69488. serializationObject.leftColor = this.leftColor.asArray();
  69489. serializationObject.rightColor = this.rightColor.asArray();
  69490. serializationObject.bias = this.bias;
  69491. serializationObject.power = this.power;
  69492. return serializationObject;
  69493. };
  69494. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69495. var fresnelParameters = new FresnelParameters();
  69496. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69497. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69498. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69499. fresnelParameters.bias = parsedFresnelParameters.bias;
  69500. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69501. return fresnelParameters;
  69502. };
  69503. return FresnelParameters;
  69504. }());
  69505. BABYLON.FresnelParameters = FresnelParameters;
  69506. })(BABYLON || (BABYLON = {}));
  69507. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69508. var BABYLON;
  69509. (function (BABYLON) {
  69510. var MultiMaterial = /** @class */ (function (_super) {
  69511. __extends(MultiMaterial, _super);
  69512. function MultiMaterial(name, scene) {
  69513. var _this = _super.call(this, name, scene, true) || this;
  69514. scene.multiMaterials.push(_this);
  69515. _this.subMaterials = new Array();
  69516. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69517. return _this;
  69518. }
  69519. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69520. get: function () {
  69521. return this._subMaterials;
  69522. },
  69523. set: function (value) {
  69524. this._subMaterials = value;
  69525. this._hookArray(value);
  69526. },
  69527. enumerable: true,
  69528. configurable: true
  69529. });
  69530. MultiMaterial.prototype._hookArray = function (array) {
  69531. var _this = this;
  69532. var oldPush = array.push;
  69533. array.push = function () {
  69534. var items = [];
  69535. for (var _i = 0; _i < arguments.length; _i++) {
  69536. items[_i] = arguments[_i];
  69537. }
  69538. var result = oldPush.apply(array, items);
  69539. _this._markAllSubMeshesAsTexturesDirty();
  69540. return result;
  69541. };
  69542. var oldSplice = array.splice;
  69543. array.splice = function (index, deleteCount) {
  69544. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69545. _this._markAllSubMeshesAsTexturesDirty();
  69546. return deleted;
  69547. };
  69548. };
  69549. // Properties
  69550. MultiMaterial.prototype.getSubMaterial = function (index) {
  69551. if (index < 0 || index >= this.subMaterials.length) {
  69552. return this.getScene().defaultMaterial;
  69553. }
  69554. return this.subMaterials[index];
  69555. };
  69556. MultiMaterial.prototype.getActiveTextures = function () {
  69557. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69558. if (subMaterial) {
  69559. return subMaterial.getActiveTextures();
  69560. }
  69561. else {
  69562. return [];
  69563. }
  69564. }));
  69565. var _a;
  69566. };
  69567. // Methods
  69568. MultiMaterial.prototype.getClassName = function () {
  69569. return "MultiMaterial";
  69570. };
  69571. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69572. for (var index = 0; index < this.subMaterials.length; index++) {
  69573. var subMaterial = this.subMaterials[index];
  69574. if (subMaterial) {
  69575. if (subMaterial.storeEffectOnSubMeshes) {
  69576. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69577. return false;
  69578. }
  69579. continue;
  69580. }
  69581. if (!subMaterial.isReady(mesh)) {
  69582. return false;
  69583. }
  69584. }
  69585. }
  69586. return true;
  69587. };
  69588. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69589. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69590. for (var index = 0; index < this.subMaterials.length; index++) {
  69591. var subMaterial = null;
  69592. var current = this.subMaterials[index];
  69593. if (cloneChildren && current) {
  69594. subMaterial = current.clone(name + "-" + current.name);
  69595. }
  69596. else {
  69597. subMaterial = this.subMaterials[index];
  69598. }
  69599. newMultiMaterial.subMaterials.push(subMaterial);
  69600. }
  69601. return newMultiMaterial;
  69602. };
  69603. MultiMaterial.prototype.serialize = function () {
  69604. var serializationObject = {};
  69605. serializationObject.name = this.name;
  69606. serializationObject.id = this.id;
  69607. if (BABYLON.Tags) {
  69608. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69609. }
  69610. serializationObject.materials = [];
  69611. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69612. var subMat = this.subMaterials[matIndex];
  69613. if (subMat) {
  69614. serializationObject.materials.push(subMat.id);
  69615. }
  69616. else {
  69617. serializationObject.materials.push(null);
  69618. }
  69619. }
  69620. return serializationObject;
  69621. };
  69622. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69623. var scene = this.getScene();
  69624. if (!scene) {
  69625. return;
  69626. }
  69627. var index = scene.multiMaterials.indexOf(this);
  69628. if (index >= 0) {
  69629. scene.multiMaterials.splice(index, 1);
  69630. }
  69631. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69632. };
  69633. return MultiMaterial;
  69634. }(BABYLON.Material));
  69635. BABYLON.MultiMaterial = MultiMaterial;
  69636. })(BABYLON || (BABYLON = {}));
  69637. //# sourceMappingURL=babylon.multiMaterial.js.map
  69638. var BABYLON;
  69639. (function (BABYLON) {
  69640. var FreeCameraTouchInput = /** @class */ (function () {
  69641. function FreeCameraTouchInput() {
  69642. this._offsetX = null;
  69643. this._offsetY = null;
  69644. this._pointerPressed = new Array();
  69645. this.touchAngularSensibility = 200000.0;
  69646. this.touchMoveSensibility = 250.0;
  69647. }
  69648. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69649. var _this = this;
  69650. var previousPosition = null;
  69651. if (this._pointerInput === undefined) {
  69652. this._onLostFocus = function (evt) {
  69653. _this._offsetX = null;
  69654. _this._offsetY = null;
  69655. };
  69656. this._pointerInput = function (p, s) {
  69657. var evt = p.event;
  69658. if (evt.pointerType === "mouse") {
  69659. return;
  69660. }
  69661. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69662. if (!noPreventDefault) {
  69663. evt.preventDefault();
  69664. }
  69665. _this._pointerPressed.push(evt.pointerId);
  69666. if (_this._pointerPressed.length !== 1) {
  69667. return;
  69668. }
  69669. previousPosition = {
  69670. x: evt.clientX,
  69671. y: evt.clientY
  69672. };
  69673. }
  69674. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69675. if (!noPreventDefault) {
  69676. evt.preventDefault();
  69677. }
  69678. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69679. if (index === -1) {
  69680. return;
  69681. }
  69682. _this._pointerPressed.splice(index, 1);
  69683. if (index != 0) {
  69684. return;
  69685. }
  69686. previousPosition = null;
  69687. _this._offsetX = null;
  69688. _this._offsetY = null;
  69689. }
  69690. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69691. if (!noPreventDefault) {
  69692. evt.preventDefault();
  69693. }
  69694. if (!previousPosition) {
  69695. return;
  69696. }
  69697. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69698. if (index != 0) {
  69699. return;
  69700. }
  69701. _this._offsetX = evt.clientX - previousPosition.x;
  69702. _this._offsetY = -(evt.clientY - previousPosition.y);
  69703. }
  69704. };
  69705. }
  69706. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69707. if (this._onLostFocus) {
  69708. element.addEventListener("blur", this._onLostFocus);
  69709. }
  69710. };
  69711. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69712. if (this._pointerInput && element) {
  69713. if (this._observer) {
  69714. this.camera.getScene().onPointerObservable.remove(this._observer);
  69715. this._observer = null;
  69716. }
  69717. if (this._onLostFocus) {
  69718. element.removeEventListener("blur", this._onLostFocus);
  69719. this._onLostFocus = null;
  69720. }
  69721. this._pointerPressed = [];
  69722. this._offsetX = null;
  69723. this._offsetY = null;
  69724. }
  69725. };
  69726. FreeCameraTouchInput.prototype.checkInputs = function () {
  69727. if (this._offsetX && this._offsetY) {
  69728. var camera = this.camera;
  69729. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69730. if (this._pointerPressed.length > 1) {
  69731. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69732. }
  69733. else {
  69734. var speed = camera._computeLocalCameraSpeed();
  69735. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69736. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69737. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69738. }
  69739. }
  69740. };
  69741. FreeCameraTouchInput.prototype.getClassName = function () {
  69742. return "FreeCameraTouchInput";
  69743. };
  69744. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69745. return "touch";
  69746. };
  69747. __decorate([
  69748. BABYLON.serialize()
  69749. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69750. __decorate([
  69751. BABYLON.serialize()
  69752. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69753. return FreeCameraTouchInput;
  69754. }());
  69755. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69756. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69757. })(BABYLON || (BABYLON = {}));
  69758. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69759. var BABYLON;
  69760. (function (BABYLON) {
  69761. // We're mainly based on the logic defined into the FreeCamera code
  69762. var TouchCamera = /** @class */ (function (_super) {
  69763. __extends(TouchCamera, _super);
  69764. //-- end properties for backward compatibility for inputs
  69765. function TouchCamera(name, position, scene) {
  69766. var _this = _super.call(this, name, position, scene) || this;
  69767. _this.inputs.addTouch();
  69768. _this._setupInputs();
  69769. return _this;
  69770. }
  69771. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69772. //-- Begin properties for backward compatibility for inputs
  69773. get: function () {
  69774. var touch = this.inputs.attached["touch"];
  69775. if (touch)
  69776. return touch.touchAngularSensibility;
  69777. return 0;
  69778. },
  69779. set: function (value) {
  69780. var touch = this.inputs.attached["touch"];
  69781. if (touch)
  69782. touch.touchAngularSensibility = value;
  69783. },
  69784. enumerable: true,
  69785. configurable: true
  69786. });
  69787. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69788. get: function () {
  69789. var touch = this.inputs.attached["touch"];
  69790. if (touch)
  69791. return touch.touchMoveSensibility;
  69792. return 0;
  69793. },
  69794. set: function (value) {
  69795. var touch = this.inputs.attached["touch"];
  69796. if (touch)
  69797. touch.touchMoveSensibility = value;
  69798. },
  69799. enumerable: true,
  69800. configurable: true
  69801. });
  69802. TouchCamera.prototype.getClassName = function () {
  69803. return "TouchCamera";
  69804. };
  69805. TouchCamera.prototype._setupInputs = function () {
  69806. var mouse = this.inputs.attached["mouse"];
  69807. if (mouse) {
  69808. mouse.touchEnabled = false;
  69809. }
  69810. };
  69811. return TouchCamera;
  69812. }(BABYLON.FreeCamera));
  69813. BABYLON.TouchCamera = TouchCamera;
  69814. })(BABYLON || (BABYLON = {}));
  69815. //# sourceMappingURL=babylon.touchCamera.js.map
  69816. var BABYLON;
  69817. (function (BABYLON) {
  69818. var ProceduralTexture = /** @class */ (function (_super) {
  69819. __extends(ProceduralTexture, _super);
  69820. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69821. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69822. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69823. if (isCube === void 0) { isCube = false; }
  69824. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69825. _this.isCube = isCube;
  69826. _this.isEnabled = true;
  69827. _this._currentRefreshId = -1;
  69828. _this._refreshRate = 1;
  69829. _this._vertexBuffers = {};
  69830. _this._uniforms = new Array();
  69831. _this._samplers = new Array();
  69832. _this._textures = {};
  69833. _this._floats = {};
  69834. _this._floatsArrays = {};
  69835. _this._colors3 = {};
  69836. _this._colors4 = {};
  69837. _this._vectors2 = {};
  69838. _this._vectors3 = {};
  69839. _this._matrices = {};
  69840. _this._fallbackTextureUsed = false;
  69841. scene.proceduralTextures.push(_this);
  69842. _this._engine = scene.getEngine();
  69843. _this.name = name;
  69844. _this.isRenderTarget = true;
  69845. _this._size = size;
  69846. _this._generateMipMaps = generateMipMaps;
  69847. _this.setFragment(fragment);
  69848. _this._fallbackTexture = fallbackTexture;
  69849. if (isCube) {
  69850. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69851. _this.setFloat("face", 0);
  69852. }
  69853. else {
  69854. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69855. }
  69856. // VBO
  69857. var vertices = [];
  69858. vertices.push(1, 1);
  69859. vertices.push(-1, 1);
  69860. vertices.push(-1, -1);
  69861. vertices.push(1, -1);
  69862. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69863. _this._createIndexBuffer();
  69864. return _this;
  69865. }
  69866. ProceduralTexture.prototype._createIndexBuffer = function () {
  69867. var engine = this._engine;
  69868. // Indices
  69869. var indices = [];
  69870. indices.push(0);
  69871. indices.push(1);
  69872. indices.push(2);
  69873. indices.push(0);
  69874. indices.push(2);
  69875. indices.push(3);
  69876. this._indexBuffer = engine.createIndexBuffer(indices);
  69877. };
  69878. ProceduralTexture.prototype._rebuild = function () {
  69879. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69880. if (vb) {
  69881. vb._rebuild();
  69882. }
  69883. this._createIndexBuffer();
  69884. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69885. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69886. }
  69887. };
  69888. ProceduralTexture.prototype.reset = function () {
  69889. if (this._effect === undefined) {
  69890. return;
  69891. }
  69892. var engine = this._engine;
  69893. engine._releaseEffect(this._effect);
  69894. };
  69895. ProceduralTexture.prototype.isReady = function () {
  69896. var _this = this;
  69897. var engine = this._engine;
  69898. var shaders;
  69899. if (!this._fragment) {
  69900. return false;
  69901. }
  69902. if (this._fallbackTextureUsed) {
  69903. return true;
  69904. }
  69905. if (this._fragment.fragmentElement !== undefined) {
  69906. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69907. }
  69908. else {
  69909. shaders = { vertex: "procedural", fragment: this._fragment };
  69910. }
  69911. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69912. _this.releaseInternalTexture();
  69913. if (_this._fallbackTexture) {
  69914. _this._texture = _this._fallbackTexture._texture;
  69915. if (_this._texture) {
  69916. _this._texture.incrementReferences();
  69917. }
  69918. }
  69919. _this._fallbackTextureUsed = true;
  69920. });
  69921. return this._effect.isReady();
  69922. };
  69923. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69924. this._currentRefreshId = -1;
  69925. };
  69926. ProceduralTexture.prototype.setFragment = function (fragment) {
  69927. this._fragment = fragment;
  69928. };
  69929. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69930. get: function () {
  69931. return this._refreshRate;
  69932. },
  69933. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69934. set: function (value) {
  69935. this._refreshRate = value;
  69936. this.resetRefreshCounter();
  69937. },
  69938. enumerable: true,
  69939. configurable: true
  69940. });
  69941. ProceduralTexture.prototype._shouldRender = function () {
  69942. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69943. return false;
  69944. }
  69945. if (this._fallbackTextureUsed) {
  69946. return false;
  69947. }
  69948. if (this._currentRefreshId === -1) { // At least render once
  69949. this._currentRefreshId = 1;
  69950. return true;
  69951. }
  69952. if (this.refreshRate === this._currentRefreshId) {
  69953. this._currentRefreshId = 1;
  69954. return true;
  69955. }
  69956. this._currentRefreshId++;
  69957. return false;
  69958. };
  69959. ProceduralTexture.prototype.getRenderSize = function () {
  69960. return this._size;
  69961. };
  69962. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69963. if (this._fallbackTextureUsed) {
  69964. return;
  69965. }
  69966. this.releaseInternalTexture();
  69967. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69968. };
  69969. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69970. if (this._uniforms.indexOf(uniformName) === -1) {
  69971. this._uniforms.push(uniformName);
  69972. }
  69973. };
  69974. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69975. if (this._samplers.indexOf(name) === -1) {
  69976. this._samplers.push(name);
  69977. }
  69978. this._textures[name] = texture;
  69979. return this;
  69980. };
  69981. ProceduralTexture.prototype.setFloat = function (name, value) {
  69982. this._checkUniform(name);
  69983. this._floats[name] = value;
  69984. return this;
  69985. };
  69986. ProceduralTexture.prototype.setFloats = function (name, value) {
  69987. this._checkUniform(name);
  69988. this._floatsArrays[name] = value;
  69989. return this;
  69990. };
  69991. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69992. this._checkUniform(name);
  69993. this._colors3[name] = value;
  69994. return this;
  69995. };
  69996. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69997. this._checkUniform(name);
  69998. this._colors4[name] = value;
  69999. return this;
  70000. };
  70001. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70002. this._checkUniform(name);
  70003. this._vectors2[name] = value;
  70004. return this;
  70005. };
  70006. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70007. this._checkUniform(name);
  70008. this._vectors3[name] = value;
  70009. return this;
  70010. };
  70011. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70012. this._checkUniform(name);
  70013. this._matrices[name] = value;
  70014. return this;
  70015. };
  70016. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70017. var scene = this.getScene();
  70018. if (!scene) {
  70019. return;
  70020. }
  70021. var engine = this._engine;
  70022. // Render
  70023. engine.enableEffect(this._effect);
  70024. engine.setState(false);
  70025. // Texture
  70026. for (var name in this._textures) {
  70027. this._effect.setTexture(name, this._textures[name]);
  70028. }
  70029. // Float
  70030. for (name in this._floats) {
  70031. this._effect.setFloat(name, this._floats[name]);
  70032. }
  70033. // Floats
  70034. for (name in this._floatsArrays) {
  70035. this._effect.setArray(name, this._floatsArrays[name]);
  70036. }
  70037. // Color3
  70038. for (name in this._colors3) {
  70039. this._effect.setColor3(name, this._colors3[name]);
  70040. }
  70041. // Color4
  70042. for (name in this._colors4) {
  70043. var color = this._colors4[name];
  70044. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70045. }
  70046. // Vector2
  70047. for (name in this._vectors2) {
  70048. this._effect.setVector2(name, this._vectors2[name]);
  70049. }
  70050. // Vector3
  70051. for (name in this._vectors3) {
  70052. this._effect.setVector3(name, this._vectors3[name]);
  70053. }
  70054. // Matrix
  70055. for (name in this._matrices) {
  70056. this._effect.setMatrix(name, this._matrices[name]);
  70057. }
  70058. if (!this._texture) {
  70059. return;
  70060. }
  70061. if (this.isCube) {
  70062. for (var face = 0; face < 6; face++) {
  70063. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70064. // VBOs
  70065. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70066. this._effect.setFloat("face", face);
  70067. // Clear
  70068. engine.clear(scene.clearColor, true, true, true);
  70069. // Draw order
  70070. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70071. // Mipmaps
  70072. if (face === 5) {
  70073. engine.generateMipMapsForCubemap(this._texture);
  70074. }
  70075. }
  70076. }
  70077. else {
  70078. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70079. // VBOs
  70080. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70081. // Clear
  70082. engine.clear(scene.clearColor, true, true, true);
  70083. // Draw order
  70084. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70085. }
  70086. // Unbind
  70087. engine.unBindFramebuffer(this._texture, this.isCube);
  70088. if (this.onGenerated) {
  70089. this.onGenerated();
  70090. }
  70091. };
  70092. ProceduralTexture.prototype.clone = function () {
  70093. var textureSize = this.getSize();
  70094. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70095. // Base texture
  70096. newTexture.hasAlpha = this.hasAlpha;
  70097. newTexture.level = this.level;
  70098. // RenderTarget Texture
  70099. newTexture.coordinatesMode = this.coordinatesMode;
  70100. return newTexture;
  70101. };
  70102. ProceduralTexture.prototype.dispose = function () {
  70103. var scene = this.getScene();
  70104. if (!scene) {
  70105. return;
  70106. }
  70107. var index = scene.proceduralTextures.indexOf(this);
  70108. if (index >= 0) {
  70109. scene.proceduralTextures.splice(index, 1);
  70110. }
  70111. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70112. if (vertexBuffer) {
  70113. vertexBuffer.dispose();
  70114. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70115. }
  70116. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70117. this._indexBuffer = null;
  70118. }
  70119. _super.prototype.dispose.call(this);
  70120. };
  70121. return ProceduralTexture;
  70122. }(BABYLON.Texture));
  70123. BABYLON.ProceduralTexture = ProceduralTexture;
  70124. })(BABYLON || (BABYLON = {}));
  70125. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70126. var BABYLON;
  70127. (function (BABYLON) {
  70128. var CustomProceduralTexture = /** @class */ (function (_super) {
  70129. __extends(CustomProceduralTexture, _super);
  70130. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70131. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70132. _this._animate = true;
  70133. _this._time = 0;
  70134. _this._texturePath = texturePath;
  70135. //Try to load json
  70136. _this.loadJson(texturePath);
  70137. _this.refreshRate = 1;
  70138. return _this;
  70139. }
  70140. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70141. var _this = this;
  70142. var noConfigFile = function () {
  70143. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70144. try {
  70145. _this.setFragment(_this._texturePath);
  70146. }
  70147. catch (ex) {
  70148. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70149. }
  70150. };
  70151. var configFileUrl = jsonUrl + "/config.json";
  70152. var xhr = new XMLHttpRequest();
  70153. xhr.open("GET", configFileUrl, true);
  70154. xhr.addEventListener("load", function () {
  70155. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70156. try {
  70157. _this._config = JSON.parse(xhr.response);
  70158. _this.updateShaderUniforms();
  70159. _this.updateTextures();
  70160. _this.setFragment(_this._texturePath + "/custom");
  70161. _this._animate = _this._config.animate;
  70162. _this.refreshRate = _this._config.refreshrate;
  70163. }
  70164. catch (ex) {
  70165. noConfigFile();
  70166. }
  70167. }
  70168. else {
  70169. noConfigFile();
  70170. }
  70171. }, false);
  70172. xhr.addEventListener("error", function () {
  70173. noConfigFile();
  70174. }, false);
  70175. try {
  70176. xhr.send();
  70177. }
  70178. catch (ex) {
  70179. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70180. }
  70181. };
  70182. CustomProceduralTexture.prototype.isReady = function () {
  70183. if (!_super.prototype.isReady.call(this)) {
  70184. return false;
  70185. }
  70186. for (var name in this._textures) {
  70187. var texture = this._textures[name];
  70188. if (!texture.isReady()) {
  70189. return false;
  70190. }
  70191. }
  70192. return true;
  70193. };
  70194. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70195. var scene = this.getScene();
  70196. if (this._animate && scene) {
  70197. this._time += scene.getAnimationRatio() * 0.03;
  70198. this.updateShaderUniforms();
  70199. }
  70200. _super.prototype.render.call(this, useCameraPostProcess);
  70201. };
  70202. CustomProceduralTexture.prototype.updateTextures = function () {
  70203. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70204. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70205. }
  70206. };
  70207. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70208. if (this._config) {
  70209. for (var j = 0; j < this._config.uniforms.length; j++) {
  70210. var uniform = this._config.uniforms[j];
  70211. switch (uniform.type) {
  70212. case "float":
  70213. this.setFloat(uniform.name, uniform.value);
  70214. break;
  70215. case "color3":
  70216. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70217. break;
  70218. case "color4":
  70219. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70220. break;
  70221. case "vector2":
  70222. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70223. break;
  70224. case "vector3":
  70225. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70226. break;
  70227. }
  70228. }
  70229. }
  70230. this.setFloat("time", this._time);
  70231. };
  70232. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70233. get: function () {
  70234. return this._animate;
  70235. },
  70236. set: function (value) {
  70237. this._animate = value;
  70238. },
  70239. enumerable: true,
  70240. configurable: true
  70241. });
  70242. return CustomProceduralTexture;
  70243. }(BABYLON.ProceduralTexture));
  70244. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70245. })(BABYLON || (BABYLON = {}));
  70246. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70247. var BABYLON;
  70248. (function (BABYLON) {
  70249. var FreeCameraGamepadInput = /** @class */ (function () {
  70250. function FreeCameraGamepadInput() {
  70251. this.gamepadAngularSensibility = 200;
  70252. this.gamepadMoveSensibility = 40;
  70253. // private members
  70254. this._cameraTransform = BABYLON.Matrix.Identity();
  70255. this._deltaTransform = BABYLON.Vector3.Zero();
  70256. this._vector3 = BABYLON.Vector3.Zero();
  70257. this._vector2 = BABYLON.Vector2.Zero();
  70258. }
  70259. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70260. var _this = this;
  70261. var manager = this.camera.getScene().gamepadManager;
  70262. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70263. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70264. // prioritize XBOX gamepads.
  70265. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70266. _this.gamepad = gamepad;
  70267. }
  70268. }
  70269. });
  70270. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70271. if (_this.gamepad === gamepad) {
  70272. _this.gamepad = null;
  70273. }
  70274. });
  70275. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70276. };
  70277. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70278. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70279. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70280. this.gamepad = null;
  70281. };
  70282. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70283. if (this.gamepad && this.gamepad.leftStick) {
  70284. var camera = this.camera;
  70285. var LSValues = this.gamepad.leftStick;
  70286. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70287. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70288. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70289. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70290. var RSValues = this.gamepad.rightStick;
  70291. if (RSValues) {
  70292. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70293. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70294. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70295. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70296. }
  70297. else {
  70298. RSValues = { x: 0, y: 0 };
  70299. }
  70300. if (!camera.rotationQuaternion) {
  70301. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70302. }
  70303. else {
  70304. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70305. }
  70306. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70307. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70308. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70309. camera.cameraDirection.addInPlace(this._deltaTransform);
  70310. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70311. camera.cameraRotation.addInPlace(this._vector2);
  70312. }
  70313. };
  70314. FreeCameraGamepadInput.prototype.getClassName = function () {
  70315. return "FreeCameraGamepadInput";
  70316. };
  70317. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70318. return "gamepad";
  70319. };
  70320. __decorate([
  70321. BABYLON.serialize()
  70322. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70323. __decorate([
  70324. BABYLON.serialize()
  70325. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70326. return FreeCameraGamepadInput;
  70327. }());
  70328. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70329. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70330. })(BABYLON || (BABYLON = {}));
  70331. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70332. var BABYLON;
  70333. (function (BABYLON) {
  70334. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70335. function ArcRotateCameraGamepadInput() {
  70336. this.gamepadRotationSensibility = 80;
  70337. this.gamepadMoveSensibility = 40;
  70338. }
  70339. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70340. var _this = this;
  70341. var manager = this.camera.getScene().gamepadManager;
  70342. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70343. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70344. // prioritize XBOX gamepads.
  70345. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70346. _this.gamepad = gamepad;
  70347. }
  70348. }
  70349. });
  70350. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70351. if (_this.gamepad === gamepad) {
  70352. _this.gamepad = null;
  70353. }
  70354. });
  70355. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70356. };
  70357. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70358. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70359. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70360. this.gamepad = null;
  70361. };
  70362. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70363. if (this.gamepad) {
  70364. var camera = this.camera;
  70365. var RSValues = this.gamepad.rightStick;
  70366. if (RSValues) {
  70367. if (RSValues.x != 0) {
  70368. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70369. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70370. camera.inertialAlphaOffset += normalizedRX;
  70371. }
  70372. }
  70373. if (RSValues.y != 0) {
  70374. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70375. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70376. camera.inertialBetaOffset += normalizedRY;
  70377. }
  70378. }
  70379. }
  70380. var LSValues = this.gamepad.leftStick;
  70381. if (LSValues && LSValues.y != 0) {
  70382. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70383. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70384. this.camera.inertialRadiusOffset -= normalizedLY;
  70385. }
  70386. }
  70387. }
  70388. };
  70389. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70390. return "ArcRotateCameraGamepadInput";
  70391. };
  70392. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70393. return "gamepad";
  70394. };
  70395. __decorate([
  70396. BABYLON.serialize()
  70397. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70398. __decorate([
  70399. BABYLON.serialize()
  70400. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70401. return ArcRotateCameraGamepadInput;
  70402. }());
  70403. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70404. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70405. })(BABYLON || (BABYLON = {}));
  70406. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70407. var BABYLON;
  70408. (function (BABYLON) {
  70409. var GamepadManager = /** @class */ (function () {
  70410. function GamepadManager(_scene) {
  70411. var _this = this;
  70412. this._scene = _scene;
  70413. this._babylonGamepads = [];
  70414. this._oneGamepadConnected = false;
  70415. this._isMonitoring = false;
  70416. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70417. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70418. this._gamepadEventSupported = false;
  70419. }
  70420. else {
  70421. this._gamepadEventSupported = 'GamepadEvent' in window;
  70422. this._gamepadSupport = (navigator.getGamepads ||
  70423. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70424. }
  70425. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70426. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70427. for (var i in _this._babylonGamepads) {
  70428. var gamepad = _this._babylonGamepads[i];
  70429. if (gamepad && gamepad._isConnected) {
  70430. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70431. }
  70432. }
  70433. });
  70434. this._onGamepadConnectedEvent = function (evt) {
  70435. var gamepad = evt.gamepad;
  70436. if (gamepad.index in _this._babylonGamepads) {
  70437. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70438. return;
  70439. }
  70440. }
  70441. var newGamepad;
  70442. if (_this._babylonGamepads[gamepad.index]) {
  70443. newGamepad = _this._babylonGamepads[gamepad.index];
  70444. newGamepad.browserGamepad = gamepad;
  70445. newGamepad._isConnected = true;
  70446. }
  70447. else {
  70448. newGamepad = _this._addNewGamepad(gamepad);
  70449. }
  70450. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70451. _this._startMonitoringGamepads();
  70452. };
  70453. this._onGamepadDisconnectedEvent = function (evt) {
  70454. var gamepad = evt.gamepad;
  70455. // Remove the gamepad from the list of gamepads to monitor.
  70456. for (var i in _this._babylonGamepads) {
  70457. if (_this._babylonGamepads[i].index === gamepad.index) {
  70458. var disconnectedGamepad = _this._babylonGamepads[i];
  70459. disconnectedGamepad._isConnected = false;
  70460. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70461. break;
  70462. }
  70463. }
  70464. };
  70465. if (this._gamepadSupport) {
  70466. //first add already-connected gamepads
  70467. this._updateGamepadObjects();
  70468. if (this._babylonGamepads.length) {
  70469. this._startMonitoringGamepads();
  70470. }
  70471. // Checking if the gamepad connected event is supported (like in Firefox)
  70472. if (this._gamepadEventSupported) {
  70473. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70474. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70475. }
  70476. else {
  70477. this._startMonitoringGamepads();
  70478. }
  70479. }
  70480. }
  70481. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70482. get: function () {
  70483. return this._babylonGamepads;
  70484. },
  70485. enumerable: true,
  70486. configurable: true
  70487. });
  70488. GamepadManager.prototype.getGamepadByType = function (type) {
  70489. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70490. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70491. var gamepad = _a[_i];
  70492. if (gamepad && gamepad.type === type) {
  70493. return gamepad;
  70494. }
  70495. }
  70496. return null;
  70497. };
  70498. GamepadManager.prototype.dispose = function () {
  70499. if (this._gamepadEventSupported) {
  70500. if (this._onGamepadConnectedEvent) {
  70501. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70502. }
  70503. if (this._onGamepadDisconnectedEvent) {
  70504. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70505. }
  70506. this._onGamepadConnectedEvent = null;
  70507. this._onGamepadDisconnectedEvent = null;
  70508. }
  70509. this._babylonGamepads.forEach(function (gamepad) {
  70510. gamepad.dispose();
  70511. });
  70512. this.onGamepadConnectedObservable.clear();
  70513. this.onGamepadDisconnectedObservable.clear();
  70514. this._oneGamepadConnected = false;
  70515. this._stopMonitoringGamepads();
  70516. this._babylonGamepads = [];
  70517. };
  70518. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70519. if (!this._oneGamepadConnected) {
  70520. this._oneGamepadConnected = true;
  70521. }
  70522. var newGamepad;
  70523. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70524. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70525. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70526. }
  70527. // if pose is supported, use the (WebVR) pose enabled controller
  70528. else if (gamepad.pose) {
  70529. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70530. }
  70531. else {
  70532. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70533. }
  70534. this._babylonGamepads[newGamepad.index] = newGamepad;
  70535. return newGamepad;
  70536. };
  70537. GamepadManager.prototype._startMonitoringGamepads = function () {
  70538. if (!this._isMonitoring) {
  70539. this._isMonitoring = true;
  70540. //back-comp
  70541. if (!this._scene) {
  70542. this._checkGamepadsStatus();
  70543. }
  70544. }
  70545. };
  70546. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70547. this._isMonitoring = false;
  70548. };
  70549. GamepadManager.prototype._checkGamepadsStatus = function () {
  70550. var _this = this;
  70551. // Hack to be compatible Chrome
  70552. this._updateGamepadObjects();
  70553. for (var i in this._babylonGamepads) {
  70554. var gamepad = this._babylonGamepads[i];
  70555. if (!gamepad || !gamepad.isConnected) {
  70556. continue;
  70557. }
  70558. gamepad.update();
  70559. }
  70560. if (this._isMonitoring && !this._scene) {
  70561. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70562. }
  70563. };
  70564. // This function is called only on Chrome, which does not properly support
  70565. // connection/disconnection events and forces you to recopy again the gamepad object
  70566. GamepadManager.prototype._updateGamepadObjects = function () {
  70567. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70568. for (var i = 0; i < gamepads.length; i++) {
  70569. var gamepad = gamepads[i];
  70570. if (gamepad) {
  70571. if (!this._babylonGamepads[gamepad.index]) {
  70572. var newGamepad = this._addNewGamepad(gamepad);
  70573. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70574. }
  70575. else {
  70576. // Forced to copy again this object for Chrome for unknown reason
  70577. this._babylonGamepads[i].browserGamepad = gamepad;
  70578. if (!this._babylonGamepads[i].isConnected) {
  70579. this._babylonGamepads[i]._isConnected = true;
  70580. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70581. }
  70582. }
  70583. }
  70584. }
  70585. };
  70586. return GamepadManager;
  70587. }());
  70588. BABYLON.GamepadManager = GamepadManager;
  70589. })(BABYLON || (BABYLON = {}));
  70590. //# sourceMappingURL=babylon.gamepadManager.js.map
  70591. var BABYLON;
  70592. (function (BABYLON) {
  70593. var StickValues = /** @class */ (function () {
  70594. function StickValues(x, y) {
  70595. this.x = x;
  70596. this.y = y;
  70597. }
  70598. return StickValues;
  70599. }());
  70600. BABYLON.StickValues = StickValues;
  70601. var Gamepad = /** @class */ (function () {
  70602. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70603. if (leftStickX === void 0) { leftStickX = 0; }
  70604. if (leftStickY === void 0) { leftStickY = 1; }
  70605. if (rightStickX === void 0) { rightStickX = 2; }
  70606. if (rightStickY === void 0) { rightStickY = 3; }
  70607. this.id = id;
  70608. this.index = index;
  70609. this.browserGamepad = browserGamepad;
  70610. this._isConnected = true;
  70611. this._invertLeftStickY = false;
  70612. this.type = Gamepad.GAMEPAD;
  70613. this._leftStickAxisX = leftStickX;
  70614. this._leftStickAxisY = leftStickY;
  70615. this._rightStickAxisX = rightStickX;
  70616. this._rightStickAxisY = rightStickY;
  70617. if (this.browserGamepad.axes.length >= 2) {
  70618. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70619. }
  70620. if (this.browserGamepad.axes.length >= 4) {
  70621. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70622. }
  70623. }
  70624. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70625. get: function () {
  70626. return this._isConnected;
  70627. },
  70628. enumerable: true,
  70629. configurable: true
  70630. });
  70631. Gamepad.prototype.onleftstickchanged = function (callback) {
  70632. this._onleftstickchanged = callback;
  70633. };
  70634. Gamepad.prototype.onrightstickchanged = function (callback) {
  70635. this._onrightstickchanged = callback;
  70636. };
  70637. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70638. get: function () {
  70639. return this._leftStick;
  70640. },
  70641. set: function (newValues) {
  70642. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70643. this._onleftstickchanged(newValues);
  70644. }
  70645. this._leftStick = newValues;
  70646. },
  70647. enumerable: true,
  70648. configurable: true
  70649. });
  70650. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70651. get: function () {
  70652. return this._rightStick;
  70653. },
  70654. set: function (newValues) {
  70655. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70656. this._onrightstickchanged(newValues);
  70657. }
  70658. this._rightStick = newValues;
  70659. },
  70660. enumerable: true,
  70661. configurable: true
  70662. });
  70663. Gamepad.prototype.update = function () {
  70664. if (this._leftStick) {
  70665. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70666. if (this._invertLeftStickY) {
  70667. this.leftStick.y *= -1;
  70668. }
  70669. }
  70670. if (this._rightStick) {
  70671. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70672. }
  70673. };
  70674. Gamepad.prototype.dispose = function () {
  70675. };
  70676. Gamepad.GAMEPAD = 0;
  70677. Gamepad.GENERIC = 1;
  70678. Gamepad.XBOX = 2;
  70679. Gamepad.POSE_ENABLED = 3;
  70680. return Gamepad;
  70681. }());
  70682. BABYLON.Gamepad = Gamepad;
  70683. var GenericPad = /** @class */ (function (_super) {
  70684. __extends(GenericPad, _super);
  70685. function GenericPad(id, index, browserGamepad) {
  70686. var _this = _super.call(this, id, index, browserGamepad) || this;
  70687. _this.onButtonDownObservable = new BABYLON.Observable();
  70688. _this.onButtonUpObservable = new BABYLON.Observable();
  70689. _this.type = Gamepad.GENERIC;
  70690. _this._buttons = new Array(browserGamepad.buttons.length);
  70691. return _this;
  70692. }
  70693. GenericPad.prototype.onbuttondown = function (callback) {
  70694. this._onbuttondown = callback;
  70695. };
  70696. GenericPad.prototype.onbuttonup = function (callback) {
  70697. this._onbuttonup = callback;
  70698. };
  70699. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70700. if (newValue !== currentValue) {
  70701. if (newValue === 1) {
  70702. if (this._onbuttondown) {
  70703. this._onbuttondown(buttonIndex);
  70704. }
  70705. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70706. }
  70707. if (newValue === 0) {
  70708. if (this._onbuttonup) {
  70709. this._onbuttonup(buttonIndex);
  70710. }
  70711. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70712. }
  70713. }
  70714. return newValue;
  70715. };
  70716. GenericPad.prototype.update = function () {
  70717. _super.prototype.update.call(this);
  70718. for (var index = 0; index < this._buttons.length; index++) {
  70719. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70720. }
  70721. };
  70722. GenericPad.prototype.dispose = function () {
  70723. _super.prototype.dispose.call(this);
  70724. this.onButtonDownObservable.clear();
  70725. this.onButtonUpObservable.clear();
  70726. };
  70727. return GenericPad;
  70728. }(Gamepad));
  70729. BABYLON.GenericPad = GenericPad;
  70730. })(BABYLON || (BABYLON = {}));
  70731. //# sourceMappingURL=babylon.gamepad.js.map
  70732. var BABYLON;
  70733. (function (BABYLON) {
  70734. /**
  70735. * Defines supported buttons for XBox360 compatible gamepads
  70736. */
  70737. var Xbox360Button;
  70738. (function (Xbox360Button) {
  70739. /** A */
  70740. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70741. /** B */
  70742. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70743. /** X */
  70744. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70745. /** Y */
  70746. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70747. /** Start */
  70748. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70749. /** Back */
  70750. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70751. /** Left button */
  70752. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70753. /** Right button */
  70754. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70755. /** Left stick */
  70756. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70757. /** Right stick */
  70758. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70759. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70760. /** Defines values for XBox360 DPad */
  70761. var Xbox360Dpad;
  70762. (function (Xbox360Dpad) {
  70763. /** Up */
  70764. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70765. /** Down */
  70766. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70767. /** Left */
  70768. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70769. /** Right */
  70770. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70771. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70772. /**
  70773. * Defines a XBox360 gamepad
  70774. */
  70775. var Xbox360Pad = /** @class */ (function (_super) {
  70776. __extends(Xbox360Pad, _super);
  70777. /**
  70778. * Creates a new XBox360 gamepad object
  70779. * @param id defines the id of this gamepad
  70780. * @param index defines its index
  70781. * @param gamepad defines the internal HTML gamepad object
  70782. * @param xboxOne defines if it is a XBox One gamepad
  70783. */
  70784. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70785. if (xboxOne === void 0) { xboxOne = false; }
  70786. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70787. _this._leftTrigger = 0;
  70788. _this._rightTrigger = 0;
  70789. /** Observable raised when a button is pressed */
  70790. _this.onButtonDownObservable = new BABYLON.Observable();
  70791. /** Observable raised when a button is released */
  70792. _this.onButtonUpObservable = new BABYLON.Observable();
  70793. /** Observable raised when a pad is pressed */
  70794. _this.onPadDownObservable = new BABYLON.Observable();
  70795. /** Observable raised when a pad is released */
  70796. _this.onPadUpObservable = new BABYLON.Observable();
  70797. _this._buttonA = 0;
  70798. _this._buttonB = 0;
  70799. _this._buttonX = 0;
  70800. _this._buttonY = 0;
  70801. _this._buttonBack = 0;
  70802. _this._buttonStart = 0;
  70803. _this._buttonLB = 0;
  70804. _this._buttonRB = 0;
  70805. _this._buttonLeftStick = 0;
  70806. _this._buttonRightStick = 0;
  70807. _this._dPadUp = 0;
  70808. _this._dPadDown = 0;
  70809. _this._dPadLeft = 0;
  70810. _this._dPadRight = 0;
  70811. _this._isXboxOnePad = false;
  70812. _this.type = BABYLON.Gamepad.XBOX;
  70813. _this._isXboxOnePad = xboxOne;
  70814. return _this;
  70815. }
  70816. /**
  70817. * Defines the callback to call when left trigger is pressed
  70818. * @param callback defines the callback to use
  70819. */
  70820. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70821. this._onlefttriggerchanged = callback;
  70822. };
  70823. /**
  70824. * Defines the callback to call when right trigger is pressed
  70825. * @param callback defines the callback to use
  70826. */
  70827. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70828. this._onrighttriggerchanged = callback;
  70829. };
  70830. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70831. /**
  70832. * Gets or sets left trigger value
  70833. */
  70834. get: function () {
  70835. return this._leftTrigger;
  70836. },
  70837. set: function (newValue) {
  70838. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70839. this._onlefttriggerchanged(newValue);
  70840. }
  70841. this._leftTrigger = newValue;
  70842. },
  70843. enumerable: true,
  70844. configurable: true
  70845. });
  70846. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70847. /**
  70848. * Gets or sets right trigger value
  70849. */
  70850. get: function () {
  70851. return this._rightTrigger;
  70852. },
  70853. set: function (newValue) {
  70854. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70855. this._onrighttriggerchanged(newValue);
  70856. }
  70857. this._rightTrigger = newValue;
  70858. },
  70859. enumerable: true,
  70860. configurable: true
  70861. });
  70862. /**
  70863. * Defines the callback to call when a button is pressed
  70864. * @param callback defines the callback to use
  70865. */
  70866. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70867. this._onbuttondown = callback;
  70868. };
  70869. /**
  70870. * Defines the callback to call when a button is released
  70871. * @param callback defines the callback to use
  70872. */
  70873. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70874. this._onbuttonup = callback;
  70875. };
  70876. /**
  70877. * Defines the callback to call when a pad is pressed
  70878. * @param callback defines the callback to use
  70879. */
  70880. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70881. this._ondpaddown = callback;
  70882. };
  70883. /**
  70884. * Defines the callback to call when a pad is released
  70885. * @param callback defines the callback to use
  70886. */
  70887. Xbox360Pad.prototype.ondpadup = function (callback) {
  70888. this._ondpadup = callback;
  70889. };
  70890. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70891. if (newValue !== currentValue) {
  70892. if (newValue === 1) {
  70893. if (this._onbuttondown) {
  70894. this._onbuttondown(buttonType);
  70895. }
  70896. this.onButtonDownObservable.notifyObservers(buttonType);
  70897. }
  70898. if (newValue === 0) {
  70899. if (this._onbuttonup) {
  70900. this._onbuttonup(buttonType);
  70901. }
  70902. this.onButtonUpObservable.notifyObservers(buttonType);
  70903. }
  70904. }
  70905. return newValue;
  70906. };
  70907. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70908. if (newValue !== currentValue) {
  70909. if (newValue === 1) {
  70910. if (this._ondpaddown) {
  70911. this._ondpaddown(buttonType);
  70912. }
  70913. this.onPadDownObservable.notifyObservers(buttonType);
  70914. }
  70915. if (newValue === 0) {
  70916. if (this._ondpadup) {
  70917. this._ondpadup(buttonType);
  70918. }
  70919. this.onPadUpObservable.notifyObservers(buttonType);
  70920. }
  70921. }
  70922. return newValue;
  70923. };
  70924. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70925. /** Gets or sets value of A button */
  70926. get: function () {
  70927. return this._buttonA;
  70928. },
  70929. set: function (value) {
  70930. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70931. },
  70932. enumerable: true,
  70933. configurable: true
  70934. });
  70935. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70936. /** Gets or sets value of B button */
  70937. get: function () {
  70938. return this._buttonB;
  70939. },
  70940. set: function (value) {
  70941. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70942. },
  70943. enumerable: true,
  70944. configurable: true
  70945. });
  70946. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70947. /** Gets or sets value of X button */
  70948. get: function () {
  70949. return this._buttonX;
  70950. },
  70951. set: function (value) {
  70952. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70953. },
  70954. enumerable: true,
  70955. configurable: true
  70956. });
  70957. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70958. /** Gets or sets value of Y button */
  70959. get: function () {
  70960. return this._buttonY;
  70961. },
  70962. set: function (value) {
  70963. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70964. },
  70965. enumerable: true,
  70966. configurable: true
  70967. });
  70968. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70969. /** Gets or sets value of Start button */
  70970. get: function () {
  70971. return this._buttonStart;
  70972. },
  70973. set: function (value) {
  70974. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70975. },
  70976. enumerable: true,
  70977. configurable: true
  70978. });
  70979. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70980. /** Gets or sets value of Back button */
  70981. get: function () {
  70982. return this._buttonBack;
  70983. },
  70984. set: function (value) {
  70985. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70986. },
  70987. enumerable: true,
  70988. configurable: true
  70989. });
  70990. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70991. /** Gets or sets value of Left button */
  70992. get: function () {
  70993. return this._buttonLB;
  70994. },
  70995. set: function (value) {
  70996. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70997. },
  70998. enumerable: true,
  70999. configurable: true
  71000. });
  71001. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71002. /** Gets or sets value of Right button */
  71003. get: function () {
  71004. return this._buttonRB;
  71005. },
  71006. set: function (value) {
  71007. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71008. },
  71009. enumerable: true,
  71010. configurable: true
  71011. });
  71012. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71013. /** Gets or sets value of left stick */
  71014. get: function () {
  71015. return this._buttonLeftStick;
  71016. },
  71017. set: function (value) {
  71018. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71019. },
  71020. enumerable: true,
  71021. configurable: true
  71022. });
  71023. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71024. /** Gets or sets value of right stick */
  71025. get: function () {
  71026. return this._buttonRightStick;
  71027. },
  71028. set: function (value) {
  71029. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71030. },
  71031. enumerable: true,
  71032. configurable: true
  71033. });
  71034. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71035. /** Gets or sets value of DPad up */
  71036. get: function () {
  71037. return this._dPadUp;
  71038. },
  71039. set: function (value) {
  71040. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71041. },
  71042. enumerable: true,
  71043. configurable: true
  71044. });
  71045. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71046. /** Gets or sets value of DPad down */
  71047. get: function () {
  71048. return this._dPadDown;
  71049. },
  71050. set: function (value) {
  71051. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71052. },
  71053. enumerable: true,
  71054. configurable: true
  71055. });
  71056. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71057. /** Gets or sets value of DPad left */
  71058. get: function () {
  71059. return this._dPadLeft;
  71060. },
  71061. set: function (value) {
  71062. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71063. },
  71064. enumerable: true,
  71065. configurable: true
  71066. });
  71067. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71068. /** Gets or sets value of DPad right */
  71069. get: function () {
  71070. return this._dPadRight;
  71071. },
  71072. set: function (value) {
  71073. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71074. },
  71075. enumerable: true,
  71076. configurable: true
  71077. });
  71078. /**
  71079. * Force the gamepad to synchronize with device values
  71080. */
  71081. Xbox360Pad.prototype.update = function () {
  71082. _super.prototype.update.call(this);
  71083. if (this._isXboxOnePad) {
  71084. this.buttonA = this.browserGamepad.buttons[0].value;
  71085. this.buttonB = this.browserGamepad.buttons[1].value;
  71086. this.buttonX = this.browserGamepad.buttons[2].value;
  71087. this.buttonY = this.browserGamepad.buttons[3].value;
  71088. this.buttonLB = this.browserGamepad.buttons[4].value;
  71089. this.buttonRB = this.browserGamepad.buttons[5].value;
  71090. this.leftTrigger = this.browserGamepad.axes[2];
  71091. this.rightTrigger = this.browserGamepad.axes[5];
  71092. this.buttonBack = this.browserGamepad.buttons[9].value;
  71093. this.buttonStart = this.browserGamepad.buttons[8].value;
  71094. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71095. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71096. this.dPadUp = this.browserGamepad.buttons[11].value;
  71097. this.dPadDown = this.browserGamepad.buttons[12].value;
  71098. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71099. this.dPadRight = this.browserGamepad.buttons[14].value;
  71100. }
  71101. else {
  71102. this.buttonA = this.browserGamepad.buttons[0].value;
  71103. this.buttonB = this.browserGamepad.buttons[1].value;
  71104. this.buttonX = this.browserGamepad.buttons[2].value;
  71105. this.buttonY = this.browserGamepad.buttons[3].value;
  71106. this.buttonLB = this.browserGamepad.buttons[4].value;
  71107. this.buttonRB = this.browserGamepad.buttons[5].value;
  71108. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71109. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71110. this.buttonBack = this.browserGamepad.buttons[8].value;
  71111. this.buttonStart = this.browserGamepad.buttons[9].value;
  71112. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71113. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71114. this.dPadUp = this.browserGamepad.buttons[12].value;
  71115. this.dPadDown = this.browserGamepad.buttons[13].value;
  71116. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71117. this.dPadRight = this.browserGamepad.buttons[15].value;
  71118. }
  71119. };
  71120. Xbox360Pad.prototype.dispose = function () {
  71121. _super.prototype.dispose.call(this);
  71122. this.onButtonDownObservable.clear();
  71123. this.onButtonUpObservable.clear();
  71124. this.onPadDownObservable.clear();
  71125. this.onPadUpObservable.clear();
  71126. };
  71127. return Xbox360Pad;
  71128. }(BABYLON.Gamepad));
  71129. BABYLON.Xbox360Pad = Xbox360Pad;
  71130. })(BABYLON || (BABYLON = {}));
  71131. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71132. var BABYLON;
  71133. (function (BABYLON) {
  71134. /**
  71135. * Defines the types of pose enabled controllers that are supported
  71136. */
  71137. var PoseEnabledControllerType;
  71138. (function (PoseEnabledControllerType) {
  71139. /**
  71140. * HTC Vive
  71141. */
  71142. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71143. /**
  71144. * Oculus Rift
  71145. */
  71146. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71147. /**
  71148. * Windows mixed reality
  71149. */
  71150. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71151. /**
  71152. * Samsung gear VR
  71153. */
  71154. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71155. /**
  71156. * Google Daydream
  71157. */
  71158. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71159. /**
  71160. * Generic
  71161. */
  71162. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71163. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71164. /**
  71165. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71166. */
  71167. var PoseEnabledControllerHelper = /** @class */ (function () {
  71168. function PoseEnabledControllerHelper() {
  71169. }
  71170. /**
  71171. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71172. * @param vrGamepad the gamepad to initialized
  71173. * @returns a vr controller of the type the gamepad identified as
  71174. */
  71175. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71176. // Oculus Touch
  71177. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71178. return new BABYLON.OculusTouchController(vrGamepad);
  71179. }
  71180. // Windows Mixed Reality controllers
  71181. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71182. return new BABYLON.WindowsMotionController(vrGamepad);
  71183. }
  71184. // HTC Vive
  71185. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71186. return new BABYLON.ViveController(vrGamepad);
  71187. }
  71188. // Samsung/Oculus Gear VR or Oculus Go
  71189. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71190. return new BABYLON.GearVRController(vrGamepad);
  71191. }
  71192. // Google Daydream
  71193. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71194. return new BABYLON.DaydreamController(vrGamepad);
  71195. }
  71196. // Generic
  71197. else {
  71198. return new BABYLON.GenericController(vrGamepad);
  71199. }
  71200. };
  71201. return PoseEnabledControllerHelper;
  71202. }());
  71203. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71204. /**
  71205. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71206. */
  71207. var PoseEnabledController = /** @class */ (function (_super) {
  71208. __extends(PoseEnabledController, _super);
  71209. /**
  71210. * Creates a new PoseEnabledController from a gamepad
  71211. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71212. */
  71213. function PoseEnabledController(browserGamepad) {
  71214. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71215. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71216. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71217. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71218. /**
  71219. * The device position in babylon space
  71220. */
  71221. _this.devicePosition = BABYLON.Vector3.Zero();
  71222. /**
  71223. * The device rotation in babylon space
  71224. */
  71225. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71226. /**
  71227. * The scale factor of the device in babylon space
  71228. */
  71229. _this.deviceScaleFactor = 1;
  71230. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71231. /**
  71232. * Internal, matrix used to convert room space to babylon space
  71233. */
  71234. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71235. /**
  71236. * Node to be used when casting a ray from the controller
  71237. */
  71238. _this._pointingPoseNode = null;
  71239. _this._workingMatrix = BABYLON.Matrix.Identity();
  71240. /**
  71241. * @hidden
  71242. */
  71243. _this._meshAttachedObservable = new BABYLON.Observable();
  71244. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71245. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71246. _this.position = BABYLON.Vector3.Zero();
  71247. _this.rotationQuaternion = new BABYLON.Quaternion();
  71248. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71249. _this._calculatedRotation = new BABYLON.Quaternion();
  71250. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71251. return _this;
  71252. }
  71253. /**
  71254. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71255. */
  71256. PoseEnabledController.prototype.update = function () {
  71257. _super.prototype.update.call(this);
  71258. var pose = this.browserGamepad.pose;
  71259. this.updateFromDevice(pose);
  71260. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71261. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71262. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71263. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71264. if (this._mesh) {
  71265. this._mesh.position.copyFrom(this.devicePosition);
  71266. if (this._mesh.rotationQuaternion) {
  71267. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71268. }
  71269. }
  71270. };
  71271. /**
  71272. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71273. * @param poseData raw pose fromthe device
  71274. */
  71275. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71276. if (poseData) {
  71277. this.rawPose = poseData;
  71278. if (poseData.position) {
  71279. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71280. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71281. this._deviceRoomPosition.z *= -1;
  71282. }
  71283. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71284. this._calculatedPosition.addInPlace(this.position);
  71285. }
  71286. var pose = this.rawPose;
  71287. if (poseData.orientation && pose.orientation) {
  71288. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71289. if (this._mesh) {
  71290. if (this._mesh.getScene().useRightHandedSystem) {
  71291. this._deviceRoomRotationQuaternion.z *= -1;
  71292. this._deviceRoomRotationQuaternion.w *= -1;
  71293. }
  71294. else {
  71295. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71296. }
  71297. }
  71298. // if the camera is set, rotate to the camera's rotation
  71299. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71300. }
  71301. }
  71302. };
  71303. /**
  71304. * Attaches a mesh to the controller
  71305. * @param mesh the mesh to be attached
  71306. */
  71307. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71308. if (this._mesh) {
  71309. this._mesh.parent = null;
  71310. }
  71311. this._mesh = mesh;
  71312. if (this._poseControlledCamera) {
  71313. this._mesh.parent = this._poseControlledCamera;
  71314. }
  71315. if (!this._mesh.rotationQuaternion) {
  71316. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71317. }
  71318. this._meshAttachedObservable.notifyObservers(mesh);
  71319. };
  71320. /**
  71321. * Attaches the controllers mesh to a camera
  71322. * @param camera the camera the mesh should be attached to
  71323. */
  71324. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71325. this._poseControlledCamera = camera;
  71326. if (this._mesh) {
  71327. this._mesh.parent = this._poseControlledCamera;
  71328. }
  71329. };
  71330. /**
  71331. * Disposes of the controller
  71332. */
  71333. PoseEnabledController.prototype.dispose = function () {
  71334. if (this._mesh) {
  71335. this._mesh.dispose();
  71336. }
  71337. this._mesh = null;
  71338. _super.prototype.dispose.call(this);
  71339. };
  71340. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71341. /**
  71342. * The mesh that is attached to the controller
  71343. */
  71344. get: function () {
  71345. return this._mesh;
  71346. },
  71347. enumerable: true,
  71348. configurable: true
  71349. });
  71350. /**
  71351. * Gets the ray of the controller in the direction the controller is pointing
  71352. * @param length the length the resulting ray should be
  71353. * @returns a ray in the direction the controller is pointing
  71354. */
  71355. PoseEnabledController.prototype.getForwardRay = function (length) {
  71356. if (length === void 0) { length = 100; }
  71357. if (!this.mesh) {
  71358. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71359. }
  71360. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71361. var origin = m.getTranslation();
  71362. var forward = new BABYLON.Vector3(0, 0, -1);
  71363. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71364. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71365. return new BABYLON.Ray(origin, direction, length);
  71366. };
  71367. /**
  71368. * Name of the child mesh that can be used to cast a ray from the controller
  71369. */
  71370. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71371. return PoseEnabledController;
  71372. }(BABYLON.Gamepad));
  71373. BABYLON.PoseEnabledController = PoseEnabledController;
  71374. })(BABYLON || (BABYLON = {}));
  71375. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71376. var BABYLON;
  71377. (function (BABYLON) {
  71378. /**
  71379. * Defines the WebVRController object that represents controllers tracked in 3D space
  71380. */
  71381. var WebVRController = /** @class */ (function (_super) {
  71382. __extends(WebVRController, _super);
  71383. /**
  71384. * Creates a new WebVRController from a gamepad
  71385. * @param vrGamepad the gamepad that the WebVRController should be created from
  71386. */
  71387. function WebVRController(vrGamepad) {
  71388. var _this = _super.call(this, vrGamepad) || this;
  71389. // Observables
  71390. /**
  71391. * Fired when the trigger state has changed
  71392. */
  71393. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71394. /**
  71395. * Fired when the main button state has changed
  71396. */
  71397. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71398. /**
  71399. * Fired when the secondary button state has changed
  71400. */
  71401. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71402. /**
  71403. * Fired when the pad state has changed
  71404. */
  71405. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71406. /**
  71407. * Fired when controllers stick values have changed
  71408. */
  71409. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71410. /**
  71411. * X and Y axis corrisponding to the controllers joystick
  71412. */
  71413. _this.pad = { x: 0, y: 0 };
  71414. // avoid GC, store state in a tmp object
  71415. _this._changes = {
  71416. pressChanged: false,
  71417. touchChanged: false,
  71418. valueChanged: false,
  71419. changed: false
  71420. };
  71421. _this._buttons = new Array(vrGamepad.buttons.length);
  71422. _this.hand = vrGamepad.hand;
  71423. return _this;
  71424. }
  71425. /**
  71426. * Fired when a controller button's state has changed
  71427. * @param callback the callback containing the button that was modified
  71428. */
  71429. WebVRController.prototype.onButtonStateChange = function (callback) {
  71430. this._onButtonStateChange = callback;
  71431. };
  71432. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71433. /**
  71434. * The default controller model for the controller
  71435. */
  71436. get: function () {
  71437. return this._defaultModel;
  71438. },
  71439. enumerable: true,
  71440. configurable: true
  71441. });
  71442. /**
  71443. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71444. */
  71445. WebVRController.prototype.update = function () {
  71446. _super.prototype.update.call(this);
  71447. for (var index = 0; index < this._buttons.length; index++) {
  71448. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71449. }
  71450. ;
  71451. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71452. this.pad.x = this.leftStick.x;
  71453. this.pad.y = this.leftStick.y;
  71454. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71455. }
  71456. };
  71457. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71458. if (!newState) {
  71459. newState = {
  71460. pressed: false,
  71461. touched: false,
  71462. value: 0
  71463. };
  71464. }
  71465. if (!currentState) {
  71466. this._buttons[buttonIndex] = {
  71467. pressed: newState.pressed,
  71468. touched: newState.touched,
  71469. value: newState.value
  71470. };
  71471. return;
  71472. }
  71473. this._checkChanges(newState, currentState);
  71474. if (this._changes.changed) {
  71475. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71476. this._handleButtonChange(buttonIndex, newState, this._changes);
  71477. }
  71478. this._buttons[buttonIndex].pressed = newState.pressed;
  71479. this._buttons[buttonIndex].touched = newState.touched;
  71480. // oculus triggers are never 0, thou not touched.
  71481. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71482. };
  71483. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71484. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71485. this._changes.touchChanged = newState.touched !== currentState.touched;
  71486. this._changes.valueChanged = newState.value !== currentState.value;
  71487. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71488. return this._changes;
  71489. };
  71490. /**
  71491. * Disposes of th webVRCOntroller
  71492. */
  71493. WebVRController.prototype.dispose = function () {
  71494. _super.prototype.dispose.call(this);
  71495. this.onTriggerStateChangedObservable.clear();
  71496. this.onMainButtonStateChangedObservable.clear();
  71497. this.onSecondaryButtonStateChangedObservable.clear();
  71498. this.onPadStateChangedObservable.clear();
  71499. this.onPadValuesChangedObservable.clear();
  71500. };
  71501. return WebVRController;
  71502. }(BABYLON.PoseEnabledController));
  71503. BABYLON.WebVRController = WebVRController;
  71504. })(BABYLON || (BABYLON = {}));
  71505. //# sourceMappingURL=babylon.webVRController.js.map
  71506. var BABYLON;
  71507. (function (BABYLON) {
  71508. /**
  71509. * Oculus Touch Controller
  71510. */
  71511. var OculusTouchController = /** @class */ (function (_super) {
  71512. __extends(OculusTouchController, _super);
  71513. /**
  71514. * Creates a new OculusTouchController from a gamepad
  71515. * @param vrGamepad the gamepad that the controller should be created from
  71516. */
  71517. function OculusTouchController(vrGamepad) {
  71518. var _this = _super.call(this, vrGamepad) || this;
  71519. /**
  71520. * Fired when the secondary trigger on this controller is modified
  71521. */
  71522. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71523. /**
  71524. * Fired when the thumb rest on this controller is modified
  71525. */
  71526. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71527. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71528. return _this;
  71529. }
  71530. /**
  71531. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71532. * @param scene scene in which to add meshes
  71533. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71534. */
  71535. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71536. var _this = this;
  71537. var meshName;
  71538. // Hand
  71539. if (this.hand === 'left') {
  71540. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71541. }
  71542. else { // Right is the default if no hand is specified
  71543. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71544. }
  71545. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71546. /*
  71547. Parent Mesh name: oculus_touch_left
  71548. - body
  71549. - trigger
  71550. - thumbstick
  71551. - grip
  71552. - button_y
  71553. - button_x
  71554. - button_enter
  71555. */
  71556. _this._defaultModel = newMeshes[1];
  71557. _this.attachToMesh(_this._defaultModel);
  71558. if (meshLoaded) {
  71559. meshLoaded(_this._defaultModel);
  71560. }
  71561. });
  71562. };
  71563. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71564. /**
  71565. * Fired when the A button on this controller is modified
  71566. */
  71567. get: function () {
  71568. if (this.hand === 'right') {
  71569. return this.onMainButtonStateChangedObservable;
  71570. }
  71571. else {
  71572. throw new Error('No A button on left hand');
  71573. }
  71574. },
  71575. enumerable: true,
  71576. configurable: true
  71577. });
  71578. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71579. /**
  71580. * Fired when the B button on this controller is modified
  71581. */
  71582. get: function () {
  71583. if (this.hand === 'right') {
  71584. return this.onSecondaryButtonStateChangedObservable;
  71585. }
  71586. else {
  71587. throw new Error('No B button on left hand');
  71588. }
  71589. },
  71590. enumerable: true,
  71591. configurable: true
  71592. });
  71593. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71594. /**
  71595. * Fired when the X button on this controller is modified
  71596. */
  71597. get: function () {
  71598. if (this.hand === 'left') {
  71599. return this.onMainButtonStateChangedObservable;
  71600. }
  71601. else {
  71602. throw new Error('No X button on right hand');
  71603. }
  71604. },
  71605. enumerable: true,
  71606. configurable: true
  71607. });
  71608. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71609. /**
  71610. * Fired when the Y button on this controller is modified
  71611. */
  71612. get: function () {
  71613. if (this.hand === 'left') {
  71614. return this.onSecondaryButtonStateChangedObservable;
  71615. }
  71616. else {
  71617. throw new Error('No Y button on right hand');
  71618. }
  71619. },
  71620. enumerable: true,
  71621. configurable: true
  71622. });
  71623. /**
  71624. * Called once for each button that changed state since the last frame
  71625. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71626. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71627. * 2) secondary trigger (same)
  71628. * 3) A (right) X (left), touch, pressed = value
  71629. * 4) B / Y
  71630. * 5) thumb rest
  71631. * @param buttonIdx Which button index changed
  71632. * @param state New state of the button
  71633. * @param changes Which properties on the state changed since last frame
  71634. */
  71635. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71636. var notifyObject = state; //{ state: state, changes: changes };
  71637. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71638. switch (buttonIdx) {
  71639. case 0:
  71640. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71641. return;
  71642. case 1: // index trigger
  71643. if (this._defaultModel) {
  71644. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71645. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71646. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71647. }
  71648. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71649. return;
  71650. case 2: // secondary trigger
  71651. if (this._defaultModel) {
  71652. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71653. }
  71654. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71655. return;
  71656. case 3:
  71657. if (this._defaultModel) {
  71658. if (notifyObject.pressed) {
  71659. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71660. }
  71661. else {
  71662. (this._defaultModel.getChildren()[1]).position.y = 0;
  71663. }
  71664. }
  71665. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71666. return;
  71667. case 4:
  71668. if (this._defaultModel) {
  71669. if (notifyObject.pressed) {
  71670. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71671. }
  71672. else {
  71673. (this._defaultModel.getChildren()[2]).position.y = 0;
  71674. }
  71675. }
  71676. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71677. return;
  71678. case 5:
  71679. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71680. return;
  71681. }
  71682. };
  71683. /**
  71684. * Base Url for the controller model.
  71685. */
  71686. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71687. /**
  71688. * File name for the left controller model.
  71689. */
  71690. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71691. /**
  71692. * File name for the right controller model.
  71693. */
  71694. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71695. return OculusTouchController;
  71696. }(BABYLON.WebVRController));
  71697. BABYLON.OculusTouchController = OculusTouchController;
  71698. })(BABYLON || (BABYLON = {}));
  71699. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71700. var BABYLON;
  71701. (function (BABYLON) {
  71702. /**
  71703. * Vive Controller
  71704. */
  71705. var ViveController = /** @class */ (function (_super) {
  71706. __extends(ViveController, _super);
  71707. /**
  71708. * Creates a new ViveController from a gamepad
  71709. * @param vrGamepad the gamepad that the controller should be created from
  71710. */
  71711. function ViveController(vrGamepad) {
  71712. var _this = _super.call(this, vrGamepad) || this;
  71713. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71714. _this._invertLeftStickY = true;
  71715. return _this;
  71716. }
  71717. /**
  71718. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71719. * @param scene scene in which to add meshes
  71720. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71721. */
  71722. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71723. var _this = this;
  71724. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71725. /*
  71726. Parent Mesh name: ViveWand
  71727. - body
  71728. - r_gripper
  71729. - l_gripper
  71730. - menu_button
  71731. - system_button
  71732. - trackpad
  71733. - trigger
  71734. - LED
  71735. */
  71736. _this._defaultModel = newMeshes[1];
  71737. _this.attachToMesh(_this._defaultModel);
  71738. if (meshLoaded) {
  71739. meshLoaded(_this._defaultModel);
  71740. }
  71741. });
  71742. };
  71743. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71744. /**
  71745. * Fired when the left button on this controller is modified
  71746. */
  71747. get: function () {
  71748. return this.onMainButtonStateChangedObservable;
  71749. },
  71750. enumerable: true,
  71751. configurable: true
  71752. });
  71753. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71754. /**
  71755. * Fired when the right button on this controller is modified
  71756. */
  71757. get: function () {
  71758. return this.onMainButtonStateChangedObservable;
  71759. },
  71760. enumerable: true,
  71761. configurable: true
  71762. });
  71763. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71764. /**
  71765. * Fired when the menu button on this controller is modified
  71766. */
  71767. get: function () {
  71768. return this.onSecondaryButtonStateChangedObservable;
  71769. },
  71770. enumerable: true,
  71771. configurable: true
  71772. });
  71773. /**
  71774. * Called once for each button that changed state since the last frame
  71775. * Vive mapping:
  71776. * 0: touchpad
  71777. * 1: trigger
  71778. * 2: left AND right buttons
  71779. * 3: menu button
  71780. * @param buttonIdx Which button index changed
  71781. * @param state New state of the button
  71782. * @param changes Which properties on the state changed since last frame
  71783. */
  71784. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71785. var notifyObject = state; //{ state: state, changes: changes };
  71786. switch (buttonIdx) {
  71787. case 0:
  71788. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71789. return;
  71790. case 1: // index trigger
  71791. if (this._defaultModel) {
  71792. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71793. }
  71794. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71795. return;
  71796. case 2: // left AND right button
  71797. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71798. return;
  71799. case 3:
  71800. if (this._defaultModel) {
  71801. if (notifyObject.pressed) {
  71802. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71803. }
  71804. else {
  71805. (this._defaultModel.getChildren()[2]).position.y = 0;
  71806. }
  71807. }
  71808. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71809. return;
  71810. }
  71811. };
  71812. /**
  71813. * Base Url for the controller model.
  71814. */
  71815. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71816. /**
  71817. * File name for the controller model.
  71818. */
  71819. ViveController.MODEL_FILENAME = 'wand.babylon';
  71820. return ViveController;
  71821. }(BABYLON.WebVRController));
  71822. BABYLON.ViveController = ViveController;
  71823. })(BABYLON || (BABYLON = {}));
  71824. //# sourceMappingURL=babylon.viveController.js.map
  71825. var BABYLON;
  71826. (function (BABYLON) {
  71827. /**
  71828. * Generic Controller
  71829. */
  71830. var GenericController = /** @class */ (function (_super) {
  71831. __extends(GenericController, _super);
  71832. /**
  71833. * Creates a new GenericController from a gamepad
  71834. * @param vrGamepad the gamepad that the controller should be created from
  71835. */
  71836. function GenericController(vrGamepad) {
  71837. return _super.call(this, vrGamepad) || this;
  71838. }
  71839. /**
  71840. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71841. * @param scene scene in which to add meshes
  71842. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71843. */
  71844. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71845. var _this = this;
  71846. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71847. _this._defaultModel = newMeshes[1];
  71848. _this.attachToMesh(_this._defaultModel);
  71849. if (meshLoaded) {
  71850. meshLoaded(_this._defaultModel);
  71851. }
  71852. });
  71853. };
  71854. /**
  71855. * Called once for each button that changed state since the last frame
  71856. * @param buttonIdx Which button index changed
  71857. * @param state New state of the button
  71858. * @param changes Which properties on the state changed since last frame
  71859. */
  71860. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71861. console.log("Button id: " + buttonIdx + "state: ");
  71862. console.dir(state);
  71863. };
  71864. /**
  71865. * Base Url for the controller model.
  71866. */
  71867. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71868. /**
  71869. * File name for the controller model.
  71870. */
  71871. GenericController.MODEL_FILENAME = 'generic.babylon';
  71872. return GenericController;
  71873. }(BABYLON.WebVRController));
  71874. BABYLON.GenericController = GenericController;
  71875. })(BABYLON || (BABYLON = {}));
  71876. //# sourceMappingURL=babylon.genericController.js.map
  71877. var BABYLON;
  71878. (function (BABYLON) {
  71879. /**
  71880. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71881. */
  71882. var LoadedMeshInfo = /** @class */ (function () {
  71883. function LoadedMeshInfo() {
  71884. /**
  71885. * Map of the button meshes contained in the controller
  71886. */
  71887. this.buttonMeshes = {};
  71888. /**
  71889. * Map of the axis meshes contained in the controller
  71890. */
  71891. this.axisMeshes = {};
  71892. }
  71893. return LoadedMeshInfo;
  71894. }());
  71895. /**
  71896. * Defines the WindowsMotionController object that the state of the windows motion controller
  71897. */
  71898. var WindowsMotionController = /** @class */ (function (_super) {
  71899. __extends(WindowsMotionController, _super);
  71900. /**
  71901. * Creates a new WindowsMotionController from a gamepad
  71902. * @param vrGamepad the gamepad that the controller should be created from
  71903. */
  71904. function WindowsMotionController(vrGamepad) {
  71905. var _this = _super.call(this, vrGamepad) || this;
  71906. _this._mapping = {
  71907. // Semantic button names
  71908. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71909. // A mapping of the button name to glTF model node name
  71910. // that should be transformed by button value.
  71911. buttonMeshNames: {
  71912. 'trigger': 'SELECT',
  71913. 'menu': 'MENU',
  71914. 'grip': 'GRASP',
  71915. 'thumbstick': 'THUMBSTICK_PRESS',
  71916. 'trackpad': 'TOUCHPAD_PRESS'
  71917. },
  71918. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71919. buttonObservableNames: {
  71920. 'trigger': 'onTriggerStateChangedObservable',
  71921. 'menu': 'onSecondaryButtonStateChangedObservable',
  71922. 'grip': 'onMainButtonStateChangedObservable',
  71923. 'thumbstick': 'onPadStateChangedObservable',
  71924. 'trackpad': 'onTrackpadChangedObservable'
  71925. },
  71926. // A mapping of the axis name to glTF model node name
  71927. // that should be transformed by axis value.
  71928. // This array mirrors the browserGamepad.axes array, such that
  71929. // the mesh corresponding to axis 0 is in this array index 0.
  71930. axisMeshNames: [
  71931. 'THUMBSTICK_X',
  71932. 'THUMBSTICK_Y',
  71933. 'TOUCHPAD_TOUCH_X',
  71934. 'TOUCHPAD_TOUCH_Y'
  71935. ],
  71936. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71937. };
  71938. /**
  71939. * Fired when the trackpad on this controller is clicked
  71940. */
  71941. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71942. /**
  71943. * Fired when the trackpad on this controller is modified
  71944. */
  71945. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71946. /**
  71947. * The current x and y values of this controller's trackpad
  71948. */
  71949. _this.trackpad = { x: 0, y: 0 };
  71950. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71951. _this._loadedMeshInfo = null;
  71952. return _this;
  71953. }
  71954. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71955. /**
  71956. * Fired when the trigger on this controller is modified
  71957. */
  71958. get: function () {
  71959. return this.onTriggerStateChangedObservable;
  71960. },
  71961. enumerable: true,
  71962. configurable: true
  71963. });
  71964. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71965. /**
  71966. * Fired when the menu button on this controller is modified
  71967. */
  71968. get: function () {
  71969. return this.onSecondaryButtonStateChangedObservable;
  71970. },
  71971. enumerable: true,
  71972. configurable: true
  71973. });
  71974. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71975. /**
  71976. * Fired when the grip button on this controller is modified
  71977. */
  71978. get: function () {
  71979. return this.onMainButtonStateChangedObservable;
  71980. },
  71981. enumerable: true,
  71982. configurable: true
  71983. });
  71984. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71985. /**
  71986. * Fired when the thumbstick button on this controller is modified
  71987. */
  71988. get: function () {
  71989. return this.onPadStateChangedObservable;
  71990. },
  71991. enumerable: true,
  71992. configurable: true
  71993. });
  71994. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71995. /**
  71996. * Fired when the touchpad button on this controller is modified
  71997. */
  71998. get: function () {
  71999. return this.onTrackpadChangedObservable;
  72000. },
  72001. enumerable: true,
  72002. configurable: true
  72003. });
  72004. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72005. /**
  72006. * Fired when the touchpad values on this controller are modified
  72007. */
  72008. get: function () {
  72009. return this.onTrackpadValuesChangedObservable;
  72010. },
  72011. enumerable: true,
  72012. configurable: true
  72013. });
  72014. /**
  72015. * Called once per frame by the engine.
  72016. */
  72017. WindowsMotionController.prototype.update = function () {
  72018. _super.prototype.update.call(this);
  72019. if (this.browserGamepad.axes) {
  72020. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  72021. this.trackpad.x = this.browserGamepad["axes"][2];
  72022. this.trackpad.y = this.browserGamepad["axes"][3];
  72023. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72024. }
  72025. // Only need to animate axes if there is a loaded mesh
  72026. if (this._loadedMeshInfo) {
  72027. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72028. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72029. }
  72030. }
  72031. }
  72032. };
  72033. /**
  72034. * Called once for each button that changed state since the last frame
  72035. * @param buttonIdx Which button index changed
  72036. * @param state New state of the button
  72037. * @param changes Which properties on the state changed since last frame
  72038. */
  72039. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72040. var buttonName = this._mapping.buttons[buttonIdx];
  72041. if (!buttonName) {
  72042. return;
  72043. }
  72044. // Only emit events for buttons that we know how to map from index to name
  72045. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72046. if (observable) {
  72047. observable.notifyObservers(state);
  72048. }
  72049. this._lerpButtonTransform(buttonName, state.value);
  72050. };
  72051. /**
  72052. * Moves the buttons on the controller mesh based on their current state
  72053. * @param buttonName the name of the button to move
  72054. * @param buttonValue the value of the button which determines the buttons new position
  72055. */
  72056. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72057. // If there is no loaded mesh, there is nothing to transform.
  72058. if (!this._loadedMeshInfo) {
  72059. return;
  72060. }
  72061. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72062. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72063. return;
  72064. }
  72065. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72066. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72067. };
  72068. /**
  72069. * Moves the axis on the controller mesh based on its current state
  72070. * @param axis the index of the axis
  72071. * @param axisValue the value of the axis which determines the meshes new position
  72072. * @hidden
  72073. */
  72074. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72075. if (!this._loadedMeshInfo) {
  72076. return;
  72077. }
  72078. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72079. if (!meshInfo) {
  72080. return;
  72081. }
  72082. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72083. return;
  72084. }
  72085. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72086. var lerpValue = axisValue * 0.5 + 0.5;
  72087. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72088. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72089. };
  72090. /**
  72091. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72092. * @param scene scene in which to add meshes
  72093. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72094. */
  72095. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72096. var _this = this;
  72097. if (forceDefault === void 0) { forceDefault = false; }
  72098. var path;
  72099. var filename;
  72100. // Checking if GLB loader is present
  72101. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72102. // Determine the device specific folder based on the ID suffix
  72103. var device = 'default';
  72104. if (this.id && !forceDefault) {
  72105. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72106. device = ((match && match[0]) || device);
  72107. }
  72108. // Hand
  72109. if (this.hand === 'left') {
  72110. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72111. }
  72112. else { // Right is the default if no hand is specified
  72113. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72114. }
  72115. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72116. }
  72117. else {
  72118. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72119. path = BABYLON.GenericController.MODEL_BASE_URL;
  72120. filename = BABYLON.GenericController.MODEL_FILENAME;
  72121. }
  72122. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72123. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72124. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72125. if (!_this._loadedMeshInfo) {
  72126. return;
  72127. }
  72128. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72129. _this.attachToMesh(_this._defaultModel);
  72130. if (meshLoaded) {
  72131. meshLoaded(_this._defaultModel);
  72132. }
  72133. }, null, function (scene, message) {
  72134. BABYLON.Tools.Log(message);
  72135. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72136. if (!forceDefault) {
  72137. _this.initControllerMesh(scene, meshLoaded, true);
  72138. }
  72139. });
  72140. };
  72141. /**
  72142. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72143. * can be transformed by button presses and axes values, based on this._mapping.
  72144. *
  72145. * @param scene scene in which the meshes exist
  72146. * @param meshes list of meshes that make up the controller model to process
  72147. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72148. */
  72149. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72150. var loadedMeshInfo = null;
  72151. // Create a new mesh to contain the glTF hierarchy
  72152. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72153. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72154. var childMesh = null;
  72155. for (var i = 0; i < meshes.length; i++) {
  72156. var mesh = meshes[i];
  72157. if (!mesh.parent) {
  72158. // Exclude controller meshes from picking results
  72159. mesh.isPickable = false;
  72160. // Handle root node, attach to the new parentMesh
  72161. childMesh = mesh;
  72162. break;
  72163. }
  72164. }
  72165. if (childMesh) {
  72166. childMesh.setParent(parentMesh);
  72167. // Create our mesh info. Note that this method will always return non-null.
  72168. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72169. }
  72170. else {
  72171. BABYLON.Tools.Warn('Could not find root node in model file.');
  72172. }
  72173. return loadedMeshInfo;
  72174. };
  72175. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72176. var loadedMeshInfo = new LoadedMeshInfo();
  72177. var i;
  72178. loadedMeshInfo.rootNode = rootNode;
  72179. // Reset the caches
  72180. loadedMeshInfo.buttonMeshes = {};
  72181. loadedMeshInfo.axisMeshes = {};
  72182. // Button Meshes
  72183. for (i = 0; i < this._mapping.buttons.length; i++) {
  72184. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72185. if (!buttonMeshName) {
  72186. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72187. continue;
  72188. }
  72189. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72190. if (!buttonMesh) {
  72191. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72192. continue;
  72193. }
  72194. var buttonMeshInfo = {
  72195. index: i,
  72196. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72197. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72198. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72199. };
  72200. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72201. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72202. }
  72203. else {
  72204. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72205. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72206. '(VALUE: ' + !!buttonMeshInfo.value +
  72207. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72208. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72209. ')');
  72210. }
  72211. }
  72212. // Axis Meshes
  72213. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72214. var axisMeshName = this._mapping.axisMeshNames[i];
  72215. if (!axisMeshName) {
  72216. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72217. continue;
  72218. }
  72219. var axisMesh = getChildByName(rootNode, axisMeshName);
  72220. if (!axisMesh) {
  72221. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72222. continue;
  72223. }
  72224. var axisMeshInfo = {
  72225. index: i,
  72226. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72227. min: getImmediateChildByName(axisMesh, 'MIN'),
  72228. max: getImmediateChildByName(axisMesh, 'MAX')
  72229. };
  72230. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72231. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72232. }
  72233. else {
  72234. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72235. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72236. '(VALUE: ' + !!axisMeshInfo.value +
  72237. ', MIN: ' + !!axisMeshInfo.min +
  72238. ', MAX:' + !!axisMeshInfo.max +
  72239. ')');
  72240. }
  72241. }
  72242. // Pointing Ray
  72243. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72244. if (!loadedMeshInfo.pointingPoseNode) {
  72245. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72246. }
  72247. return loadedMeshInfo;
  72248. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72249. function getChildByName(node, name) {
  72250. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72251. }
  72252. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72253. function getImmediateChildByName(node, name) {
  72254. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72255. }
  72256. };
  72257. /**
  72258. * Gets the ray of the controller in the direction the controller is pointing
  72259. * @param length the length the resulting ray should be
  72260. * @returns a ray in the direction the controller is pointing
  72261. */
  72262. WindowsMotionController.prototype.getForwardRay = function (length) {
  72263. if (length === void 0) { length = 100; }
  72264. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72265. return _super.prototype.getForwardRay.call(this, length);
  72266. }
  72267. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72268. var origin = m.getTranslation();
  72269. var forward = new BABYLON.Vector3(0, 0, -1);
  72270. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72271. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72272. return new BABYLON.Ray(origin, direction, length);
  72273. };
  72274. /**
  72275. * Disposes of the controller
  72276. */
  72277. WindowsMotionController.prototype.dispose = function () {
  72278. _super.prototype.dispose.call(this);
  72279. this.onTrackpadChangedObservable.clear();
  72280. };
  72281. /**
  72282. * The base url used to load the left and right controller models
  72283. */
  72284. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72285. /**
  72286. * The name of the left controller model file
  72287. */
  72288. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72289. /**
  72290. * The name of the right controller model file
  72291. */
  72292. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72293. /**
  72294. * The controller name prefix for this controller type
  72295. */
  72296. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72297. /**
  72298. * The controller id pattern for this controller type
  72299. */
  72300. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72301. return WindowsMotionController;
  72302. }(BABYLON.WebVRController));
  72303. BABYLON.WindowsMotionController = WindowsMotionController;
  72304. })(BABYLON || (BABYLON = {}));
  72305. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72306. var BABYLON;
  72307. (function (BABYLON) {
  72308. /**
  72309. * Gear VR Controller
  72310. */
  72311. var GearVRController = /** @class */ (function (_super) {
  72312. __extends(GearVRController, _super);
  72313. /**
  72314. * Creates a new GearVRController from a gamepad
  72315. * @param vrGamepad the gamepad that the controller should be created from
  72316. */
  72317. function GearVRController(vrGamepad) {
  72318. var _this = _super.call(this, vrGamepad) || this;
  72319. _this._buttonIndexToObservableNameMap = [
  72320. 'onTrackpadChangedObservable',
  72321. 'onTriggerStateChangedObservable' // Trigger
  72322. ];
  72323. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72324. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72325. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72326. return _this;
  72327. }
  72328. /**
  72329. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72330. * @param scene scene in which to add meshes
  72331. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72332. */
  72333. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72334. var _this = this;
  72335. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72336. _this._defaultModel = newMeshes[1];
  72337. _this.attachToMesh(_this._defaultModel);
  72338. if (meshLoaded) {
  72339. meshLoaded(_this._defaultModel);
  72340. }
  72341. });
  72342. };
  72343. /**
  72344. * Called once for each button that changed state since the last frame
  72345. * @param buttonIdx Which button index changed
  72346. * @param state New state of the button
  72347. * @param changes Which properties on the state changed since last frame
  72348. */
  72349. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72350. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72351. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72352. // Only emit events for buttons that we know how to map from index to observable
  72353. var observable = this[observableName];
  72354. if (observable) {
  72355. observable.notifyObservers(state);
  72356. }
  72357. }
  72358. };
  72359. /**
  72360. * Base Url for the controller model.
  72361. */
  72362. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72363. /**
  72364. * File name for the controller model.
  72365. */
  72366. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72367. /**
  72368. * Gamepad Id prefix used to identify this controller.
  72369. */
  72370. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72371. return GearVRController;
  72372. }(BABYLON.WebVRController));
  72373. BABYLON.GearVRController = GearVRController;
  72374. })(BABYLON || (BABYLON = {}));
  72375. //# sourceMappingURL=babylon.gearVRController.js.map
  72376. var BABYLON;
  72377. (function (BABYLON) {
  72378. /**
  72379. * Google Daydream controller
  72380. */
  72381. var DaydreamController = /** @class */ (function (_super) {
  72382. __extends(DaydreamController, _super);
  72383. /**
  72384. * Creates a new DaydreamController from a gamepad
  72385. * @param vrGamepad the gamepad that the controller should be created from
  72386. */
  72387. function DaydreamController(vrGamepad) {
  72388. var _this = _super.call(this, vrGamepad) || this;
  72389. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72390. return _this;
  72391. }
  72392. /**
  72393. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72394. * @param scene scene in which to add meshes
  72395. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72396. */
  72397. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72398. var _this = this;
  72399. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72400. _this._defaultModel = newMeshes[1];
  72401. _this.attachToMesh(_this._defaultModel);
  72402. if (meshLoaded) {
  72403. meshLoaded(_this._defaultModel);
  72404. }
  72405. });
  72406. };
  72407. /**
  72408. * Called once for each button that changed state since the last frame
  72409. * @param buttonIdx Which button index changed
  72410. * @param state New state of the button
  72411. * @param changes Which properties on the state changed since last frame
  72412. */
  72413. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72414. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72415. if (buttonIdx === 0) {
  72416. var observable = this.onTriggerStateChangedObservable;
  72417. if (observable) {
  72418. observable.notifyObservers(state);
  72419. }
  72420. }
  72421. else {
  72422. // If the app or home buttons are ever made available
  72423. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72424. }
  72425. };
  72426. /**
  72427. * Base Url for the controller model.
  72428. */
  72429. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72430. /**
  72431. * File name for the controller model.
  72432. */
  72433. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72434. /**
  72435. * Gamepad Id prefix used to identify Daydream Controller.
  72436. */
  72437. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72438. return DaydreamController;
  72439. }(BABYLON.WebVRController));
  72440. BABYLON.DaydreamController = DaydreamController;
  72441. })(BABYLON || (BABYLON = {}));
  72442. //# sourceMappingURL=babylon.daydreamController.js.map
  72443. var BABYLON;
  72444. (function (BABYLON) {
  72445. var FollowCamera = /** @class */ (function (_super) {
  72446. __extends(FollowCamera, _super);
  72447. function FollowCamera(name, position, scene, lockedTarget) {
  72448. if (lockedTarget === void 0) { lockedTarget = null; }
  72449. var _this = _super.call(this, name, position, scene) || this;
  72450. _this.radius = 12;
  72451. _this.rotationOffset = 0;
  72452. _this.heightOffset = 4;
  72453. _this.cameraAcceleration = 0.05;
  72454. _this.maxCameraSpeed = 20;
  72455. _this.lockedTarget = lockedTarget;
  72456. return _this;
  72457. }
  72458. FollowCamera.prototype.getRadians = function (degrees) {
  72459. return degrees * Math.PI / 180;
  72460. };
  72461. FollowCamera.prototype.follow = function (cameraTarget) {
  72462. if (!cameraTarget)
  72463. return;
  72464. var yRotation;
  72465. if (cameraTarget.rotationQuaternion) {
  72466. var rotMatrix = new BABYLON.Matrix();
  72467. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72468. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72469. }
  72470. else {
  72471. yRotation = cameraTarget.rotation.y;
  72472. }
  72473. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72474. var targetPosition = cameraTarget.getAbsolutePosition();
  72475. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72476. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72477. var dx = targetX - this.position.x;
  72478. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72479. var dz = (targetZ) - this.position.z;
  72480. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72481. var vy = dy * this.cameraAcceleration;
  72482. var vz = dz * this.cameraAcceleration * 2;
  72483. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72484. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72485. }
  72486. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72487. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72488. }
  72489. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72490. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72491. }
  72492. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72493. this.setTarget(targetPosition);
  72494. };
  72495. FollowCamera.prototype._checkInputs = function () {
  72496. _super.prototype._checkInputs.call(this);
  72497. if (this.lockedTarget) {
  72498. this.follow(this.lockedTarget);
  72499. }
  72500. };
  72501. FollowCamera.prototype.getClassName = function () {
  72502. return "FollowCamera";
  72503. };
  72504. __decorate([
  72505. BABYLON.serialize()
  72506. ], FollowCamera.prototype, "radius", void 0);
  72507. __decorate([
  72508. BABYLON.serialize()
  72509. ], FollowCamera.prototype, "rotationOffset", void 0);
  72510. __decorate([
  72511. BABYLON.serialize()
  72512. ], FollowCamera.prototype, "heightOffset", void 0);
  72513. __decorate([
  72514. BABYLON.serialize()
  72515. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72516. __decorate([
  72517. BABYLON.serialize()
  72518. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72519. __decorate([
  72520. BABYLON.serializeAsMeshReference("lockedTargetId")
  72521. ], FollowCamera.prototype, "lockedTarget", void 0);
  72522. return FollowCamera;
  72523. }(BABYLON.TargetCamera));
  72524. BABYLON.FollowCamera = FollowCamera;
  72525. var ArcFollowCamera = /** @class */ (function (_super) {
  72526. __extends(ArcFollowCamera, _super);
  72527. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72528. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72529. _this.alpha = alpha;
  72530. _this.beta = beta;
  72531. _this.radius = radius;
  72532. _this.target = target;
  72533. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72534. _this.follow();
  72535. return _this;
  72536. }
  72537. ArcFollowCamera.prototype.follow = function () {
  72538. if (!this.target) {
  72539. return;
  72540. }
  72541. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72542. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72543. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72544. var targetPosition = this.target.getAbsolutePosition();
  72545. this.position = targetPosition.add(this._cartesianCoordinates);
  72546. this.setTarget(targetPosition);
  72547. };
  72548. ArcFollowCamera.prototype._checkInputs = function () {
  72549. _super.prototype._checkInputs.call(this);
  72550. this.follow();
  72551. };
  72552. ArcFollowCamera.prototype.getClassName = function () {
  72553. return "ArcFollowCamera";
  72554. };
  72555. return ArcFollowCamera;
  72556. }(BABYLON.TargetCamera));
  72557. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72558. })(BABYLON || (BABYLON = {}));
  72559. //# sourceMappingURL=babylon.followCamera.js.map
  72560. var BABYLON;
  72561. (function (BABYLON) {
  72562. // We're mainly based on the logic defined into the FreeCamera code
  72563. var UniversalCamera = /** @class */ (function (_super) {
  72564. __extends(UniversalCamera, _super);
  72565. //-- end properties for backward compatibility for inputs
  72566. function UniversalCamera(name, position, scene) {
  72567. var _this = _super.call(this, name, position, scene) || this;
  72568. _this.inputs.addGamepad();
  72569. return _this;
  72570. }
  72571. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72572. //-- Begin properties for backward compatibility for inputs
  72573. get: function () {
  72574. var gamepad = this.inputs.attached["gamepad"];
  72575. if (gamepad)
  72576. return gamepad.gamepadAngularSensibility;
  72577. return 0;
  72578. },
  72579. set: function (value) {
  72580. var gamepad = this.inputs.attached["gamepad"];
  72581. if (gamepad)
  72582. gamepad.gamepadAngularSensibility = value;
  72583. },
  72584. enumerable: true,
  72585. configurable: true
  72586. });
  72587. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72588. get: function () {
  72589. var gamepad = this.inputs.attached["gamepad"];
  72590. if (gamepad)
  72591. return gamepad.gamepadMoveSensibility;
  72592. return 0;
  72593. },
  72594. set: function (value) {
  72595. var gamepad = this.inputs.attached["gamepad"];
  72596. if (gamepad)
  72597. gamepad.gamepadMoveSensibility = value;
  72598. },
  72599. enumerable: true,
  72600. configurable: true
  72601. });
  72602. UniversalCamera.prototype.getClassName = function () {
  72603. return "UniversalCamera";
  72604. };
  72605. return UniversalCamera;
  72606. }(BABYLON.TouchCamera));
  72607. BABYLON.UniversalCamera = UniversalCamera;
  72608. })(BABYLON || (BABYLON = {}));
  72609. //# sourceMappingURL=babylon.universalCamera.js.map
  72610. var BABYLON;
  72611. (function (BABYLON) {
  72612. // We're mainly based on the logic defined into the FreeCamera code
  72613. var GamepadCamera = /** @class */ (function (_super) {
  72614. __extends(GamepadCamera, _super);
  72615. //-- end properties for backward compatibility for inputs
  72616. function GamepadCamera(name, position, scene) {
  72617. return _super.call(this, name, position, scene) || this;
  72618. }
  72619. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72620. //-- Begin properties for backward compatibility for inputs
  72621. get: function () {
  72622. var gamepad = this.inputs.attached["gamepad"];
  72623. if (gamepad)
  72624. return gamepad.gamepadAngularSensibility;
  72625. return 0;
  72626. },
  72627. set: function (value) {
  72628. var gamepad = this.inputs.attached["gamepad"];
  72629. if (gamepad)
  72630. gamepad.gamepadAngularSensibility = value;
  72631. },
  72632. enumerable: true,
  72633. configurable: true
  72634. });
  72635. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72636. get: function () {
  72637. var gamepad = this.inputs.attached["gamepad"];
  72638. if (gamepad)
  72639. return gamepad.gamepadMoveSensibility;
  72640. return 0;
  72641. },
  72642. set: function (value) {
  72643. var gamepad = this.inputs.attached["gamepad"];
  72644. if (gamepad)
  72645. gamepad.gamepadMoveSensibility = value;
  72646. },
  72647. enumerable: true,
  72648. configurable: true
  72649. });
  72650. GamepadCamera.prototype.getClassName = function () {
  72651. return "GamepadCamera";
  72652. };
  72653. return GamepadCamera;
  72654. }(BABYLON.UniversalCamera));
  72655. BABYLON.GamepadCamera = GamepadCamera;
  72656. })(BABYLON || (BABYLON = {}));
  72657. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72658. var BABYLON;
  72659. (function (BABYLON) {
  72660. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72661. function PostProcessRenderPipelineManager() {
  72662. this._renderPipelines = {};
  72663. }
  72664. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72665. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72666. };
  72667. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72668. if (unique === void 0) { unique = false; }
  72669. var renderPipeline = this._renderPipelines[renderPipelineName];
  72670. if (!renderPipeline) {
  72671. return;
  72672. }
  72673. renderPipeline._attachCameras(cameras, unique);
  72674. };
  72675. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72676. var renderPipeline = this._renderPipelines[renderPipelineName];
  72677. if (!renderPipeline) {
  72678. return;
  72679. }
  72680. renderPipeline._detachCameras(cameras);
  72681. };
  72682. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72683. var renderPipeline = this._renderPipelines[renderPipelineName];
  72684. if (!renderPipeline) {
  72685. return;
  72686. }
  72687. renderPipeline._enableEffect(renderEffectName, cameras);
  72688. };
  72689. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72690. var renderPipeline = this._renderPipelines[renderPipelineName];
  72691. if (!renderPipeline) {
  72692. return;
  72693. }
  72694. renderPipeline._disableEffect(renderEffectName, cameras);
  72695. };
  72696. PostProcessRenderPipelineManager.prototype.update = function () {
  72697. for (var renderPipelineName in this._renderPipelines) {
  72698. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72699. var pipeline = this._renderPipelines[renderPipelineName];
  72700. if (!pipeline.isSupported) {
  72701. pipeline.dispose();
  72702. delete this._renderPipelines[renderPipelineName];
  72703. }
  72704. else {
  72705. pipeline._update();
  72706. }
  72707. }
  72708. }
  72709. };
  72710. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72711. for (var renderPipelineName in this._renderPipelines) {
  72712. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72713. var pipeline = this._renderPipelines[renderPipelineName];
  72714. pipeline._rebuild();
  72715. }
  72716. }
  72717. };
  72718. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72719. for (var renderPipelineName in this._renderPipelines) {
  72720. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72721. var pipeline = this._renderPipelines[renderPipelineName];
  72722. pipeline.dispose();
  72723. }
  72724. }
  72725. };
  72726. return PostProcessRenderPipelineManager;
  72727. }());
  72728. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72729. })(BABYLON || (BABYLON = {}));
  72730. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72731. var BABYLON;
  72732. (function (BABYLON) {
  72733. /**
  72734. * This represents a set of one or more post processes in Babylon.
  72735. * A post process can be used to apply a shader to a texture after it is rendered.
  72736. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72737. */
  72738. var PostProcessRenderEffect = /** @class */ (function () {
  72739. /**
  72740. * Instantiates a post process render effect.
  72741. * A post process can be used to apply a shader to a texture after it is rendered.
  72742. * @param engine The engine the effect is tied to
  72743. * @param name The name of the effect
  72744. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72745. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72746. */
  72747. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72748. this._name = name;
  72749. this._singleInstance = singleInstance || true;
  72750. this._getPostProcesses = getPostProcesses;
  72751. this._cameras = {};
  72752. this._indicesForCamera = {};
  72753. this._postProcesses = {};
  72754. }
  72755. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72756. /**
  72757. * Checks if all the post processes in the effect are supported.
  72758. */
  72759. get: function () {
  72760. for (var index in this._postProcesses) {
  72761. if (this._postProcesses.hasOwnProperty(index)) {
  72762. var pps = this._postProcesses[index];
  72763. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72764. if (!pps[ppIndex].isSupported) {
  72765. return false;
  72766. }
  72767. }
  72768. }
  72769. }
  72770. return true;
  72771. },
  72772. enumerable: true,
  72773. configurable: true
  72774. });
  72775. /**
  72776. * Updates the current state of the effect
  72777. */
  72778. PostProcessRenderEffect.prototype._update = function () {
  72779. };
  72780. /**
  72781. * Attaches the effect on cameras
  72782. * @param cameras The camera to attach to.
  72783. */
  72784. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72785. var _this = this;
  72786. var cameraKey;
  72787. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72788. if (!cams) {
  72789. return;
  72790. }
  72791. for (var i = 0; i < cams.length; i++) {
  72792. var camera = cams[i];
  72793. var cameraName = camera.name;
  72794. if (this._singleInstance) {
  72795. cameraKey = 0;
  72796. }
  72797. else {
  72798. cameraKey = cameraName;
  72799. }
  72800. if (!this._postProcesses[cameraKey]) {
  72801. var postProcess = this._getPostProcesses();
  72802. if (postProcess) {
  72803. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72804. }
  72805. }
  72806. if (!this._indicesForCamera[cameraName]) {
  72807. this._indicesForCamera[cameraName] = [];
  72808. }
  72809. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72810. var index = camera.attachPostProcess(postProcess);
  72811. _this._indicesForCamera[cameraName].push(index);
  72812. });
  72813. if (!this._cameras[cameraName]) {
  72814. this._cameras[cameraName] = camera;
  72815. }
  72816. }
  72817. };
  72818. /**
  72819. * Detatches the effect on cameras
  72820. * @param cameras The camera to detatch from.
  72821. */
  72822. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72823. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72824. if (!cams) {
  72825. return;
  72826. }
  72827. for (var i = 0; i < cams.length; i++) {
  72828. var camera = cams[i];
  72829. var cameraName = camera.name;
  72830. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72831. camera.detachPostProcess(postProcess);
  72832. });
  72833. if (this._cameras[cameraName]) {
  72834. //this._indicesForCamera.splice(index, 1);
  72835. this._cameras[cameraName] = null;
  72836. }
  72837. }
  72838. };
  72839. /**
  72840. * Enables the effect on given cameras
  72841. * @param cameras The camera to enable.
  72842. */
  72843. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72844. var _this = this;
  72845. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72846. if (!cams) {
  72847. return;
  72848. }
  72849. for (var i = 0; i < cams.length; i++) {
  72850. var camera = cams[i];
  72851. var cameraName = camera.name;
  72852. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72853. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72854. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72855. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72856. });
  72857. }
  72858. }
  72859. }
  72860. };
  72861. /**
  72862. * Disables the effect on the given cameras
  72863. * @param cameras The camera to disable.
  72864. */
  72865. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72866. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72867. if (!cams) {
  72868. return;
  72869. }
  72870. for (var i = 0; i < cams.length; i++) {
  72871. var camera = cams[i];
  72872. var cameraName = camera.name;
  72873. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72874. camera.detachPostProcess(postProcess);
  72875. });
  72876. }
  72877. };
  72878. /**
  72879. * Gets a list of the post processes contained in the effect.
  72880. * @param camera The camera to get the post processes on.
  72881. * @returns The list of the post processes in the effect.
  72882. */
  72883. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72884. if (this._singleInstance) {
  72885. return this._postProcesses[0];
  72886. }
  72887. else {
  72888. if (!camera) {
  72889. return null;
  72890. }
  72891. return this._postProcesses[camera.name];
  72892. }
  72893. };
  72894. return PostProcessRenderEffect;
  72895. }());
  72896. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72897. })(BABYLON || (BABYLON = {}));
  72898. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72899. var BABYLON;
  72900. (function (BABYLON) {
  72901. var PostProcessRenderPipeline = /** @class */ (function () {
  72902. function PostProcessRenderPipeline(engine, name) {
  72903. this.engine = engine;
  72904. this._name = name;
  72905. this._renderEffects = {};
  72906. this._renderEffectsForIsolatedPass = new Array();
  72907. this._cameras = [];
  72908. }
  72909. PostProcessRenderPipeline.prototype.getClassName = function () {
  72910. return "PostProcessRenderPipeline";
  72911. };
  72912. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72913. get: function () {
  72914. for (var renderEffectName in this._renderEffects) {
  72915. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72916. if (!this._renderEffects[renderEffectName].isSupported) {
  72917. return false;
  72918. }
  72919. }
  72920. }
  72921. return true;
  72922. },
  72923. enumerable: true,
  72924. configurable: true
  72925. });
  72926. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72927. this._renderEffects[renderEffect._name] = renderEffect;
  72928. };
  72929. // private
  72930. PostProcessRenderPipeline.prototype._rebuild = function () {
  72931. };
  72932. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72933. var renderEffects = this._renderEffects[renderEffectName];
  72934. if (!renderEffects) {
  72935. return;
  72936. }
  72937. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72938. };
  72939. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72940. var renderEffects = this._renderEffects[renderEffectName];
  72941. if (!renderEffects) {
  72942. return;
  72943. }
  72944. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72945. };
  72946. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72947. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72948. if (!cams) {
  72949. return;
  72950. }
  72951. var indicesToDelete = [];
  72952. var i;
  72953. for (i = 0; i < cams.length; i++) {
  72954. var camera = cams[i];
  72955. var cameraName = camera.name;
  72956. if (this._cameras.indexOf(camera) === -1) {
  72957. this._cameras[cameraName] = camera;
  72958. }
  72959. else if (unique) {
  72960. indicesToDelete.push(i);
  72961. }
  72962. }
  72963. for (i = 0; i < indicesToDelete.length; i++) {
  72964. cameras.splice(indicesToDelete[i], 1);
  72965. }
  72966. for (var renderEffectName in this._renderEffects) {
  72967. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72968. this._renderEffects[renderEffectName]._attachCameras(cams);
  72969. }
  72970. }
  72971. };
  72972. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72973. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72974. if (!cams) {
  72975. return;
  72976. }
  72977. for (var renderEffectName in this._renderEffects) {
  72978. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72979. this._renderEffects[renderEffectName]._detachCameras(cams);
  72980. }
  72981. }
  72982. for (var i = 0; i < cams.length; i++) {
  72983. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72984. }
  72985. };
  72986. PostProcessRenderPipeline.prototype._update = function () {
  72987. for (var renderEffectName in this._renderEffects) {
  72988. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72989. this._renderEffects[renderEffectName]._update();
  72990. }
  72991. }
  72992. for (var i = 0; i < this._cameras.length; i++) {
  72993. var cameraName = this._cameras[i].name;
  72994. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72995. this._renderEffectsForIsolatedPass[cameraName]._update();
  72996. }
  72997. }
  72998. };
  72999. PostProcessRenderPipeline.prototype._reset = function () {
  73000. this._renderEffects = {};
  73001. this._renderEffectsForIsolatedPass = new Array();
  73002. };
  73003. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73004. // 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)
  73005. var effectKeys = Object.keys(this._renderEffects);
  73006. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73007. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73008. if (postProcesses) {
  73009. postProcesses[0].samples = sampleCount;
  73010. return true;
  73011. }
  73012. }
  73013. return false;
  73014. };
  73015. PostProcessRenderPipeline.prototype.dispose = function () {
  73016. // Must be implemented by children
  73017. };
  73018. __decorate([
  73019. BABYLON.serialize()
  73020. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73021. return PostProcessRenderPipeline;
  73022. }());
  73023. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73024. })(BABYLON || (BABYLON = {}));
  73025. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73026. var BABYLON;
  73027. (function (BABYLON) {
  73028. /**
  73029. * This represents a depth renderer in Babylon.
  73030. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73031. */
  73032. var DepthRenderer = /** @class */ (function () {
  73033. /**
  73034. * Instantiates a depth renderer
  73035. * @param scene The scene the renderer belongs to
  73036. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73037. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73038. */
  73039. function DepthRenderer(scene, type, camera) {
  73040. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73041. if (camera === void 0) { camera = null; }
  73042. var _this = this;
  73043. this._scene = scene;
  73044. this._camera = camera;
  73045. var engine = scene.getEngine();
  73046. // Render target
  73047. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73048. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73049. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73050. this._depthMap.refreshRate = 1;
  73051. this._depthMap.renderParticles = false;
  73052. this._depthMap.renderList = null;
  73053. // Camera to get depth map from to support multiple concurrent cameras
  73054. this._depthMap.activeCamera = this._camera;
  73055. this._depthMap.ignoreCameraViewport = true;
  73056. this._depthMap.useCameraPostProcesses = false;
  73057. // set default depth value to 1.0 (far away)
  73058. this._depthMap.onClearObservable.add(function (engine) {
  73059. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73060. });
  73061. // Custom render function
  73062. var renderSubMesh = function (subMesh) {
  73063. var mesh = subMesh.getRenderingMesh();
  73064. var scene = _this._scene;
  73065. var engine = scene.getEngine();
  73066. var material = subMesh.getMaterial();
  73067. if (!material) {
  73068. return;
  73069. }
  73070. // Culling and reverse (right handed system)
  73071. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73072. // Managing instances
  73073. var batch = mesh._getInstancesRenderList(subMesh._id);
  73074. if (batch.mustReturn) {
  73075. return;
  73076. }
  73077. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73078. var camera = _this._camera || scene.activeCamera;
  73079. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73080. engine.enableEffect(_this._effect);
  73081. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73082. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73083. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73084. // Alpha test
  73085. if (material && material.needAlphaTesting()) {
  73086. var alphaTexture = material.getAlphaTestTexture();
  73087. if (alphaTexture) {
  73088. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73089. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73090. }
  73091. }
  73092. // Bones
  73093. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73094. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73095. }
  73096. // Draw
  73097. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73098. }
  73099. };
  73100. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73101. var index;
  73102. if (depthOnlySubMeshes.length) {
  73103. engine.setColorWrite(false);
  73104. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73105. renderSubMesh(depthOnlySubMeshes.data[index]);
  73106. }
  73107. engine.setColorWrite(true);
  73108. }
  73109. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73110. renderSubMesh(opaqueSubMeshes.data[index]);
  73111. }
  73112. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73113. renderSubMesh(alphaTestSubMeshes.data[index]);
  73114. }
  73115. };
  73116. }
  73117. /**
  73118. * Creates the depth rendering effect and checks if the effect is ready.
  73119. * @param subMesh The submesh to be used to render the depth map of
  73120. * @param useInstances If multiple world instances should be used
  73121. * @returns if the depth renderer is ready to render the depth map
  73122. */
  73123. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73124. var material = subMesh.getMaterial();
  73125. if (material.disableDepthWrite) {
  73126. return false;
  73127. }
  73128. var defines = [];
  73129. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73130. var mesh = subMesh.getMesh();
  73131. // Alpha test
  73132. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73133. defines.push("#define ALPHATEST");
  73134. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73135. attribs.push(BABYLON.VertexBuffer.UVKind);
  73136. defines.push("#define UV1");
  73137. }
  73138. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73139. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73140. defines.push("#define UV2");
  73141. }
  73142. }
  73143. // Bones
  73144. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73145. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73146. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73147. if (mesh.numBoneInfluencers > 4) {
  73148. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73149. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73150. }
  73151. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73152. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73153. }
  73154. else {
  73155. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73156. }
  73157. // Instances
  73158. if (useInstances) {
  73159. defines.push("#define INSTANCES");
  73160. attribs.push("world0");
  73161. attribs.push("world1");
  73162. attribs.push("world2");
  73163. attribs.push("world3");
  73164. }
  73165. // Get correct effect
  73166. var join = defines.join("\n");
  73167. if (this._cachedDefines !== join) {
  73168. this._cachedDefines = join;
  73169. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73170. }
  73171. return this._effect.isReady();
  73172. };
  73173. /**
  73174. * Gets the texture which the depth map will be written to.
  73175. * @returns The depth map texture
  73176. */
  73177. DepthRenderer.prototype.getDepthMap = function () {
  73178. return this._depthMap;
  73179. };
  73180. /**
  73181. * Disposes of the depth renderer.
  73182. */
  73183. DepthRenderer.prototype.dispose = function () {
  73184. this._depthMap.dispose();
  73185. };
  73186. return DepthRenderer;
  73187. }());
  73188. BABYLON.DepthRenderer = DepthRenderer;
  73189. })(BABYLON || (BABYLON = {}));
  73190. //# sourceMappingURL=babylon.depthRenderer.js.map
  73191. var BABYLON;
  73192. (function (BABYLON) {
  73193. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73194. __extends(SSAORenderingPipeline, _super);
  73195. /**
  73196. * @constructor
  73197. * @param {string} name - The rendering pipeline name
  73198. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73199. * @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 }
  73200. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73201. */
  73202. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73203. var _this = _super.call(this, scene.getEngine(), name) || this;
  73204. // Members
  73205. /**
  73206. * The PassPostProcess id in the pipeline that contains the original scene color
  73207. */
  73208. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73209. /**
  73210. * The SSAO PostProcess id in the pipeline
  73211. */
  73212. _this.SSAORenderEffect = "SSAORenderEffect";
  73213. /**
  73214. * The horizontal blur PostProcess id in the pipeline
  73215. */
  73216. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73217. /**
  73218. * The vertical blur PostProcess id in the pipeline
  73219. */
  73220. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73221. /**
  73222. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73223. */
  73224. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73225. /**
  73226. * The output strength of the SSAO post-process. Default value is 1.0.
  73227. */
  73228. _this.totalStrength = 1.0;
  73229. /**
  73230. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73231. */
  73232. _this.radius = 0.0001;
  73233. /**
  73234. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73235. * Must not be equal to fallOff and superior to fallOff.
  73236. * Default value is 0.975
  73237. */
  73238. _this.area = 0.0075;
  73239. /**
  73240. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73241. * Must not be equal to area and inferior to area.
  73242. * Default value is 0.0
  73243. */
  73244. _this.fallOff = 0.000001;
  73245. /**
  73246. * The base color of the SSAO post-process
  73247. * The final result is "base + ssao" between [0, 1]
  73248. */
  73249. _this.base = 0.5;
  73250. _this._firstUpdate = true;
  73251. _this._scene = scene;
  73252. // Set up assets
  73253. _this._createRandomTexture();
  73254. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73255. var ssaoRatio = ratio.ssaoRatio || ratio;
  73256. var combineRatio = ratio.combineRatio || ratio;
  73257. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73258. _this._createSSAOPostProcess(ssaoRatio);
  73259. _this._createBlurPostProcess(ssaoRatio);
  73260. _this._createSSAOCombinePostProcess(combineRatio);
  73261. // Set up pipeline
  73262. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73263. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73264. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73265. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73266. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73267. // Finish
  73268. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73269. if (cameras)
  73270. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73271. return _this;
  73272. }
  73273. // Public Methods
  73274. /**
  73275. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73276. */
  73277. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73278. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73279. for (var i = 0; i < this._scene.cameras.length; i++) {
  73280. var camera = this._scene.cameras[i];
  73281. this._originalColorPostProcess.dispose(camera);
  73282. this._ssaoPostProcess.dispose(camera);
  73283. this._blurHPostProcess.dispose(camera);
  73284. this._blurVPostProcess.dispose(camera);
  73285. this._ssaoCombinePostProcess.dispose(camera);
  73286. }
  73287. this._randomTexture.dispose();
  73288. if (disableDepthRender)
  73289. this._scene.disableDepthRenderer();
  73290. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73291. _super.prototype.dispose.call(this);
  73292. };
  73293. // Private Methods
  73294. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73295. var _this = this;
  73296. var size = 16;
  73297. 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);
  73298. 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);
  73299. this._blurHPostProcess.onActivateObservable.add(function () {
  73300. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73301. _this._blurHPostProcess.kernel = size * dw;
  73302. });
  73303. this._blurVPostProcess.onActivateObservable.add(function () {
  73304. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73305. _this._blurVPostProcess.kernel = size * dw;
  73306. });
  73307. };
  73308. SSAORenderingPipeline.prototype._rebuild = function () {
  73309. this._firstUpdate = true;
  73310. _super.prototype._rebuild.call(this);
  73311. };
  73312. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73313. var _this = this;
  73314. var numSamples = 16;
  73315. var sampleSphere = [
  73316. 0.5381, 0.1856, -0.4319,
  73317. 0.1379, 0.2486, 0.4430,
  73318. 0.3371, 0.5679, -0.0057,
  73319. -0.6999, -0.0451, -0.0019,
  73320. 0.0689, -0.1598, -0.8547,
  73321. 0.0560, 0.0069, -0.1843,
  73322. -0.0146, 0.1402, 0.0762,
  73323. 0.0100, -0.1924, -0.0344,
  73324. -0.3577, -0.5301, -0.4358,
  73325. -0.3169, 0.1063, 0.0158,
  73326. 0.0103, -0.5869, 0.0046,
  73327. -0.0897, -0.4940, 0.3287,
  73328. 0.7119, -0.0154, -0.0918,
  73329. -0.0533, 0.0596, -0.5411,
  73330. 0.0352, -0.0631, 0.5460,
  73331. -0.4776, 0.2847, -0.0271
  73332. ];
  73333. var samplesFactor = 1.0 / numSamples;
  73334. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73335. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73336. "area", "fallOff", "base", "range", "viewport"
  73337. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73338. this._ssaoPostProcess.onApply = function (effect) {
  73339. if (_this._firstUpdate) {
  73340. effect.setArray3("sampleSphere", sampleSphere);
  73341. effect.setFloat("samplesFactor", samplesFactor);
  73342. effect.setFloat("randTextureTiles", 4.0);
  73343. }
  73344. effect.setFloat("totalStrength", _this.totalStrength);
  73345. effect.setFloat("radius", _this.radius);
  73346. effect.setFloat("area", _this.area);
  73347. effect.setFloat("fallOff", _this.fallOff);
  73348. effect.setFloat("base", _this.base);
  73349. effect.setTexture("textureSampler", _this._depthTexture);
  73350. effect.setTexture("randomSampler", _this._randomTexture);
  73351. };
  73352. };
  73353. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73354. var _this = this;
  73355. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73356. this._ssaoCombinePostProcess.onApply = function (effect) {
  73357. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73358. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73359. };
  73360. };
  73361. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73362. var size = 512;
  73363. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73364. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73365. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73366. var context = this._randomTexture.getContext();
  73367. var rand = function (min, max) {
  73368. return Math.random() * (max - min) + min;
  73369. };
  73370. var randVector = BABYLON.Vector3.Zero();
  73371. for (var x = 0; x < size; x++) {
  73372. for (var y = 0; y < size; y++) {
  73373. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73374. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73375. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73376. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73377. context.fillRect(x, y, 1, 1);
  73378. }
  73379. }
  73380. this._randomTexture.update(false);
  73381. };
  73382. __decorate([
  73383. BABYLON.serialize()
  73384. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73385. __decorate([
  73386. BABYLON.serialize()
  73387. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73388. __decorate([
  73389. BABYLON.serialize()
  73390. ], SSAORenderingPipeline.prototype, "area", void 0);
  73391. __decorate([
  73392. BABYLON.serialize()
  73393. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73394. __decorate([
  73395. BABYLON.serialize()
  73396. ], SSAORenderingPipeline.prototype, "base", void 0);
  73397. return SSAORenderingPipeline;
  73398. }(BABYLON.PostProcessRenderPipeline));
  73399. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73400. })(BABYLON || (BABYLON = {}));
  73401. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73402. var BABYLON;
  73403. (function (BABYLON) {
  73404. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73405. __extends(SSAO2RenderingPipeline, _super);
  73406. /**
  73407. * @constructor
  73408. * @param {string} name - The rendering pipeline name
  73409. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73410. * @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 }
  73411. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73412. */
  73413. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73414. var _this = _super.call(this, scene.getEngine(), name) || this;
  73415. // Members
  73416. /**
  73417. * The PassPostProcess id in the pipeline that contains the original scene color
  73418. */
  73419. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73420. /**
  73421. * The SSAO PostProcess id in the pipeline
  73422. */
  73423. _this.SSAORenderEffect = "SSAORenderEffect";
  73424. /**
  73425. * The horizontal blur PostProcess id in the pipeline
  73426. */
  73427. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73428. /**
  73429. * The vertical blur PostProcess id in the pipeline
  73430. */
  73431. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73432. /**
  73433. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73434. */
  73435. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73436. /**
  73437. * The output strength of the SSAO post-process. Default value is 1.0.
  73438. */
  73439. _this.totalStrength = 1.0;
  73440. /**
  73441. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73442. */
  73443. _this.maxZ = 100.0;
  73444. /**
  73445. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73446. */
  73447. _this.minZAspect = 0.2;
  73448. /**
  73449. * Number of samples used for the SSAO calculations. Default value is 8
  73450. */
  73451. _this._samples = 8;
  73452. /**
  73453. * Are we using bilateral blur ?
  73454. */
  73455. _this._expensiveBlur = true;
  73456. /**
  73457. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73458. */
  73459. _this.radius = 2.0;
  73460. /**
  73461. * The base color of the SSAO post-process
  73462. * The final result is "base + ssao" between [0, 1]
  73463. */
  73464. _this.base = 0.1;
  73465. _this._firstUpdate = true;
  73466. _this._scene = scene;
  73467. _this._ratio = ratio;
  73468. if (!_this.isSupported) {
  73469. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73470. return _this;
  73471. }
  73472. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73473. var blurRatio = _this._ratio.blurRatio || ratio;
  73474. // Set up assets
  73475. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73476. _this._createRandomTexture();
  73477. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73478. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73479. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73480. _this._createSSAOPostProcess(1.0);
  73481. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73482. _this._createSSAOCombinePostProcess(blurRatio);
  73483. // Set up pipeline
  73484. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73485. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73486. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73487. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73488. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73489. // Finish
  73490. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73491. if (cameras)
  73492. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73493. return _this;
  73494. }
  73495. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73496. get: function () {
  73497. return this._samples;
  73498. },
  73499. set: function (n) {
  73500. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73501. this._samples = n;
  73502. this._sampleSphere = this._generateHemisphere();
  73503. this._firstUpdate = true;
  73504. },
  73505. enumerable: true,
  73506. configurable: true
  73507. });
  73508. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73509. get: function () {
  73510. return this._expensiveBlur;
  73511. },
  73512. set: function (b) {
  73513. 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"]);
  73514. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73515. this._expensiveBlur = b;
  73516. this._firstUpdate = true;
  73517. },
  73518. enumerable: true,
  73519. configurable: true
  73520. });
  73521. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73522. /**
  73523. * Support test.
  73524. */
  73525. get: function () {
  73526. var engine = BABYLON.Engine.LastCreatedEngine;
  73527. if (!engine) {
  73528. return false;
  73529. }
  73530. return engine.getCaps().drawBuffersExtension;
  73531. },
  73532. enumerable: true,
  73533. configurable: true
  73534. });
  73535. // Public Methods
  73536. /**
  73537. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73538. */
  73539. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73540. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73541. for (var i = 0; i < this._scene.cameras.length; i++) {
  73542. var camera = this._scene.cameras[i];
  73543. this._originalColorPostProcess.dispose(camera);
  73544. this._ssaoPostProcess.dispose(camera);
  73545. this._blurHPostProcess.dispose(camera);
  73546. this._blurVPostProcess.dispose(camera);
  73547. this._ssaoCombinePostProcess.dispose(camera);
  73548. }
  73549. this._randomTexture.dispose();
  73550. if (disableGeometryBufferRenderer)
  73551. this._scene.disableGeometryBufferRenderer();
  73552. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73553. _super.prototype.dispose.call(this);
  73554. };
  73555. // Private Methods
  73556. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73557. var _this = this;
  73558. this._samplerOffsets = [];
  73559. var expensive = this.expensiveBlur;
  73560. for (var i = -8; i < 8; i++) {
  73561. this._samplerOffsets.push(i * 2 + 0.5);
  73562. }
  73563. 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");
  73564. this._blurHPostProcess.onApply = function (effect) {
  73565. if (!_this._scene.activeCamera) {
  73566. return;
  73567. }
  73568. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73569. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73570. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73571. effect.setFloat("radius", _this.radius);
  73572. effect.setTexture("depthSampler", _this._depthTexture);
  73573. if (_this._firstUpdate) {
  73574. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73575. }
  73576. };
  73577. 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");
  73578. this._blurVPostProcess.onApply = function (effect) {
  73579. if (!_this._scene.activeCamera) {
  73580. return;
  73581. }
  73582. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73583. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73584. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73585. effect.setFloat("radius", _this.radius);
  73586. effect.setTexture("depthSampler", _this._depthTexture);
  73587. if (_this._firstUpdate) {
  73588. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73589. _this._firstUpdate = false;
  73590. }
  73591. };
  73592. };
  73593. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73594. this._firstUpdate = true;
  73595. _super.prototype._rebuild.call(this);
  73596. };
  73597. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73598. var numSamples = this.samples;
  73599. var result = [];
  73600. var vector, scale;
  73601. var rand = function (min, max) {
  73602. return Math.random() * (max - min) + min;
  73603. };
  73604. var i = 0;
  73605. while (i < numSamples) {
  73606. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73607. vector.normalize();
  73608. scale = i / numSamples;
  73609. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73610. vector.scaleInPlace(scale);
  73611. result.push(vector.x, vector.y, vector.z);
  73612. i++;
  73613. }
  73614. return result;
  73615. };
  73616. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73617. var _this = this;
  73618. var numSamples = this.samples;
  73619. this._sampleSphere = this._generateHemisphere();
  73620. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73621. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73622. "base", "range", "projection", "near", "far", "texelSize",
  73623. "xViewport", "yViewport", "maxZ", "minZAspect"
  73624. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73625. this._ssaoPostProcess.onApply = function (effect) {
  73626. if (_this._firstUpdate) {
  73627. effect.setArray3("sampleSphere", _this._sampleSphere);
  73628. effect.setFloat("randTextureTiles", 4.0);
  73629. }
  73630. if (!_this._scene.activeCamera) {
  73631. return;
  73632. }
  73633. effect.setFloat("samplesFactor", 1 / _this.samples);
  73634. effect.setFloat("totalStrength", _this.totalStrength);
  73635. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73636. effect.setFloat("radius", _this.radius);
  73637. effect.setFloat("maxZ", _this.maxZ);
  73638. effect.setFloat("minZAspect", _this.minZAspect);
  73639. effect.setFloat("base", _this.base);
  73640. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73641. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73642. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73643. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73644. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73645. effect.setTexture("textureSampler", _this._depthTexture);
  73646. effect.setTexture("normalSampler", _this._normalTexture);
  73647. effect.setTexture("randomSampler", _this._randomTexture);
  73648. };
  73649. };
  73650. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73651. var _this = this;
  73652. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73653. this._ssaoCombinePostProcess.onApply = function (effect) {
  73654. var viewport = _this._scene.activeCamera.viewport;
  73655. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73656. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73657. };
  73658. };
  73659. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73660. var size = 512;
  73661. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73662. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73663. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73664. var context = this._randomTexture.getContext();
  73665. var rand = function (min, max) {
  73666. return Math.random() * (max - min) + min;
  73667. };
  73668. var randVector = BABYLON.Vector3.Zero();
  73669. for (var x = 0; x < size; x++) {
  73670. for (var y = 0; y < size; y++) {
  73671. randVector.x = rand(0.0, 1.0);
  73672. randVector.y = rand(0.0, 1.0);
  73673. randVector.z = 0.0;
  73674. randVector.normalize();
  73675. randVector.scaleInPlace(255);
  73676. randVector.x = Math.floor(randVector.x);
  73677. randVector.y = Math.floor(randVector.y);
  73678. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73679. context.fillRect(x, y, 1, 1);
  73680. }
  73681. }
  73682. this._randomTexture.update(false);
  73683. };
  73684. /**
  73685. * Serialize the rendering pipeline (Used when exporting)
  73686. * @returns the serialized object
  73687. */
  73688. SSAO2RenderingPipeline.prototype.serialize = function () {
  73689. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73690. serializationObject.customType = "SSAO2RenderingPipeline";
  73691. return serializationObject;
  73692. };
  73693. /**
  73694. * Parse the serialized pipeline
  73695. * @param source Source pipeline.
  73696. * @param scene The scene to load the pipeline to.
  73697. * @param rootUrl The URL of the serialized pipeline.
  73698. * @returns An instantiated pipeline from the serialized object.
  73699. */
  73700. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73701. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73702. };
  73703. __decorate([
  73704. BABYLON.serialize()
  73705. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73706. __decorate([
  73707. BABYLON.serialize()
  73708. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73709. __decorate([
  73710. BABYLON.serialize()
  73711. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73712. __decorate([
  73713. BABYLON.serialize("samples")
  73714. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73715. __decorate([
  73716. BABYLON.serialize()
  73717. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73718. __decorate([
  73719. BABYLON.serialize("expensiveBlur")
  73720. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73721. __decorate([
  73722. BABYLON.serialize()
  73723. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73724. __decorate([
  73725. BABYLON.serialize()
  73726. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73727. return SSAO2RenderingPipeline;
  73728. }(BABYLON.PostProcessRenderPipeline));
  73729. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73730. })(BABYLON || (BABYLON = {}));
  73731. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73732. // BABYLON.JS Chromatic Aberration GLSL Shader
  73733. // Author: Olivier Guyot
  73734. // Separates very slightly R, G and B colors on the edges of the screen
  73735. // Inspired by Francois Tarlier & Martins Upitis
  73736. var BABYLON;
  73737. (function (BABYLON) {
  73738. var LensRenderingPipeline = /** @class */ (function (_super) {
  73739. __extends(LensRenderingPipeline, _super);
  73740. /**
  73741. * @constructor
  73742. *
  73743. * Effect parameters are as follow:
  73744. * {
  73745. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73746. * edge_blur: number; // from 0 to x (1 for realism)
  73747. * distortion: number; // from 0 to x (1 for realism)
  73748. * grain_amount: number; // from 0 to 1
  73749. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73750. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73751. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73752. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73753. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73754. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73755. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73756. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73757. * }
  73758. * Note: if an effect parameter is unset, effect is disabled
  73759. *
  73760. * @param {string} name - The rendering pipeline name
  73761. * @param {object} parameters - An object containing all parameters (see above)
  73762. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73763. * @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)
  73764. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73765. */
  73766. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73767. if (ratio === void 0) { ratio = 1.0; }
  73768. var _this = _super.call(this, scene.getEngine(), name) || this;
  73769. // Lens effects can be of the following:
  73770. // - chromatic aberration (slight shift of RGB colors)
  73771. // - blur on the edge of the lens
  73772. // - lens distortion
  73773. // - depth-of-field blur & highlights enhancing
  73774. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73775. // - grain effect (noise or custom texture)
  73776. // Two additional texture samplers are needed:
  73777. // - depth map (for depth-of-field)
  73778. // - grain texture
  73779. /**
  73780. * The chromatic aberration PostProcess id in the pipeline
  73781. */
  73782. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73783. /**
  73784. * The highlights enhancing PostProcess id in the pipeline
  73785. */
  73786. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73787. /**
  73788. * The depth-of-field PostProcess id in the pipeline
  73789. */
  73790. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73791. _this._scene = scene;
  73792. // Fetch texture samplers
  73793. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73794. if (parameters.grain_texture) {
  73795. _this._grainTexture = parameters.grain_texture;
  73796. }
  73797. else {
  73798. _this._createGrainTexture();
  73799. }
  73800. // save parameters
  73801. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73802. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73803. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73804. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73805. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73806. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73807. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73808. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73809. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73810. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73811. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73812. // Create effects
  73813. _this._createChromaticAberrationPostProcess(ratio);
  73814. _this._createHighlightsPostProcess(ratio);
  73815. _this._createDepthOfFieldPostProcess(ratio / 4);
  73816. // Set up pipeline
  73817. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73818. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73819. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73820. if (_this._highlightsGain === -1) {
  73821. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73822. }
  73823. // Finish
  73824. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73825. if (cameras) {
  73826. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73827. }
  73828. return _this;
  73829. }
  73830. // public methods (self explanatory)
  73831. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73832. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73833. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73834. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73835. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73836. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73837. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73838. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73839. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73840. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73841. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73842. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73843. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73844. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73845. };
  73846. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73847. this._highlightsPostProcess.updateEffect();
  73848. };
  73849. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73850. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73851. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73852. this._highlightsGain = amount;
  73853. };
  73854. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73855. if (this._highlightsGain === -1) {
  73856. this._highlightsGain = 1.0;
  73857. }
  73858. this._highlightsThreshold = amount;
  73859. };
  73860. LensRenderingPipeline.prototype.disableHighlights = function () {
  73861. this._highlightsGain = -1;
  73862. };
  73863. /**
  73864. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73865. */
  73866. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73867. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73868. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73869. this._chromaticAberrationPostProcess = null;
  73870. this._highlightsPostProcess = null;
  73871. this._depthOfFieldPostProcess = null;
  73872. this._grainTexture.dispose();
  73873. if (disableDepthRender)
  73874. this._scene.disableDepthRenderer();
  73875. };
  73876. // colors shifting and distortion
  73877. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73878. var _this = this;
  73879. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73880. [], // samplers
  73881. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73882. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73883. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73884. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73885. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73886. effect.setFloat('radialIntensity', 1);
  73887. effect.setFloat2('direction', 17, 17);
  73888. effect.setFloat2('centerPosition', 0.5, 0.5);
  73889. };
  73890. };
  73891. // highlights enhancing
  73892. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73893. var _this = this;
  73894. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73895. [], // samplers
  73896. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73897. this._highlightsPostProcess.onApply = function (effect) {
  73898. effect.setFloat('gain', _this._highlightsGain);
  73899. effect.setFloat('threshold', _this._highlightsThreshold);
  73900. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73901. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73902. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73903. };
  73904. };
  73905. // colors shifting and distortion
  73906. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73907. var _this = this;
  73908. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73909. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73910. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73911. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73912. this._depthOfFieldPostProcess.onApply = function (effect) {
  73913. effect.setTexture("depthSampler", _this._depthTexture);
  73914. effect.setTexture("grainSampler", _this._grainTexture);
  73915. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73916. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73917. effect.setFloat('grain_amount', _this._grainAmount);
  73918. effect.setBool('blur_noise', _this._blurNoise);
  73919. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73920. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73921. effect.setFloat('distortion', _this._distortion);
  73922. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73923. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73924. effect.setFloat('aperture', _this._dofAperture);
  73925. effect.setFloat('darken', _this._dofDarken);
  73926. effect.setFloat('edge_blur', _this._edgeBlur);
  73927. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73928. if (_this._scene.activeCamera) {
  73929. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73930. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73931. }
  73932. };
  73933. };
  73934. // creates a black and white random noise texture, 512x512
  73935. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73936. var size = 512;
  73937. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73938. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73939. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73940. var context = this._grainTexture.getContext();
  73941. var rand = function (min, max) {
  73942. return Math.random() * (max - min) + min;
  73943. };
  73944. var value;
  73945. for (var x = 0; x < size; x++) {
  73946. for (var y = 0; y < size; y++) {
  73947. value = Math.floor(rand(0.42, 0.58) * 255);
  73948. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73949. context.fillRect(x, y, 1, 1);
  73950. }
  73951. }
  73952. this._grainTexture.update(false);
  73953. };
  73954. return LensRenderingPipeline;
  73955. }(BABYLON.PostProcessRenderPipeline));
  73956. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73957. })(BABYLON || (BABYLON = {}));
  73958. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73959. var BABYLON;
  73960. (function (BABYLON) {
  73961. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73962. __extends(StandardRenderingPipeline, _super);
  73963. /**
  73964. * @constructor
  73965. * @param {string} name - The rendering pipeline name
  73966. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73967. * @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)
  73968. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73969. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73970. */
  73971. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73972. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73973. var _this = _super.call(this, scene.getEngine(), name) || this;
  73974. _this.downSampleX4PostProcess = null;
  73975. _this.brightPassPostProcess = null;
  73976. _this.blurHPostProcesses = [];
  73977. _this.blurVPostProcesses = [];
  73978. _this.textureAdderPostProcess = null;
  73979. _this.volumetricLightPostProcess = null;
  73980. _this.volumetricLightSmoothXPostProcess = null;
  73981. _this.volumetricLightSmoothYPostProcess = null;
  73982. _this.volumetricLightMergePostProces = null;
  73983. _this.volumetricLightFinalPostProcess = null;
  73984. _this.luminancePostProcess = null;
  73985. _this.luminanceDownSamplePostProcesses = [];
  73986. _this.hdrPostProcess = null;
  73987. _this.textureAdderFinalPostProcess = null;
  73988. _this.lensFlareFinalPostProcess = null;
  73989. _this.hdrFinalPostProcess = null;
  73990. _this.lensFlarePostProcess = null;
  73991. _this.lensFlareComposePostProcess = null;
  73992. _this.motionBlurPostProcess = null;
  73993. _this.depthOfFieldPostProcess = null;
  73994. // Values
  73995. _this.brightThreshold = 1.0;
  73996. _this.blurWidth = 512.0;
  73997. _this.horizontalBlur = false;
  73998. _this.exposure = 1.0;
  73999. _this.lensTexture = null;
  74000. _this.volumetricLightCoefficient = 0.2;
  74001. _this.volumetricLightPower = 4.0;
  74002. _this.volumetricLightBlurScale = 64.0;
  74003. _this.sourceLight = null;
  74004. _this.hdrMinimumLuminance = 1.0;
  74005. _this.hdrDecreaseRate = 0.5;
  74006. _this.hdrIncreaseRate = 0.5;
  74007. _this.lensColorTexture = null;
  74008. _this.lensFlareStrength = 20.0;
  74009. _this.lensFlareGhostDispersal = 1.4;
  74010. _this.lensFlareHaloWidth = 0.7;
  74011. _this.lensFlareDistortionStrength = 16.0;
  74012. _this.lensStarTexture = null;
  74013. _this.lensFlareDirtTexture = null;
  74014. _this.depthOfFieldDistance = 10.0;
  74015. _this.depthOfFieldBlurWidth = 64.0;
  74016. _this.motionStrength = 1.0;
  74017. // IAnimatable
  74018. _this.animations = [];
  74019. _this._currentDepthOfFieldSource = null;
  74020. _this._hdrCurrentLuminance = 1.0;
  74021. // Getters and setters
  74022. _this._bloomEnabled = true;
  74023. _this._depthOfFieldEnabled = false;
  74024. _this._vlsEnabled = false;
  74025. _this._lensFlareEnabled = false;
  74026. _this._hdrEnabled = false;
  74027. _this._motionBlurEnabled = false;
  74028. _this._motionBlurSamples = 64.0;
  74029. _this._volumetricLightStepsCount = 50.0;
  74030. _this._cameras = cameras || [];
  74031. // Initialize
  74032. _this._scene = scene;
  74033. _this._basePostProcess = originalPostProcess;
  74034. _this._ratio = ratio;
  74035. // Misc
  74036. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74037. // Finish
  74038. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74039. _this._buildPipeline();
  74040. return _this;
  74041. }
  74042. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74043. get: function () {
  74044. return this._bloomEnabled;
  74045. },
  74046. set: function (enabled) {
  74047. if (this._bloomEnabled === enabled) {
  74048. return;
  74049. }
  74050. this._bloomEnabled = enabled;
  74051. this._buildPipeline();
  74052. },
  74053. enumerable: true,
  74054. configurable: true
  74055. });
  74056. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74057. get: function () {
  74058. return this._depthOfFieldEnabled;
  74059. },
  74060. set: function (enabled) {
  74061. if (this._depthOfFieldEnabled === enabled) {
  74062. return;
  74063. }
  74064. this._depthOfFieldEnabled = enabled;
  74065. this._buildPipeline();
  74066. },
  74067. enumerable: true,
  74068. configurable: true
  74069. });
  74070. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74071. get: function () {
  74072. return this._lensFlareEnabled;
  74073. },
  74074. set: function (enabled) {
  74075. if (this._lensFlareEnabled === enabled) {
  74076. return;
  74077. }
  74078. this._lensFlareEnabled = enabled;
  74079. this._buildPipeline();
  74080. },
  74081. enumerable: true,
  74082. configurable: true
  74083. });
  74084. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74085. get: function () {
  74086. return this._hdrEnabled;
  74087. },
  74088. set: function (enabled) {
  74089. if (this._hdrEnabled === enabled) {
  74090. return;
  74091. }
  74092. this._hdrEnabled = enabled;
  74093. this._buildPipeline();
  74094. },
  74095. enumerable: true,
  74096. configurable: true
  74097. });
  74098. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74099. get: function () {
  74100. return this._vlsEnabled;
  74101. },
  74102. set: function (enabled) {
  74103. if (this._vlsEnabled === enabled) {
  74104. return;
  74105. }
  74106. if (enabled) {
  74107. var geometry = this._scene.enableGeometryBufferRenderer();
  74108. if (!geometry) {
  74109. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74110. return;
  74111. }
  74112. }
  74113. this._vlsEnabled = enabled;
  74114. this._buildPipeline();
  74115. },
  74116. enumerable: true,
  74117. configurable: true
  74118. });
  74119. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74120. get: function () {
  74121. return this._motionBlurEnabled;
  74122. },
  74123. set: function (enabled) {
  74124. if (this._motionBlurEnabled === enabled) {
  74125. return;
  74126. }
  74127. this._motionBlurEnabled = enabled;
  74128. this._buildPipeline();
  74129. },
  74130. enumerable: true,
  74131. configurable: true
  74132. });
  74133. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74134. get: function () {
  74135. return this._volumetricLightStepsCount;
  74136. },
  74137. set: function (count) {
  74138. if (this.volumetricLightPostProcess) {
  74139. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74140. }
  74141. this._volumetricLightStepsCount = count;
  74142. },
  74143. enumerable: true,
  74144. configurable: true
  74145. });
  74146. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74147. get: function () {
  74148. return this._motionBlurSamples;
  74149. },
  74150. set: function (samples) {
  74151. if (this.motionBlurPostProcess) {
  74152. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74153. }
  74154. this._motionBlurSamples = samples;
  74155. },
  74156. enumerable: true,
  74157. configurable: true
  74158. });
  74159. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74160. var _this = this;
  74161. var ratio = this._ratio;
  74162. var scene = this._scene;
  74163. this._disposePostProcesses();
  74164. this._reset();
  74165. // Create pass post-process
  74166. if (!this._basePostProcess) {
  74167. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74168. this.originalPostProcess.onApply = function (effect) {
  74169. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74170. };
  74171. }
  74172. else {
  74173. this.originalPostProcess = this._basePostProcess;
  74174. }
  74175. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74176. this._currentDepthOfFieldSource = this.originalPostProcess;
  74177. if (this._bloomEnabled) {
  74178. // Create down sample X4 post-process
  74179. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74180. // Create bright pass post-process
  74181. this._createBrightPassPostProcess(scene, ratio / 2);
  74182. // Create gaussian blur post-processes (down sampling blurs)
  74183. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74184. // Create texture adder post-process
  74185. this._createTextureAdderPostProcess(scene, ratio);
  74186. // Create depth-of-field source post-process
  74187. 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);
  74188. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74189. }
  74190. if (this._vlsEnabled) {
  74191. // Create volumetric light
  74192. this._createVolumetricLightPostProcess(scene, ratio);
  74193. // Create volumetric light final post-process
  74194. 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);
  74195. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74196. }
  74197. if (this._lensFlareEnabled) {
  74198. // Create lens flare post-process
  74199. this._createLensFlarePostProcess(scene, ratio);
  74200. // Create depth-of-field source post-process post lens-flare and disable it now
  74201. 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);
  74202. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74203. }
  74204. if (this._hdrEnabled) {
  74205. // Create luminance
  74206. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74207. // Create HDR
  74208. this._createHdrPostProcess(scene, ratio);
  74209. // Create depth-of-field source post-process post hdr and disable it now
  74210. 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);
  74211. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74212. }
  74213. if (this._depthOfFieldEnabled) {
  74214. // Create gaussian blur used by depth-of-field
  74215. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74216. // Create depth-of-field post-process
  74217. this._createDepthOfFieldPostProcess(scene, ratio);
  74218. }
  74219. if (this._motionBlurEnabled) {
  74220. // Create motion blur post-process
  74221. this._createMotionBlurPostProcess(scene, ratio);
  74222. }
  74223. if (this._cameras !== null) {
  74224. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74225. }
  74226. };
  74227. // Down Sample X4 Post-Processs
  74228. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74229. var _this = this;
  74230. var downSampleX4Offsets = new Array(32);
  74231. 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);
  74232. this.downSampleX4PostProcess.onApply = function (effect) {
  74233. var id = 0;
  74234. var width = _this.downSampleX4PostProcess.width;
  74235. var height = _this.downSampleX4PostProcess.height;
  74236. for (var i = -2; i < 2; i++) {
  74237. for (var j = -2; j < 2; j++) {
  74238. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74239. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74240. id += 2;
  74241. }
  74242. }
  74243. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74244. };
  74245. // Add to pipeline
  74246. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74247. };
  74248. // Brightpass Post-Process
  74249. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74250. var _this = this;
  74251. var brightOffsets = new Array(8);
  74252. 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);
  74253. this.brightPassPostProcess.onApply = function (effect) {
  74254. var sU = (1.0 / _this.brightPassPostProcess.width);
  74255. var sV = (1.0 / _this.brightPassPostProcess.height);
  74256. brightOffsets[0] = -0.5 * sU;
  74257. brightOffsets[1] = 0.5 * sV;
  74258. brightOffsets[2] = 0.5 * sU;
  74259. brightOffsets[3] = 0.5 * sV;
  74260. brightOffsets[4] = -0.5 * sU;
  74261. brightOffsets[5] = -0.5 * sV;
  74262. brightOffsets[6] = 0.5 * sU;
  74263. brightOffsets[7] = -0.5 * sV;
  74264. effect.setArray2("dsOffsets", brightOffsets);
  74265. effect.setFloat("brightThreshold", _this.brightThreshold);
  74266. };
  74267. // Add to pipeline
  74268. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74269. };
  74270. // Create blur H&V post-processes
  74271. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74272. var _this = this;
  74273. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74274. var engine = scene.getEngine();
  74275. 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);
  74276. 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);
  74277. blurX.onActivateObservable.add(function () {
  74278. var dw = blurX.width / engine.getRenderWidth();
  74279. blurX.kernel = _this[blurWidthKey] * dw;
  74280. });
  74281. blurY.onActivateObservable.add(function () {
  74282. var dw = blurY.height / engine.getRenderHeight();
  74283. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74284. });
  74285. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74286. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74287. this.blurHPostProcesses.push(blurX);
  74288. this.blurVPostProcesses.push(blurY);
  74289. };
  74290. // Create texture adder post-process
  74291. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74292. var _this = this;
  74293. 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);
  74294. this.textureAdderPostProcess.onApply = function (effect) {
  74295. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74296. effect.setTexture("lensSampler", _this.lensTexture);
  74297. effect.setFloat("exposure", _this.exposure);
  74298. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74299. };
  74300. // Add to pipeline
  74301. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74302. };
  74303. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74304. var _this = this;
  74305. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74306. geometryRenderer.enablePosition = true;
  74307. var geometry = geometryRenderer.getGBuffer();
  74308. // Base post-process
  74309. 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));
  74310. var depthValues = BABYLON.Vector2.Zero();
  74311. this.volumetricLightPostProcess.onApply = function (effect) {
  74312. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74313. var generator = _this.sourceLight.getShadowGenerator();
  74314. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74315. effect.setTexture("positionSampler", geometry.textures[2]);
  74316. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74317. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74318. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74319. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74320. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74321. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74322. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74323. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74324. effect.setVector2("depthValues", depthValues);
  74325. }
  74326. };
  74327. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74328. // Smooth
  74329. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74330. // Merge
  74331. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74332. this.volumetricLightMergePostProces.onApply = function (effect) {
  74333. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74334. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74335. };
  74336. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74337. };
  74338. // Create luminance
  74339. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74340. var _this = this;
  74341. // Create luminance
  74342. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74343. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74344. var offsets = [];
  74345. this.luminancePostProcess.onApply = function (effect) {
  74346. var sU = (1.0 / _this.luminancePostProcess.width);
  74347. var sV = (1.0 / _this.luminancePostProcess.height);
  74348. offsets[0] = -0.5 * sU;
  74349. offsets[1] = 0.5 * sV;
  74350. offsets[2] = 0.5 * sU;
  74351. offsets[3] = 0.5 * sV;
  74352. offsets[4] = -0.5 * sU;
  74353. offsets[5] = -0.5 * sV;
  74354. offsets[6] = 0.5 * sU;
  74355. offsets[7] = -0.5 * sV;
  74356. effect.setArray2("lumOffsets", offsets);
  74357. };
  74358. // Add to pipeline
  74359. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74360. // Create down sample luminance
  74361. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74362. var size = Math.pow(3, i);
  74363. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74364. if (i === 0) {
  74365. defines += "#define FINAL_DOWN_SAMPLER";
  74366. }
  74367. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74368. this.luminanceDownSamplePostProcesses.push(postProcess);
  74369. }
  74370. // Create callbacks and add effects
  74371. var lastLuminance = this.luminancePostProcess;
  74372. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74373. var downSampleOffsets = new Array(18);
  74374. pp.onApply = function (effect) {
  74375. if (!lastLuminance) {
  74376. return;
  74377. }
  74378. var id = 0;
  74379. for (var x = -1; x < 2; x++) {
  74380. for (var y = -1; y < 2; y++) {
  74381. downSampleOffsets[id] = x / lastLuminance.width;
  74382. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74383. id += 2;
  74384. }
  74385. }
  74386. effect.setArray2("dsOffsets", downSampleOffsets);
  74387. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74388. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74389. lastLuminance = _this.luminancePostProcess;
  74390. }
  74391. else {
  74392. lastLuminance = pp;
  74393. }
  74394. };
  74395. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74396. pp.onAfterRender = function (effect) {
  74397. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74398. 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);
  74399. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74400. };
  74401. }
  74402. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74403. });
  74404. };
  74405. // Create HDR post-process
  74406. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74407. var _this = this;
  74408. 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);
  74409. var outputLiminance = 1;
  74410. var time = 0;
  74411. var lastTime = 0;
  74412. this.hdrPostProcess.onApply = function (effect) {
  74413. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74414. time += scene.getEngine().getDeltaTime();
  74415. if (outputLiminance < 0) {
  74416. outputLiminance = _this._hdrCurrentLuminance;
  74417. }
  74418. else {
  74419. var dt = (lastTime - time) / 1000.0;
  74420. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74421. outputLiminance += _this.hdrDecreaseRate * dt;
  74422. }
  74423. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74424. outputLiminance -= _this.hdrIncreaseRate * dt;
  74425. }
  74426. else {
  74427. outputLiminance = _this._hdrCurrentLuminance;
  74428. }
  74429. }
  74430. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74431. effect.setFloat("averageLuminance", outputLiminance);
  74432. lastTime = time;
  74433. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74434. };
  74435. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74436. };
  74437. // Create lens flare post-process
  74438. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74439. var _this = this;
  74440. 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);
  74441. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74442. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74443. 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);
  74444. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74445. var resolution = new BABYLON.Vector2(0, 0);
  74446. // Lens flare
  74447. this.lensFlarePostProcess.onApply = function (effect) {
  74448. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74449. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74450. effect.setFloat("strength", _this.lensFlareStrength);
  74451. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74452. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74453. // Shift
  74454. resolution.x = _this.lensFlarePostProcess.width;
  74455. resolution.y = _this.lensFlarePostProcess.height;
  74456. effect.setVector2("resolution", resolution);
  74457. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74458. };
  74459. // Compose
  74460. 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);
  74461. 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);
  74462. this.lensFlareComposePostProcess.onApply = function (effect) {
  74463. if (!_this._scene.activeCamera) {
  74464. return;
  74465. }
  74466. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74467. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74468. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74469. // Lens start rotation matrix
  74470. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74471. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74472. 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));
  74473. camRot *= 4.0;
  74474. 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);
  74475. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74476. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74477. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74478. };
  74479. };
  74480. // Create depth-of-field post-process
  74481. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74482. var _this = this;
  74483. 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);
  74484. this.depthOfFieldPostProcess.onApply = function (effect) {
  74485. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74486. effect.setTexture("depthSampler", _this._getDepthTexture());
  74487. effect.setFloat("distance", _this.depthOfFieldDistance);
  74488. };
  74489. // Add to pipeline
  74490. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74491. };
  74492. // Create motion blur post-process
  74493. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74494. var _this = this;
  74495. 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);
  74496. var motionScale = 0;
  74497. var prevViewProjection = BABYLON.Matrix.Identity();
  74498. var invViewProjection = BABYLON.Matrix.Identity();
  74499. var viewProjection = BABYLON.Matrix.Identity();
  74500. var screenSize = BABYLON.Vector2.Zero();
  74501. this.motionBlurPostProcess.onApply = function (effect) {
  74502. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74503. viewProjection.invertToRef(invViewProjection);
  74504. effect.setMatrix("inverseViewProjection", invViewProjection);
  74505. effect.setMatrix("prevViewProjection", prevViewProjection);
  74506. prevViewProjection = viewProjection;
  74507. screenSize.x = _this.motionBlurPostProcess.width;
  74508. screenSize.y = _this.motionBlurPostProcess.height;
  74509. effect.setVector2("screenSize", screenSize);
  74510. motionScale = scene.getEngine().getFps() / 60.0;
  74511. effect.setFloat("motionScale", motionScale);
  74512. effect.setFloat("motionStrength", _this.motionStrength);
  74513. effect.setTexture("depthSampler", _this._getDepthTexture());
  74514. };
  74515. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74516. };
  74517. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74518. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74519. var renderer = this._scene.enableGeometryBufferRenderer();
  74520. return renderer.getGBuffer().textures[0];
  74521. }
  74522. return this._scene.enableDepthRenderer().getDepthMap();
  74523. };
  74524. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74525. for (var i = 0; i < this._cameras.length; i++) {
  74526. var camera = this._cameras[i];
  74527. if (this.originalPostProcess) {
  74528. this.originalPostProcess.dispose(camera);
  74529. }
  74530. if (this.downSampleX4PostProcess) {
  74531. this.downSampleX4PostProcess.dispose(camera);
  74532. }
  74533. if (this.brightPassPostProcess) {
  74534. this.brightPassPostProcess.dispose(camera);
  74535. }
  74536. if (this.textureAdderPostProcess) {
  74537. this.textureAdderPostProcess.dispose(camera);
  74538. }
  74539. if (this.textureAdderFinalPostProcess) {
  74540. this.textureAdderFinalPostProcess.dispose(camera);
  74541. }
  74542. if (this.volumetricLightPostProcess) {
  74543. this.volumetricLightPostProcess.dispose(camera);
  74544. }
  74545. if (this.volumetricLightSmoothXPostProcess) {
  74546. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74547. }
  74548. if (this.volumetricLightSmoothYPostProcess) {
  74549. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74550. }
  74551. if (this.volumetricLightMergePostProces) {
  74552. this.volumetricLightMergePostProces.dispose(camera);
  74553. }
  74554. if (this.volumetricLightFinalPostProcess) {
  74555. this.volumetricLightFinalPostProcess.dispose(camera);
  74556. }
  74557. if (this.lensFlarePostProcess) {
  74558. this.lensFlarePostProcess.dispose(camera);
  74559. }
  74560. if (this.lensFlareComposePostProcess) {
  74561. this.lensFlareComposePostProcess.dispose(camera);
  74562. }
  74563. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74564. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74565. }
  74566. if (this.luminancePostProcess) {
  74567. this.luminancePostProcess.dispose(camera);
  74568. }
  74569. if (this.hdrPostProcess) {
  74570. this.hdrPostProcess.dispose(camera);
  74571. }
  74572. if (this.hdrFinalPostProcess) {
  74573. this.hdrFinalPostProcess.dispose(camera);
  74574. }
  74575. if (this.depthOfFieldPostProcess) {
  74576. this.depthOfFieldPostProcess.dispose(camera);
  74577. }
  74578. if (this.motionBlurPostProcess) {
  74579. this.motionBlurPostProcess.dispose(camera);
  74580. }
  74581. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74582. this.blurHPostProcesses[j].dispose(camera);
  74583. }
  74584. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74585. this.blurVPostProcesses[j].dispose(camera);
  74586. }
  74587. }
  74588. this.originalPostProcess = null;
  74589. this.downSampleX4PostProcess = null;
  74590. this.brightPassPostProcess = null;
  74591. this.textureAdderPostProcess = null;
  74592. this.textureAdderFinalPostProcess = null;
  74593. this.volumetricLightPostProcess = null;
  74594. this.volumetricLightSmoothXPostProcess = null;
  74595. this.volumetricLightSmoothYPostProcess = null;
  74596. this.volumetricLightMergePostProces = null;
  74597. this.volumetricLightFinalPostProcess = null;
  74598. this.lensFlarePostProcess = null;
  74599. this.lensFlareComposePostProcess = null;
  74600. this.luminancePostProcess = null;
  74601. this.hdrPostProcess = null;
  74602. this.hdrFinalPostProcess = null;
  74603. this.depthOfFieldPostProcess = null;
  74604. this.motionBlurPostProcess = null;
  74605. this.luminanceDownSamplePostProcesses = [];
  74606. this.blurHPostProcesses = [];
  74607. this.blurVPostProcesses = [];
  74608. };
  74609. /**
  74610. * Dispose of the pipeline and stop all post processes
  74611. */
  74612. StandardRenderingPipeline.prototype.dispose = function () {
  74613. this._disposePostProcesses();
  74614. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74615. _super.prototype.dispose.call(this);
  74616. };
  74617. /**
  74618. * Serialize the rendering pipeline (Used when exporting)
  74619. * @returns the serialized object
  74620. */
  74621. StandardRenderingPipeline.prototype.serialize = function () {
  74622. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74623. if (this.sourceLight) {
  74624. serializationObject.sourceLightId = this.sourceLight.id;
  74625. }
  74626. serializationObject.customType = "StandardRenderingPipeline";
  74627. return serializationObject;
  74628. };
  74629. /**
  74630. * Parse the serialized pipeline
  74631. * @param source Source pipeline.
  74632. * @param scene The scene to load the pipeline to.
  74633. * @param rootUrl The URL of the serialized pipeline.
  74634. * @returns An instantiated pipeline from the serialized object.
  74635. */
  74636. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74637. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74638. if (source.sourceLightId) {
  74639. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74640. }
  74641. return p;
  74642. };
  74643. // Luminance steps
  74644. StandardRenderingPipeline.LuminanceSteps = 6;
  74645. __decorate([
  74646. BABYLON.serialize()
  74647. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74648. __decorate([
  74649. BABYLON.serialize()
  74650. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74651. __decorate([
  74652. BABYLON.serialize()
  74653. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74654. __decorate([
  74655. BABYLON.serialize()
  74656. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74657. __decorate([
  74658. BABYLON.serializeAsTexture("lensTexture")
  74659. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74660. __decorate([
  74661. BABYLON.serialize()
  74662. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74663. __decorate([
  74664. BABYLON.serialize()
  74665. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74666. __decorate([
  74667. BABYLON.serialize()
  74668. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74669. __decorate([
  74670. BABYLON.serialize()
  74671. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74672. __decorate([
  74673. BABYLON.serialize()
  74674. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74675. __decorate([
  74676. BABYLON.serialize()
  74677. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74678. __decorate([
  74679. BABYLON.serializeAsTexture("lensColorTexture")
  74680. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74681. __decorate([
  74682. BABYLON.serialize()
  74683. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74684. __decorate([
  74685. BABYLON.serialize()
  74686. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74687. __decorate([
  74688. BABYLON.serialize()
  74689. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74690. __decorate([
  74691. BABYLON.serialize()
  74692. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74693. __decorate([
  74694. BABYLON.serializeAsTexture("lensStarTexture")
  74695. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74696. __decorate([
  74697. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74698. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74699. __decorate([
  74700. BABYLON.serialize()
  74701. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74702. __decorate([
  74703. BABYLON.serialize()
  74704. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74705. __decorate([
  74706. BABYLON.serialize()
  74707. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74708. __decorate([
  74709. BABYLON.serialize()
  74710. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74711. __decorate([
  74712. BABYLON.serialize()
  74713. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74714. __decorate([
  74715. BABYLON.serialize()
  74716. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74717. __decorate([
  74718. BABYLON.serialize()
  74719. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74720. __decorate([
  74721. BABYLON.serialize()
  74722. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74723. __decorate([
  74724. BABYLON.serialize()
  74725. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74726. __decorate([
  74727. BABYLON.serialize()
  74728. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74729. __decorate([
  74730. BABYLON.serialize()
  74731. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74732. __decorate([
  74733. BABYLON.serialize()
  74734. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74735. return StandardRenderingPipeline;
  74736. }(BABYLON.PostProcessRenderPipeline));
  74737. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74738. })(BABYLON || (BABYLON = {}));
  74739. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74740. var BABYLON;
  74741. (function (BABYLON) {
  74742. var FxaaPostProcess = /** @class */ (function (_super) {
  74743. __extends(FxaaPostProcess, _super);
  74744. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74745. if (camera === void 0) { camera = null; }
  74746. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74747. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74748. var defines = _this._getDefines();
  74749. _this.updateEffect(defines);
  74750. _this.onApplyObservable.add(function (effect) {
  74751. var texelSize = _this.texelSize;
  74752. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74753. });
  74754. return _this;
  74755. }
  74756. FxaaPostProcess.prototype._getDefines = function () {
  74757. var engine = this.getEngine();
  74758. if (!engine) {
  74759. return null;
  74760. }
  74761. var glInfo = engine.getGlInfo();
  74762. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74763. return "#define MALI 1\n";
  74764. }
  74765. return null;
  74766. };
  74767. return FxaaPostProcess;
  74768. }(BABYLON.PostProcess));
  74769. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74770. })(BABYLON || (BABYLON = {}));
  74771. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74772. var BABYLON;
  74773. (function (BABYLON) {
  74774. /**
  74775. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74776. */
  74777. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74778. __extends(ChromaticAberrationPostProcess, _super);
  74779. /**
  74780. * Creates a new instance ChromaticAberrationPostProcess
  74781. * @param name The name of the effect.
  74782. * @param screenWidth The width of the screen to apply the effect on.
  74783. * @param screenHeight The height of the screen to apply the effect on.
  74784. * @param options The required width/height ratio to downsize to before computing the render pass.
  74785. * @param camera The camera to apply the render pass to.
  74786. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74787. * @param engine The engine which the post process will be applied. (default: current engine)
  74788. * @param reusable If the post process can be reused on the same frame. (default: false)
  74789. * @param textureType Type of textures used when performing the post process. (default: 0)
  74790. * @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)
  74791. */
  74792. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74793. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74794. if (blockCompilation === void 0) { blockCompilation = false; }
  74795. 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;
  74796. /**
  74797. * The amount of seperation of rgb channels (default: 30)
  74798. */
  74799. _this.aberrationAmount = 30;
  74800. /**
  74801. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74802. */
  74803. _this.radialIntensity = 0;
  74804. /**
  74805. * 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))
  74806. */
  74807. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74808. /**
  74809. * 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))
  74810. */
  74811. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74812. _this.onApplyObservable.add(function (effect) {
  74813. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74814. effect.setFloat('screen_width', screenWidth);
  74815. effect.setFloat('screen_height', screenHeight);
  74816. effect.setFloat('radialIntensity', _this.radialIntensity);
  74817. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74818. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74819. });
  74820. return _this;
  74821. }
  74822. return ChromaticAberrationPostProcess;
  74823. }(BABYLON.PostProcess));
  74824. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74825. })(BABYLON || (BABYLON = {}));
  74826. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74827. var BABYLON;
  74828. (function (BABYLON) {
  74829. /**
  74830. * The GrainPostProcess adds noise to the image at mid luminance levels
  74831. */
  74832. var GrainPostProcess = /** @class */ (function (_super) {
  74833. __extends(GrainPostProcess, _super);
  74834. /**
  74835. * Creates a new instance of @see GrainPostProcess
  74836. * @param name The name of the effect.
  74837. * @param options The required width/height ratio to downsize to before computing the render pass.
  74838. * @param camera The camera to apply the render pass to.
  74839. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74840. * @param engine The engine which the post process will be applied. (default: current engine)
  74841. * @param reusable If the post process can be reused on the same frame. (default: false)
  74842. * @param textureType Type of textures used when performing the post process. (default: 0)
  74843. * @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)
  74844. */
  74845. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74846. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74847. if (blockCompilation === void 0) { blockCompilation = false; }
  74848. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74849. /**
  74850. * The intensity of the grain added (default: 30)
  74851. */
  74852. _this.intensity = 30;
  74853. /**
  74854. * If the grain should be randomized on every frame
  74855. */
  74856. _this.animated = false;
  74857. _this.onApplyObservable.add(function (effect) {
  74858. effect.setFloat('intensity', _this.intensity);
  74859. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74860. });
  74861. return _this;
  74862. }
  74863. return GrainPostProcess;
  74864. }(BABYLON.PostProcess));
  74865. BABYLON.GrainPostProcess = GrainPostProcess;
  74866. })(BABYLON || (BABYLON = {}));
  74867. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74868. var BABYLON;
  74869. (function (BABYLON) {
  74870. /**
  74871. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74872. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74873. */
  74874. var SharpenPostProcess = /** @class */ (function (_super) {
  74875. __extends(SharpenPostProcess, _super);
  74876. /**
  74877. * Creates a new instance ConvolutionPostProcess
  74878. * @param name The name of the effect.
  74879. * @param options The required width/height ratio to downsize to before computing the render pass.
  74880. * @param camera The camera to apply the render pass to.
  74881. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74882. * @param engine The engine which the post process will be applied. (default: current engine)
  74883. * @param reusable If the post process can be reused on the same frame. (default: false)
  74884. * @param textureType Type of textures used when performing the post process. (default: 0)
  74885. * @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)
  74886. */
  74887. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74888. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74889. if (blockCompilation === void 0) { blockCompilation = false; }
  74890. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74891. /**
  74892. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74893. */
  74894. _this.colorAmount = 1.0;
  74895. /**
  74896. * How much sharpness should be applied (default: 0.3)
  74897. */
  74898. _this.edgeAmount = 0.3;
  74899. _this.onApply = function (effect) {
  74900. effect.setFloat2("screenSize", _this.width, _this.height);
  74901. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74902. };
  74903. return _this;
  74904. }
  74905. return SharpenPostProcess;
  74906. }(BABYLON.PostProcess));
  74907. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74908. })(BABYLON || (BABYLON = {}));
  74909. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74910. var BABYLON;
  74911. (function (BABYLON) {
  74912. /**
  74913. * The Blur Post Process which blurs an image based on a kernel and direction.
  74914. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74915. */
  74916. var BlurPostProcess = /** @class */ (function (_super) {
  74917. __extends(BlurPostProcess, _super);
  74918. /**
  74919. * Creates a new instance BlurPostProcess
  74920. * @param name The name of the effect.
  74921. * @param direction The direction in which to blur the image.
  74922. * @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.
  74923. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74924. * @param camera The camera to apply the render pass to.
  74925. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74926. * @param engine The engine which the post process will be applied. (default: current engine)
  74927. * @param reusable If the post process can be reused on the same frame. (default: false)
  74928. * @param textureType Type of textures used when performing the post process. (default: 0)
  74929. * @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)
  74930. */
  74931. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74932. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74933. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74934. if (defines === void 0) { defines = ""; }
  74935. if (blockCompilation === void 0) { blockCompilation = false; }
  74936. 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;
  74937. _this.direction = direction;
  74938. _this.blockCompilation = blockCompilation;
  74939. _this._packedFloat = false;
  74940. _this._staticDefines = "";
  74941. _this._staticDefines = defines;
  74942. _this.onApplyObservable.add(function (effect) {
  74943. if (_this._outputTexture) {
  74944. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74945. }
  74946. else {
  74947. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74948. }
  74949. });
  74950. _this.kernel = kernel;
  74951. return _this;
  74952. }
  74953. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74954. /**
  74955. * Gets the length in pixels of the blur sample region
  74956. */
  74957. get: function () {
  74958. return this._idealKernel;
  74959. },
  74960. /**
  74961. * Sets the length in pixels of the blur sample region
  74962. */
  74963. set: function (v) {
  74964. if (this._idealKernel === v) {
  74965. return;
  74966. }
  74967. v = Math.max(v, 1);
  74968. this._idealKernel = v;
  74969. this._kernel = this._nearestBestKernel(v);
  74970. if (!this.blockCompilation) {
  74971. this._updateParameters();
  74972. }
  74973. },
  74974. enumerable: true,
  74975. configurable: true
  74976. });
  74977. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74978. /**
  74979. * Gets wether or not the blur is unpacking/repacking floats
  74980. */
  74981. get: function () {
  74982. return this._packedFloat;
  74983. },
  74984. /**
  74985. * Sets wether or not the blur needs to unpack/repack floats
  74986. */
  74987. set: function (v) {
  74988. if (this._packedFloat === v) {
  74989. return;
  74990. }
  74991. this._packedFloat = v;
  74992. if (!this.blockCompilation) {
  74993. this._updateParameters();
  74994. }
  74995. },
  74996. enumerable: true,
  74997. configurable: true
  74998. });
  74999. /**
  75000. * Updates the effect with the current post process compile time values and recompiles the shader.
  75001. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75002. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75003. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75004. * @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
  75005. * @param onCompiled Called when the shader has been compiled.
  75006. * @param onError Called if there is an error when compiling a shader.
  75007. */
  75008. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75009. if (defines === void 0) { defines = null; }
  75010. if (uniforms === void 0) { uniforms = null; }
  75011. if (samplers === void 0) { samplers = null; }
  75012. this._updateParameters(onCompiled, onError);
  75013. };
  75014. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75015. // Generate sampling offsets and weights
  75016. var N = this._kernel;
  75017. var centerIndex = (N - 1) / 2;
  75018. // Generate Gaussian sampling weights over kernel
  75019. var offsets = [];
  75020. var weights = [];
  75021. var totalWeight = 0;
  75022. for (var i = 0; i < N; i++) {
  75023. var u = i / (N - 1);
  75024. var w = this._gaussianWeight(u * 2.0 - 1);
  75025. offsets[i] = (i - centerIndex);
  75026. weights[i] = w;
  75027. totalWeight += w;
  75028. }
  75029. // Normalize weights
  75030. for (var i = 0; i < weights.length; i++) {
  75031. weights[i] /= totalWeight;
  75032. }
  75033. // Optimize: combine samples to take advantage of hardware linear sampling
  75034. // Walk from left to center, combining pairs (symmetrically)
  75035. var linearSamplingWeights = [];
  75036. var linearSamplingOffsets = [];
  75037. var linearSamplingMap = [];
  75038. for (var i = 0; i <= centerIndex; i += 2) {
  75039. var j = Math.min(i + 1, Math.floor(centerIndex));
  75040. var singleCenterSample = i === j;
  75041. if (singleCenterSample) {
  75042. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75043. }
  75044. else {
  75045. var sharedCell = j === centerIndex;
  75046. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75047. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75048. if (offsetLinear === 0) {
  75049. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75050. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75051. }
  75052. else {
  75053. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75054. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75055. }
  75056. }
  75057. }
  75058. for (var i = 0; i < linearSamplingMap.length; i++) {
  75059. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75060. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75061. }
  75062. // Replace with optimized
  75063. offsets = linearSamplingOffsets;
  75064. weights = linearSamplingWeights;
  75065. // Generate shaders
  75066. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75067. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75068. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75069. var defines = "";
  75070. defines += this._staticDefines;
  75071. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75072. if (this._staticDefines.indexOf("DOF") != -1) {
  75073. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75074. varyingCount--;
  75075. }
  75076. for (var i = 0; i < varyingCount; i++) {
  75077. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75078. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75079. }
  75080. var depCount = 0;
  75081. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75082. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75083. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75084. depCount++;
  75085. }
  75086. if (this.packedFloat) {
  75087. defines += "#define PACKEDFLOAT 1";
  75088. }
  75089. this.blockCompilation = false;
  75090. _super.prototype.updateEffect.call(this, defines, null, null, {
  75091. varyingCount: varyingCount,
  75092. depCount: depCount
  75093. }, onCompiled, onError);
  75094. };
  75095. /**
  75096. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75097. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75098. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75099. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75100. * The gaps between physical kernels are compensated for in the weighting of the samples
  75101. * @param idealKernel Ideal blur kernel.
  75102. * @return Nearest best kernel.
  75103. */
  75104. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75105. var v = Math.round(idealKernel);
  75106. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75107. var k = _a[_i];
  75108. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75109. return Math.max(k, 3);
  75110. }
  75111. }
  75112. return Math.max(v, 3);
  75113. };
  75114. /**
  75115. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75116. * @param x The point on the Gaussian distribution to sample.
  75117. * @return the value of the Gaussian function at x.
  75118. */
  75119. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75120. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75121. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75122. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75123. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75124. // truncated at around 1.3% of peak strength.
  75125. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75126. var sigma = (1 / 3);
  75127. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75128. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75129. var weight = (1.0 / denominator) * Math.exp(exponent);
  75130. return weight;
  75131. };
  75132. /**
  75133. * Generates a string that can be used as a floating point number in GLSL.
  75134. * @param x Value to print.
  75135. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75136. * @return GLSL float string.
  75137. */
  75138. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75139. if (decimalFigures === void 0) { decimalFigures = 8; }
  75140. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75141. };
  75142. return BlurPostProcess;
  75143. }(BABYLON.PostProcess));
  75144. BABYLON.BlurPostProcess = BlurPostProcess;
  75145. })(BABYLON || (BABYLON = {}));
  75146. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75147. var BABYLON;
  75148. (function (BABYLON) {
  75149. /**
  75150. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75151. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75152. * based on samples that have a large difference in distance than the center pixel.
  75153. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75154. */
  75155. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75156. __extends(DepthOfFieldBlurPostProcess, _super);
  75157. /**
  75158. * Creates a new instance CircleOfConfusionPostProcess
  75159. * @param name The name of the effect.
  75160. * @param scene The scene the effect belongs to.
  75161. * @param direction The direction the blur should be applied.
  75162. * @param kernel The size of the kernel used to blur.
  75163. * @param options The required width/height ratio to downsize to before computing the render pass.
  75164. * @param camera The camera to apply the render pass to.
  75165. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75166. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75167. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75168. * @param engine The engine which the post process will be applied. (default: current engine)
  75169. * @param reusable If the post process can be reused on the same frame. (default: false)
  75170. * @param textureType Type of textures used when performing the post process. (default: 0)
  75171. * @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)
  75172. */
  75173. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75174. if (imageToBlur === void 0) { imageToBlur = null; }
  75175. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75176. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75177. if (blockCompilation === void 0) { blockCompilation = false; }
  75178. 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;
  75179. _this.direction = direction;
  75180. _this.onApplyObservable.add(function (effect) {
  75181. if (imageToBlur != null) {
  75182. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75183. }
  75184. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75185. if (scene.activeCamera) {
  75186. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75187. }
  75188. });
  75189. return _this;
  75190. }
  75191. return DepthOfFieldBlurPostProcess;
  75192. }(BABYLON.BlurPostProcess));
  75193. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75194. })(BABYLON || (BABYLON = {}));
  75195. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75196. var BABYLON;
  75197. (function (BABYLON) {
  75198. /**
  75199. * Options to be set when merging outputs from the default pipeline.
  75200. */
  75201. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75202. function DepthOfFieldMergePostProcessOptions() {
  75203. }
  75204. return DepthOfFieldMergePostProcessOptions;
  75205. }());
  75206. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75207. /**
  75208. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75209. */
  75210. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75211. __extends(DepthOfFieldMergePostProcess, _super);
  75212. /**
  75213. * Creates a new instance of DepthOfFieldMergePostProcess
  75214. * @param name The name of the effect.
  75215. * @param originalFromInput Post process which's input will be used for the merge.
  75216. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75217. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75218. * @param options The required width/height ratio to downsize to before computing the render pass.
  75219. * @param camera The camera to apply the render pass to.
  75220. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75221. * @param engine The engine which the post process will be applied. (default: current engine)
  75222. * @param reusable If the post process can be reused on the same frame. (default: false)
  75223. * @param textureType Type of textures used when performing the post process. (default: 0)
  75224. * @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)
  75225. */
  75226. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75227. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75228. if (blockCompilation === void 0) { blockCompilation = false; }
  75229. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75230. _this.blurSteps = blurSteps;
  75231. _this.onApplyObservable.add(function (effect) {
  75232. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75233. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75234. blurSteps.forEach(function (step, index) {
  75235. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75236. });
  75237. });
  75238. if (!blockCompilation) {
  75239. _this.updateEffect();
  75240. }
  75241. return _this;
  75242. }
  75243. /**
  75244. * Updates the effect with the current post process compile time values and recompiles the shader.
  75245. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75246. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75247. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75248. * @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
  75249. * @param onCompiled Called when the shader has been compiled.
  75250. * @param onError Called if there is an error when compiling a shader.
  75251. */
  75252. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75253. if (defines === void 0) { defines = null; }
  75254. if (uniforms === void 0) { uniforms = null; }
  75255. if (samplers === void 0) { samplers = null; }
  75256. if (!defines) {
  75257. defines = "";
  75258. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75259. }
  75260. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75261. };
  75262. return DepthOfFieldMergePostProcess;
  75263. }(BABYLON.PostProcess));
  75264. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75265. })(BABYLON || (BABYLON = {}));
  75266. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75267. var BABYLON;
  75268. (function (BABYLON) {
  75269. /**
  75270. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75271. */
  75272. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75273. __extends(CircleOfConfusionPostProcess, _super);
  75274. /**
  75275. * Creates a new instance CircleOfConfusionPostProcess
  75276. * @param name The name of the effect.
  75277. * @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.
  75278. * @param options The required width/height ratio to downsize to before computing the render pass.
  75279. * @param camera The camera to apply the render pass to.
  75280. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75281. * @param engine The engine which the post process will be applied. (default: current engine)
  75282. * @param reusable If the post process can be reused on the same frame. (default: false)
  75283. * @param textureType Type of textures used when performing the post process. (default: 0)
  75284. * @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)
  75285. */
  75286. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75287. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75288. if (blockCompilation === void 0) { blockCompilation = false; }
  75289. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75290. /**
  75291. * 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.
  75292. */
  75293. _this.lensSize = 50;
  75294. /**
  75295. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75296. */
  75297. _this.fStop = 1.4;
  75298. /**
  75299. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75300. */
  75301. _this.focusDistance = 2000;
  75302. /**
  75303. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75304. */
  75305. _this.focalLength = 50;
  75306. _this._depthTexture = null;
  75307. _this._depthTexture = depthTexture;
  75308. _this.onApplyObservable.add(function (effect) {
  75309. if (!_this._depthTexture) {
  75310. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75311. return;
  75312. }
  75313. effect.setTexture("depthSampler", _this._depthTexture);
  75314. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75315. var aperture = _this.lensSize / _this.fStop;
  75316. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75317. effect.setFloat('focusDistance', _this.focusDistance);
  75318. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75319. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75320. });
  75321. return _this;
  75322. }
  75323. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75324. /**
  75325. * 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.
  75326. */
  75327. set: function (value) {
  75328. this._depthTexture = value;
  75329. },
  75330. enumerable: true,
  75331. configurable: true
  75332. });
  75333. return CircleOfConfusionPostProcess;
  75334. }(BABYLON.PostProcess));
  75335. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75336. })(BABYLON || (BABYLON = {}));
  75337. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75338. var BABYLON;
  75339. (function (BABYLON) {
  75340. /**
  75341. * Specifies the level of max blur that should be applied when using the depth of field effect
  75342. */
  75343. var DepthOfFieldEffectBlurLevel;
  75344. (function (DepthOfFieldEffectBlurLevel) {
  75345. /**
  75346. * Subtle blur
  75347. */
  75348. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75349. /**
  75350. * Medium blur
  75351. */
  75352. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75353. /**
  75354. * Large blur
  75355. */
  75356. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75357. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75358. ;
  75359. /**
  75360. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75361. */
  75362. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75363. __extends(DepthOfFieldEffect, _super);
  75364. /**
  75365. * Creates a new instance DepthOfFieldEffect
  75366. * @param scene The scene the effect belongs to.
  75367. * @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.
  75368. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75369. * @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)
  75370. */
  75371. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75372. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75373. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75374. if (blockCompilation === void 0) { blockCompilation = false; }
  75375. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75376. return _this._effects;
  75377. }, true) || this;
  75378. /**
  75379. * Internal post processes in depth of field effect
  75380. */
  75381. _this._effects = [];
  75382. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75383. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75384. // 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)
  75385. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75386. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75387. _this._depthOfFieldBlurY = [];
  75388. _this._depthOfFieldBlurX = [];
  75389. var blurCount = 1;
  75390. var kernelSize = 15;
  75391. switch (blurLevel) {
  75392. case DepthOfFieldEffectBlurLevel.High: {
  75393. blurCount = 3;
  75394. kernelSize = 51;
  75395. break;
  75396. }
  75397. case DepthOfFieldEffectBlurLevel.Medium: {
  75398. blurCount = 2;
  75399. kernelSize = 31;
  75400. break;
  75401. }
  75402. default: {
  75403. kernelSize = 15;
  75404. blurCount = 1;
  75405. break;
  75406. }
  75407. }
  75408. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75409. var ratio = 1.0;
  75410. for (var i = 0; i < blurCount; i++) {
  75411. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75412. blurY.autoClear = false;
  75413. ratio = 0.75 / Math.pow(2, i);
  75414. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75415. blurX.autoClear = false;
  75416. _this._depthOfFieldBlurY.push(blurY);
  75417. _this._depthOfFieldBlurX.push(blurX);
  75418. }
  75419. // Set all post processes on the effect.
  75420. _this._effects = [_this._circleOfConfusion];
  75421. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75422. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75423. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75424. }
  75425. // Merge blurred images with original image based on circleOfConfusion
  75426. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75427. _this._dofMerge.autoClear = false;
  75428. _this._effects.push(_this._dofMerge);
  75429. return _this;
  75430. }
  75431. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75432. get: function () {
  75433. return this._circleOfConfusion.focalLength;
  75434. },
  75435. /**
  75436. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75437. */
  75438. set: function (value) {
  75439. this._circleOfConfusion.focalLength = value;
  75440. },
  75441. enumerable: true,
  75442. configurable: true
  75443. });
  75444. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75445. get: function () {
  75446. return this._circleOfConfusion.fStop;
  75447. },
  75448. /**
  75449. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75450. */
  75451. set: function (value) {
  75452. this._circleOfConfusion.fStop = value;
  75453. },
  75454. enumerable: true,
  75455. configurable: true
  75456. });
  75457. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75458. get: function () {
  75459. return this._circleOfConfusion.focusDistance;
  75460. },
  75461. /**
  75462. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75463. */
  75464. set: function (value) {
  75465. this._circleOfConfusion.focusDistance = value;
  75466. },
  75467. enumerable: true,
  75468. configurable: true
  75469. });
  75470. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75471. get: function () {
  75472. return this._circleOfConfusion.lensSize;
  75473. },
  75474. /**
  75475. * 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.
  75476. */
  75477. set: function (value) {
  75478. this._circleOfConfusion.lensSize = value;
  75479. },
  75480. enumerable: true,
  75481. configurable: true
  75482. });
  75483. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75484. /**
  75485. * 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.
  75486. */
  75487. set: function (value) {
  75488. this._circleOfConfusion.depthTexture = value;
  75489. },
  75490. enumerable: true,
  75491. configurable: true
  75492. });
  75493. /**
  75494. * Disposes each of the internal effects for a given camera.
  75495. * @param camera The camera to dispose the effect on.
  75496. */
  75497. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75498. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75499. this._effects[effectIndex].dispose(camera);
  75500. }
  75501. };
  75502. /**
  75503. * Internal
  75504. */
  75505. DepthOfFieldEffect.prototype._updateEffects = function () {
  75506. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75507. this._effects[effectIndex].updateEffect();
  75508. }
  75509. };
  75510. /**
  75511. * Internal
  75512. * @returns if all the contained post processes are ready.
  75513. */
  75514. DepthOfFieldEffect.prototype._isReady = function () {
  75515. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75516. if (!this._effects[effectIndex].isReady()) {
  75517. return false;
  75518. }
  75519. }
  75520. return true;
  75521. };
  75522. return DepthOfFieldEffect;
  75523. }(BABYLON.PostProcessRenderEffect));
  75524. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75525. })(BABYLON || (BABYLON = {}));
  75526. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75527. var BABYLON;
  75528. (function (BABYLON) {
  75529. /**
  75530. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75531. */
  75532. var BloomMergePostProcess = /** @class */ (function (_super) {
  75533. __extends(BloomMergePostProcess, _super);
  75534. /**
  75535. * Creates a new instance of @see BloomMergePostProcess
  75536. * @param name The name of the effect.
  75537. * @param originalFromInput Post process which's input will be used for the merge.
  75538. * @param blurred Blurred highlights post process which's output will be used.
  75539. * @param weight Weight of the bloom to be added to the original input.
  75540. * @param options The required width/height ratio to downsize to before computing the render pass.
  75541. * @param camera The camera to apply the render pass to.
  75542. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75543. * @param engine The engine which the post process will be applied. (default: current engine)
  75544. * @param reusable If the post process can be reused on the same frame. (default: false)
  75545. * @param textureType Type of textures used when performing the post process. (default: 0)
  75546. * @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)
  75547. */
  75548. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75549. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75550. if (blockCompilation === void 0) { blockCompilation = false; }
  75551. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75552. _this.weight = weight;
  75553. _this.onApplyObservable.add(function (effect) {
  75554. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75555. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75556. effect.setFloat("bloomWeight", _this.weight);
  75557. });
  75558. if (!blockCompilation) {
  75559. _this.updateEffect();
  75560. }
  75561. return _this;
  75562. }
  75563. return BloomMergePostProcess;
  75564. }(BABYLON.PostProcess));
  75565. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75566. })(BABYLON || (BABYLON = {}));
  75567. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75568. var BABYLON;
  75569. (function (BABYLON) {
  75570. /**
  75571. * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
  75572. */
  75573. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75574. __extends(ExtractHighlightsPostProcess, _super);
  75575. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75576. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75577. if (blockCompilation === void 0) { blockCompilation = false; }
  75578. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75579. /**
  75580. * The luminance threshold, pixels below this value will be set to black.
  75581. */
  75582. _this.threshold = 0.9;
  75583. /**
  75584. * Internal
  75585. */
  75586. _this._exposure = 1;
  75587. /**
  75588. * Post process which has the input texture to be used when performing highlight extraction
  75589. */
  75590. _this._inputPostProcess = null;
  75591. _this.onApplyObservable.add(function (effect) {
  75592. if (_this._inputPostProcess) {
  75593. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75594. }
  75595. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75596. effect.setFloat('exposure', _this._exposure);
  75597. });
  75598. return _this;
  75599. }
  75600. return ExtractHighlightsPostProcess;
  75601. }(BABYLON.PostProcess));
  75602. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75603. })(BABYLON || (BABYLON = {}));
  75604. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75605. var BABYLON;
  75606. (function (BABYLON) {
  75607. /**
  75608. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75609. */
  75610. var BloomEffect = /** @class */ (function (_super) {
  75611. __extends(BloomEffect, _super);
  75612. /**
  75613. * Creates a new instance of @see BloomEffect
  75614. * @param scene The scene the effect belongs to.
  75615. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75616. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75617. * @param bloomWeight The the strength of bloom.
  75618. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75619. * @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)
  75620. */
  75621. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75622. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75623. if (blockCompilation === void 0) { blockCompilation = false; }
  75624. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75625. return _this._effects;
  75626. }, true) || this;
  75627. _this.bloomScale = bloomScale;
  75628. /**
  75629. * Internal
  75630. */
  75631. _this._effects = [];
  75632. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75633. _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  75634. _this._blurX.alwaysForcePOT = true;
  75635. _this._blurX.autoClear = false;
  75636. _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  75637. _this._blurY.alwaysForcePOT = true;
  75638. _this._blurY.autoClear = false;
  75639. _this.kernel = bloomKernel;
  75640. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75641. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75642. _this._merge.autoClear = false;
  75643. _this._effects.push(_this._merge);
  75644. return _this;
  75645. }
  75646. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75647. /**
  75648. * The luminance threshold to find bright areas of the image to bloom.
  75649. */
  75650. get: function () {
  75651. return this._downscale.threshold;
  75652. },
  75653. set: function (value) {
  75654. this._downscale.threshold = value;
  75655. },
  75656. enumerable: true,
  75657. configurable: true
  75658. });
  75659. Object.defineProperty(BloomEffect.prototype, "weight", {
  75660. /**
  75661. * The strength of the bloom.
  75662. */
  75663. get: function () {
  75664. return this._merge.weight;
  75665. },
  75666. set: function (value) {
  75667. this._merge.weight = value;
  75668. },
  75669. enumerable: true,
  75670. configurable: true
  75671. });
  75672. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75673. /**
  75674. * Specifies the size of the bloom blur kernel, relative to the final output size
  75675. */
  75676. get: function () {
  75677. return this._blurX.kernel / this.bloomScale;
  75678. },
  75679. set: function (value) {
  75680. this._blurX.kernel = value * this.bloomScale;
  75681. this._blurY.kernel = value * this.bloomScale;
  75682. },
  75683. enumerable: true,
  75684. configurable: true
  75685. });
  75686. /**
  75687. * Disposes each of the internal effects for a given camera.
  75688. * @param camera The camera to dispose the effect on.
  75689. */
  75690. BloomEffect.prototype.disposeEffects = function (camera) {
  75691. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75692. this._effects[effectIndex].dispose(camera);
  75693. }
  75694. };
  75695. /**
  75696. * Internal
  75697. */
  75698. BloomEffect.prototype._updateEffects = function () {
  75699. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75700. this._effects[effectIndex].updateEffect();
  75701. }
  75702. };
  75703. /**
  75704. * Internal
  75705. * @returns if all the contained post processes are ready.
  75706. */
  75707. BloomEffect.prototype._isReady = function () {
  75708. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75709. if (!this._effects[effectIndex].isReady()) {
  75710. return false;
  75711. }
  75712. }
  75713. return true;
  75714. };
  75715. return BloomEffect;
  75716. }(BABYLON.PostProcessRenderEffect));
  75717. BABYLON.BloomEffect = BloomEffect;
  75718. })(BABYLON || (BABYLON = {}));
  75719. //# sourceMappingURL=babylon.bloomEffect.js.map
  75720. var BABYLON;
  75721. (function (BABYLON) {
  75722. /**
  75723. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75724. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75725. */
  75726. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75727. __extends(DefaultRenderingPipeline, _super);
  75728. /**
  75729. * @constructor
  75730. * @param {string} name - The rendering pipeline name (default: "")
  75731. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  75732. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  75733. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  75734. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  75735. */
  75736. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75737. if (name === void 0) { name = ""; }
  75738. if (hdr === void 0) { hdr = true; }
  75739. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75740. if (automaticBuild === void 0) { automaticBuild = true; }
  75741. var _this = _super.call(this, scene.getEngine(), name) || this;
  75742. _this._originalCameras = [];
  75743. /**
  75744. * ID of the sharpen post process,
  75745. */
  75746. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75747. /**
  75748. * ID of the image processing post process;
  75749. */
  75750. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75751. /**
  75752. * ID of the Fast Approximate Anti-Aliasing post process;
  75753. */
  75754. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75755. /**
  75756. * ID of the chromatic aberration post process,
  75757. */
  75758. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75759. /**
  75760. * ID of the grain post process
  75761. */
  75762. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75763. /**
  75764. * Glow post process which adds a glow to emmisive areas of the image
  75765. */
  75766. _this._glowLayer = null;
  75767. /**
  75768. * Animations which can be used to tweak settings over a period of time
  75769. */
  75770. _this.animations = [];
  75771. _this._imageProcessingConfigurationObserver = null;
  75772. // Values
  75773. _this._sharpenEnabled = false;
  75774. _this._bloomEnabled = false;
  75775. _this._depthOfFieldEnabled = false;
  75776. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75777. _this._fxaaEnabled = false;
  75778. _this._imageProcessingEnabled = true;
  75779. _this._bloomScale = 0.5;
  75780. _this._chromaticAberrationEnabled = false;
  75781. _this._grainEnabled = false;
  75782. _this._buildAllowed = true;
  75783. _this._resizeObserver = null;
  75784. _this._hardwareScaleLevel = 1.0;
  75785. _this._bloomKernel = 64;
  75786. /**
  75787. * Specifies the weight of the bloom in the final rendering
  75788. */
  75789. _this._bloomWeight = 0.15;
  75790. /**
  75791. * Specifies the luma threshold for the area that will be blurred by the bloom
  75792. */
  75793. _this._bloomThreshold = 0.9;
  75794. _this._samples = 1;
  75795. _this._hasCleared = false;
  75796. _this._prevPostProcess = null;
  75797. _this._prevPrevPostProcess = null;
  75798. _this._cameras = cameras || scene.cameras;
  75799. _this._originalCameras = _this._cameras.slice();
  75800. _this._buildAllowed = automaticBuild;
  75801. // Initialize
  75802. _this._scene = scene;
  75803. var caps = _this._scene.getEngine().getCaps();
  75804. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75805. // Misc
  75806. if (_this._hdr) {
  75807. if (caps.textureHalfFloatRender) {
  75808. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75809. }
  75810. else if (caps.textureFloatRender) {
  75811. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75812. }
  75813. }
  75814. else {
  75815. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75816. }
  75817. // Attach
  75818. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75819. var engine = _this._scene.getEngine();
  75820. // Create post processes before hand so they can be modified before enabled.
  75821. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75822. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75823. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75824. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75825. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75826. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75827. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75828. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75829. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75830. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75831. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75832. _this.bloomKernel = _this.bloomKernel;
  75833. });
  75834. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75835. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75836. });
  75837. _this._buildPipeline();
  75838. return _this;
  75839. }
  75840. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75841. get: function () {
  75842. return this._sharpenEnabled;
  75843. },
  75844. /**
  75845. * Enable or disable the sharpen process from the pipeline
  75846. */
  75847. set: function (enabled) {
  75848. if (this._sharpenEnabled === enabled) {
  75849. return;
  75850. }
  75851. this._sharpenEnabled = enabled;
  75852. this._buildPipeline();
  75853. },
  75854. enumerable: true,
  75855. configurable: true
  75856. });
  75857. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75858. /**
  75859. * Specifies the size of the bloom blur kernel, relative to the final output size
  75860. */
  75861. get: function () {
  75862. return this._bloomKernel;
  75863. },
  75864. set: function (value) {
  75865. this._bloomKernel = value;
  75866. this.bloom.kernel = value / this._hardwareScaleLevel;
  75867. },
  75868. enumerable: true,
  75869. configurable: true
  75870. });
  75871. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75872. get: function () {
  75873. return this._bloomWeight;
  75874. },
  75875. /**
  75876. * The strength of the bloom.
  75877. */
  75878. set: function (value) {
  75879. if (this._bloomWeight === value) {
  75880. return;
  75881. }
  75882. this.bloom.weight = value;
  75883. this._bloomWeight = value;
  75884. },
  75885. enumerable: true,
  75886. configurable: true
  75887. });
  75888. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75889. get: function () {
  75890. return this._bloomThreshold;
  75891. },
  75892. /**
  75893. * The strength of the bloom.
  75894. */
  75895. set: function (value) {
  75896. if (this._bloomThreshold === value) {
  75897. return;
  75898. }
  75899. this.bloom.threshold = value;
  75900. this._bloomThreshold = value;
  75901. },
  75902. enumerable: true,
  75903. configurable: true
  75904. });
  75905. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75906. get: function () {
  75907. return this._bloomScale;
  75908. },
  75909. /**
  75910. * The scale of the bloom, lower value will provide better performance.
  75911. */
  75912. set: function (value) {
  75913. if (this._bloomScale === value) {
  75914. return;
  75915. }
  75916. this._bloomScale = value;
  75917. // recreate bloom and dispose old as this setting is not dynamic
  75918. this._rebuildBloom();
  75919. this._buildPipeline();
  75920. },
  75921. enumerable: true,
  75922. configurable: true
  75923. });
  75924. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75925. get: function () {
  75926. return this._bloomEnabled;
  75927. },
  75928. /**
  75929. * Enable or disable the bloom from the pipeline
  75930. */
  75931. set: function (enabled) {
  75932. if (this._bloomEnabled === enabled) {
  75933. return;
  75934. }
  75935. this._bloomEnabled = enabled;
  75936. this._buildPipeline();
  75937. },
  75938. enumerable: true,
  75939. configurable: true
  75940. });
  75941. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75942. // recreate bloom and dispose old as this setting is not dynamic
  75943. var oldBloom = this.bloom;
  75944. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75945. this.bloom.threshold = oldBloom.threshold;
  75946. for (var i = 0; i < this._cameras.length; i++) {
  75947. oldBloom.disposeEffects(this._cameras[i]);
  75948. }
  75949. };
  75950. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75951. /**
  75952. * If the depth of field is enabled.
  75953. */
  75954. get: function () {
  75955. return this._depthOfFieldEnabled;
  75956. },
  75957. set: function (enabled) {
  75958. if (this._depthOfFieldEnabled === enabled) {
  75959. return;
  75960. }
  75961. this._depthOfFieldEnabled = enabled;
  75962. this._buildPipeline();
  75963. },
  75964. enumerable: true,
  75965. configurable: true
  75966. });
  75967. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75968. /**
  75969. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75970. */
  75971. get: function () {
  75972. return this._depthOfFieldBlurLevel;
  75973. },
  75974. set: function (value) {
  75975. if (this._depthOfFieldBlurLevel === value) {
  75976. return;
  75977. }
  75978. this._depthOfFieldBlurLevel = value;
  75979. // recreate dof and dispose old as this setting is not dynamic
  75980. var oldDof = this.depthOfField;
  75981. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75982. this.depthOfField.focalLength = oldDof.focalLength;
  75983. this.depthOfField.focusDistance = oldDof.focusDistance;
  75984. this.depthOfField.fStop = oldDof.fStop;
  75985. this.depthOfField.lensSize = oldDof.lensSize;
  75986. for (var i = 0; i < this._cameras.length; i++) {
  75987. oldDof.disposeEffects(this._cameras[i]);
  75988. }
  75989. this._buildPipeline();
  75990. },
  75991. enumerable: true,
  75992. configurable: true
  75993. });
  75994. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75995. get: function () {
  75996. return this._fxaaEnabled;
  75997. },
  75998. /**
  75999. * If the anti aliasing is enabled.
  76000. */
  76001. set: function (enabled) {
  76002. if (this._fxaaEnabled === enabled) {
  76003. return;
  76004. }
  76005. this._fxaaEnabled = enabled;
  76006. this._buildPipeline();
  76007. },
  76008. enumerable: true,
  76009. configurable: true
  76010. });
  76011. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76012. get: function () {
  76013. return this._samples;
  76014. },
  76015. /**
  76016. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76017. */
  76018. set: function (sampleCount) {
  76019. if (this._samples === sampleCount) {
  76020. return;
  76021. }
  76022. this._samples = sampleCount;
  76023. this._buildPipeline();
  76024. },
  76025. enumerable: true,
  76026. configurable: true
  76027. });
  76028. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76029. get: function () {
  76030. return this._imageProcessingEnabled;
  76031. },
  76032. /**
  76033. * If image processing is enabled.
  76034. */
  76035. set: function (enabled) {
  76036. if (this._imageProcessingEnabled === enabled) {
  76037. return;
  76038. }
  76039. this._imageProcessingEnabled = enabled;
  76040. this._buildPipeline();
  76041. },
  76042. enumerable: true,
  76043. configurable: true
  76044. });
  76045. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76046. get: function () {
  76047. return this._glowLayer == null;
  76048. },
  76049. /**
  76050. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76051. */
  76052. set: function (enabled) {
  76053. if (enabled && !this._glowLayer) {
  76054. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76055. }
  76056. else if (!enabled && this._glowLayer) {
  76057. this._glowLayer.dispose();
  76058. this._glowLayer = null;
  76059. }
  76060. },
  76061. enumerable: true,
  76062. configurable: true
  76063. });
  76064. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76065. get: function () {
  76066. return this._chromaticAberrationEnabled;
  76067. },
  76068. /**
  76069. * Enable or disable the chromaticAberration process from the pipeline
  76070. */
  76071. set: function (enabled) {
  76072. if (this._chromaticAberrationEnabled === enabled) {
  76073. return;
  76074. }
  76075. this._chromaticAberrationEnabled = enabled;
  76076. this._buildPipeline();
  76077. },
  76078. enumerable: true,
  76079. configurable: true
  76080. });
  76081. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76082. get: function () {
  76083. return this._grainEnabled;
  76084. },
  76085. /**
  76086. * Enable or disable the grain process from the pipeline
  76087. */
  76088. set: function (enabled) {
  76089. if (this._grainEnabled === enabled) {
  76090. return;
  76091. }
  76092. this._grainEnabled = enabled;
  76093. this._buildPipeline();
  76094. },
  76095. enumerable: true,
  76096. configurable: true
  76097. });
  76098. /**
  76099. * Force the compilation of the entire pipeline.
  76100. */
  76101. DefaultRenderingPipeline.prototype.prepare = function () {
  76102. var previousState = this._buildAllowed;
  76103. this._buildAllowed = true;
  76104. this._buildPipeline();
  76105. this._buildAllowed = previousState;
  76106. };
  76107. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76108. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76109. if (this._hasCleared) {
  76110. postProcess.autoClear = false;
  76111. }
  76112. else {
  76113. postProcess.autoClear = true;
  76114. this._scene.autoClear = false;
  76115. this._hasCleared = true;
  76116. }
  76117. if (!skipTextureSharing) {
  76118. if (this._prevPrevPostProcess) {
  76119. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76120. }
  76121. else {
  76122. postProcess.useOwnOutput();
  76123. }
  76124. if (this._prevPostProcess) {
  76125. this._prevPrevPostProcess = this._prevPostProcess;
  76126. }
  76127. this._prevPostProcess = postProcess;
  76128. }
  76129. };
  76130. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76131. var _this = this;
  76132. if (!this._buildAllowed) {
  76133. return;
  76134. }
  76135. this._scene.autoClear = true;
  76136. var engine = this._scene.getEngine();
  76137. this._disposePostProcesses();
  76138. if (this._cameras !== null) {
  76139. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76140. // get back cameras to be used to reattach pipeline
  76141. this._cameras = this._originalCameras.slice();
  76142. }
  76143. this._reset();
  76144. this._prevPostProcess = null;
  76145. this._prevPrevPostProcess = null;
  76146. this._hasCleared = false;
  76147. if (this.depthOfFieldEnabled) {
  76148. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76149. this.depthOfField.depthTexture = depthTexture;
  76150. if (!this.depthOfField._isReady()) {
  76151. this.depthOfField._updateEffects();
  76152. }
  76153. this.addEffect(this.depthOfField);
  76154. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76155. }
  76156. if (this.bloomEnabled) {
  76157. if (!this.bloom._isReady()) {
  76158. this.bloom._updateEffects();
  76159. }
  76160. this.addEffect(this.bloom);
  76161. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76162. }
  76163. if (this._imageProcessingEnabled) {
  76164. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76165. if (this._hdr) {
  76166. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76167. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76168. }
  76169. else {
  76170. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76171. }
  76172. }
  76173. if (this.sharpenEnabled) {
  76174. if (!this.sharpen.isReady()) {
  76175. this.sharpen.updateEffect();
  76176. }
  76177. this.addEffect(this._sharpenEffect);
  76178. this._setAutoClearAndTextureSharing(this.sharpen);
  76179. }
  76180. if (this.grainEnabled) {
  76181. if (!this.grain.isReady()) {
  76182. this.grain.updateEffect();
  76183. }
  76184. this.addEffect(this._grainEffect);
  76185. this._setAutoClearAndTextureSharing(this.grain);
  76186. }
  76187. if (this.chromaticAberrationEnabled) {
  76188. if (!this.chromaticAberration.isReady()) {
  76189. this.chromaticAberration.updateEffect();
  76190. }
  76191. this.addEffect(this._chromaticAberrationEffect);
  76192. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76193. }
  76194. if (this.fxaaEnabled) {
  76195. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76196. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76197. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76198. }
  76199. if (this._cameras !== null) {
  76200. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76201. }
  76202. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76203. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76204. }
  76205. };
  76206. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76207. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76208. for (var i = 0; i < this._cameras.length; i++) {
  76209. var camera = this._cameras[i];
  76210. if (this.imageProcessing) {
  76211. this.imageProcessing.dispose(camera);
  76212. }
  76213. if (this.fxaa) {
  76214. this.fxaa.dispose(camera);
  76215. }
  76216. // These are created in the constructor and should not be disposed on every pipeline change
  76217. if (disposeNonRecreated) {
  76218. if (this.sharpen) {
  76219. this.sharpen.dispose(camera);
  76220. }
  76221. if (this.depthOfField) {
  76222. this.depthOfField.disposeEffects(camera);
  76223. }
  76224. if (this.bloom) {
  76225. this.bloom.disposeEffects(camera);
  76226. }
  76227. if (this.chromaticAberration) {
  76228. this.chromaticAberration.dispose(camera);
  76229. }
  76230. if (this.grain) {
  76231. this.grain.dispose(camera);
  76232. }
  76233. if (this._glowLayer) {
  76234. this._glowLayer.dispose();
  76235. }
  76236. }
  76237. }
  76238. this.imageProcessing = null;
  76239. this.fxaa = null;
  76240. if (disposeNonRecreated) {
  76241. this.sharpen = null;
  76242. this._sharpenEffect = null;
  76243. this.depthOfField = null;
  76244. this.bloom = null;
  76245. this.chromaticAberration = null;
  76246. this._chromaticAberrationEffect = null;
  76247. this.grain = null;
  76248. this._grainEffect = null;
  76249. this._glowLayer = null;
  76250. }
  76251. };
  76252. /**
  76253. * Dispose of the pipeline and stop all post processes
  76254. */
  76255. DefaultRenderingPipeline.prototype.dispose = function () {
  76256. this._disposePostProcesses(true);
  76257. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76258. this._scene.autoClear = true;
  76259. if (this._resizeObserver) {
  76260. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76261. this._resizeObserver = null;
  76262. }
  76263. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76264. _super.prototype.dispose.call(this);
  76265. };
  76266. /**
  76267. * Serialize the rendering pipeline (Used when exporting)
  76268. * @returns the serialized object
  76269. */
  76270. DefaultRenderingPipeline.prototype.serialize = function () {
  76271. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76272. serializationObject.customType = "DefaultRenderingPipeline";
  76273. return serializationObject;
  76274. };
  76275. /**
  76276. * Parse the serialized pipeline
  76277. * @param source Source pipeline.
  76278. * @param scene The scene to load the pipeline to.
  76279. * @param rootUrl The URL of the serialized pipeline.
  76280. * @returns An instantiated pipeline from the serialized object.
  76281. */
  76282. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76283. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76284. };
  76285. __decorate([
  76286. BABYLON.serialize()
  76287. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76288. __decorate([
  76289. BABYLON.serialize()
  76290. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76291. __decorate([
  76292. BABYLON.serialize()
  76293. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76294. __decorate([
  76295. BABYLON.serialize()
  76296. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76297. __decorate([
  76298. BABYLON.serialize()
  76299. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76300. __decorate([
  76301. BABYLON.serialize()
  76302. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76303. __decorate([
  76304. BABYLON.serialize()
  76305. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76306. __decorate([
  76307. BABYLON.serialize()
  76308. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76309. __decorate([
  76310. BABYLON.serialize()
  76311. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76312. __decorate([
  76313. BABYLON.serialize()
  76314. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76315. __decorate([
  76316. BABYLON.serialize()
  76317. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76318. __decorate([
  76319. BABYLON.serialize()
  76320. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76321. __decorate([
  76322. BABYLON.serialize()
  76323. ], DefaultRenderingPipeline.prototype, "samples", null);
  76324. __decorate([
  76325. BABYLON.serialize()
  76326. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76327. __decorate([
  76328. BABYLON.serialize()
  76329. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76330. __decorate([
  76331. BABYLON.serialize()
  76332. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76333. __decorate([
  76334. BABYLON.serialize()
  76335. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76336. return DefaultRenderingPipeline;
  76337. }(BABYLON.PostProcessRenderPipeline));
  76338. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76339. })(BABYLON || (BABYLON = {}));
  76340. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76341. var BABYLON;
  76342. (function (BABYLON) {
  76343. /**
  76344. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76345. */
  76346. var GeometryBufferRenderer = /** @class */ (function () {
  76347. /**
  76348. * Creates a new G Buffer for the scene
  76349. * @param scene The scene the buffer belongs to
  76350. * @param ratio How big is the buffer related to the main canvas.
  76351. */
  76352. function GeometryBufferRenderer(scene, ratio) {
  76353. if (ratio === void 0) { ratio = 1; }
  76354. this._enablePosition = false;
  76355. this._scene = scene;
  76356. this._ratio = ratio;
  76357. // Render target
  76358. this._createRenderTargets();
  76359. }
  76360. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76361. /**
  76362. * Set the render list (meshes to be rendered) used in the G buffer.
  76363. */
  76364. set: function (meshes) {
  76365. this._multiRenderTarget.renderList = meshes;
  76366. },
  76367. enumerable: true,
  76368. configurable: true
  76369. });
  76370. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76371. /**
  76372. * Gets wether or not G buffer are supported by the running hardware.
  76373. * This requires draw buffer supports
  76374. */
  76375. get: function () {
  76376. return this._multiRenderTarget.isSupported;
  76377. },
  76378. enumerable: true,
  76379. configurable: true
  76380. });
  76381. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76382. /**
  76383. * Gets wether or not position are enabled for the G buffer.
  76384. */
  76385. get: function () {
  76386. return this._enablePosition;
  76387. },
  76388. /**
  76389. * Sets wether or not position are enabled for the G buffer.
  76390. */
  76391. set: function (enable) {
  76392. this._enablePosition = enable;
  76393. this.dispose();
  76394. this._createRenderTargets();
  76395. },
  76396. enumerable: true,
  76397. configurable: true
  76398. });
  76399. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76400. /**
  76401. * Gets the scene associated with the buffer.
  76402. */
  76403. get: function () {
  76404. return this._scene;
  76405. },
  76406. enumerable: true,
  76407. configurable: true
  76408. });
  76409. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76410. /**
  76411. * Gets the ratio used by the buffer during its creation.
  76412. * How big is the buffer related to the main canvas.
  76413. */
  76414. get: function () {
  76415. return this._ratio;
  76416. },
  76417. enumerable: true,
  76418. configurable: true
  76419. });
  76420. /**
  76421. * Checks wether everything is ready to render a submesh to the G buffer.
  76422. * @param subMesh the submesh to check readiness for
  76423. * @param useInstances is the mesh drawn using instance or not
  76424. * @returns true if ready otherwise false
  76425. */
  76426. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76427. var material = subMesh.getMaterial();
  76428. if (material && material.disableDepthWrite) {
  76429. return false;
  76430. }
  76431. var defines = [];
  76432. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76433. var mesh = subMesh.getMesh();
  76434. // Alpha test
  76435. if (material && material.needAlphaTesting()) {
  76436. defines.push("#define ALPHATEST");
  76437. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76438. attribs.push(BABYLON.VertexBuffer.UVKind);
  76439. defines.push("#define UV1");
  76440. }
  76441. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76442. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76443. defines.push("#define UV2");
  76444. }
  76445. }
  76446. // Buffers
  76447. if (this._enablePosition) {
  76448. defines.push("#define POSITION");
  76449. }
  76450. // Bones
  76451. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76452. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76453. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76454. if (mesh.numBoneInfluencers > 4) {
  76455. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76456. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76457. }
  76458. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76459. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76460. }
  76461. else {
  76462. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76463. }
  76464. // Instances
  76465. if (useInstances) {
  76466. defines.push("#define INSTANCES");
  76467. attribs.push("world0");
  76468. attribs.push("world1");
  76469. attribs.push("world2");
  76470. attribs.push("world3");
  76471. }
  76472. // Get correct effect
  76473. var join = defines.join("\n");
  76474. if (this._cachedDefines !== join) {
  76475. this._cachedDefines = join;
  76476. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76477. }
  76478. return this._effect.isReady();
  76479. };
  76480. /**
  76481. * Gets the current underlying G Buffer.
  76482. * @returns the buffer
  76483. */
  76484. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76485. return this._multiRenderTarget;
  76486. };
  76487. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76488. /**
  76489. * Gets the number of samples used to render the buffer (anti aliasing).
  76490. */
  76491. get: function () {
  76492. return this._multiRenderTarget.samples;
  76493. },
  76494. /**
  76495. * Sets the number of samples used to render the buffer (anti aliasing).
  76496. */
  76497. set: function (value) {
  76498. this._multiRenderTarget.samples = value;
  76499. },
  76500. enumerable: true,
  76501. configurable: true
  76502. });
  76503. /**
  76504. * Disposes the renderer and frees up associated resources.
  76505. */
  76506. GeometryBufferRenderer.prototype.dispose = function () {
  76507. this.getGBuffer().dispose();
  76508. };
  76509. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76510. var _this = this;
  76511. var engine = this._scene.getEngine();
  76512. var count = this._enablePosition ? 3 : 2;
  76513. 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 });
  76514. if (!this.isSupported) {
  76515. return;
  76516. }
  76517. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76518. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76519. this._multiRenderTarget.refreshRate = 1;
  76520. this._multiRenderTarget.renderParticles = false;
  76521. this._multiRenderTarget.renderList = null;
  76522. // set default depth value to 1.0 (far away)
  76523. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76524. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76525. });
  76526. // Custom render function
  76527. var renderSubMesh = function (subMesh) {
  76528. var mesh = subMesh.getRenderingMesh();
  76529. var scene = _this._scene;
  76530. var engine = scene.getEngine();
  76531. var material = subMesh.getMaterial();
  76532. if (!material) {
  76533. return;
  76534. }
  76535. // Culling
  76536. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76537. // Managing instances
  76538. var batch = mesh._getInstancesRenderList(subMesh._id);
  76539. if (batch.mustReturn) {
  76540. return;
  76541. }
  76542. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76543. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76544. engine.enableEffect(_this._effect);
  76545. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76546. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76547. _this._effect.setMatrix("view", scene.getViewMatrix());
  76548. // Alpha test
  76549. if (material && material.needAlphaTesting()) {
  76550. var alphaTexture = material.getAlphaTestTexture();
  76551. if (alphaTexture) {
  76552. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76553. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76554. }
  76555. }
  76556. // Bones
  76557. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76558. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76559. }
  76560. // Draw
  76561. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76562. }
  76563. };
  76564. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76565. var index;
  76566. if (depthOnlySubMeshes.length) {
  76567. engine.setColorWrite(false);
  76568. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76569. renderSubMesh(depthOnlySubMeshes.data[index]);
  76570. }
  76571. engine.setColorWrite(true);
  76572. }
  76573. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76574. renderSubMesh(opaqueSubMeshes.data[index]);
  76575. }
  76576. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76577. renderSubMesh(alphaTestSubMeshes.data[index]);
  76578. }
  76579. };
  76580. };
  76581. return GeometryBufferRenderer;
  76582. }());
  76583. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76584. })(BABYLON || (BABYLON = {}));
  76585. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76586. var BABYLON;
  76587. (function (BABYLON) {
  76588. var RefractionPostProcess = /** @class */ (function (_super) {
  76589. __extends(RefractionPostProcess, _super);
  76590. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76591. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76592. _this.color = color;
  76593. _this.depth = depth;
  76594. _this.colorLevel = colorLevel;
  76595. _this._ownRefractionTexture = true;
  76596. _this.onActivateObservable.add(function (cam) {
  76597. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76598. });
  76599. _this.onApplyObservable.add(function (effect) {
  76600. effect.setColor3("baseColor", _this.color);
  76601. effect.setFloat("depth", _this.depth);
  76602. effect.setFloat("colorLevel", _this.colorLevel);
  76603. effect.setTexture("refractionSampler", _this._refTexture);
  76604. });
  76605. return _this;
  76606. }
  76607. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76608. /**
  76609. * Gets or sets the refraction texture
  76610. * Please note that you are responsible for disposing the texture if you set it manually
  76611. */
  76612. get: function () {
  76613. return this._refTexture;
  76614. },
  76615. set: function (value) {
  76616. if (this._refTexture && this._ownRefractionTexture) {
  76617. this._refTexture.dispose();
  76618. }
  76619. this._refTexture = value;
  76620. this._ownRefractionTexture = false;
  76621. },
  76622. enumerable: true,
  76623. configurable: true
  76624. });
  76625. // Methods
  76626. RefractionPostProcess.prototype.dispose = function (camera) {
  76627. if (this._refTexture && this._ownRefractionTexture) {
  76628. this._refTexture.dispose();
  76629. this._refTexture = null;
  76630. }
  76631. _super.prototype.dispose.call(this, camera);
  76632. };
  76633. return RefractionPostProcess;
  76634. }(BABYLON.PostProcess));
  76635. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76636. })(BABYLON || (BABYLON = {}));
  76637. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76638. var BABYLON;
  76639. (function (BABYLON) {
  76640. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76641. __extends(BlackAndWhitePostProcess, _super);
  76642. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76643. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76644. _this.degree = 1;
  76645. _this.onApplyObservable.add(function (effect) {
  76646. effect.setFloat("degree", _this.degree);
  76647. });
  76648. return _this;
  76649. }
  76650. return BlackAndWhitePostProcess;
  76651. }(BABYLON.PostProcess));
  76652. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76653. })(BABYLON || (BABYLON = {}));
  76654. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76655. var BABYLON;
  76656. (function (BABYLON) {
  76657. /**
  76658. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76659. * input texture to perform effects such as edge detection or sharpening
  76660. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76661. */
  76662. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76663. __extends(ConvolutionPostProcess, _super);
  76664. /**
  76665. * Creates a new instance ConvolutionPostProcess
  76666. * @param name The name of the effect.
  76667. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76668. * @param options The required width/height ratio to downsize to before computing the render pass.
  76669. * @param camera The camera to apply the render pass to.
  76670. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76671. * @param engine The engine which the post process will be applied. (default: current engine)
  76672. * @param reusable If the post process can be reused on the same frame. (default: false)
  76673. * @param textureType Type of textures used when performing the post process. (default: 0)
  76674. */
  76675. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76676. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76677. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76678. _this.kernel = kernel;
  76679. _this.onApply = function (effect) {
  76680. effect.setFloat2("screenSize", _this.width, _this.height);
  76681. effect.setArray("kernel", _this.kernel);
  76682. };
  76683. return _this;
  76684. }
  76685. // Statics
  76686. /**
  76687. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76688. */
  76689. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76690. /**
  76691. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76692. */
  76693. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76694. /**
  76695. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76696. */
  76697. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76698. /**
  76699. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76700. */
  76701. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76702. /**
  76703. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76704. */
  76705. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76706. /**
  76707. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76708. */
  76709. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76710. return ConvolutionPostProcess;
  76711. }(BABYLON.PostProcess));
  76712. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76713. })(BABYLON || (BABYLON = {}));
  76714. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76715. var BABYLON;
  76716. (function (BABYLON) {
  76717. var FilterPostProcess = /** @class */ (function (_super) {
  76718. __extends(FilterPostProcess, _super);
  76719. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76720. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76721. _this.kernelMatrix = kernelMatrix;
  76722. _this.onApply = function (effect) {
  76723. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76724. };
  76725. return _this;
  76726. }
  76727. return FilterPostProcess;
  76728. }(BABYLON.PostProcess));
  76729. BABYLON.FilterPostProcess = FilterPostProcess;
  76730. })(BABYLON || (BABYLON = {}));
  76731. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76732. var BABYLON;
  76733. (function (BABYLON) {
  76734. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76735. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76736. __extends(VolumetricLightScatteringPostProcess, _super);
  76737. /**
  76738. * @constructor
  76739. * @param {string} name - The post-process name
  76740. * @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)
  76741. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76742. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76743. * @param {number} samples - The post-process quality, default 100
  76744. * @param {number} samplingMode - The post-process filtering mode
  76745. * @param {BABYLON.Engine} engine - The babylon engine
  76746. * @param {boolean} reusable - If the post-process is reusable
  76747. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76748. */
  76749. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76750. if (samples === void 0) { samples = 100; }
  76751. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76752. 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;
  76753. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76754. /**
  76755. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76756. */
  76757. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76758. /**
  76759. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76760. */
  76761. _this.useCustomMeshPosition = false;
  76762. /**
  76763. * If the post-process should inverse the light scattering direction
  76764. */
  76765. _this.invert = true;
  76766. /**
  76767. * Array containing the excluded meshes not rendered in the internal pass
  76768. */
  76769. _this.excludedMeshes = new Array();
  76770. /**
  76771. * Controls the overall intensity of the post-process
  76772. */
  76773. _this.exposure = 0.3;
  76774. /**
  76775. * Dissipates each sample's contribution in range [0, 1]
  76776. */
  76777. _this.decay = 0.96815;
  76778. /**
  76779. * Controls the overall intensity of each sample
  76780. */
  76781. _this.weight = 0.58767;
  76782. /**
  76783. * Controls the density of each sample
  76784. */
  76785. _this.density = 0.926;
  76786. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76787. engine = scene.getEngine();
  76788. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76789. // Configure mesh
  76790. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76791. // Configure
  76792. _this._createPass(scene, ratio.passRatio || ratio);
  76793. _this.onActivate = function (camera) {
  76794. if (!_this.isSupported) {
  76795. _this.dispose(camera);
  76796. }
  76797. _this.onActivate = null;
  76798. };
  76799. _this.onApplyObservable.add(function (effect) {
  76800. _this._updateMeshScreenCoordinates(scene);
  76801. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76802. effect.setFloat("exposure", _this.exposure);
  76803. effect.setFloat("decay", _this.decay);
  76804. effect.setFloat("weight", _this.weight);
  76805. effect.setFloat("density", _this.density);
  76806. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76807. });
  76808. return _this;
  76809. }
  76810. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76811. get: function () {
  76812. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76813. return false;
  76814. },
  76815. set: function (useDiffuseColor) {
  76816. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76817. },
  76818. enumerable: true,
  76819. configurable: true
  76820. });
  76821. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76822. return "VolumetricLightScatteringPostProcess";
  76823. };
  76824. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76825. var mesh = subMesh.getMesh();
  76826. // Render this.mesh as default
  76827. if (mesh === this.mesh && mesh.material) {
  76828. return mesh.material.isReady(mesh);
  76829. }
  76830. var defines = [];
  76831. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76832. var material = subMesh.getMaterial();
  76833. // Alpha test
  76834. if (material) {
  76835. if (material.needAlphaTesting()) {
  76836. defines.push("#define ALPHATEST");
  76837. }
  76838. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76839. attribs.push(BABYLON.VertexBuffer.UVKind);
  76840. defines.push("#define UV1");
  76841. }
  76842. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76843. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76844. defines.push("#define UV2");
  76845. }
  76846. }
  76847. // Bones
  76848. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76849. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76850. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76851. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76852. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76853. }
  76854. else {
  76855. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76856. }
  76857. // Instances
  76858. if (useInstances) {
  76859. defines.push("#define INSTANCES");
  76860. attribs.push("world0");
  76861. attribs.push("world1");
  76862. attribs.push("world2");
  76863. attribs.push("world3");
  76864. }
  76865. // Get correct effect
  76866. var join = defines.join("\n");
  76867. if (this._cachedDefines !== join) {
  76868. this._cachedDefines = join;
  76869. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76870. }
  76871. return this._volumetricLightScatteringPass.isReady();
  76872. };
  76873. /**
  76874. * Sets the new light position for light scattering effect
  76875. * @param {BABYLON.Vector3} The new custom light position
  76876. */
  76877. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76878. this.customMeshPosition = position;
  76879. };
  76880. /**
  76881. * Returns the light position for light scattering effect
  76882. * @return {BABYLON.Vector3} The custom light position
  76883. */
  76884. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76885. return this.customMeshPosition;
  76886. };
  76887. /**
  76888. * Disposes the internal assets and detaches the post-process from the camera
  76889. */
  76890. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76891. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76892. if (rttIndex !== -1) {
  76893. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76894. }
  76895. this._volumetricLightScatteringRTT.dispose();
  76896. _super.prototype.dispose.call(this, camera);
  76897. };
  76898. /**
  76899. * Returns the render target texture used by the post-process
  76900. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76901. */
  76902. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76903. return this._volumetricLightScatteringRTT;
  76904. };
  76905. // Private methods
  76906. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76907. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76908. return true;
  76909. }
  76910. return false;
  76911. };
  76912. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76913. var _this = this;
  76914. var engine = scene.getEngine();
  76915. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76916. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76917. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76918. this._volumetricLightScatteringRTT.renderList = null;
  76919. this._volumetricLightScatteringRTT.renderParticles = false;
  76920. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76921. var camera = this.getCamera();
  76922. if (camera) {
  76923. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76924. }
  76925. else {
  76926. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76927. }
  76928. // Custom render function for submeshes
  76929. var renderSubMesh = function (subMesh) {
  76930. var mesh = subMesh.getRenderingMesh();
  76931. if (_this._meshExcluded(mesh)) {
  76932. return;
  76933. }
  76934. var material = subMesh.getMaterial();
  76935. if (!material) {
  76936. return;
  76937. }
  76938. var scene = mesh.getScene();
  76939. var engine = scene.getEngine();
  76940. // Culling
  76941. engine.setState(material.backFaceCulling);
  76942. // Managing instances
  76943. var batch = mesh._getInstancesRenderList(subMesh._id);
  76944. if (batch.mustReturn) {
  76945. return;
  76946. }
  76947. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76948. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76949. var effect = _this._volumetricLightScatteringPass;
  76950. if (mesh === _this.mesh) {
  76951. if (subMesh.effect) {
  76952. effect = subMesh.effect;
  76953. }
  76954. else {
  76955. effect = material.getEffect();
  76956. }
  76957. }
  76958. engine.enableEffect(effect);
  76959. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76960. if (mesh === _this.mesh) {
  76961. material.bind(mesh.getWorldMatrix(), mesh);
  76962. }
  76963. else {
  76964. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76965. // Alpha test
  76966. if (material && material.needAlphaTesting()) {
  76967. var alphaTexture = material.getAlphaTestTexture();
  76968. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76969. if (alphaTexture) {
  76970. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76971. }
  76972. }
  76973. // Bones
  76974. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76975. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76976. }
  76977. }
  76978. // Draw
  76979. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76980. }
  76981. };
  76982. // Render target texture callbacks
  76983. var savedSceneClearColor;
  76984. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76985. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76986. savedSceneClearColor = scene.clearColor;
  76987. scene.clearColor = sceneClearColor;
  76988. });
  76989. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76990. scene.clearColor = savedSceneClearColor;
  76991. });
  76992. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76993. var engine = scene.getEngine();
  76994. var index;
  76995. if (depthOnlySubMeshes.length) {
  76996. engine.setColorWrite(false);
  76997. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76998. renderSubMesh(depthOnlySubMeshes.data[index]);
  76999. }
  77000. engine.setColorWrite(true);
  77001. }
  77002. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77003. renderSubMesh(opaqueSubMeshes.data[index]);
  77004. }
  77005. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77006. renderSubMesh(alphaTestSubMeshes.data[index]);
  77007. }
  77008. if (transparentSubMeshes.length) {
  77009. // Sort sub meshes
  77010. for (index = 0; index < transparentSubMeshes.length; index++) {
  77011. var submesh = transparentSubMeshes.data[index];
  77012. var boundingInfo = submesh.getBoundingInfo();
  77013. if (boundingInfo && scene.activeCamera) {
  77014. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77015. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77016. }
  77017. }
  77018. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77019. sortedArray.sort(function (a, b) {
  77020. // Alpha index first
  77021. if (a._alphaIndex > b._alphaIndex) {
  77022. return 1;
  77023. }
  77024. if (a._alphaIndex < b._alphaIndex) {
  77025. return -1;
  77026. }
  77027. // Then distance to camera
  77028. if (a._distanceToCamera < b._distanceToCamera) {
  77029. return 1;
  77030. }
  77031. if (a._distanceToCamera > b._distanceToCamera) {
  77032. return -1;
  77033. }
  77034. return 0;
  77035. });
  77036. // Render sub meshes
  77037. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77038. for (index = 0; index < sortedArray.length; index++) {
  77039. renderSubMesh(sortedArray[index]);
  77040. }
  77041. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77042. }
  77043. };
  77044. };
  77045. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77046. var transform = scene.getTransformMatrix();
  77047. var meshPosition;
  77048. if (this.useCustomMeshPosition) {
  77049. meshPosition = this.customMeshPosition;
  77050. }
  77051. else if (this.attachedNode) {
  77052. meshPosition = this.attachedNode.position;
  77053. }
  77054. else {
  77055. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77056. }
  77057. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77058. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77059. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77060. if (this.invert)
  77061. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77062. };
  77063. // Static methods
  77064. /**
  77065. * Creates a default mesh for the Volumeric Light Scattering post-process
  77066. * @param {string} The mesh name
  77067. * @param {BABYLON.Scene} The scene where to create the mesh
  77068. * @return {BABYLON.Mesh} the default mesh
  77069. */
  77070. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77071. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77072. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77073. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77074. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77075. mesh.material = material;
  77076. return mesh;
  77077. };
  77078. __decorate([
  77079. BABYLON.serializeAsVector3()
  77080. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77081. __decorate([
  77082. BABYLON.serialize()
  77083. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77084. __decorate([
  77085. BABYLON.serialize()
  77086. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77087. __decorate([
  77088. BABYLON.serializeAsMeshReference()
  77089. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77090. __decorate([
  77091. BABYLON.serialize()
  77092. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77093. __decorate([
  77094. BABYLON.serialize()
  77095. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77096. __decorate([
  77097. BABYLON.serialize()
  77098. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77099. __decorate([
  77100. BABYLON.serialize()
  77101. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77102. __decorate([
  77103. BABYLON.serialize()
  77104. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77105. return VolumetricLightScatteringPostProcess;
  77106. }(BABYLON.PostProcess));
  77107. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77108. })(BABYLON || (BABYLON = {}));
  77109. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77110. //
  77111. // This post-process allows the modification of rendered colors by using
  77112. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77113. //
  77114. // The object needs to be provided an url to a texture containing the color
  77115. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77116. // Use an image editing software to tweak the LUT to match your needs.
  77117. //
  77118. // For an example of a color LUT, see here:
  77119. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77120. // For explanations on color grading, see here:
  77121. // http://udn.epicgames.com/Three/ColorGrading.html
  77122. //
  77123. var BABYLON;
  77124. (function (BABYLON) {
  77125. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77126. __extends(ColorCorrectionPostProcess, _super);
  77127. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77128. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77129. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77130. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77131. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77132. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77133. _this.onApply = function (effect) {
  77134. effect.setTexture("colorTable", _this._colorTableTexture);
  77135. };
  77136. return _this;
  77137. }
  77138. return ColorCorrectionPostProcess;
  77139. }(BABYLON.PostProcess));
  77140. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77141. })(BABYLON || (BABYLON = {}));
  77142. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77143. var BABYLON;
  77144. (function (BABYLON) {
  77145. /** Defines operator used for tonemapping */
  77146. var TonemappingOperator;
  77147. (function (TonemappingOperator) {
  77148. /** Hable */
  77149. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77150. /** Reinhard */
  77151. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77152. /** HejiDawson */
  77153. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77154. /** Photographic */
  77155. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77156. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77157. ;
  77158. /**
  77159. * Defines a post process to apply tone mapping
  77160. */
  77161. var TonemapPostProcess = /** @class */ (function (_super) {
  77162. __extends(TonemapPostProcess, _super);
  77163. /**
  77164. * Creates a new TonemapPostProcess
  77165. * @param name defines the name of the postprocess
  77166. * @param _operator defines the operator to use
  77167. * @param exposureAdjustment defines the required exposure adjustement
  77168. * @param camera defines the camera to use (can be null)
  77169. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77170. * @param engine defines the hosting engine (can be ignore if camera is set)
  77171. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77172. */
  77173. function TonemapPostProcess(name, _operator,
  77174. /** Defines the required exposure adjustement */
  77175. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77176. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77177. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77178. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77179. _this._operator = _operator;
  77180. _this.exposureAdjustment = exposureAdjustment;
  77181. var defines = "#define ";
  77182. if (_this._operator === TonemappingOperator.Hable)
  77183. defines += "HABLE_TONEMAPPING";
  77184. else if (_this._operator === TonemappingOperator.Reinhard)
  77185. defines += "REINHARD_TONEMAPPING";
  77186. else if (_this._operator === TonemappingOperator.HejiDawson)
  77187. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77188. else if (_this._operator === TonemappingOperator.Photographic)
  77189. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77190. //sadly a second call to create the effect.
  77191. _this.updateEffect(defines);
  77192. _this.onApply = function (effect) {
  77193. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77194. };
  77195. return _this;
  77196. }
  77197. return TonemapPostProcess;
  77198. }(BABYLON.PostProcess));
  77199. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77200. })(BABYLON || (BABYLON = {}));
  77201. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77202. var BABYLON;
  77203. (function (BABYLON) {
  77204. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77205. __extends(DisplayPassPostProcess, _super);
  77206. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77207. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77208. }
  77209. return DisplayPassPostProcess;
  77210. }(BABYLON.PostProcess));
  77211. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77212. })(BABYLON || (BABYLON = {}));
  77213. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77214. var BABYLON;
  77215. (function (BABYLON) {
  77216. var HighlightsPostProcess = /** @class */ (function (_super) {
  77217. __extends(HighlightsPostProcess, _super);
  77218. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77219. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77220. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77221. }
  77222. return HighlightsPostProcess;
  77223. }(BABYLON.PostProcess));
  77224. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77225. })(BABYLON || (BABYLON = {}));
  77226. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77227. var BABYLON;
  77228. (function (BABYLON) {
  77229. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77230. __extends(ImageProcessingPostProcess, _super);
  77231. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77232. if (camera === void 0) { camera = null; }
  77233. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77234. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77235. _this._fromLinearSpace = true;
  77236. /**
  77237. * Defines cache preventing GC.
  77238. */
  77239. _this._defines = {
  77240. IMAGEPROCESSING: false,
  77241. VIGNETTE: false,
  77242. VIGNETTEBLENDMODEMULTIPLY: false,
  77243. VIGNETTEBLENDMODEOPAQUE: false,
  77244. TONEMAPPING: false,
  77245. CONTRAST: false,
  77246. COLORCURVES: false,
  77247. COLORGRADING: false,
  77248. COLORGRADING3D: false,
  77249. FROMLINEARSPACE: false,
  77250. SAMPLER3DGREENDEPTH: false,
  77251. SAMPLER3DBGRMAP: false,
  77252. IMAGEPROCESSINGPOSTPROCESS: false,
  77253. EXPOSURE: false,
  77254. };
  77255. // Setup the configuration as forced by the constructor. This would then not force the
  77256. // scene materials output in linear space and let untouched the default forward pass.
  77257. if (imageProcessingConfiguration) {
  77258. imageProcessingConfiguration.applyByPostProcess = true;
  77259. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77260. // This will cause the shader to be compiled
  77261. _this.fromLinearSpace = false;
  77262. }
  77263. // Setup the default processing configuration to the scene.
  77264. else {
  77265. _this._attachImageProcessingConfiguration(null, true);
  77266. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77267. }
  77268. _this.onApply = function (effect) {
  77269. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77270. };
  77271. return _this;
  77272. }
  77273. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77274. /**
  77275. * Gets the image processing configuration used either in this material.
  77276. */
  77277. get: function () {
  77278. return this._imageProcessingConfiguration;
  77279. },
  77280. /**
  77281. * Sets the Default image processing configuration used either in the this material.
  77282. *
  77283. * If sets to null, the scene one is in use.
  77284. */
  77285. set: function (value) {
  77286. this._attachImageProcessingConfiguration(value);
  77287. },
  77288. enumerable: true,
  77289. configurable: true
  77290. });
  77291. /**
  77292. * Attaches a new image processing configuration to the PBR Material.
  77293. * @param configuration
  77294. */
  77295. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77296. var _this = this;
  77297. if (doNotBuild === void 0) { doNotBuild = false; }
  77298. if (configuration === this._imageProcessingConfiguration) {
  77299. return;
  77300. }
  77301. // Detaches observer.
  77302. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77303. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77304. }
  77305. // Pick the scene configuration if needed.
  77306. if (!configuration) {
  77307. var scene = null;
  77308. var engine = this.getEngine();
  77309. var camera = this.getCamera();
  77310. if (camera) {
  77311. scene = camera.getScene();
  77312. }
  77313. else if (engine && engine.scenes) {
  77314. var scenes = engine.scenes;
  77315. scene = scenes[scenes.length - 1];
  77316. }
  77317. else {
  77318. scene = BABYLON.Engine.LastCreatedScene;
  77319. }
  77320. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77321. }
  77322. else {
  77323. this._imageProcessingConfiguration = configuration;
  77324. }
  77325. // Attaches observer.
  77326. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77327. _this._updateParameters();
  77328. });
  77329. // Ensure the effect will be rebuilt.
  77330. if (!doNotBuild) {
  77331. this._updateParameters();
  77332. }
  77333. };
  77334. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77335. /**
  77336. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77337. */
  77338. get: function () {
  77339. return this.imageProcessingConfiguration.colorCurves;
  77340. },
  77341. /**
  77342. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77343. */
  77344. set: function (value) {
  77345. this.imageProcessingConfiguration.colorCurves = value;
  77346. },
  77347. enumerable: true,
  77348. configurable: true
  77349. });
  77350. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77351. /**
  77352. * Gets wether the color curves effect is enabled.
  77353. */
  77354. get: function () {
  77355. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77356. },
  77357. /**
  77358. * Sets wether the color curves effect is enabled.
  77359. */
  77360. set: function (value) {
  77361. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77362. },
  77363. enumerable: true,
  77364. configurable: true
  77365. });
  77366. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77367. /**
  77368. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77369. */
  77370. get: function () {
  77371. return this.imageProcessingConfiguration.colorGradingTexture;
  77372. },
  77373. /**
  77374. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77375. */
  77376. set: function (value) {
  77377. this.imageProcessingConfiguration.colorGradingTexture = value;
  77378. },
  77379. enumerable: true,
  77380. configurable: true
  77381. });
  77382. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77383. /**
  77384. * Gets wether the color grading effect is enabled.
  77385. */
  77386. get: function () {
  77387. return this.imageProcessingConfiguration.colorGradingEnabled;
  77388. },
  77389. /**
  77390. * Gets wether the color grading effect is enabled.
  77391. */
  77392. set: function (value) {
  77393. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77394. },
  77395. enumerable: true,
  77396. configurable: true
  77397. });
  77398. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77399. /**
  77400. * Gets exposure used in the effect.
  77401. */
  77402. get: function () {
  77403. return this.imageProcessingConfiguration.exposure;
  77404. },
  77405. /**
  77406. * Sets exposure used in the effect.
  77407. */
  77408. set: function (value) {
  77409. this.imageProcessingConfiguration.exposure = value;
  77410. },
  77411. enumerable: true,
  77412. configurable: true
  77413. });
  77414. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77415. /**
  77416. * Gets wether tonemapping is enabled or not.
  77417. */
  77418. get: function () {
  77419. return this._imageProcessingConfiguration.toneMappingEnabled;
  77420. },
  77421. /**
  77422. * Sets wether tonemapping is enabled or not
  77423. */
  77424. set: function (value) {
  77425. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77426. },
  77427. enumerable: true,
  77428. configurable: true
  77429. });
  77430. ;
  77431. ;
  77432. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77433. /**
  77434. * Gets contrast used in the effect.
  77435. */
  77436. get: function () {
  77437. return this.imageProcessingConfiguration.contrast;
  77438. },
  77439. /**
  77440. * Sets contrast used in the effect.
  77441. */
  77442. set: function (value) {
  77443. this.imageProcessingConfiguration.contrast = value;
  77444. },
  77445. enumerable: true,
  77446. configurable: true
  77447. });
  77448. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77449. /**
  77450. * Gets Vignette stretch size.
  77451. */
  77452. get: function () {
  77453. return this.imageProcessingConfiguration.vignetteStretch;
  77454. },
  77455. /**
  77456. * Sets Vignette stretch size.
  77457. */
  77458. set: function (value) {
  77459. this.imageProcessingConfiguration.vignetteStretch = value;
  77460. },
  77461. enumerable: true,
  77462. configurable: true
  77463. });
  77464. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77465. /**
  77466. * Gets Vignette centre X Offset.
  77467. */
  77468. get: function () {
  77469. return this.imageProcessingConfiguration.vignetteCentreX;
  77470. },
  77471. /**
  77472. * Sets Vignette centre X Offset.
  77473. */
  77474. set: function (value) {
  77475. this.imageProcessingConfiguration.vignetteCentreX = value;
  77476. },
  77477. enumerable: true,
  77478. configurable: true
  77479. });
  77480. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77481. /**
  77482. * Gets Vignette centre Y Offset.
  77483. */
  77484. get: function () {
  77485. return this.imageProcessingConfiguration.vignetteCentreY;
  77486. },
  77487. /**
  77488. * Sets Vignette centre Y Offset.
  77489. */
  77490. set: function (value) {
  77491. this.imageProcessingConfiguration.vignetteCentreY = value;
  77492. },
  77493. enumerable: true,
  77494. configurable: true
  77495. });
  77496. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77497. /**
  77498. * Gets Vignette weight or intensity of the vignette effect.
  77499. */
  77500. get: function () {
  77501. return this.imageProcessingConfiguration.vignetteWeight;
  77502. },
  77503. /**
  77504. * Sets Vignette weight or intensity of the vignette effect.
  77505. */
  77506. set: function (value) {
  77507. this.imageProcessingConfiguration.vignetteWeight = value;
  77508. },
  77509. enumerable: true,
  77510. configurable: true
  77511. });
  77512. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77513. /**
  77514. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77515. * if vignetteEnabled is set to true.
  77516. */
  77517. get: function () {
  77518. return this.imageProcessingConfiguration.vignetteColor;
  77519. },
  77520. /**
  77521. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77522. * if vignetteEnabled is set to true.
  77523. */
  77524. set: function (value) {
  77525. this.imageProcessingConfiguration.vignetteColor = value;
  77526. },
  77527. enumerable: true,
  77528. configurable: true
  77529. });
  77530. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77531. /**
  77532. * Gets Camera field of view used by the Vignette effect.
  77533. */
  77534. get: function () {
  77535. return this.imageProcessingConfiguration.vignetteCameraFov;
  77536. },
  77537. /**
  77538. * Sets Camera field of view used by the Vignette effect.
  77539. */
  77540. set: function (value) {
  77541. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77542. },
  77543. enumerable: true,
  77544. configurable: true
  77545. });
  77546. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77547. /**
  77548. * Gets the vignette blend mode allowing different kind of effect.
  77549. */
  77550. get: function () {
  77551. return this.imageProcessingConfiguration.vignetteBlendMode;
  77552. },
  77553. /**
  77554. * Sets the vignette blend mode allowing different kind of effect.
  77555. */
  77556. set: function (value) {
  77557. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77558. },
  77559. enumerable: true,
  77560. configurable: true
  77561. });
  77562. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77563. /**
  77564. * Gets wether the vignette effect is enabled.
  77565. */
  77566. get: function () {
  77567. return this.imageProcessingConfiguration.vignetteEnabled;
  77568. },
  77569. /**
  77570. * Sets wether the vignette effect is enabled.
  77571. */
  77572. set: function (value) {
  77573. this.imageProcessingConfiguration.vignetteEnabled = value;
  77574. },
  77575. enumerable: true,
  77576. configurable: true
  77577. });
  77578. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77579. /**
  77580. * Gets wether the input of the processing is in Gamma or Linear Space.
  77581. */
  77582. get: function () {
  77583. return this._fromLinearSpace;
  77584. },
  77585. /**
  77586. * Sets wether the input of the processing is in Gamma or Linear Space.
  77587. */
  77588. set: function (value) {
  77589. if (this._fromLinearSpace === value) {
  77590. return;
  77591. }
  77592. this._fromLinearSpace = value;
  77593. this._updateParameters();
  77594. },
  77595. enumerable: true,
  77596. configurable: true
  77597. });
  77598. ImageProcessingPostProcess.prototype.getClassName = function () {
  77599. return "ImageProcessingPostProcess";
  77600. };
  77601. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77602. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77603. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77604. var defines = "";
  77605. for (var define in this._defines) {
  77606. if (this._defines[define]) {
  77607. defines += "#define " + define + ";\r\n";
  77608. }
  77609. }
  77610. var samplers = ["textureSampler"];
  77611. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77612. var uniforms = ["scale"];
  77613. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77614. this.updateEffect(defines, uniforms, samplers);
  77615. };
  77616. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77617. _super.prototype.dispose.call(this, camera);
  77618. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77619. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77620. }
  77621. this.imageProcessingConfiguration.applyByPostProcess = false;
  77622. };
  77623. __decorate([
  77624. BABYLON.serialize()
  77625. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77626. return ImageProcessingPostProcess;
  77627. }(BABYLON.PostProcess));
  77628. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77629. })(BABYLON || (BABYLON = {}));
  77630. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77631. var BABYLON;
  77632. (function (BABYLON) {
  77633. /**
  77634. * Class used to store bone information
  77635. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77636. */
  77637. var Bone = /** @class */ (function (_super) {
  77638. __extends(Bone, _super);
  77639. /**
  77640. * Create a new bone
  77641. * @param name defines the bone name
  77642. * @param skeleton defines the parent skeleton
  77643. * @param parentBone defines the parent (can be null if the bone is the root)
  77644. * @param localMatrix defines the local matrix
  77645. * @param restPose defines the rest pose matrix
  77646. * @param baseMatrix defines the base matrix
  77647. * @param index defines index of the bone in the hiearchy
  77648. */
  77649. function Bone(
  77650. /**
  77651. * defines the bone name
  77652. */
  77653. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77654. if (parentBone === void 0) { parentBone = null; }
  77655. if (localMatrix === void 0) { localMatrix = null; }
  77656. if (restPose === void 0) { restPose = null; }
  77657. if (baseMatrix === void 0) { baseMatrix = null; }
  77658. if (index === void 0) { index = null; }
  77659. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77660. _this.name = name;
  77661. /**
  77662. * Gets the list of child bones
  77663. */
  77664. _this.children = new Array();
  77665. /** Gets the animations associated with this bone */
  77666. _this.animations = new Array();
  77667. /**
  77668. * @hidden Internal only
  77669. * Set this value to map this bone to a different index in the transform matrices
  77670. * Set this value to -1 to exclude the bone from the transform matrices
  77671. */
  77672. _this._index = null;
  77673. _this._absoluteTransform = new BABYLON.Matrix();
  77674. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77675. _this._scalingDeterminant = 1;
  77676. _this._worldTransform = new BABYLON.Matrix();
  77677. _this._needToDecompose = true;
  77678. _this._needToCompose = false;
  77679. _this._skeleton = skeleton;
  77680. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77681. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77682. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77683. _this._index = index;
  77684. skeleton.bones.push(_this);
  77685. _this.setParent(parentBone, false);
  77686. if (baseMatrix || localMatrix) {
  77687. _this._updateDifferenceMatrix();
  77688. }
  77689. return _this;
  77690. }
  77691. Object.defineProperty(Bone.prototype, "_matrix", {
  77692. /** @hidden */
  77693. get: function () {
  77694. this._compose();
  77695. return this._localMatrix;
  77696. },
  77697. /** @hidden */
  77698. set: function (value) {
  77699. this._localMatrix.copyFrom(value);
  77700. this._needToDecompose = true;
  77701. },
  77702. enumerable: true,
  77703. configurable: true
  77704. });
  77705. // Members
  77706. /**
  77707. * Gets the parent skeleton
  77708. * @returns a skeleton
  77709. */
  77710. Bone.prototype.getSkeleton = function () {
  77711. return this._skeleton;
  77712. };
  77713. /**
  77714. * Gets parent bone
  77715. * @returns a bone or null if the bone is the root of the bone hierarchy
  77716. */
  77717. Bone.prototype.getParent = function () {
  77718. return this._parent;
  77719. };
  77720. /**
  77721. * Sets the parent bone
  77722. * @param parent defines the parent (can be null if the bone is the root)
  77723. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77724. */
  77725. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77726. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77727. if (this._parent === parent) {
  77728. return;
  77729. }
  77730. if (this._parent) {
  77731. var index = this._parent.children.indexOf(this);
  77732. if (index !== -1) {
  77733. this._parent.children.splice(index, 1);
  77734. }
  77735. }
  77736. this._parent = parent;
  77737. if (this._parent) {
  77738. this._parent.children.push(this);
  77739. }
  77740. if (updateDifferenceMatrix) {
  77741. this._updateDifferenceMatrix();
  77742. }
  77743. this.markAsDirty();
  77744. };
  77745. /**
  77746. * Gets the local matrix
  77747. * @returns a matrix
  77748. */
  77749. Bone.prototype.getLocalMatrix = function () {
  77750. this._compose();
  77751. return this._localMatrix;
  77752. };
  77753. /**
  77754. * Gets the base matrix (initial matrix which remains unchanged)
  77755. * @returns a matrix
  77756. */
  77757. Bone.prototype.getBaseMatrix = function () {
  77758. return this._baseMatrix;
  77759. };
  77760. /**
  77761. * Gets the rest pose matrix
  77762. * @returns a matrix
  77763. */
  77764. Bone.prototype.getRestPose = function () {
  77765. return this._restPose;
  77766. };
  77767. /**
  77768. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77769. */
  77770. Bone.prototype.getWorldMatrix = function () {
  77771. return this._worldTransform;
  77772. };
  77773. /**
  77774. * Sets the local matrix to rest pose matrix
  77775. */
  77776. Bone.prototype.returnToRest = function () {
  77777. this.updateMatrix(this._restPose.clone());
  77778. };
  77779. /**
  77780. * Gets the inverse of the absolute transform matrix.
  77781. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77782. * @returns a matrix
  77783. */
  77784. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77785. return this._invertedAbsoluteTransform;
  77786. };
  77787. /**
  77788. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77789. * @returns a matrix
  77790. */
  77791. Bone.prototype.getAbsoluteTransform = function () {
  77792. return this._absoluteTransform;
  77793. };
  77794. Object.defineProperty(Bone.prototype, "position", {
  77795. // Properties (matches AbstractMesh properties)
  77796. /** Gets or sets current position (in local space) */
  77797. get: function () {
  77798. this._decompose();
  77799. return this._localPosition;
  77800. },
  77801. set: function (newPosition) {
  77802. this._decompose();
  77803. this._localPosition.copyFrom(newPosition);
  77804. this._markAsDirtyAndCompose();
  77805. },
  77806. enumerable: true,
  77807. configurable: true
  77808. });
  77809. Object.defineProperty(Bone.prototype, "rotation", {
  77810. /** Gets or sets current rotation (in local space) */
  77811. get: function () {
  77812. return this.getRotation();
  77813. },
  77814. set: function (newRotation) {
  77815. this.setRotation(newRotation);
  77816. },
  77817. enumerable: true,
  77818. configurable: true
  77819. });
  77820. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77821. /** Gets or sets current rotation quaternion (in local space) */
  77822. get: function () {
  77823. this._decompose();
  77824. return this._localRotation;
  77825. },
  77826. set: function (newRotation) {
  77827. this.setRotationQuaternion(newRotation);
  77828. },
  77829. enumerable: true,
  77830. configurable: true
  77831. });
  77832. Object.defineProperty(Bone.prototype, "scaling", {
  77833. /** Gets or sets current scaling (in local space) */
  77834. get: function () {
  77835. return this.getScale();
  77836. },
  77837. set: function (newScaling) {
  77838. this.setScale(newScaling);
  77839. },
  77840. enumerable: true,
  77841. configurable: true
  77842. });
  77843. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77844. /**
  77845. * Gets the animation properties override
  77846. */
  77847. get: function () {
  77848. return this._skeleton.animationPropertiesOverride;
  77849. },
  77850. enumerable: true,
  77851. configurable: true
  77852. });
  77853. // Methods
  77854. Bone.prototype._decompose = function () {
  77855. if (!this._needToDecompose) {
  77856. return;
  77857. }
  77858. this._needToDecompose = false;
  77859. if (!this._localScaling) {
  77860. this._localScaling = BABYLON.Vector3.Zero();
  77861. this._localRotation = BABYLON.Quaternion.Zero();
  77862. this._localPosition = BABYLON.Vector3.Zero();
  77863. }
  77864. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77865. };
  77866. Bone.prototype._compose = function () {
  77867. if (!this._needToCompose) {
  77868. return;
  77869. }
  77870. this._needToCompose = false;
  77871. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77872. };
  77873. /**
  77874. * Update the base and local matrices
  77875. * @param matrix defines the new base or local matrix
  77876. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77877. * @param updateLocalMatrix defines if the local matrix should be updated
  77878. */
  77879. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77880. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77881. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77882. this._baseMatrix.copyFrom(matrix);
  77883. if (updateDifferenceMatrix) {
  77884. this._updateDifferenceMatrix();
  77885. }
  77886. if (updateLocalMatrix) {
  77887. this._localMatrix.copyFrom(matrix);
  77888. this._markAsDirtyAndDecompose();
  77889. }
  77890. else {
  77891. this.markAsDirty();
  77892. }
  77893. };
  77894. /** @hidden */
  77895. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77896. if (updateChildren === void 0) { updateChildren = true; }
  77897. if (!rootMatrix) {
  77898. rootMatrix = this._baseMatrix;
  77899. }
  77900. if (this._parent) {
  77901. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77902. }
  77903. else {
  77904. this._absoluteTransform.copyFrom(rootMatrix);
  77905. }
  77906. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77907. if (updateChildren) {
  77908. for (var index = 0; index < this.children.length; index++) {
  77909. this.children[index]._updateDifferenceMatrix();
  77910. }
  77911. }
  77912. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77913. };
  77914. /**
  77915. * Flag the bone as dirty (Forcing it to update everything)
  77916. */
  77917. Bone.prototype.markAsDirty = function () {
  77918. this._currentRenderId++;
  77919. this._childRenderId++;
  77920. this._skeleton._markAsDirty();
  77921. };
  77922. Bone.prototype._markAsDirtyAndCompose = function () {
  77923. this.markAsDirty();
  77924. this._needToCompose = true;
  77925. };
  77926. Bone.prototype._markAsDirtyAndDecompose = function () {
  77927. this.markAsDirty();
  77928. this._needToDecompose = true;
  77929. };
  77930. /**
  77931. * Copy an animation range from another bone
  77932. * @param source defines the source bone
  77933. * @param rangeName defines the range name to copy
  77934. * @param frameOffset defines the frame offset
  77935. * @param rescaleAsRequired defines if rescaling must be applied if required
  77936. * @param skelDimensionsRatio defines the scaling ratio
  77937. * @returns true if operation was successful
  77938. */
  77939. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77940. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77941. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77942. // all animation may be coming from a library skeleton, so may need to create animation
  77943. if (this.animations.length === 0) {
  77944. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77945. this.animations[0].setKeys([]);
  77946. }
  77947. // get animation info / verify there is such a range from the source bone
  77948. var sourceRange = source.animations[0].getRange(rangeName);
  77949. if (!sourceRange) {
  77950. return false;
  77951. }
  77952. var from = sourceRange.from;
  77953. var to = sourceRange.to;
  77954. var sourceKeys = source.animations[0].getKeys();
  77955. // rescaling prep
  77956. var sourceBoneLength = source.length;
  77957. var sourceParent = source.getParent();
  77958. var parent = this.getParent();
  77959. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77960. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77961. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77962. var destKeys = this.animations[0].getKeys();
  77963. // loop vars declaration
  77964. var orig;
  77965. var origTranslation;
  77966. var mat;
  77967. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77968. orig = sourceKeys[key];
  77969. if (orig.frame >= from && orig.frame <= to) {
  77970. if (rescaleAsRequired) {
  77971. mat = orig.value.clone();
  77972. // scale based on parent ratio, when bone has parent
  77973. if (parentScalingReqd) {
  77974. origTranslation = mat.getTranslation();
  77975. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77976. // scale based on skeleton dimension ratio when root bone, and value is passed
  77977. }
  77978. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77979. origTranslation = mat.getTranslation();
  77980. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77981. // use original when root bone, and no data for skelDimensionsRatio
  77982. }
  77983. else {
  77984. mat = orig.value;
  77985. }
  77986. }
  77987. else {
  77988. mat = orig.value;
  77989. }
  77990. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77991. }
  77992. }
  77993. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77994. return true;
  77995. };
  77996. /**
  77997. * Translate the bone in local or world space
  77998. * @param vec The amount to translate the bone
  77999. * @param space The space that the translation is in
  78000. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78001. */
  78002. Bone.prototype.translate = function (vec, space, mesh) {
  78003. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78004. var lm = this.getLocalMatrix();
  78005. if (space == BABYLON.Space.LOCAL) {
  78006. lm.m[12] += vec.x;
  78007. lm.m[13] += vec.y;
  78008. lm.m[14] += vec.z;
  78009. }
  78010. else {
  78011. var wm = null;
  78012. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78013. if (mesh) {
  78014. wm = mesh.getWorldMatrix();
  78015. }
  78016. this._skeleton.computeAbsoluteTransforms();
  78017. var tmat = Bone._tmpMats[0];
  78018. var tvec = Bone._tmpVecs[0];
  78019. if (this._parent) {
  78020. if (mesh && wm) {
  78021. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78022. tmat.multiplyToRef(wm, tmat);
  78023. }
  78024. else {
  78025. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78026. }
  78027. }
  78028. tmat.m[12] = 0;
  78029. tmat.m[13] = 0;
  78030. tmat.m[14] = 0;
  78031. tmat.invert();
  78032. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78033. lm.m[12] += tvec.x;
  78034. lm.m[13] += tvec.y;
  78035. lm.m[14] += tvec.z;
  78036. }
  78037. this._markAsDirtyAndDecompose();
  78038. };
  78039. /**
  78040. * Set the postion of the bone in local or world space
  78041. * @param position The position to set the bone
  78042. * @param space The space that the position is in
  78043. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78044. */
  78045. Bone.prototype.setPosition = function (position, space, mesh) {
  78046. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78047. var lm = this.getLocalMatrix();
  78048. if (space == BABYLON.Space.LOCAL) {
  78049. lm.m[12] = position.x;
  78050. lm.m[13] = position.y;
  78051. lm.m[14] = position.z;
  78052. }
  78053. else {
  78054. var wm = null;
  78055. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78056. if (mesh) {
  78057. wm = mesh.getWorldMatrix();
  78058. }
  78059. this._skeleton.computeAbsoluteTransforms();
  78060. var tmat = Bone._tmpMats[0];
  78061. var vec = Bone._tmpVecs[0];
  78062. if (this._parent) {
  78063. if (mesh && wm) {
  78064. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78065. tmat.multiplyToRef(wm, tmat);
  78066. }
  78067. else {
  78068. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78069. }
  78070. }
  78071. tmat.invert();
  78072. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78073. lm.m[12] = vec.x;
  78074. lm.m[13] = vec.y;
  78075. lm.m[14] = vec.z;
  78076. }
  78077. this._markAsDirtyAndDecompose();
  78078. };
  78079. /**
  78080. * Set the absolute position of the bone (world space)
  78081. * @param position The position to set the bone
  78082. * @param mesh The mesh that this bone is attached to
  78083. */
  78084. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78085. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78086. };
  78087. /**
  78088. * Scale the bone on the x, y and z axes (in local space)
  78089. * @param x The amount to scale the bone on the x axis
  78090. * @param y The amount to scale the bone on the y axis
  78091. * @param z The amount to scale the bone on the z axis
  78092. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78093. */
  78094. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78095. if (scaleChildren === void 0) { scaleChildren = false; }
  78096. var locMat = this.getLocalMatrix();
  78097. // Apply new scaling on top of current local matrix
  78098. var scaleMat = Bone._tmpMats[0];
  78099. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78100. scaleMat.multiplyToRef(locMat, locMat);
  78101. // Invert scaling matrix and apply the inverse to all children
  78102. scaleMat.invert();
  78103. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78104. var child = _a[_i];
  78105. var cm = child.getLocalMatrix();
  78106. cm.multiplyToRef(scaleMat, cm);
  78107. cm.m[12] *= x;
  78108. cm.m[13] *= y;
  78109. cm.m[14] *= z;
  78110. child._markAsDirtyAndDecompose();
  78111. }
  78112. this._markAsDirtyAndDecompose();
  78113. if (scaleChildren) {
  78114. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78115. var child = _c[_b];
  78116. child.scale(x, y, z, scaleChildren);
  78117. }
  78118. }
  78119. };
  78120. /**
  78121. * Set the bone scaling in local space
  78122. * @param scale defines the scaling vector
  78123. */
  78124. Bone.prototype.setScale = function (scale) {
  78125. this._decompose();
  78126. this._localScaling.copyFrom(scale);
  78127. this._markAsDirtyAndCompose();
  78128. };
  78129. /**
  78130. * Gets the current scaling in local space
  78131. * @returns the current scaling vector
  78132. */
  78133. Bone.prototype.getScale = function () {
  78134. this._decompose();
  78135. return this._localScaling;
  78136. };
  78137. /**
  78138. * Gets the current scaling in local space and stores it in a target vector
  78139. * @param result defines the target vector
  78140. */
  78141. Bone.prototype.getScaleToRef = function (result) {
  78142. this._decompose();
  78143. result.copyFrom(this._localScaling);
  78144. };
  78145. /**
  78146. * Set the yaw, pitch, and roll of the bone in local or world space
  78147. * @param yaw The rotation of the bone on the y axis
  78148. * @param pitch The rotation of the bone on the x axis
  78149. * @param roll The rotation of the bone on the z axis
  78150. * @param space The space that the axes of rotation are in
  78151. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78152. */
  78153. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78154. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78155. if (space === BABYLON.Space.LOCAL) {
  78156. var quat = Bone._tmpQuat;
  78157. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78158. this.setRotationQuaternion(quat, space, mesh);
  78159. return;
  78160. }
  78161. var rotMatInv = Bone._tmpMats[0];
  78162. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78163. return;
  78164. }
  78165. var rotMat = Bone._tmpMats[1];
  78166. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78167. rotMatInv.multiplyToRef(rotMat, rotMat);
  78168. this._rotateWithMatrix(rotMat, space, mesh);
  78169. };
  78170. /**
  78171. * Add a rotation to the bone on an axis in local or world space
  78172. * @param axis The axis to rotate the bone on
  78173. * @param amount The amount to rotate the bone
  78174. * @param space The space that the axis is in
  78175. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78176. */
  78177. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78178. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78179. var rmat = Bone._tmpMats[0];
  78180. rmat.m[12] = 0;
  78181. rmat.m[13] = 0;
  78182. rmat.m[14] = 0;
  78183. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78184. this._rotateWithMatrix(rmat, space, mesh);
  78185. };
  78186. /**
  78187. * Set the rotation of the bone to a particular axis angle in local or world space
  78188. * @param axis The axis to rotate the bone on
  78189. * @param angle The angle that the bone should be rotated to
  78190. * @param space The space that the axis is in
  78191. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78192. */
  78193. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78194. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78195. if (space === BABYLON.Space.LOCAL) {
  78196. var quat = Bone._tmpQuat;
  78197. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78198. this.setRotationQuaternion(quat, space, mesh);
  78199. return;
  78200. }
  78201. var rotMatInv = Bone._tmpMats[0];
  78202. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78203. return;
  78204. }
  78205. var rotMat = Bone._tmpMats[1];
  78206. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78207. rotMatInv.multiplyToRef(rotMat, rotMat);
  78208. this._rotateWithMatrix(rotMat, space, mesh);
  78209. };
  78210. /**
  78211. * Set the euler rotation of the bone in local of world space
  78212. * @param rotation The euler rotation that the bone should be set to
  78213. * @param space The space that the rotation is in
  78214. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78215. */
  78216. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78217. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78218. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78219. };
  78220. /**
  78221. * Set the quaternion rotation of the bone in local of world space
  78222. * @param quat The quaternion rotation that the bone should be set to
  78223. * @param space The space that the rotation is in
  78224. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78225. */
  78226. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78227. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78228. if (space === BABYLON.Space.LOCAL) {
  78229. this._decompose();
  78230. this._localRotation.copyFrom(quat);
  78231. this._markAsDirtyAndCompose();
  78232. return;
  78233. }
  78234. var rotMatInv = Bone._tmpMats[0];
  78235. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78236. return;
  78237. }
  78238. var rotMat = Bone._tmpMats[1];
  78239. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78240. rotMatInv.multiplyToRef(rotMat, rotMat);
  78241. this._rotateWithMatrix(rotMat, space, mesh);
  78242. };
  78243. /**
  78244. * Set the rotation matrix of the bone in local of world space
  78245. * @param rotMat The rotation matrix that the bone should be set to
  78246. * @param space The space that the rotation is in
  78247. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78248. */
  78249. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78250. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78251. if (space === BABYLON.Space.LOCAL) {
  78252. var quat = Bone._tmpQuat;
  78253. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78254. this.setRotationQuaternion(quat, space, mesh);
  78255. return;
  78256. }
  78257. var rotMatInv = Bone._tmpMats[0];
  78258. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78259. return;
  78260. }
  78261. var rotMat2 = Bone._tmpMats[1];
  78262. rotMat2.copyFrom(rotMat);
  78263. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78264. this._rotateWithMatrix(rotMat2, space, mesh);
  78265. };
  78266. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78267. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78268. var lmat = this.getLocalMatrix();
  78269. var lx = lmat.m[12];
  78270. var ly = lmat.m[13];
  78271. var lz = lmat.m[14];
  78272. var parent = this.getParent();
  78273. var parentScale = Bone._tmpMats[3];
  78274. var parentScaleInv = Bone._tmpMats[4];
  78275. if (parent && space == BABYLON.Space.WORLD) {
  78276. if (mesh) {
  78277. parentScale.copyFrom(mesh.getWorldMatrix());
  78278. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78279. }
  78280. else {
  78281. parentScale.copyFrom(parent.getAbsoluteTransform());
  78282. }
  78283. parentScaleInv.copyFrom(parentScale);
  78284. parentScaleInv.invert();
  78285. lmat.multiplyToRef(parentScale, lmat);
  78286. lmat.multiplyToRef(rmat, lmat);
  78287. lmat.multiplyToRef(parentScaleInv, lmat);
  78288. }
  78289. else {
  78290. if (space == BABYLON.Space.WORLD && mesh) {
  78291. parentScale.copyFrom(mesh.getWorldMatrix());
  78292. parentScaleInv.copyFrom(parentScale);
  78293. parentScaleInv.invert();
  78294. lmat.multiplyToRef(parentScale, lmat);
  78295. lmat.multiplyToRef(rmat, lmat);
  78296. lmat.multiplyToRef(parentScaleInv, lmat);
  78297. }
  78298. else {
  78299. lmat.multiplyToRef(rmat, lmat);
  78300. }
  78301. }
  78302. lmat.m[12] = lx;
  78303. lmat.m[13] = ly;
  78304. lmat.m[14] = lz;
  78305. this.computeAbsoluteTransforms();
  78306. this._markAsDirtyAndDecompose();
  78307. };
  78308. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78309. var scaleMatrix = Bone._tmpMats[2];
  78310. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78311. if (mesh) {
  78312. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78313. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78314. }
  78315. rotMatInv.invert();
  78316. if (isNaN(rotMatInv.m[0])) {
  78317. // Matrix failed to invert.
  78318. // This can happen if scale is zero for example.
  78319. return false;
  78320. }
  78321. scaleMatrix.m[0] *= this._scalingDeterminant;
  78322. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78323. return true;
  78324. };
  78325. /**
  78326. * Get the position of the bone in local or world space
  78327. * @param space The space that the returned position is in
  78328. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78329. * @returns The position of the bone
  78330. */
  78331. Bone.prototype.getPosition = function (space, mesh) {
  78332. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78333. if (mesh === void 0) { mesh = null; }
  78334. var pos = BABYLON.Vector3.Zero();
  78335. this.getPositionToRef(space, mesh, pos);
  78336. return pos;
  78337. };
  78338. /**
  78339. * Copy the position of the bone to a vector3 in local or world space
  78340. * @param space The space that the returned position is in
  78341. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78342. * @param result The vector3 to copy the position to
  78343. */
  78344. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78345. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78346. if (space == BABYLON.Space.LOCAL) {
  78347. var lm = this.getLocalMatrix();
  78348. result.x = lm.m[12];
  78349. result.y = lm.m[13];
  78350. result.z = lm.m[14];
  78351. }
  78352. else {
  78353. var wm = null;
  78354. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78355. if (mesh) {
  78356. wm = mesh.getWorldMatrix();
  78357. }
  78358. this._skeleton.computeAbsoluteTransforms();
  78359. var tmat = Bone._tmpMats[0];
  78360. if (mesh && wm) {
  78361. tmat.copyFrom(this.getAbsoluteTransform());
  78362. tmat.multiplyToRef(wm, tmat);
  78363. }
  78364. else {
  78365. tmat = this.getAbsoluteTransform();
  78366. }
  78367. result.x = tmat.m[12];
  78368. result.y = tmat.m[13];
  78369. result.z = tmat.m[14];
  78370. }
  78371. };
  78372. /**
  78373. * Get the absolute position of the bone (world space)
  78374. * @param mesh The mesh that this bone is attached to
  78375. * @returns The absolute position of the bone
  78376. */
  78377. Bone.prototype.getAbsolutePosition = function (mesh) {
  78378. if (mesh === void 0) { mesh = null; }
  78379. var pos = BABYLON.Vector3.Zero();
  78380. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78381. return pos;
  78382. };
  78383. /**
  78384. * Copy the absolute position of the bone (world space) to the result param
  78385. * @param mesh The mesh that this bone is attached to
  78386. * @param result The vector3 to copy the absolute position to
  78387. */
  78388. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78389. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78390. };
  78391. /**
  78392. * Compute the absolute transforms of this bone and its children
  78393. */
  78394. Bone.prototype.computeAbsoluteTransforms = function () {
  78395. this._compose();
  78396. if (this._parent) {
  78397. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78398. }
  78399. else {
  78400. this._absoluteTransform.copyFrom(this._localMatrix);
  78401. var poseMatrix = this._skeleton.getPoseMatrix();
  78402. if (poseMatrix) {
  78403. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78404. }
  78405. }
  78406. var children = this.children;
  78407. var len = children.length;
  78408. for (var i = 0; i < len; i++) {
  78409. children[i].computeAbsoluteTransforms();
  78410. }
  78411. };
  78412. /**
  78413. * Get the world direction from an axis that is in the local space of the bone
  78414. * @param localAxis The local direction that is used to compute the world direction
  78415. * @param mesh The mesh that this bone is attached to
  78416. * @returns The world direction
  78417. */
  78418. Bone.prototype.getDirection = function (localAxis, mesh) {
  78419. if (mesh === void 0) { mesh = null; }
  78420. var result = BABYLON.Vector3.Zero();
  78421. this.getDirectionToRef(localAxis, mesh, result);
  78422. return result;
  78423. };
  78424. /**
  78425. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78426. * @param localAxis The local direction that is used to compute the world direction
  78427. * @param mesh The mesh that this bone is attached to
  78428. * @param result The vector3 that the world direction will be copied to
  78429. */
  78430. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78431. if (mesh === void 0) { mesh = null; }
  78432. var wm = null;
  78433. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78434. if (mesh) {
  78435. wm = mesh.getWorldMatrix();
  78436. }
  78437. this._skeleton.computeAbsoluteTransforms();
  78438. var mat = Bone._tmpMats[0];
  78439. mat.copyFrom(this.getAbsoluteTransform());
  78440. if (mesh && wm) {
  78441. mat.multiplyToRef(wm, mat);
  78442. }
  78443. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78444. result.normalize();
  78445. };
  78446. /**
  78447. * Get the euler rotation of the bone in local or world space
  78448. * @param space The space that the rotation should be in
  78449. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78450. * @returns The euler rotation
  78451. */
  78452. Bone.prototype.getRotation = function (space, mesh) {
  78453. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78454. if (mesh === void 0) { mesh = null; }
  78455. var result = BABYLON.Vector3.Zero();
  78456. this.getRotationToRef(space, mesh, result);
  78457. return result;
  78458. };
  78459. /**
  78460. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78461. * @param space The space that the rotation should be in
  78462. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78463. * @param result The vector3 that the rotation should be copied to
  78464. */
  78465. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78466. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78467. if (mesh === void 0) { mesh = null; }
  78468. var quat = Bone._tmpQuat;
  78469. this.getRotationQuaternionToRef(space, mesh, quat);
  78470. quat.toEulerAnglesToRef(result);
  78471. };
  78472. /**
  78473. * Get the quaternion rotation of the bone in either local or world space
  78474. * @param space The space that the rotation should be in
  78475. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78476. * @returns The quaternion rotation
  78477. */
  78478. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78479. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78480. if (mesh === void 0) { mesh = null; }
  78481. var result = BABYLON.Quaternion.Identity();
  78482. this.getRotationQuaternionToRef(space, mesh, result);
  78483. return result;
  78484. };
  78485. /**
  78486. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78487. * @param space The space that the rotation should be in
  78488. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78489. * @param result The quaternion that the rotation should be copied to
  78490. */
  78491. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78492. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78493. if (mesh === void 0) { mesh = null; }
  78494. if (space == BABYLON.Space.LOCAL) {
  78495. this._decompose();
  78496. result.copyFrom(this._localRotation);
  78497. }
  78498. else {
  78499. var mat = Bone._tmpMats[0];
  78500. var amat = this.getAbsoluteTransform();
  78501. if (mesh) {
  78502. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78503. }
  78504. else {
  78505. mat.copyFrom(amat);
  78506. }
  78507. mat.m[0] *= this._scalingDeterminant;
  78508. mat.m[1] *= this._scalingDeterminant;
  78509. mat.m[2] *= this._scalingDeterminant;
  78510. mat.decompose(undefined, result, undefined);
  78511. }
  78512. };
  78513. /**
  78514. * Get the rotation matrix of the bone in local or world space
  78515. * @param space The space that the rotation should be in
  78516. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78517. * @returns The rotation matrix
  78518. */
  78519. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78520. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78521. var result = BABYLON.Matrix.Identity();
  78522. this.getRotationMatrixToRef(space, mesh, result);
  78523. return result;
  78524. };
  78525. /**
  78526. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78527. * @param space The space that the rotation should be in
  78528. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78529. * @param result The quaternion that the rotation should be copied to
  78530. */
  78531. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78532. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78533. if (space == BABYLON.Space.LOCAL) {
  78534. this.getLocalMatrix().getRotationMatrixToRef(result);
  78535. }
  78536. else {
  78537. var mat = Bone._tmpMats[0];
  78538. var amat = this.getAbsoluteTransform();
  78539. if (mesh) {
  78540. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78541. }
  78542. else {
  78543. mat.copyFrom(amat);
  78544. }
  78545. mat.m[0] *= this._scalingDeterminant;
  78546. mat.m[1] *= this._scalingDeterminant;
  78547. mat.m[2] *= this._scalingDeterminant;
  78548. mat.getRotationMatrixToRef(result);
  78549. }
  78550. };
  78551. /**
  78552. * Get the world position of a point that is in the local space of the bone
  78553. * @param position The local position
  78554. * @param mesh The mesh that this bone is attached to
  78555. * @returns The world position
  78556. */
  78557. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78558. if (mesh === void 0) { mesh = null; }
  78559. var result = BABYLON.Vector3.Zero();
  78560. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78561. return result;
  78562. };
  78563. /**
  78564. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78565. * @param position The local position
  78566. * @param mesh The mesh that this bone is attached to
  78567. * @param result The vector3 that the world position should be copied to
  78568. */
  78569. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78570. if (mesh === void 0) { mesh = null; }
  78571. var wm = null;
  78572. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78573. if (mesh) {
  78574. wm = mesh.getWorldMatrix();
  78575. }
  78576. this._skeleton.computeAbsoluteTransforms();
  78577. var tmat = Bone._tmpMats[0];
  78578. if (mesh && wm) {
  78579. tmat.copyFrom(this.getAbsoluteTransform());
  78580. tmat.multiplyToRef(wm, tmat);
  78581. }
  78582. else {
  78583. tmat = this.getAbsoluteTransform();
  78584. }
  78585. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78586. };
  78587. /**
  78588. * Get the local position of a point that is in world space
  78589. * @param position The world position
  78590. * @param mesh The mesh that this bone is attached to
  78591. * @returns The local position
  78592. */
  78593. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78594. if (mesh === void 0) { mesh = null; }
  78595. var result = BABYLON.Vector3.Zero();
  78596. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78597. return result;
  78598. };
  78599. /**
  78600. * Get the local position of a point that is in world space and copy it to the result param
  78601. * @param position The world position
  78602. * @param mesh The mesh that this bone is attached to
  78603. * @param result The vector3 that the local position should be copied to
  78604. */
  78605. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78606. if (mesh === void 0) { mesh = null; }
  78607. var wm = null;
  78608. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78609. if (mesh) {
  78610. wm = mesh.getWorldMatrix();
  78611. }
  78612. this._skeleton.computeAbsoluteTransforms();
  78613. var tmat = Bone._tmpMats[0];
  78614. tmat.copyFrom(this.getAbsoluteTransform());
  78615. if (mesh && wm) {
  78616. tmat.multiplyToRef(wm, tmat);
  78617. }
  78618. tmat.invert();
  78619. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78620. };
  78621. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78622. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78623. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78624. return Bone;
  78625. }(BABYLON.Node));
  78626. BABYLON.Bone = Bone;
  78627. })(BABYLON || (BABYLON = {}));
  78628. //# sourceMappingURL=babylon.bone.js.map
  78629. var BABYLON;
  78630. (function (BABYLON) {
  78631. /**
  78632. * Class used to apply inverse kinematics to bones
  78633. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78634. */
  78635. var BoneIKController = /** @class */ (function () {
  78636. /**
  78637. * Creates a new BoneIKController
  78638. * @param mesh defines the mesh to control
  78639. * @param bone defines the bone to control
  78640. * @param options defines options to set up the controller
  78641. */
  78642. function BoneIKController(mesh, bone, options) {
  78643. /**
  78644. * Gets or sets the target position
  78645. */
  78646. this.targetPosition = BABYLON.Vector3.Zero();
  78647. /**
  78648. * Gets or sets the pole target position
  78649. */
  78650. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78651. /**
  78652. * Gets or sets the pole target local offset
  78653. */
  78654. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78655. /**
  78656. * Gets or sets the pole angle
  78657. */
  78658. this.poleAngle = 0;
  78659. /**
  78660. * 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)
  78661. */
  78662. this.slerpAmount = 1;
  78663. this._bone1Quat = BABYLON.Quaternion.Identity();
  78664. this._bone1Mat = BABYLON.Matrix.Identity();
  78665. this._bone2Ang = Math.PI;
  78666. this._maxAngle = Math.PI;
  78667. this._rightHandedSystem = false;
  78668. this._bendAxis = BABYLON.Vector3.Right();
  78669. this._slerping = false;
  78670. this._adjustRoll = 0;
  78671. this._bone2 = bone;
  78672. this._bone1 = bone.getParent();
  78673. if (!this._bone1) {
  78674. return;
  78675. }
  78676. this.mesh = mesh;
  78677. var bonePos = bone.getPosition();
  78678. if (bone.getAbsoluteTransform().determinant() > 0) {
  78679. this._rightHandedSystem = true;
  78680. this._bendAxis.x = 0;
  78681. this._bendAxis.y = 0;
  78682. this._bendAxis.z = -1;
  78683. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78684. this._adjustRoll = Math.PI * .5;
  78685. this._bendAxis.z = 1;
  78686. }
  78687. }
  78688. if (this._bone1.length) {
  78689. var boneScale1 = this._bone1.getScale();
  78690. var boneScale2 = this._bone2.getScale();
  78691. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78692. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78693. }
  78694. else if (this._bone1.children[0]) {
  78695. mesh.computeWorldMatrix(true);
  78696. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78697. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78698. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78699. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78700. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78701. }
  78702. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78703. this.maxAngle = Math.PI;
  78704. if (options) {
  78705. if (options.targetMesh) {
  78706. this.targetMesh = options.targetMesh;
  78707. this.targetMesh.computeWorldMatrix(true);
  78708. }
  78709. if (options.poleTargetMesh) {
  78710. this.poleTargetMesh = options.poleTargetMesh;
  78711. this.poleTargetMesh.computeWorldMatrix(true);
  78712. }
  78713. else if (options.poleTargetBone) {
  78714. this.poleTargetBone = options.poleTargetBone;
  78715. }
  78716. else if (this._bone1.getParent()) {
  78717. this.poleTargetBone = this._bone1.getParent();
  78718. }
  78719. if (options.poleTargetLocalOffset) {
  78720. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78721. }
  78722. if (options.poleAngle) {
  78723. this.poleAngle = options.poleAngle;
  78724. }
  78725. if (options.bendAxis) {
  78726. this._bendAxis.copyFrom(options.bendAxis);
  78727. }
  78728. if (options.maxAngle) {
  78729. this.maxAngle = options.maxAngle;
  78730. }
  78731. if (options.slerpAmount) {
  78732. this.slerpAmount = options.slerpAmount;
  78733. }
  78734. }
  78735. }
  78736. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78737. /**
  78738. * Gets or sets maximum allowed angle
  78739. */
  78740. get: function () {
  78741. return this._maxAngle;
  78742. },
  78743. set: function (value) {
  78744. this._setMaxAngle(value);
  78745. },
  78746. enumerable: true,
  78747. configurable: true
  78748. });
  78749. BoneIKController.prototype._setMaxAngle = function (ang) {
  78750. if (ang < 0) {
  78751. ang = 0;
  78752. }
  78753. if (ang > Math.PI || ang == undefined) {
  78754. ang = Math.PI;
  78755. }
  78756. this._maxAngle = ang;
  78757. var a = this._bone1Length;
  78758. var b = this._bone2Length;
  78759. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78760. };
  78761. /**
  78762. * Force the controller to update the bones
  78763. */
  78764. BoneIKController.prototype.update = function () {
  78765. var bone1 = this._bone1;
  78766. if (!bone1) {
  78767. return;
  78768. }
  78769. var target = this.targetPosition;
  78770. var poleTarget = this.poleTargetPosition;
  78771. var mat1 = BoneIKController._tmpMats[0];
  78772. var mat2 = BoneIKController._tmpMats[1];
  78773. if (this.targetMesh) {
  78774. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78775. }
  78776. if (this.poleTargetBone) {
  78777. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78778. }
  78779. else if (this.poleTargetMesh) {
  78780. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78781. }
  78782. var bonePos = BoneIKController._tmpVecs[0];
  78783. var zaxis = BoneIKController._tmpVecs[1];
  78784. var xaxis = BoneIKController._tmpVecs[2];
  78785. var yaxis = BoneIKController._tmpVecs[3];
  78786. var upAxis = BoneIKController._tmpVecs[4];
  78787. var _tmpQuat = BoneIKController._tmpQuat;
  78788. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78789. poleTarget.subtractToRef(bonePos, upAxis);
  78790. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78791. upAxis.y = 1;
  78792. }
  78793. else {
  78794. upAxis.normalize();
  78795. }
  78796. target.subtractToRef(bonePos, yaxis);
  78797. yaxis.normalize();
  78798. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78799. zaxis.normalize();
  78800. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78801. xaxis.normalize();
  78802. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78803. var a = this._bone1Length;
  78804. var b = this._bone2Length;
  78805. var c = BABYLON.Vector3.Distance(bonePos, target);
  78806. if (this._maxReach > 0) {
  78807. c = Math.min(this._maxReach, c);
  78808. }
  78809. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78810. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78811. if (acosa > 1) {
  78812. acosa = 1;
  78813. }
  78814. if (acosb > 1) {
  78815. acosb = 1;
  78816. }
  78817. if (acosa < -1) {
  78818. acosa = -1;
  78819. }
  78820. if (acosb < -1) {
  78821. acosb = -1;
  78822. }
  78823. var angA = Math.acos(acosa);
  78824. var angB = Math.acos(acosb);
  78825. var angC = -angA - angB;
  78826. if (this._rightHandedSystem) {
  78827. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78828. mat2.multiplyToRef(mat1, mat1);
  78829. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78830. mat2.multiplyToRef(mat1, mat1);
  78831. }
  78832. else {
  78833. var _tmpVec = BoneIKController._tmpVecs[5];
  78834. _tmpVec.copyFrom(this._bendAxis);
  78835. _tmpVec.x *= -1;
  78836. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78837. mat2.multiplyToRef(mat1, mat1);
  78838. }
  78839. if (this.poleAngle) {
  78840. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78841. mat1.multiplyToRef(mat2, mat1);
  78842. }
  78843. if (this._bone1) {
  78844. if (this.slerpAmount < 1) {
  78845. if (!this._slerping) {
  78846. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78847. }
  78848. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78849. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78850. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78851. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78852. this._slerping = true;
  78853. }
  78854. else {
  78855. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78856. this._bone1Mat.copyFrom(mat1);
  78857. this._slerping = false;
  78858. }
  78859. }
  78860. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78861. this._bone2Ang = angC;
  78862. };
  78863. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78864. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78865. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78866. return BoneIKController;
  78867. }());
  78868. BABYLON.BoneIKController = BoneIKController;
  78869. })(BABYLON || (BABYLON = {}));
  78870. //# sourceMappingURL=babylon.boneIKController.js.map
  78871. var BABYLON;
  78872. (function (BABYLON) {
  78873. /**
  78874. * Class used to make a bone look toward a point in space
  78875. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78876. */
  78877. var BoneLookController = /** @class */ (function () {
  78878. /**
  78879. * Create a BoneLookController
  78880. * @param mesh the mesh that the bone belongs to
  78881. * @param bone the bone that will be looking to the target
  78882. * @param target the target Vector3 to look at
  78883. * @param settings optional settings:
  78884. * * maxYaw: the maximum angle the bone will yaw to
  78885. * * minYaw: the minimum angle the bone will yaw to
  78886. * * maxPitch: the maximum angle the bone will pitch to
  78887. * * minPitch: the minimum angle the bone will yaw to
  78888. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78889. * * upAxis: the up axis of the coordinate system
  78890. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78891. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78892. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78893. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78894. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78895. * * adjustRoll: used to make an adjustment to the roll of the bone
  78896. **/
  78897. function BoneLookController(mesh, bone, target, options) {
  78898. /**
  78899. * The up axis of the coordinate system that is used when the bone is rotated
  78900. */
  78901. this.upAxis = BABYLON.Vector3.Up();
  78902. /**
  78903. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78904. */
  78905. this.upAxisSpace = BABYLON.Space.LOCAL;
  78906. /**
  78907. * Used to make an adjustment to the yaw of the bone
  78908. */
  78909. this.adjustYaw = 0;
  78910. /**
  78911. * Used to make an adjustment to the pitch of the bone
  78912. */
  78913. this.adjustPitch = 0;
  78914. /**
  78915. * Used to make an adjustment to the roll of the bone
  78916. */
  78917. this.adjustRoll = 0;
  78918. /**
  78919. * 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)
  78920. */
  78921. this.slerpAmount = 1;
  78922. this._boneQuat = BABYLON.Quaternion.Identity();
  78923. this._slerping = false;
  78924. this._firstFrameSkipped = false;
  78925. this._fowardAxis = BABYLON.Vector3.Forward();
  78926. this.mesh = mesh;
  78927. this.bone = bone;
  78928. this.target = target;
  78929. if (options) {
  78930. if (options.adjustYaw) {
  78931. this.adjustYaw = options.adjustYaw;
  78932. }
  78933. if (options.adjustPitch) {
  78934. this.adjustPitch = options.adjustPitch;
  78935. }
  78936. if (options.adjustRoll) {
  78937. this.adjustRoll = options.adjustRoll;
  78938. }
  78939. if (options.maxYaw != null) {
  78940. this.maxYaw = options.maxYaw;
  78941. }
  78942. else {
  78943. this.maxYaw = Math.PI;
  78944. }
  78945. if (options.minYaw != null) {
  78946. this.minYaw = options.minYaw;
  78947. }
  78948. else {
  78949. this.minYaw = -Math.PI;
  78950. }
  78951. if (options.maxPitch != null) {
  78952. this.maxPitch = options.maxPitch;
  78953. }
  78954. else {
  78955. this.maxPitch = Math.PI;
  78956. }
  78957. if (options.minPitch != null) {
  78958. this.minPitch = options.minPitch;
  78959. }
  78960. else {
  78961. this.minPitch = -Math.PI;
  78962. }
  78963. if (options.slerpAmount != null) {
  78964. this.slerpAmount = options.slerpAmount;
  78965. }
  78966. if (options.upAxis != null) {
  78967. this.upAxis = options.upAxis;
  78968. }
  78969. if (options.upAxisSpace != null) {
  78970. this.upAxisSpace = options.upAxisSpace;
  78971. }
  78972. if (options.yawAxis != null || options.pitchAxis != null) {
  78973. var newYawAxis = BABYLON.Axis.Y;
  78974. var newPitchAxis = BABYLON.Axis.X;
  78975. if (options.yawAxis != null) {
  78976. newYawAxis = options.yawAxis.clone();
  78977. newYawAxis.normalize();
  78978. }
  78979. if (options.pitchAxis != null) {
  78980. newPitchAxis = options.pitchAxis.clone();
  78981. newPitchAxis.normalize();
  78982. }
  78983. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78984. this._transformYawPitch = BABYLON.Matrix.Identity();
  78985. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78986. this._transformYawPitchInv = this._transformYawPitch.clone();
  78987. this._transformYawPitch.invert();
  78988. }
  78989. }
  78990. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78991. this.upAxisSpace = BABYLON.Space.LOCAL;
  78992. }
  78993. }
  78994. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78995. /**
  78996. * Gets or sets the minimum yaw angle that the bone can look to
  78997. */
  78998. get: function () {
  78999. return this._minYaw;
  79000. },
  79001. set: function (value) {
  79002. this._minYaw = value;
  79003. this._minYawSin = Math.sin(value);
  79004. this._minYawCos = Math.cos(value);
  79005. if (this._maxYaw != null) {
  79006. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79007. this._yawRange = this._maxYaw - this._minYaw;
  79008. }
  79009. },
  79010. enumerable: true,
  79011. configurable: true
  79012. });
  79013. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79014. /**
  79015. * Gets or sets the maximum yaw angle that the bone can look to
  79016. */
  79017. get: function () {
  79018. return this._maxYaw;
  79019. },
  79020. set: function (value) {
  79021. this._maxYaw = value;
  79022. this._maxYawSin = Math.sin(value);
  79023. this._maxYawCos = Math.cos(value);
  79024. if (this._minYaw != null) {
  79025. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79026. this._yawRange = this._maxYaw - this._minYaw;
  79027. }
  79028. },
  79029. enumerable: true,
  79030. configurable: true
  79031. });
  79032. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79033. /**
  79034. * Gets or sets the minimum pitch angle that the bone can look to
  79035. */
  79036. get: function () {
  79037. return this._minPitch;
  79038. },
  79039. set: function (value) {
  79040. this._minPitch = value;
  79041. this._minPitchTan = Math.tan(value);
  79042. },
  79043. enumerable: true,
  79044. configurable: true
  79045. });
  79046. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79047. /**
  79048. * Gets or sets the maximum pitch angle that the bone can look to
  79049. */
  79050. get: function () {
  79051. return this._maxPitch;
  79052. },
  79053. set: function (value) {
  79054. this._maxPitch = value;
  79055. this._maxPitchTan = Math.tan(value);
  79056. },
  79057. enumerable: true,
  79058. configurable: true
  79059. });
  79060. /**
  79061. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79062. */
  79063. BoneLookController.prototype.update = function () {
  79064. //skip the first frame when slerping so that the mesh rotation is correct
  79065. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79066. this._firstFrameSkipped = true;
  79067. return;
  79068. }
  79069. var bone = this.bone;
  79070. var bonePos = BoneLookController._tmpVecs[0];
  79071. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79072. var target = this.target;
  79073. var _tmpMat1 = BoneLookController._tmpMats[0];
  79074. var _tmpMat2 = BoneLookController._tmpMats[1];
  79075. var mesh = this.mesh;
  79076. var parentBone = bone.getParent();
  79077. var upAxis = BoneLookController._tmpVecs[1];
  79078. upAxis.copyFrom(this.upAxis);
  79079. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79080. if (this._transformYawPitch) {
  79081. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79082. }
  79083. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79084. }
  79085. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79086. mesh.getDirectionToRef(upAxis, upAxis);
  79087. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79088. upAxis.normalize();
  79089. }
  79090. }
  79091. var checkYaw = false;
  79092. var checkPitch = false;
  79093. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79094. checkYaw = true;
  79095. }
  79096. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79097. checkPitch = true;
  79098. }
  79099. if (checkYaw || checkPitch) {
  79100. var spaceMat = BoneLookController._tmpMats[2];
  79101. var spaceMatInv = BoneLookController._tmpMats[3];
  79102. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79103. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79104. }
  79105. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79106. spaceMat.copyFrom(mesh.getWorldMatrix());
  79107. }
  79108. else {
  79109. var forwardAxis = BoneLookController._tmpVecs[2];
  79110. forwardAxis.copyFrom(this._fowardAxis);
  79111. if (this._transformYawPitch) {
  79112. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79113. }
  79114. if (parentBone) {
  79115. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79116. }
  79117. else {
  79118. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79119. }
  79120. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79121. rightAxis.normalize();
  79122. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79123. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79124. }
  79125. spaceMat.invertToRef(spaceMatInv);
  79126. var xzlen = null;
  79127. if (checkPitch) {
  79128. var localTarget = BoneLookController._tmpVecs[3];
  79129. target.subtractToRef(bonePos, localTarget);
  79130. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79131. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79132. var pitch = Math.atan2(localTarget.y, xzlen);
  79133. var newPitch = pitch;
  79134. if (pitch > this._maxPitch) {
  79135. localTarget.y = this._maxPitchTan * xzlen;
  79136. newPitch = this._maxPitch;
  79137. }
  79138. else if (pitch < this._minPitch) {
  79139. localTarget.y = this._minPitchTan * xzlen;
  79140. newPitch = this._minPitch;
  79141. }
  79142. if (pitch != newPitch) {
  79143. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79144. localTarget.addInPlace(bonePos);
  79145. target = localTarget;
  79146. }
  79147. }
  79148. if (checkYaw) {
  79149. var localTarget = BoneLookController._tmpVecs[4];
  79150. target.subtractToRef(bonePos, localTarget);
  79151. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79152. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79153. var newYaw = yaw;
  79154. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79155. if (xzlen == null) {
  79156. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79157. }
  79158. if (this._yawRange > Math.PI) {
  79159. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79160. localTarget.z = this._maxYawCos * xzlen;
  79161. localTarget.x = this._maxYawSin * xzlen;
  79162. newYaw = this._maxYaw;
  79163. }
  79164. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79165. localTarget.z = this._minYawCos * xzlen;
  79166. localTarget.x = this._minYawSin * xzlen;
  79167. newYaw = this._minYaw;
  79168. }
  79169. }
  79170. else {
  79171. if (yaw > this._maxYaw) {
  79172. localTarget.z = this._maxYawCos * xzlen;
  79173. localTarget.x = this._maxYawSin * xzlen;
  79174. newYaw = this._maxYaw;
  79175. }
  79176. else if (yaw < this._minYaw) {
  79177. localTarget.z = this._minYawCos * xzlen;
  79178. localTarget.x = this._minYawSin * xzlen;
  79179. newYaw = this._minYaw;
  79180. }
  79181. }
  79182. }
  79183. if (this._slerping && this._yawRange > Math.PI) {
  79184. //are we going to be crossing into the min/max region?
  79185. var boneFwd = BoneLookController._tmpVecs[8];
  79186. boneFwd.copyFrom(BABYLON.Axis.Z);
  79187. if (this._transformYawPitch) {
  79188. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79189. }
  79190. var boneRotMat = BoneLookController._tmpMats[4];
  79191. this._boneQuat.toRotationMatrix(boneRotMat);
  79192. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79193. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79194. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79195. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79196. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79197. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79198. if (angBtwTar > angBtwMidYaw) {
  79199. if (xzlen == null) {
  79200. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79201. }
  79202. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79203. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79204. if (angBtwMin < angBtwMax) {
  79205. newYaw = boneYaw + Math.PI * .75;
  79206. localTarget.z = Math.cos(newYaw) * xzlen;
  79207. localTarget.x = Math.sin(newYaw) * xzlen;
  79208. }
  79209. else {
  79210. newYaw = boneYaw - Math.PI * .75;
  79211. localTarget.z = Math.cos(newYaw) * xzlen;
  79212. localTarget.x = Math.sin(newYaw) * xzlen;
  79213. }
  79214. }
  79215. }
  79216. if (yaw != newYaw) {
  79217. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79218. localTarget.addInPlace(bonePos);
  79219. target = localTarget;
  79220. }
  79221. }
  79222. }
  79223. var zaxis = BoneLookController._tmpVecs[5];
  79224. var xaxis = BoneLookController._tmpVecs[6];
  79225. var yaxis = BoneLookController._tmpVecs[7];
  79226. var _tmpQuat = BoneLookController._tmpQuat;
  79227. target.subtractToRef(bonePos, zaxis);
  79228. zaxis.normalize();
  79229. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79230. xaxis.normalize();
  79231. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79232. yaxis.normalize();
  79233. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79234. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79235. return;
  79236. }
  79237. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79238. return;
  79239. }
  79240. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79241. return;
  79242. }
  79243. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79244. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79245. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79246. }
  79247. if (this.slerpAmount < 1) {
  79248. if (!this._slerping) {
  79249. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79250. }
  79251. if (this._transformYawPitch) {
  79252. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79253. }
  79254. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79255. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79256. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79257. this._slerping = true;
  79258. }
  79259. else {
  79260. if (this._transformYawPitch) {
  79261. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79262. }
  79263. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79264. this._slerping = false;
  79265. }
  79266. };
  79267. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79268. var angDiff = ang2 - ang1;
  79269. angDiff %= Math.PI * 2;
  79270. if (angDiff > Math.PI) {
  79271. angDiff -= Math.PI * 2;
  79272. }
  79273. else if (angDiff < -Math.PI) {
  79274. angDiff += Math.PI * 2;
  79275. }
  79276. return angDiff;
  79277. };
  79278. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79279. ang1 %= (2 * Math.PI);
  79280. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79281. ang2 %= (2 * Math.PI);
  79282. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79283. var ab = 0;
  79284. if (ang1 < ang2) {
  79285. ab = ang2 - ang1;
  79286. }
  79287. else {
  79288. ab = ang1 - ang2;
  79289. }
  79290. if (ab > Math.PI) {
  79291. ab = Math.PI * 2 - ab;
  79292. }
  79293. return ab;
  79294. };
  79295. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79296. ang %= (2 * Math.PI);
  79297. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79298. ang1 %= (2 * Math.PI);
  79299. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79300. ang2 %= (2 * Math.PI);
  79301. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79302. if (ang1 < ang2) {
  79303. if (ang > ang1 && ang < ang2) {
  79304. return true;
  79305. }
  79306. }
  79307. else {
  79308. if (ang > ang2 && ang < ang1) {
  79309. return true;
  79310. }
  79311. }
  79312. return false;
  79313. };
  79314. 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()];
  79315. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79316. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79317. return BoneLookController;
  79318. }());
  79319. BABYLON.BoneLookController = BoneLookController;
  79320. })(BABYLON || (BABYLON = {}));
  79321. //# sourceMappingURL=babylon.boneLookController.js.map
  79322. var BABYLON;
  79323. (function (BABYLON) {
  79324. /**
  79325. * Class used to handle skinning animations
  79326. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79327. */
  79328. var Skeleton = /** @class */ (function () {
  79329. /**
  79330. * Creates a new skeleton
  79331. * @param name defines the skeleton name
  79332. * @param id defines the skeleton Id
  79333. * @param scene defines the hosting scene
  79334. */
  79335. function Skeleton(
  79336. /** defines the skeleton name */
  79337. name,
  79338. /** defines the skeleton Id */
  79339. id, scene) {
  79340. this.name = name;
  79341. this.id = id;
  79342. /**
  79343. * Gets the list of child bones
  79344. */
  79345. this.bones = new Array();
  79346. /**
  79347. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79348. */
  79349. this.needInitialSkinMatrix = false;
  79350. this._isDirty = true;
  79351. this._meshesWithPoseMatrix = new Array();
  79352. this._identity = BABYLON.Matrix.Identity();
  79353. this._ranges = {};
  79354. this._lastAbsoluteTransformsUpdateId = -1;
  79355. /**
  79356. * Specifies if the skeleton should be serialized
  79357. */
  79358. this.doNotSerialize = false;
  79359. this._animationPropertiesOverride = null;
  79360. // Events
  79361. /**
  79362. * An observable triggered before computing the skeleton's matrices
  79363. */
  79364. this.onBeforeComputeObservable = new BABYLON.Observable();
  79365. this.bones = [];
  79366. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79367. scene.skeletons.push(this);
  79368. //make sure it will recalculate the matrix next time prepare is called.
  79369. this._isDirty = true;
  79370. }
  79371. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79372. /**
  79373. * Gets or sets the animation properties override
  79374. */
  79375. get: function () {
  79376. if (!this._animationPropertiesOverride) {
  79377. return this._scene.animationPropertiesOverride;
  79378. }
  79379. return this._animationPropertiesOverride;
  79380. },
  79381. set: function (value) {
  79382. this._animationPropertiesOverride = value;
  79383. },
  79384. enumerable: true,
  79385. configurable: true
  79386. });
  79387. // Members
  79388. /**
  79389. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79390. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79391. * @returns a Float32Array containing matrices data
  79392. */
  79393. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79394. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79395. return mesh._bonesTransformMatrices;
  79396. }
  79397. if (!this._transformMatrices) {
  79398. this.prepare();
  79399. }
  79400. return this._transformMatrices;
  79401. };
  79402. /**
  79403. * Gets the current hosting scene
  79404. * @returns a scene object
  79405. */
  79406. Skeleton.prototype.getScene = function () {
  79407. return this._scene;
  79408. };
  79409. // Methods
  79410. /**
  79411. * Gets a string representing the current skeleton data
  79412. * @param fullDetails defines a boolean indicating if we want a verbose version
  79413. * @returns a string representing the current skeleton data
  79414. */
  79415. Skeleton.prototype.toString = function (fullDetails) {
  79416. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79417. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79418. if (fullDetails) {
  79419. ret += ", Ranges: {";
  79420. var first = true;
  79421. for (var name_1 in this._ranges) {
  79422. if (first) {
  79423. ret += ", ";
  79424. first = false;
  79425. }
  79426. ret += name_1;
  79427. }
  79428. ret += "}";
  79429. }
  79430. return ret;
  79431. };
  79432. /**
  79433. * Get bone's index searching by name
  79434. * @param name defines bone's name to search for
  79435. * @return the indice of the bone. Returns -1 if not found
  79436. */
  79437. Skeleton.prototype.getBoneIndexByName = function (name) {
  79438. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79439. if (this.bones[boneIndex].name === name) {
  79440. return boneIndex;
  79441. }
  79442. }
  79443. return -1;
  79444. };
  79445. /**
  79446. * Creater a new animation range
  79447. * @param name defines the name of the range
  79448. * @param from defines the start key
  79449. * @param to defines the end key
  79450. */
  79451. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79452. // check name not already in use
  79453. if (!this._ranges[name]) {
  79454. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79455. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79456. if (this.bones[i].animations[0]) {
  79457. this.bones[i].animations[0].createRange(name, from, to);
  79458. }
  79459. }
  79460. }
  79461. };
  79462. /**
  79463. * Delete a specific animation range
  79464. * @param name defines the name of the range
  79465. * @param deleteFrames defines if frames must be removed as well
  79466. */
  79467. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79468. if (deleteFrames === void 0) { deleteFrames = true; }
  79469. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79470. if (this.bones[i].animations[0]) {
  79471. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79472. }
  79473. }
  79474. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79475. };
  79476. /**
  79477. * Gets a specific animation range
  79478. * @param name defines the name of the range to look for
  79479. * @returns the requested animation range or null if not found
  79480. */
  79481. Skeleton.prototype.getAnimationRange = function (name) {
  79482. return this._ranges[name];
  79483. };
  79484. /**
  79485. * Gets the list of all animation ranges defined on this skeleton
  79486. * @returns an array
  79487. */
  79488. Skeleton.prototype.getAnimationRanges = function () {
  79489. var animationRanges = [];
  79490. var name;
  79491. var i = 0;
  79492. for (name in this._ranges) {
  79493. animationRanges[i] = this._ranges[name];
  79494. i++;
  79495. }
  79496. return animationRanges;
  79497. };
  79498. /**
  79499. * Copy animation range from a source skeleton.
  79500. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79501. * @param source defines the source skeleton
  79502. * @param name defines the name of the range to copy
  79503. * @param rescaleAsRequired defines if rescaling must be applied if required
  79504. * @returns true if operation was successful
  79505. */
  79506. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79507. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79508. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79509. return false;
  79510. }
  79511. var ret = true;
  79512. var frameOffset = this._getHighestAnimationFrame() + 1;
  79513. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79514. var boneDict = {};
  79515. var sourceBones = source.bones;
  79516. var nBones;
  79517. var i;
  79518. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79519. boneDict[sourceBones[i].name] = sourceBones[i];
  79520. }
  79521. if (this.bones.length !== sourceBones.length) {
  79522. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79523. ret = false;
  79524. }
  79525. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79526. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79527. var boneName = this.bones[i].name;
  79528. var sourceBone = boneDict[boneName];
  79529. if (sourceBone) {
  79530. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79531. }
  79532. else {
  79533. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79534. ret = false;
  79535. }
  79536. }
  79537. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79538. var range = source.getAnimationRange(name);
  79539. if (range) {
  79540. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79541. }
  79542. return ret;
  79543. };
  79544. /**
  79545. * Forces the skeleton to go to rest pose
  79546. */
  79547. Skeleton.prototype.returnToRest = function () {
  79548. for (var index = 0; index < this.bones.length; index++) {
  79549. this.bones[index].returnToRest();
  79550. }
  79551. };
  79552. Skeleton.prototype._getHighestAnimationFrame = function () {
  79553. var ret = 0;
  79554. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79555. if (this.bones[i].animations[0]) {
  79556. var highest = this.bones[i].animations[0].getHighestFrame();
  79557. if (ret < highest) {
  79558. ret = highest;
  79559. }
  79560. }
  79561. }
  79562. return ret;
  79563. };
  79564. /**
  79565. * Begin a specific animation range
  79566. * @param name defines the name of the range to start
  79567. * @param loop defines if looping must be turned on (false by default)
  79568. * @param speedRatio defines the speed ratio to apply (1 by default)
  79569. * @param onAnimationEnd defines a callback which will be called when animation will end
  79570. * @returns a new animatable
  79571. */
  79572. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79573. var range = this.getAnimationRange(name);
  79574. if (!range) {
  79575. return null;
  79576. }
  79577. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79578. };
  79579. /** @hidden */
  79580. Skeleton.prototype._markAsDirty = function () {
  79581. this._isDirty = true;
  79582. };
  79583. /** @hidden */
  79584. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79585. this._meshesWithPoseMatrix.push(mesh);
  79586. };
  79587. /** @hidden */
  79588. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79589. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79590. if (index > -1) {
  79591. this._meshesWithPoseMatrix.splice(index, 1);
  79592. }
  79593. };
  79594. /** @hidden */
  79595. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79596. this.onBeforeComputeObservable.notifyObservers(this);
  79597. for (var index = 0; index < this.bones.length; index++) {
  79598. var bone = this.bones[index];
  79599. var parentBone = bone.getParent();
  79600. if (parentBone) {
  79601. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79602. }
  79603. else {
  79604. if (initialSkinMatrix) {
  79605. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79606. }
  79607. else {
  79608. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79609. }
  79610. }
  79611. if (bone._index !== -1) {
  79612. var mappedIndex = bone._index === null ? index : bone._index;
  79613. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79614. }
  79615. }
  79616. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79617. };
  79618. /**
  79619. * Build all resources required to render a skeleton
  79620. */
  79621. Skeleton.prototype.prepare = function () {
  79622. if (!this._isDirty) {
  79623. return;
  79624. }
  79625. if (this.needInitialSkinMatrix) {
  79626. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79627. var mesh = this._meshesWithPoseMatrix[index];
  79628. var poseMatrix = mesh.getPoseMatrix();
  79629. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79630. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79631. }
  79632. if (this._synchronizedWithMesh !== mesh) {
  79633. this._synchronizedWithMesh = mesh;
  79634. // Prepare bones
  79635. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79636. var bone = this.bones[boneIndex];
  79637. if (!bone.getParent()) {
  79638. var matrix = bone.getBaseMatrix();
  79639. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79640. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79641. }
  79642. }
  79643. }
  79644. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79645. }
  79646. }
  79647. else {
  79648. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79649. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79650. }
  79651. this._computeTransformMatrices(this._transformMatrices, null);
  79652. }
  79653. this._isDirty = false;
  79654. this._scene._activeBones.addCount(this.bones.length, false);
  79655. };
  79656. /**
  79657. * Gets the list of animatables currently running for this skeleton
  79658. * @returns an array of animatables
  79659. */
  79660. Skeleton.prototype.getAnimatables = function () {
  79661. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79662. this._animatables = [];
  79663. for (var index = 0; index < this.bones.length; index++) {
  79664. this._animatables.push(this.bones[index]);
  79665. }
  79666. }
  79667. return this._animatables;
  79668. };
  79669. /**
  79670. * Clone the current skeleton
  79671. * @param name defines the name of the new skeleton
  79672. * @param id defines the id of the enw skeleton
  79673. * @returns the new skeleton
  79674. */
  79675. Skeleton.prototype.clone = function (name, id) {
  79676. var result = new Skeleton(name, id || name, this._scene);
  79677. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79678. for (var index = 0; index < this.bones.length; index++) {
  79679. var source = this.bones[index];
  79680. var parentBone = null;
  79681. var parent_1 = source.getParent();
  79682. if (parent_1) {
  79683. var parentIndex = this.bones.indexOf(parent_1);
  79684. parentBone = result.bones[parentIndex];
  79685. }
  79686. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79687. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79688. }
  79689. if (this._ranges) {
  79690. result._ranges = {};
  79691. for (var rangeName in this._ranges) {
  79692. var range = this._ranges[rangeName];
  79693. if (range) {
  79694. result._ranges[rangeName] = range.clone();
  79695. }
  79696. }
  79697. }
  79698. this._isDirty = true;
  79699. return result;
  79700. };
  79701. /**
  79702. * Enable animation blending for this skeleton
  79703. * @param blendingSpeed defines the blending speed to apply
  79704. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79705. */
  79706. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79707. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79708. this.bones.forEach(function (bone) {
  79709. bone.animations.forEach(function (animation) {
  79710. animation.enableBlending = true;
  79711. animation.blendingSpeed = blendingSpeed;
  79712. });
  79713. });
  79714. };
  79715. /**
  79716. * Releases all resources associated with the current skeleton
  79717. */
  79718. Skeleton.prototype.dispose = function () {
  79719. this._meshesWithPoseMatrix = [];
  79720. // Animations
  79721. this.getScene().stopAnimation(this);
  79722. // Remove from scene
  79723. this.getScene().removeSkeleton(this);
  79724. };
  79725. /**
  79726. * Serialize the skeleton in a JSON object
  79727. * @returns a JSON object
  79728. */
  79729. Skeleton.prototype.serialize = function () {
  79730. var serializationObject = {};
  79731. serializationObject.name = this.name;
  79732. serializationObject.id = this.id;
  79733. if (this.dimensionsAtRest) {
  79734. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79735. }
  79736. serializationObject.bones = [];
  79737. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79738. for (var index = 0; index < this.bones.length; index++) {
  79739. var bone = this.bones[index];
  79740. var parent_2 = bone.getParent();
  79741. var serializedBone = {
  79742. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79743. name: bone.name,
  79744. matrix: bone.getBaseMatrix().toArray(),
  79745. rest: bone.getRestPose().toArray()
  79746. };
  79747. serializationObject.bones.push(serializedBone);
  79748. if (bone.length) {
  79749. serializedBone.length = bone.length;
  79750. }
  79751. if (bone.metadata) {
  79752. serializedBone.metadata = bone.metadata;
  79753. }
  79754. if (bone.animations && bone.animations.length > 0) {
  79755. serializedBone.animation = bone.animations[0].serialize();
  79756. }
  79757. serializationObject.ranges = [];
  79758. for (var name in this._ranges) {
  79759. var source = this._ranges[name];
  79760. if (!source) {
  79761. continue;
  79762. }
  79763. var range = {};
  79764. range.name = name;
  79765. range.from = source.from;
  79766. range.to = source.to;
  79767. serializationObject.ranges.push(range);
  79768. }
  79769. }
  79770. return serializationObject;
  79771. };
  79772. /**
  79773. * Creates a new skeleton from serialized data
  79774. * @param parsedSkeleton defines the serialized data
  79775. * @param scene defines the hosting scene
  79776. * @returns a new skeleton
  79777. */
  79778. Skeleton.Parse = function (parsedSkeleton, scene) {
  79779. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79780. if (parsedSkeleton.dimensionsAtRest) {
  79781. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79782. }
  79783. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79784. var index;
  79785. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79786. var parsedBone = parsedSkeleton.bones[index];
  79787. var parentBone = null;
  79788. if (parsedBone.parentBoneIndex > -1) {
  79789. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79790. }
  79791. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79792. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79793. if (parsedBone.length) {
  79794. bone.length = parsedBone.length;
  79795. }
  79796. if (parsedBone.metadata) {
  79797. bone.metadata = parsedBone.metadata;
  79798. }
  79799. if (parsedBone.animation) {
  79800. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79801. }
  79802. }
  79803. // placed after bones, so createAnimationRange can cascade down
  79804. if (parsedSkeleton.ranges) {
  79805. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79806. var data = parsedSkeleton.ranges[index];
  79807. skeleton.createAnimationRange(data.name, data.from, data.to);
  79808. }
  79809. }
  79810. return skeleton;
  79811. };
  79812. /**
  79813. * Compute all node absolute transforms
  79814. * @param forceUpdate defines if computation must be done even if cache is up to date
  79815. */
  79816. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79817. if (forceUpdate === void 0) { forceUpdate = false; }
  79818. var renderId = this._scene.getRenderId();
  79819. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79820. this.bones[0].computeAbsoluteTransforms();
  79821. this._lastAbsoluteTransformsUpdateId = renderId;
  79822. }
  79823. };
  79824. /**
  79825. * Gets the root pose matrix
  79826. * @returns a matrix
  79827. */
  79828. Skeleton.prototype.getPoseMatrix = function () {
  79829. var poseMatrix = null;
  79830. if (this._meshesWithPoseMatrix.length > 0) {
  79831. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79832. }
  79833. return poseMatrix;
  79834. };
  79835. /**
  79836. * Sorts bones per internal index
  79837. */
  79838. Skeleton.prototype.sortBones = function () {
  79839. var bones = new Array();
  79840. var visited = new Array(this.bones.length);
  79841. for (var index = 0; index < this.bones.length; index++) {
  79842. this._sortBones(index, bones, visited);
  79843. }
  79844. this.bones = bones;
  79845. };
  79846. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79847. if (visited[index]) {
  79848. return;
  79849. }
  79850. visited[index] = true;
  79851. var bone = this.bones[index];
  79852. if (bone._index === undefined) {
  79853. bone._index = index;
  79854. }
  79855. var parentBone = bone.getParent();
  79856. if (parentBone) {
  79857. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79858. }
  79859. bones.push(bone);
  79860. };
  79861. return Skeleton;
  79862. }());
  79863. BABYLON.Skeleton = Skeleton;
  79864. })(BABYLON || (BABYLON = {}));
  79865. //# sourceMappingURL=babylon.skeleton.js.map
  79866. var BABYLON;
  79867. (function (BABYLON) {
  79868. var SphericalPolynomial = /** @class */ (function () {
  79869. function SphericalPolynomial() {
  79870. this.x = BABYLON.Vector3.Zero();
  79871. this.y = BABYLON.Vector3.Zero();
  79872. this.z = BABYLON.Vector3.Zero();
  79873. this.xx = BABYLON.Vector3.Zero();
  79874. this.yy = BABYLON.Vector3.Zero();
  79875. this.zz = BABYLON.Vector3.Zero();
  79876. this.xy = BABYLON.Vector3.Zero();
  79877. this.yz = BABYLON.Vector3.Zero();
  79878. this.zx = BABYLON.Vector3.Zero();
  79879. }
  79880. SphericalPolynomial.prototype.addAmbient = function (color) {
  79881. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79882. this.xx = this.xx.add(colorVector);
  79883. this.yy = this.yy.add(colorVector);
  79884. this.zz = this.zz.add(colorVector);
  79885. };
  79886. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79887. var result = new SphericalPolynomial();
  79888. result.x = harmonics.L11.scale(1.02333);
  79889. result.y = harmonics.L1_1.scale(1.02333);
  79890. result.z = harmonics.L10.scale(1.02333);
  79891. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79892. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79893. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79894. result.yz = harmonics.L2_1.scale(0.858086);
  79895. result.zx = harmonics.L21.scale(0.858086);
  79896. result.xy = harmonics.L2_2.scale(0.858086);
  79897. result.scale(1.0 / Math.PI);
  79898. return result;
  79899. };
  79900. SphericalPolynomial.prototype.scale = function (scale) {
  79901. this.x = this.x.scale(scale);
  79902. this.y = this.y.scale(scale);
  79903. this.z = this.z.scale(scale);
  79904. this.xx = this.xx.scale(scale);
  79905. this.yy = this.yy.scale(scale);
  79906. this.zz = this.zz.scale(scale);
  79907. this.yz = this.yz.scale(scale);
  79908. this.zx = this.zx.scale(scale);
  79909. this.xy = this.xy.scale(scale);
  79910. };
  79911. return SphericalPolynomial;
  79912. }());
  79913. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79914. var SphericalHarmonics = /** @class */ (function () {
  79915. function SphericalHarmonics() {
  79916. this.L00 = BABYLON.Vector3.Zero();
  79917. this.L1_1 = BABYLON.Vector3.Zero();
  79918. this.L10 = BABYLON.Vector3.Zero();
  79919. this.L11 = BABYLON.Vector3.Zero();
  79920. this.L2_2 = BABYLON.Vector3.Zero();
  79921. this.L2_1 = BABYLON.Vector3.Zero();
  79922. this.L20 = BABYLON.Vector3.Zero();
  79923. this.L21 = BABYLON.Vector3.Zero();
  79924. this.L22 = BABYLON.Vector3.Zero();
  79925. }
  79926. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79927. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79928. var c = colorVector.scale(deltaSolidAngle);
  79929. this.L00 = this.L00.add(c.scale(0.282095));
  79930. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79931. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79932. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79933. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79934. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79935. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79936. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79937. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79938. };
  79939. SphericalHarmonics.prototype.scale = function (scale) {
  79940. this.L00 = this.L00.scale(scale);
  79941. this.L1_1 = this.L1_1.scale(scale);
  79942. this.L10 = this.L10.scale(scale);
  79943. this.L11 = this.L11.scale(scale);
  79944. this.L2_2 = this.L2_2.scale(scale);
  79945. this.L2_1 = this.L2_1.scale(scale);
  79946. this.L20 = this.L20.scale(scale);
  79947. this.L21 = this.L21.scale(scale);
  79948. this.L22 = this.L22.scale(scale);
  79949. };
  79950. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79951. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79952. //
  79953. // E_lm = A_l * L_lm
  79954. //
  79955. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79956. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79957. // the scaling factors are given in equation 9.
  79958. // Constant (Band 0)
  79959. this.L00 = this.L00.scale(3.141593);
  79960. // Linear (Band 1)
  79961. this.L1_1 = this.L1_1.scale(2.094395);
  79962. this.L10 = this.L10.scale(2.094395);
  79963. this.L11 = this.L11.scale(2.094395);
  79964. // Quadratic (Band 2)
  79965. this.L2_2 = this.L2_2.scale(0.785398);
  79966. this.L2_1 = this.L2_1.scale(0.785398);
  79967. this.L20 = this.L20.scale(0.785398);
  79968. this.L21 = this.L21.scale(0.785398);
  79969. this.L22 = this.L22.scale(0.785398);
  79970. };
  79971. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79972. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79973. // L = (1/pi) * E * rho
  79974. //
  79975. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79976. this.scale(1.0 / Math.PI);
  79977. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79978. // (The pixel shader must apply albedo after texture fetches, etc).
  79979. };
  79980. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79981. var result = new SphericalHarmonics();
  79982. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79983. result.L1_1 = polynomial.y.scale(0.977204);
  79984. result.L10 = polynomial.z.scale(0.977204);
  79985. result.L11 = polynomial.x.scale(0.977204);
  79986. result.L2_2 = polynomial.xy.scale(1.16538);
  79987. result.L2_1 = polynomial.yz.scale(1.16538);
  79988. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79989. result.L21 = polynomial.zx.scale(1.16538);
  79990. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79991. result.scale(Math.PI);
  79992. return result;
  79993. };
  79994. return SphericalHarmonics;
  79995. }());
  79996. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79997. })(BABYLON || (BABYLON = {}));
  79998. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79999. var BABYLON;
  80000. (function (BABYLON) {
  80001. var FileFaceOrientation = /** @class */ (function () {
  80002. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80003. this.name = name;
  80004. this.worldAxisForNormal = worldAxisForNormal;
  80005. this.worldAxisForFileX = worldAxisForFileX;
  80006. this.worldAxisForFileY = worldAxisForFileY;
  80007. }
  80008. return FileFaceOrientation;
  80009. }());
  80010. ;
  80011. /**
  80012. * Helper class dealing with the extraction of spherical polynomial dataArray
  80013. * from a cube map.
  80014. */
  80015. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80016. function CubeMapToSphericalPolynomialTools() {
  80017. }
  80018. /**
  80019. * Converts a texture to the according Spherical Polynomial data.
  80020. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80021. *
  80022. * @param texture The texture to extract the information from.
  80023. * @return The Spherical Polynomial data.
  80024. */
  80025. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80026. if (!texture.isCube) {
  80027. // Only supports cube Textures currently.
  80028. return null;
  80029. }
  80030. var size = texture.getSize().width;
  80031. var right = texture.readPixels(0);
  80032. var left = texture.readPixels(1);
  80033. var up;
  80034. var down;
  80035. if (texture.isRenderTarget) {
  80036. up = texture.readPixels(3);
  80037. down = texture.readPixels(2);
  80038. }
  80039. else {
  80040. up = texture.readPixels(2);
  80041. down = texture.readPixels(3);
  80042. }
  80043. var front = texture.readPixels(4);
  80044. var back = texture.readPixels(5);
  80045. var gammaSpace = texture.gammaSpace;
  80046. // Always read as RGBA.
  80047. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80048. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80049. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80050. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80051. }
  80052. var cubeInfo = {
  80053. size: size,
  80054. right: right,
  80055. left: left,
  80056. up: up,
  80057. down: down,
  80058. front: front,
  80059. back: back,
  80060. format: format,
  80061. type: type,
  80062. gammaSpace: gammaSpace,
  80063. };
  80064. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80065. };
  80066. /**
  80067. * Converts a cubemap to the according Spherical Polynomial data.
  80068. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80069. *
  80070. * @param cubeInfo The Cube map to extract the information from.
  80071. * @return The Spherical Polynomial data.
  80072. */
  80073. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80074. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80075. var totalSolidAngle = 0.0;
  80076. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80077. var du = 2.0 / cubeInfo.size;
  80078. var dv = du;
  80079. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80080. var minUV = du * 0.5 - 1.0;
  80081. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80082. var fileFace = this.FileFaces[faceIndex];
  80083. var dataArray = cubeInfo[fileFace.name];
  80084. var v = minUV;
  80085. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80086. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80087. // Because SP is still linear, so summation is fine in that basis.
  80088. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80089. for (var y = 0; y < cubeInfo.size; y++) {
  80090. var u = minUV;
  80091. for (var x = 0; x < cubeInfo.size; x++) {
  80092. // World direction (not normalised)
  80093. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80094. worldDirection.normalize();
  80095. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80096. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80097. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80098. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80099. // Handle Integer types.
  80100. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80101. r /= 255;
  80102. g /= 255;
  80103. b /= 255;
  80104. }
  80105. // Handle Gamma space textures.
  80106. if (cubeInfo.gammaSpace) {
  80107. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80108. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80109. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80110. }
  80111. var color = new BABYLON.Color3(r, g, b);
  80112. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80113. totalSolidAngle += deltaSolidAngle;
  80114. u += du;
  80115. }
  80116. v += dv;
  80117. }
  80118. }
  80119. // Solid angle for entire sphere is 4*pi
  80120. var sphereSolidAngle = 4.0 * Math.PI;
  80121. // Adjust the solid angle to allow for how many faces we processed.
  80122. var facesProcessed = 6.0;
  80123. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80124. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80125. // This is needed because the numerical integration over the cube uses a
  80126. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80127. // and also to compensate for accumulative error due to float precision in the summation.
  80128. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80129. sphericalHarmonics.scale(correctionFactor);
  80130. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80131. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80132. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80133. };
  80134. CubeMapToSphericalPolynomialTools.FileFaces = [
  80135. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80136. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80137. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80138. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80139. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80140. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80141. ];
  80142. return CubeMapToSphericalPolynomialTools;
  80143. }());
  80144. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80145. })(BABYLON || (BABYLON = {}));
  80146. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80147. var BABYLON;
  80148. (function (BABYLON) {
  80149. /**
  80150. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80151. */
  80152. var PanoramaToCubeMapTools = /** @class */ (function () {
  80153. function PanoramaToCubeMapTools() {
  80154. }
  80155. /**
  80156. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80157. *
  80158. * @param float32Array The source data.
  80159. * @param inputWidth The width of the input panorama.
  80160. * @param inputhHeight The height of the input panorama.
  80161. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80162. * @return The cubemap data
  80163. */
  80164. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80165. if (!float32Array) {
  80166. throw "ConvertPanoramaToCubemap: input cannot be null";
  80167. }
  80168. if (float32Array.length != inputWidth * inputHeight * 3) {
  80169. throw "ConvertPanoramaToCubemap: input size is wrong";
  80170. }
  80171. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80172. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80173. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80174. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80175. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80176. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80177. return {
  80178. front: textureFront,
  80179. back: textureBack,
  80180. left: textureLeft,
  80181. right: textureRight,
  80182. up: textureUp,
  80183. down: textureDown,
  80184. size: size,
  80185. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80186. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80187. gammaSpace: false,
  80188. };
  80189. };
  80190. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80191. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80192. var textureArray = new Float32Array(buffer);
  80193. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80194. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80195. var dy = 1 / texSize;
  80196. var fy = 0;
  80197. for (var y = 0; y < texSize; y++) {
  80198. var xv1 = faceData[0];
  80199. var xv2 = faceData[2];
  80200. for (var x = 0; x < texSize; x++) {
  80201. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80202. v.normalize();
  80203. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80204. // 3 channels per pixels
  80205. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80206. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80207. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80208. xv1 = xv1.add(rotDX1);
  80209. xv2 = xv2.add(rotDX2);
  80210. }
  80211. fy += dy;
  80212. }
  80213. return textureArray;
  80214. };
  80215. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80216. var theta = Math.atan2(vDir.z, vDir.x);
  80217. var phi = Math.acos(vDir.y);
  80218. while (theta < -Math.PI)
  80219. theta += 2 * Math.PI;
  80220. while (theta > Math.PI)
  80221. theta -= 2 * Math.PI;
  80222. var dx = theta / Math.PI;
  80223. var dy = phi / Math.PI;
  80224. // recenter.
  80225. dx = dx * 0.5 + 0.5;
  80226. var px = Math.round(dx * inputWidth);
  80227. if (px < 0)
  80228. px = 0;
  80229. else if (px >= inputWidth)
  80230. px = inputWidth - 1;
  80231. var py = Math.round(dy * inputHeight);
  80232. if (py < 0)
  80233. py = 0;
  80234. else if (py >= inputHeight)
  80235. py = inputHeight - 1;
  80236. var inputY = (inputHeight - py - 1);
  80237. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80238. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80239. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80240. return {
  80241. r: r,
  80242. g: g,
  80243. b: b
  80244. };
  80245. };
  80246. PanoramaToCubeMapTools.FACE_FRONT = [
  80247. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80248. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80249. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80250. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80251. ];
  80252. PanoramaToCubeMapTools.FACE_BACK = [
  80253. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80254. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80255. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80256. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80257. ];
  80258. PanoramaToCubeMapTools.FACE_RIGHT = [
  80259. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80260. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80261. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80262. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80263. ];
  80264. PanoramaToCubeMapTools.FACE_LEFT = [
  80265. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80266. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80267. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80268. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80269. ];
  80270. PanoramaToCubeMapTools.FACE_DOWN = [
  80271. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80272. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80273. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80274. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80275. ];
  80276. PanoramaToCubeMapTools.FACE_UP = [
  80277. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80278. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80279. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80280. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80281. ];
  80282. return PanoramaToCubeMapTools;
  80283. }());
  80284. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80285. })(BABYLON || (BABYLON = {}));
  80286. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80287. var BABYLON;
  80288. (function (BABYLON) {
  80289. ;
  80290. /**
  80291. * This groups tools to convert HDR texture to native colors array.
  80292. */
  80293. var HDRTools = /** @class */ (function () {
  80294. function HDRTools() {
  80295. }
  80296. HDRTools.Ldexp = function (mantissa, exponent) {
  80297. if (exponent > 1023) {
  80298. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80299. }
  80300. if (exponent < -1074) {
  80301. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80302. }
  80303. return mantissa * Math.pow(2, exponent);
  80304. };
  80305. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80306. if (exponent > 0) { /*nonzero pixel*/
  80307. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80308. float32array[index + 0] = red * exponent;
  80309. float32array[index + 1] = green * exponent;
  80310. float32array[index + 2] = blue * exponent;
  80311. }
  80312. else {
  80313. float32array[index + 0] = 0;
  80314. float32array[index + 1] = 0;
  80315. float32array[index + 2] = 0;
  80316. }
  80317. };
  80318. HDRTools.readStringLine = function (uint8array, startIndex) {
  80319. var line = "";
  80320. var character = "";
  80321. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80322. character = String.fromCharCode(uint8array[i]);
  80323. if (character == "\n") {
  80324. break;
  80325. }
  80326. line += character;
  80327. }
  80328. return line;
  80329. };
  80330. /**
  80331. * Reads header information from an RGBE texture stored in a native array.
  80332. * More information on this format are available here:
  80333. * https://en.wikipedia.org/wiki/RGBE_image_format
  80334. *
  80335. * @param uint8array The binary file stored in native array.
  80336. * @return The header information.
  80337. */
  80338. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80339. var height = 0;
  80340. var width = 0;
  80341. var line = this.readStringLine(uint8array, 0);
  80342. if (line[0] != '#' || line[1] != '?') {
  80343. throw "Bad HDR Format.";
  80344. }
  80345. var endOfHeader = false;
  80346. var findFormat = false;
  80347. var lineIndex = 0;
  80348. do {
  80349. lineIndex += (line.length + 1);
  80350. line = this.readStringLine(uint8array, lineIndex);
  80351. if (line == "FORMAT=32-bit_rle_rgbe") {
  80352. findFormat = true;
  80353. }
  80354. else if (line.length == 0) {
  80355. endOfHeader = true;
  80356. }
  80357. } while (!endOfHeader);
  80358. if (!findFormat) {
  80359. throw "HDR Bad header format, unsupported FORMAT";
  80360. }
  80361. lineIndex += (line.length + 1);
  80362. line = this.readStringLine(uint8array, lineIndex);
  80363. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80364. var match = sizeRegexp.exec(line);
  80365. // TODO. Support +Y and -X if needed.
  80366. if (!match || match.length < 3) {
  80367. throw "HDR Bad header format, no size";
  80368. }
  80369. width = parseInt(match[2]);
  80370. height = parseInt(match[1]);
  80371. if (width < 8 || width > 0x7fff) {
  80372. throw "HDR Bad header format, unsupported size";
  80373. }
  80374. lineIndex += (line.length + 1);
  80375. return {
  80376. height: height,
  80377. width: width,
  80378. dataPosition: lineIndex
  80379. };
  80380. };
  80381. /**
  80382. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80383. * This RGBE texture needs to store the information as a panorama.
  80384. *
  80385. * More information on this format are available here:
  80386. * https://en.wikipedia.org/wiki/RGBE_image_format
  80387. *
  80388. * @param buffer The binary file stored in an array buffer.
  80389. * @param size The expected size of the extracted cubemap.
  80390. * @return The Cube Map information.
  80391. */
  80392. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80393. var uint8array = new Uint8Array(buffer);
  80394. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80395. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80396. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80397. return cubeMapData;
  80398. };
  80399. /**
  80400. * Returns the pixels data extracted from an RGBE texture.
  80401. * This pixels will be stored left to right up to down in the R G B order in one array.
  80402. *
  80403. * More information on this format are available here:
  80404. * https://en.wikipedia.org/wiki/RGBE_image_format
  80405. *
  80406. * @param uint8array The binary file stored in an array buffer.
  80407. * @param hdrInfo The header information of the file.
  80408. * @return The pixels data in RGB right to left up to down order.
  80409. */
  80410. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80411. // Keep for multi format supports.
  80412. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80413. };
  80414. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80415. var num_scanlines = hdrInfo.height;
  80416. var scanline_width = hdrInfo.width;
  80417. var a, b, c, d, count;
  80418. var dataIndex = hdrInfo.dataPosition;
  80419. var index = 0, endIndex = 0, i = 0;
  80420. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80421. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80422. // 3 channels of 4 bytes per pixel in float.
  80423. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80424. var resultArray = new Float32Array(resultBuffer);
  80425. // read in each successive scanline
  80426. while (num_scanlines > 0) {
  80427. a = uint8array[dataIndex++];
  80428. b = uint8array[dataIndex++];
  80429. c = uint8array[dataIndex++];
  80430. d = uint8array[dataIndex++];
  80431. if (a != 2 || b != 2 || (c & 0x80)) {
  80432. // this file is not run length encoded
  80433. throw "HDR Bad header format, not RLE";
  80434. }
  80435. if (((c << 8) | d) != scanline_width) {
  80436. throw "HDR Bad header format, wrong scan line width";
  80437. }
  80438. index = 0;
  80439. // read each of the four channels for the scanline into the buffer
  80440. for (i = 0; i < 4; i++) {
  80441. endIndex = (i + 1) * scanline_width;
  80442. while (index < endIndex) {
  80443. a = uint8array[dataIndex++];
  80444. b = uint8array[dataIndex++];
  80445. if (a > 128) {
  80446. // a run of the same value
  80447. count = a - 128;
  80448. if ((count == 0) || (count > endIndex - index)) {
  80449. throw "HDR Bad Format, bad scanline data (run)";
  80450. }
  80451. while (count-- > 0) {
  80452. scanLineArray[index++] = b;
  80453. }
  80454. }
  80455. else {
  80456. // a non-run
  80457. count = a;
  80458. if ((count == 0) || (count > endIndex - index)) {
  80459. throw "HDR Bad Format, bad scanline data (non-run)";
  80460. }
  80461. scanLineArray[index++] = b;
  80462. if (--count > 0) {
  80463. for (var j = 0; j < count; j++) {
  80464. scanLineArray[index++] = uint8array[dataIndex++];
  80465. }
  80466. }
  80467. }
  80468. }
  80469. }
  80470. // now convert data from buffer into floats
  80471. for (i = 0; i < scanline_width; i++) {
  80472. a = scanLineArray[i];
  80473. b = scanLineArray[i + scanline_width];
  80474. c = scanLineArray[i + 2 * scanline_width];
  80475. d = scanLineArray[i + 3 * scanline_width];
  80476. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80477. }
  80478. num_scanlines--;
  80479. }
  80480. return resultArray;
  80481. };
  80482. return HDRTools;
  80483. }());
  80484. BABYLON.HDRTools = HDRTools;
  80485. })(BABYLON || (BABYLON = {}));
  80486. //# sourceMappingURL=babylon.hdr.js.map
  80487. var BABYLON;
  80488. (function (BABYLON) {
  80489. /**
  80490. * This represents a texture coming from an HDR input.
  80491. *
  80492. * The only supported format is currently panorama picture stored in RGBE format.
  80493. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80494. */
  80495. var HDRCubeTexture = /** @class */ (function (_super) {
  80496. __extends(HDRCubeTexture, _super);
  80497. /**
  80498. * Instantiates an HDRTexture from the following parameters.
  80499. *
  80500. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80501. * @param scene The scene the texture will be used in
  80502. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80503. * @param noMipmap Forces to not generate the mipmap if true
  80504. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80505. * @param gammaSpace 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)
  80506. * @param reserved Reserved flag for internal use.
  80507. */
  80508. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80509. if (noMipmap === void 0) { noMipmap = false; }
  80510. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80511. if (gammaSpace === void 0) { gammaSpace = false; }
  80512. if (reserved === void 0) { reserved = false; }
  80513. if (onLoad === void 0) { onLoad = null; }
  80514. if (onError === void 0) { onError = null; }
  80515. var _this = _super.call(this, scene) || this;
  80516. _this._generateHarmonics = true;
  80517. _this._onLoad = null;
  80518. _this._onError = null;
  80519. /**
  80520. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80521. */
  80522. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80523. _this._isBlocking = true;
  80524. _this._rotationY = 0;
  80525. /**
  80526. * Gets or sets the center of the bounding box associated with the cube texture
  80527. * It must define where the camera used to render the texture was set
  80528. */
  80529. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80530. if (!url) {
  80531. return _this;
  80532. }
  80533. _this.name = url;
  80534. _this.url = url;
  80535. _this.hasAlpha = false;
  80536. _this.isCube = true;
  80537. _this._textureMatrix = BABYLON.Matrix.Identity();
  80538. _this._onLoad = onLoad;
  80539. _this._onError = onError;
  80540. _this.gammaSpace = gammaSpace;
  80541. _this._noMipmap = noMipmap;
  80542. _this._size = size;
  80543. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80544. if (!_this._texture) {
  80545. if (!scene.useDelayedTextureLoading) {
  80546. _this.loadTexture();
  80547. }
  80548. else {
  80549. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80550. }
  80551. }
  80552. return _this;
  80553. }
  80554. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80555. /**
  80556. * Gets wether or not the texture is blocking during loading.
  80557. */
  80558. get: function () {
  80559. return this._isBlocking;
  80560. },
  80561. /**
  80562. * Sets wether or not the texture is blocking during loading.
  80563. */
  80564. set: function (value) {
  80565. this._isBlocking = value;
  80566. },
  80567. enumerable: true,
  80568. configurable: true
  80569. });
  80570. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80571. /**
  80572. * Gets texture matrix rotation angle around Y axis radians.
  80573. */
  80574. get: function () {
  80575. return this._rotationY;
  80576. },
  80577. /**
  80578. * Sets texture matrix rotation angle around Y axis in radians.
  80579. */
  80580. set: function (value) {
  80581. this._rotationY = value;
  80582. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80583. },
  80584. enumerable: true,
  80585. configurable: true
  80586. });
  80587. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80588. get: function () {
  80589. return this._boundingBoxSize;
  80590. },
  80591. /**
  80592. * Gets or sets the size of the bounding box associated with the cube texture
  80593. * When defined, the cubemap will switch to local mode
  80594. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80595. * @example https://www.babylonjs-playground.com/#RNASML
  80596. */
  80597. set: function (value) {
  80598. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80599. return;
  80600. }
  80601. this._boundingBoxSize = value;
  80602. var scene = this.getScene();
  80603. if (scene) {
  80604. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80605. }
  80606. },
  80607. enumerable: true,
  80608. configurable: true
  80609. });
  80610. /**
  80611. * Occurs when the file is raw .hdr file.
  80612. */
  80613. HDRCubeTexture.prototype.loadTexture = function () {
  80614. var _this = this;
  80615. var callback = function (buffer) {
  80616. var scene = _this.getScene();
  80617. if (!scene) {
  80618. return null;
  80619. }
  80620. // Extract the raw linear data.
  80621. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80622. // Generate harmonics if needed.
  80623. if (_this._generateHarmonics) {
  80624. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80625. _this.sphericalPolynomial = sphericalPolynomial;
  80626. }
  80627. var results = [];
  80628. var byteArray = null;
  80629. // Push each faces.
  80630. for (var j = 0; j < 6; j++) {
  80631. // Create uintarray fallback.
  80632. if (!scene.getEngine().getCaps().textureFloat) {
  80633. // 3 channels of 1 bytes per pixel in bytes.
  80634. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80635. byteArray = new Uint8Array(byteBuffer);
  80636. }
  80637. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80638. // If special cases.
  80639. if (_this.gammaSpace || byteArray) {
  80640. for (var i = 0; i < _this._size * _this._size; i++) {
  80641. // Put in gamma space if requested.
  80642. if (_this.gammaSpace) {
  80643. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80644. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80645. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80646. }
  80647. // Convert to int texture for fallback.
  80648. if (byteArray) {
  80649. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80650. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80651. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80652. // May use luminance instead if the result is not accurate.
  80653. var max = Math.max(Math.max(r, g), b);
  80654. if (max > 255) {
  80655. var scale = 255 / max;
  80656. r *= scale;
  80657. g *= scale;
  80658. b *= scale;
  80659. }
  80660. byteArray[(i * 3) + 0] = r;
  80661. byteArray[(i * 3) + 1] = g;
  80662. byteArray[(i * 3) + 2] = b;
  80663. }
  80664. }
  80665. }
  80666. if (byteArray) {
  80667. results.push(byteArray);
  80668. }
  80669. else {
  80670. results.push(dataFace);
  80671. }
  80672. }
  80673. return results;
  80674. };
  80675. var scene = this.getScene();
  80676. if (scene) {
  80677. 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, null, this._onLoad, this._onError);
  80678. }
  80679. };
  80680. HDRCubeTexture.prototype.clone = function () {
  80681. var scene = this.getScene();
  80682. if (!scene) {
  80683. return this;
  80684. }
  80685. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80686. // Base texture
  80687. newTexture.level = this.level;
  80688. newTexture.wrapU = this.wrapU;
  80689. newTexture.wrapV = this.wrapV;
  80690. newTexture.coordinatesIndex = this.coordinatesIndex;
  80691. newTexture.coordinatesMode = this.coordinatesMode;
  80692. return newTexture;
  80693. };
  80694. // Methods
  80695. HDRCubeTexture.prototype.delayLoad = function () {
  80696. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80697. return;
  80698. }
  80699. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80700. this._texture = this._getFromCache(this.url, this._noMipmap);
  80701. if (!this._texture) {
  80702. this.loadTexture();
  80703. }
  80704. };
  80705. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80706. return this._textureMatrix;
  80707. };
  80708. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80709. this._textureMatrix = value;
  80710. };
  80711. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80712. var texture = null;
  80713. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80714. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  80715. texture.name = parsedTexture.name;
  80716. texture.hasAlpha = parsedTexture.hasAlpha;
  80717. texture.level = parsedTexture.level;
  80718. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80719. texture.isBlocking = parsedTexture.isBlocking;
  80720. }
  80721. if (texture) {
  80722. if (parsedTexture.boundingBoxPosition) {
  80723. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80724. }
  80725. if (parsedTexture.boundingBoxSize) {
  80726. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80727. }
  80728. if (parsedTexture.rotationY) {
  80729. texture.rotationY = parsedTexture.rotationY;
  80730. }
  80731. }
  80732. return texture;
  80733. };
  80734. HDRCubeTexture.prototype.serialize = function () {
  80735. if (!this.name) {
  80736. return null;
  80737. }
  80738. var serializationObject = {};
  80739. serializationObject.name = this.name;
  80740. serializationObject.hasAlpha = this.hasAlpha;
  80741. serializationObject.isCube = true;
  80742. serializationObject.level = this.level;
  80743. serializationObject.size = this._size;
  80744. serializationObject.coordinatesMode = this.coordinatesMode;
  80745. serializationObject.useInGammaSpace = this.gammaSpace;
  80746. serializationObject.generateHarmonics = this._generateHarmonics;
  80747. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80748. serializationObject.noMipmap = this._noMipmap;
  80749. serializationObject.isBlocking = this._isBlocking;
  80750. serializationObject.rotationY = this._rotationY;
  80751. return serializationObject;
  80752. };
  80753. HDRCubeTexture._facesMapping = [
  80754. "right",
  80755. "left",
  80756. "up",
  80757. "down",
  80758. "front",
  80759. "back"
  80760. ];
  80761. return HDRCubeTexture;
  80762. }(BABYLON.BaseTexture));
  80763. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80764. })(BABYLON || (BABYLON = {}));
  80765. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80766. var BABYLON;
  80767. (function (BABYLON) {
  80768. var IndexedVector2 = /** @class */ (function (_super) {
  80769. __extends(IndexedVector2, _super);
  80770. function IndexedVector2(original, index) {
  80771. var _this = _super.call(this, original.x, original.y) || this;
  80772. _this.index = index;
  80773. return _this;
  80774. }
  80775. return IndexedVector2;
  80776. }(BABYLON.Vector2));
  80777. var PolygonPoints = /** @class */ (function () {
  80778. function PolygonPoints() {
  80779. this.elements = new Array();
  80780. }
  80781. PolygonPoints.prototype.add = function (originalPoints) {
  80782. var _this = this;
  80783. var result = new Array();
  80784. originalPoints.forEach(function (point) {
  80785. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80786. var newPoint = new IndexedVector2(point, _this.elements.length);
  80787. result.push(newPoint);
  80788. _this.elements.push(newPoint);
  80789. }
  80790. });
  80791. return result;
  80792. };
  80793. PolygonPoints.prototype.computeBounds = function () {
  80794. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80795. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80796. this.elements.forEach(function (point) {
  80797. // x
  80798. if (point.x < lmin.x) {
  80799. lmin.x = point.x;
  80800. }
  80801. else if (point.x > lmax.x) {
  80802. lmax.x = point.x;
  80803. }
  80804. // y
  80805. if (point.y < lmin.y) {
  80806. lmin.y = point.y;
  80807. }
  80808. else if (point.y > lmax.y) {
  80809. lmax.y = point.y;
  80810. }
  80811. });
  80812. return {
  80813. min: lmin,
  80814. max: lmax,
  80815. width: lmax.x - lmin.x,
  80816. height: lmax.y - lmin.y
  80817. };
  80818. };
  80819. return PolygonPoints;
  80820. }());
  80821. var Polygon = /** @class */ (function () {
  80822. function Polygon() {
  80823. }
  80824. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80825. return [
  80826. new BABYLON.Vector2(xmin, ymin),
  80827. new BABYLON.Vector2(xmax, ymin),
  80828. new BABYLON.Vector2(xmax, ymax),
  80829. new BABYLON.Vector2(xmin, ymax)
  80830. ];
  80831. };
  80832. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80833. if (cx === void 0) { cx = 0; }
  80834. if (cy === void 0) { cy = 0; }
  80835. if (numberOfSides === void 0) { numberOfSides = 32; }
  80836. var result = new Array();
  80837. var angle = 0;
  80838. var increment = (Math.PI * 2) / numberOfSides;
  80839. for (var i = 0; i < numberOfSides; i++) {
  80840. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80841. angle -= increment;
  80842. }
  80843. return result;
  80844. };
  80845. Polygon.Parse = function (input) {
  80846. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80847. var i, result = [];
  80848. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80849. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80850. }
  80851. return result;
  80852. };
  80853. Polygon.StartingAt = function (x, y) {
  80854. return BABYLON.Path2.StartingAt(x, y);
  80855. };
  80856. return Polygon;
  80857. }());
  80858. BABYLON.Polygon = Polygon;
  80859. var PolygonMeshBuilder = /** @class */ (function () {
  80860. function PolygonMeshBuilder(name, contours, scene) {
  80861. this._points = new PolygonPoints();
  80862. this._outlinepoints = new PolygonPoints();
  80863. this._holes = new Array();
  80864. this._epoints = new Array();
  80865. this._eholes = new Array();
  80866. this._name = name;
  80867. this._scene = scene;
  80868. var points;
  80869. if (contours instanceof BABYLON.Path2) {
  80870. points = contours.getPoints();
  80871. }
  80872. else {
  80873. points = contours;
  80874. }
  80875. this._addToepoint(points);
  80876. this._points.add(points);
  80877. this._outlinepoints.add(points);
  80878. if (typeof earcut === 'undefined') {
  80879. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80880. }
  80881. }
  80882. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80883. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80884. var p = points_1[_i];
  80885. this._epoints.push(p.x, p.y);
  80886. }
  80887. };
  80888. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80889. this._points.add(hole);
  80890. var holepoints = new PolygonPoints();
  80891. holepoints.add(hole);
  80892. this._holes.push(holepoints);
  80893. this._eholes.push(this._epoints.length / 2);
  80894. this._addToepoint(hole);
  80895. return this;
  80896. };
  80897. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80898. var _this = this;
  80899. if (updatable === void 0) { updatable = false; }
  80900. if (depth === void 0) { depth = 0; }
  80901. var result = new BABYLON.Mesh(this._name, this._scene);
  80902. var normals = new Array();
  80903. var positions = new Array();
  80904. var uvs = new Array();
  80905. var bounds = this._points.computeBounds();
  80906. this._points.elements.forEach(function (p) {
  80907. normals.push(0, 1.0, 0);
  80908. positions.push(p.x, 0, p.y);
  80909. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80910. });
  80911. var indices = new Array();
  80912. var res = earcut(this._epoints, this._eholes, 2);
  80913. for (var i = 0; i < res.length; i++) {
  80914. indices.push(res[i]);
  80915. }
  80916. if (depth > 0) {
  80917. var positionscount = (positions.length / 3); //get the current pointcount
  80918. this._points.elements.forEach(function (p) {
  80919. normals.push(0, -1.0, 0);
  80920. positions.push(p.x, -depth, p.y);
  80921. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80922. });
  80923. var totalCount = indices.length;
  80924. for (var i = 0; i < totalCount; i += 3) {
  80925. var i0 = indices[i + 0];
  80926. var i1 = indices[i + 1];
  80927. var i2 = indices[i + 2];
  80928. indices.push(i2 + positionscount);
  80929. indices.push(i1 + positionscount);
  80930. indices.push(i0 + positionscount);
  80931. }
  80932. //Add the sides
  80933. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80934. this._holes.forEach(function (hole) {
  80935. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80936. });
  80937. }
  80938. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80939. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80940. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80941. result.setIndices(indices);
  80942. return result;
  80943. };
  80944. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80945. var StartIndex = positions.length / 3;
  80946. var ulength = 0;
  80947. for (var i = 0; i < points.elements.length; i++) {
  80948. var p = points.elements[i];
  80949. var p1;
  80950. if ((i + 1) > points.elements.length - 1) {
  80951. p1 = points.elements[0];
  80952. }
  80953. else {
  80954. p1 = points.elements[i + 1];
  80955. }
  80956. positions.push(p.x, 0, p.y);
  80957. positions.push(p.x, -depth, p.y);
  80958. positions.push(p1.x, 0, p1.y);
  80959. positions.push(p1.x, -depth, p1.y);
  80960. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80961. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80962. var v3 = v2.subtract(v1);
  80963. var v4 = new BABYLON.Vector3(0, 1, 0);
  80964. var vn = BABYLON.Vector3.Cross(v3, v4);
  80965. vn = vn.normalize();
  80966. uvs.push(ulength / bounds.width, 0);
  80967. uvs.push(ulength / bounds.width, 1);
  80968. ulength += v3.length();
  80969. uvs.push((ulength / bounds.width), 0);
  80970. uvs.push((ulength / bounds.width), 1);
  80971. if (!flip) {
  80972. normals.push(-vn.x, -vn.y, -vn.z);
  80973. normals.push(-vn.x, -vn.y, -vn.z);
  80974. normals.push(-vn.x, -vn.y, -vn.z);
  80975. normals.push(-vn.x, -vn.y, -vn.z);
  80976. indices.push(StartIndex);
  80977. indices.push(StartIndex + 1);
  80978. indices.push(StartIndex + 2);
  80979. indices.push(StartIndex + 1);
  80980. indices.push(StartIndex + 3);
  80981. indices.push(StartIndex + 2);
  80982. }
  80983. else {
  80984. normals.push(vn.x, vn.y, vn.z);
  80985. normals.push(vn.x, vn.y, vn.z);
  80986. normals.push(vn.x, vn.y, vn.z);
  80987. normals.push(vn.x, vn.y, vn.z);
  80988. indices.push(StartIndex);
  80989. indices.push(StartIndex + 2);
  80990. indices.push(StartIndex + 1);
  80991. indices.push(StartIndex + 1);
  80992. indices.push(StartIndex + 2);
  80993. indices.push(StartIndex + 3);
  80994. }
  80995. StartIndex += 4;
  80996. }
  80997. ;
  80998. };
  80999. return PolygonMeshBuilder;
  81000. }());
  81001. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  81002. })(BABYLON || (BABYLON = {}));
  81003. //# sourceMappingURL=babylon.polygonMesh.js.map
  81004. var BABYLON;
  81005. (function (BABYLON) {
  81006. // Unique ID when we import meshes from Babylon to CSG
  81007. var currentCSGMeshId = 0;
  81008. // # class Vertex
  81009. // Represents a vertex of a polygon. Use your own vertex class instead of this
  81010. // one to provide additional features like texture coordinates and vertex
  81011. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  81012. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  81013. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  81014. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  81015. // is not used anywhere else.
  81016. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  81017. var Vertex = /** @class */ (function () {
  81018. function Vertex(pos, normal, uv) {
  81019. this.pos = pos;
  81020. this.normal = normal;
  81021. this.uv = uv;
  81022. }
  81023. Vertex.prototype.clone = function () {
  81024. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  81025. };
  81026. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  81027. // orientation of a polygon is flipped.
  81028. Vertex.prototype.flip = function () {
  81029. this.normal = this.normal.scale(-1);
  81030. };
  81031. // Create a new vertex between this vertex and `other` by linearly
  81032. // interpolating all properties using a parameter of `t`. Subclasses should
  81033. // override this to interpolate additional properties.
  81034. Vertex.prototype.interpolate = function (other, t) {
  81035. 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));
  81036. };
  81037. return Vertex;
  81038. }());
  81039. // # class Plane
  81040. // Represents a plane in 3D space.
  81041. var Plane = /** @class */ (function () {
  81042. function Plane(normal, w) {
  81043. this.normal = normal;
  81044. this.w = w;
  81045. }
  81046. Plane.FromPoints = function (a, b, c) {
  81047. var v0 = c.subtract(a);
  81048. var v1 = b.subtract(a);
  81049. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  81050. return null;
  81051. }
  81052. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  81053. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  81054. };
  81055. Plane.prototype.clone = function () {
  81056. return new Plane(this.normal.clone(), this.w);
  81057. };
  81058. Plane.prototype.flip = function () {
  81059. this.normal.scaleInPlace(-1);
  81060. this.w = -this.w;
  81061. };
  81062. // Split `polygon` by this plane if needed, then put the polygon or polygon
  81063. // fragments in the appropriate lists. Coplanar polygons go into either
  81064. // `coplanarFront` or `coplanarBack` depending on their orientation with
  81065. // respect to this plane. Polygons in front or in back of this plane go into
  81066. // either `front` or `back`.
  81067. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  81068. var COPLANAR = 0;
  81069. var FRONT = 1;
  81070. var BACK = 2;
  81071. var SPANNING = 3;
  81072. // Classify each point as well as the entire polygon into one of the above
  81073. // four classes.
  81074. var polygonType = 0;
  81075. var types = [];
  81076. var i;
  81077. var t;
  81078. for (i = 0; i < polygon.vertices.length; i++) {
  81079. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  81080. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  81081. polygonType |= type;
  81082. types.push(type);
  81083. }
  81084. // Put the polygon in the correct list, splitting it when necessary.
  81085. switch (polygonType) {
  81086. case COPLANAR:
  81087. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  81088. break;
  81089. case FRONT:
  81090. front.push(polygon);
  81091. break;
  81092. case BACK:
  81093. back.push(polygon);
  81094. break;
  81095. case SPANNING:
  81096. var f = [], b = [];
  81097. for (i = 0; i < polygon.vertices.length; i++) {
  81098. var j = (i + 1) % polygon.vertices.length;
  81099. var ti = types[i], tj = types[j];
  81100. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  81101. if (ti !== BACK)
  81102. f.push(vi);
  81103. if (ti !== FRONT)
  81104. b.push(ti !== BACK ? vi.clone() : vi);
  81105. if ((ti | tj) === SPANNING) {
  81106. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  81107. var v = vi.interpolate(vj, t);
  81108. f.push(v);
  81109. b.push(v.clone());
  81110. }
  81111. }
  81112. var poly;
  81113. if (f.length >= 3) {
  81114. poly = new Polygon(f, polygon.shared);
  81115. if (poly.plane)
  81116. front.push(poly);
  81117. }
  81118. if (b.length >= 3) {
  81119. poly = new Polygon(b, polygon.shared);
  81120. if (poly.plane)
  81121. back.push(poly);
  81122. }
  81123. break;
  81124. }
  81125. };
  81126. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  81127. // point is on the plane.
  81128. Plane.EPSILON = 1e-5;
  81129. return Plane;
  81130. }());
  81131. // # class Polygon
  81132. // Represents a convex polygon. The vertices used to initialize a polygon must
  81133. // be coplanar and form a convex loop.
  81134. //
  81135. // Each convex polygon has a `shared` property, which is shared between all
  81136. // polygons that are clones of each other or were split from the same polygon.
  81137. // This can be used to define per-polygon properties (such as surface color).
  81138. var Polygon = /** @class */ (function () {
  81139. function Polygon(vertices, shared) {
  81140. this.vertices = vertices;
  81141. this.shared = shared;
  81142. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  81143. }
  81144. Polygon.prototype.clone = function () {
  81145. var vertices = this.vertices.map(function (v) { return v.clone(); });
  81146. return new Polygon(vertices, this.shared);
  81147. };
  81148. Polygon.prototype.flip = function () {
  81149. this.vertices.reverse().map(function (v) { v.flip(); });
  81150. this.plane.flip();
  81151. };
  81152. return Polygon;
  81153. }());
  81154. // # class Node
  81155. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  81156. // by picking a polygon to split along. That polygon (and all other coplanar
  81157. // polygons) are added directly to that node and the other polygons are added to
  81158. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  81159. // no distinction between internal and leaf nodes.
  81160. var Node = /** @class */ (function () {
  81161. function Node(polygons) {
  81162. this.plane = null;
  81163. this.front = null;
  81164. this.back = null;
  81165. this.polygons = new Array();
  81166. if (polygons) {
  81167. this.build(polygons);
  81168. }
  81169. }
  81170. Node.prototype.clone = function () {
  81171. var node = new Node();
  81172. node.plane = this.plane && this.plane.clone();
  81173. node.front = this.front && this.front.clone();
  81174. node.back = this.back && this.back.clone();
  81175. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  81176. return node;
  81177. };
  81178. // Convert solid space to empty space and empty space to solid space.
  81179. Node.prototype.invert = function () {
  81180. for (var i = 0; i < this.polygons.length; i++) {
  81181. this.polygons[i].flip();
  81182. }
  81183. if (this.plane) {
  81184. this.plane.flip();
  81185. }
  81186. if (this.front) {
  81187. this.front.invert();
  81188. }
  81189. if (this.back) {
  81190. this.back.invert();
  81191. }
  81192. var temp = this.front;
  81193. this.front = this.back;
  81194. this.back = temp;
  81195. };
  81196. // Recursively remove all polygons in `polygons` that are inside this BSP
  81197. // tree.
  81198. Node.prototype.clipPolygons = function (polygons) {
  81199. if (!this.plane)
  81200. return polygons.slice();
  81201. var front = new Array(), back = new Array();
  81202. for (var i = 0; i < polygons.length; i++) {
  81203. this.plane.splitPolygon(polygons[i], front, back, front, back);
  81204. }
  81205. if (this.front) {
  81206. front = this.front.clipPolygons(front);
  81207. }
  81208. if (this.back) {
  81209. back = this.back.clipPolygons(back);
  81210. }
  81211. else {
  81212. back = [];
  81213. }
  81214. return front.concat(back);
  81215. };
  81216. // Remove all polygons in this BSP tree that are inside the other BSP tree
  81217. // `bsp`.
  81218. Node.prototype.clipTo = function (bsp) {
  81219. this.polygons = bsp.clipPolygons(this.polygons);
  81220. if (this.front)
  81221. this.front.clipTo(bsp);
  81222. if (this.back)
  81223. this.back.clipTo(bsp);
  81224. };
  81225. // Return a list of all polygons in this BSP tree.
  81226. Node.prototype.allPolygons = function () {
  81227. var polygons = this.polygons.slice();
  81228. if (this.front)
  81229. polygons = polygons.concat(this.front.allPolygons());
  81230. if (this.back)
  81231. polygons = polygons.concat(this.back.allPolygons());
  81232. return polygons;
  81233. };
  81234. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  81235. // new polygons are filtered down to the bottom of the tree and become new
  81236. // nodes there. Each set of polygons is partitioned using the first polygon
  81237. // (no heuristic is used to pick a good split).
  81238. Node.prototype.build = function (polygons) {
  81239. if (!polygons.length)
  81240. return;
  81241. if (!this.plane)
  81242. this.plane = polygons[0].plane.clone();
  81243. var front = new Array(), back = new Array();
  81244. for (var i = 0; i < polygons.length; i++) {
  81245. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81246. }
  81247. if (front.length) {
  81248. if (!this.front)
  81249. this.front = new Node();
  81250. this.front.build(front);
  81251. }
  81252. if (back.length) {
  81253. if (!this.back)
  81254. this.back = new Node();
  81255. this.back.build(back);
  81256. }
  81257. };
  81258. return Node;
  81259. }());
  81260. var CSG = /** @class */ (function () {
  81261. function CSG() {
  81262. this.polygons = new Array();
  81263. }
  81264. // Convert BABYLON.Mesh to BABYLON.CSG
  81265. CSG.FromMesh = function (mesh) {
  81266. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81267. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81268. if (mesh instanceof BABYLON.Mesh) {
  81269. mesh.computeWorldMatrix(true);
  81270. matrix = mesh.getWorldMatrix();
  81271. meshPosition = mesh.position.clone();
  81272. meshRotation = mesh.rotation.clone();
  81273. if (mesh.rotationQuaternion) {
  81274. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81275. }
  81276. meshScaling = mesh.scaling.clone();
  81277. }
  81278. else {
  81279. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81280. }
  81281. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81282. var subMeshes = mesh.subMeshes;
  81283. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81284. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81285. vertices = [];
  81286. for (var j = 0; j < 3; j++) {
  81287. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81288. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81289. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81290. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81291. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81292. vertex = new Vertex(position, normal, uv);
  81293. vertices.push(vertex);
  81294. }
  81295. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81296. // To handle the case of degenerated triangle
  81297. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81298. if (polygon.plane)
  81299. polygons.push(polygon);
  81300. }
  81301. }
  81302. var csg = CSG.FromPolygons(polygons);
  81303. csg.matrix = matrix;
  81304. csg.position = meshPosition;
  81305. csg.rotation = meshRotation;
  81306. csg.scaling = meshScaling;
  81307. csg.rotationQuaternion = meshRotationQuaternion;
  81308. currentCSGMeshId++;
  81309. return csg;
  81310. };
  81311. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81312. CSG.FromPolygons = function (polygons) {
  81313. var csg = new CSG();
  81314. csg.polygons = polygons;
  81315. return csg;
  81316. };
  81317. CSG.prototype.clone = function () {
  81318. var csg = new CSG();
  81319. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81320. csg.copyTransformAttributes(this);
  81321. return csg;
  81322. };
  81323. CSG.prototype.union = function (csg) {
  81324. var a = new Node(this.clone().polygons);
  81325. var b = new Node(csg.clone().polygons);
  81326. a.clipTo(b);
  81327. b.clipTo(a);
  81328. b.invert();
  81329. b.clipTo(a);
  81330. b.invert();
  81331. a.build(b.allPolygons());
  81332. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81333. };
  81334. CSG.prototype.unionInPlace = function (csg) {
  81335. var a = new Node(this.polygons);
  81336. var b = new Node(csg.polygons);
  81337. a.clipTo(b);
  81338. b.clipTo(a);
  81339. b.invert();
  81340. b.clipTo(a);
  81341. b.invert();
  81342. a.build(b.allPolygons());
  81343. this.polygons = a.allPolygons();
  81344. };
  81345. CSG.prototype.subtract = function (csg) {
  81346. var a = new Node(this.clone().polygons);
  81347. var b = new Node(csg.clone().polygons);
  81348. a.invert();
  81349. a.clipTo(b);
  81350. b.clipTo(a);
  81351. b.invert();
  81352. b.clipTo(a);
  81353. b.invert();
  81354. a.build(b.allPolygons());
  81355. a.invert();
  81356. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81357. };
  81358. CSG.prototype.subtractInPlace = function (csg) {
  81359. var a = new Node(this.polygons);
  81360. var b = new Node(csg.polygons);
  81361. a.invert();
  81362. a.clipTo(b);
  81363. b.clipTo(a);
  81364. b.invert();
  81365. b.clipTo(a);
  81366. b.invert();
  81367. a.build(b.allPolygons());
  81368. a.invert();
  81369. this.polygons = a.allPolygons();
  81370. };
  81371. CSG.prototype.intersect = function (csg) {
  81372. var a = new Node(this.clone().polygons);
  81373. var b = new Node(csg.clone().polygons);
  81374. a.invert();
  81375. b.clipTo(a);
  81376. b.invert();
  81377. a.clipTo(b);
  81378. b.clipTo(a);
  81379. a.build(b.allPolygons());
  81380. a.invert();
  81381. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81382. };
  81383. CSG.prototype.intersectInPlace = function (csg) {
  81384. var a = new Node(this.polygons);
  81385. var b = new Node(csg.polygons);
  81386. a.invert();
  81387. b.clipTo(a);
  81388. b.invert();
  81389. a.clipTo(b);
  81390. b.clipTo(a);
  81391. a.build(b.allPolygons());
  81392. a.invert();
  81393. this.polygons = a.allPolygons();
  81394. };
  81395. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81396. // not modified.
  81397. CSG.prototype.inverse = function () {
  81398. var csg = this.clone();
  81399. csg.inverseInPlace();
  81400. return csg;
  81401. };
  81402. CSG.prototype.inverseInPlace = function () {
  81403. this.polygons.map(function (p) { p.flip(); });
  81404. };
  81405. // This is used to keep meshes transformations so they can be restored
  81406. // when we build back a Babylon Mesh
  81407. // NB : All CSG operations are performed in world coordinates
  81408. CSG.prototype.copyTransformAttributes = function (csg) {
  81409. this.matrix = csg.matrix;
  81410. this.position = csg.position;
  81411. this.rotation = csg.rotation;
  81412. this.scaling = csg.scaling;
  81413. this.rotationQuaternion = csg.rotationQuaternion;
  81414. return this;
  81415. };
  81416. // Build Raw mesh from CSG
  81417. // Coordinates here are in world space
  81418. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81419. var matrix = this.matrix.clone();
  81420. matrix.invert();
  81421. 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;
  81422. if (keepSubMeshes) {
  81423. // Sort Polygons, since subMeshes are indices range
  81424. polygons.sort(function (a, b) {
  81425. if (a.shared.meshId === b.shared.meshId) {
  81426. return a.shared.subMeshId - b.shared.subMeshId;
  81427. }
  81428. else {
  81429. return a.shared.meshId - b.shared.meshId;
  81430. }
  81431. });
  81432. }
  81433. for (var i = 0, il = polygons.length; i < il; i++) {
  81434. polygon = polygons[i];
  81435. // Building SubMeshes
  81436. if (!subMesh_dict[polygon.shared.meshId]) {
  81437. subMesh_dict[polygon.shared.meshId] = {};
  81438. }
  81439. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81440. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81441. indexStart: +Infinity,
  81442. indexEnd: -Infinity,
  81443. materialIndex: polygon.shared.materialIndex
  81444. };
  81445. }
  81446. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81447. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81448. polygonIndices[0] = 0;
  81449. polygonIndices[1] = j - 1;
  81450. polygonIndices[2] = j;
  81451. for (var k = 0; k < 3; k++) {
  81452. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81453. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81454. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81455. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81456. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81457. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81458. // Check if 2 points can be merged
  81459. if (!(typeof vertex_idx !== 'undefined' &&
  81460. normals[vertex_idx * 3] === localNormal.x &&
  81461. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81462. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81463. uvs[vertex_idx * 2] === uv.x &&
  81464. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81465. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81466. uvs.push(uv.x, uv.y);
  81467. normals.push(normal.x, normal.y, normal.z);
  81468. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81469. }
  81470. indices.push(vertex_idx);
  81471. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81472. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81473. currentIndex++;
  81474. }
  81475. }
  81476. }
  81477. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81478. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81479. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81480. mesh.setIndices(indices, null);
  81481. if (keepSubMeshes) {
  81482. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81483. var materialIndexOffset = 0, materialMaxIndex;
  81484. mesh.subMeshes = new Array();
  81485. for (var m in subMesh_dict) {
  81486. materialMaxIndex = -1;
  81487. for (var sm in subMesh_dict[m]) {
  81488. subMesh_obj = subMesh_dict[m][sm];
  81489. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81490. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81491. }
  81492. materialIndexOffset += ++materialMaxIndex;
  81493. }
  81494. }
  81495. return mesh;
  81496. };
  81497. // Build Mesh from CSG taking material and transforms into account
  81498. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81499. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81500. mesh.material = material;
  81501. mesh.position.copyFrom(this.position);
  81502. mesh.rotation.copyFrom(this.rotation);
  81503. if (this.rotationQuaternion) {
  81504. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81505. }
  81506. mesh.scaling.copyFrom(this.scaling);
  81507. mesh.computeWorldMatrix(true);
  81508. return mesh;
  81509. };
  81510. return CSG;
  81511. }());
  81512. BABYLON.CSG = CSG;
  81513. })(BABYLON || (BABYLON = {}));
  81514. //# sourceMappingURL=babylon.csg.js.map
  81515. var BABYLON;
  81516. (function (BABYLON) {
  81517. var LensFlare = /** @class */ (function () {
  81518. function LensFlare(size, position, color, imgUrl, system) {
  81519. this.size = size;
  81520. this.position = position;
  81521. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81522. this.color = color || new BABYLON.Color3(1, 1, 1);
  81523. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81524. this._system = system;
  81525. system.lensFlares.push(this);
  81526. }
  81527. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81528. return new LensFlare(size, position, color, imgUrl, system);
  81529. };
  81530. LensFlare.prototype.dispose = function () {
  81531. if (this.texture) {
  81532. this.texture.dispose();
  81533. }
  81534. // Remove from scene
  81535. var index = this._system.lensFlares.indexOf(this);
  81536. this._system.lensFlares.splice(index, 1);
  81537. };
  81538. ;
  81539. return LensFlare;
  81540. }());
  81541. BABYLON.LensFlare = LensFlare;
  81542. })(BABYLON || (BABYLON = {}));
  81543. //# sourceMappingURL=babylon.lensFlare.js.map
  81544. var BABYLON;
  81545. (function (BABYLON) {
  81546. var LensFlareSystem = /** @class */ (function () {
  81547. function LensFlareSystem(name, emitter, scene) {
  81548. this.name = name;
  81549. this.lensFlares = new Array();
  81550. this.borderLimit = 300;
  81551. this.viewportBorder = 0;
  81552. this.layerMask = 0x0FFFFFFF;
  81553. this._vertexBuffers = {};
  81554. this._isEnabled = true;
  81555. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81556. this._emitter = emitter;
  81557. this.id = name;
  81558. scene.lensFlareSystems.push(this);
  81559. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81560. var engine = scene.getEngine();
  81561. // VBO
  81562. var vertices = [];
  81563. vertices.push(1, 1);
  81564. vertices.push(-1, 1);
  81565. vertices.push(-1, -1);
  81566. vertices.push(1, -1);
  81567. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81568. // Indices
  81569. var indices = [];
  81570. indices.push(0);
  81571. indices.push(1);
  81572. indices.push(2);
  81573. indices.push(0);
  81574. indices.push(2);
  81575. indices.push(3);
  81576. this._indexBuffer = engine.createIndexBuffer(indices);
  81577. // Effects
  81578. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81579. }
  81580. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81581. get: function () {
  81582. return this._isEnabled;
  81583. },
  81584. set: function (value) {
  81585. this._isEnabled = value;
  81586. },
  81587. enumerable: true,
  81588. configurable: true
  81589. });
  81590. LensFlareSystem.prototype.getScene = function () {
  81591. return this._scene;
  81592. };
  81593. LensFlareSystem.prototype.getEmitter = function () {
  81594. return this._emitter;
  81595. };
  81596. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81597. this._emitter = newEmitter;
  81598. };
  81599. LensFlareSystem.prototype.getEmitterPosition = function () {
  81600. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81601. };
  81602. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81603. var position = this.getEmitterPosition();
  81604. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81605. this._positionX = position.x;
  81606. this._positionY = position.y;
  81607. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81608. if (this.viewportBorder > 0) {
  81609. globalViewport.x -= this.viewportBorder;
  81610. globalViewport.y -= this.viewportBorder;
  81611. globalViewport.width += this.viewportBorder * 2;
  81612. globalViewport.height += this.viewportBorder * 2;
  81613. position.x += this.viewportBorder;
  81614. position.y += this.viewportBorder;
  81615. this._positionX += this.viewportBorder;
  81616. this._positionY += this.viewportBorder;
  81617. }
  81618. if (position.z > 0) {
  81619. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81620. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81621. return true;
  81622. }
  81623. return true;
  81624. }
  81625. return false;
  81626. };
  81627. LensFlareSystem.prototype._isVisible = function () {
  81628. if (!this._isEnabled || !this._scene.activeCamera) {
  81629. return false;
  81630. }
  81631. var emitterPosition = this.getEmitterPosition();
  81632. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81633. var distance = direction.length();
  81634. direction.normalize();
  81635. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81636. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81637. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81638. };
  81639. LensFlareSystem.prototype.render = function () {
  81640. if (!this._effect.isReady() || !this._scene.activeCamera)
  81641. return false;
  81642. var engine = this._scene.getEngine();
  81643. var viewport = this._scene.activeCamera.viewport;
  81644. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81645. // Position
  81646. if (!this.computeEffectivePosition(globalViewport)) {
  81647. return false;
  81648. }
  81649. // Visibility
  81650. if (!this._isVisible()) {
  81651. return false;
  81652. }
  81653. // Intensity
  81654. var awayX;
  81655. var awayY;
  81656. if (this._positionX < this.borderLimit + globalViewport.x) {
  81657. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81658. }
  81659. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81660. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81661. }
  81662. else {
  81663. awayX = 0;
  81664. }
  81665. if (this._positionY < this.borderLimit + globalViewport.y) {
  81666. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81667. }
  81668. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81669. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81670. }
  81671. else {
  81672. awayY = 0;
  81673. }
  81674. var away = (awayX > awayY) ? awayX : awayY;
  81675. away -= this.viewportBorder;
  81676. if (away > this.borderLimit) {
  81677. away = this.borderLimit;
  81678. }
  81679. var intensity = 1.0 - (away / this.borderLimit);
  81680. if (intensity < 0) {
  81681. return false;
  81682. }
  81683. if (intensity > 1.0) {
  81684. intensity = 1.0;
  81685. }
  81686. if (this.viewportBorder > 0) {
  81687. globalViewport.x += this.viewportBorder;
  81688. globalViewport.y += this.viewportBorder;
  81689. globalViewport.width -= this.viewportBorder * 2;
  81690. globalViewport.height -= this.viewportBorder * 2;
  81691. this._positionX -= this.viewportBorder;
  81692. this._positionY -= this.viewportBorder;
  81693. }
  81694. // Position
  81695. var centerX = globalViewport.x + globalViewport.width / 2;
  81696. var centerY = globalViewport.y + globalViewport.height / 2;
  81697. var distX = centerX - this._positionX;
  81698. var distY = centerY - this._positionY;
  81699. // Effects
  81700. engine.enableEffect(this._effect);
  81701. engine.setState(false);
  81702. engine.setDepthBuffer(false);
  81703. // VBOs
  81704. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81705. // Flares
  81706. for (var index = 0; index < this.lensFlares.length; index++) {
  81707. var flare = this.lensFlares[index];
  81708. engine.setAlphaMode(flare.alphaMode);
  81709. var x = centerX - (distX * flare.position);
  81710. var y = centerY - (distY * flare.position);
  81711. var cw = flare.size;
  81712. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81713. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81714. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81715. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81716. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81717. // Texture
  81718. this._effect.setTexture("textureSampler", flare.texture);
  81719. // Color
  81720. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81721. // Draw order
  81722. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81723. }
  81724. engine.setDepthBuffer(true);
  81725. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81726. return true;
  81727. };
  81728. LensFlareSystem.prototype.dispose = function () {
  81729. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81730. if (vertexBuffer) {
  81731. vertexBuffer.dispose();
  81732. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81733. }
  81734. if (this._indexBuffer) {
  81735. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81736. this._indexBuffer = null;
  81737. }
  81738. while (this.lensFlares.length) {
  81739. this.lensFlares[0].dispose();
  81740. }
  81741. // Remove from scene
  81742. var index = this._scene.lensFlareSystems.indexOf(this);
  81743. this._scene.lensFlareSystems.splice(index, 1);
  81744. };
  81745. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81746. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81747. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81748. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81749. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81750. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81751. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81752. var parsedFlare = parsedLensFlareSystem.flares[index];
  81753. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81754. }
  81755. return lensFlareSystem;
  81756. };
  81757. LensFlareSystem.prototype.serialize = function () {
  81758. var serializationObject = {};
  81759. serializationObject.id = this.id;
  81760. serializationObject.name = this.name;
  81761. serializationObject.emitterId = this.getEmitter().id;
  81762. serializationObject.borderLimit = this.borderLimit;
  81763. serializationObject.flares = [];
  81764. for (var index = 0; index < this.lensFlares.length; index++) {
  81765. var flare = this.lensFlares[index];
  81766. serializationObject.flares.push({
  81767. size: flare.size,
  81768. position: flare.position,
  81769. color: flare.color.asArray(),
  81770. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81771. });
  81772. }
  81773. return serializationObject;
  81774. };
  81775. return LensFlareSystem;
  81776. }());
  81777. BABYLON.LensFlareSystem = LensFlareSystem;
  81778. })(BABYLON || (BABYLON = {}));
  81779. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81780. var BABYLON;
  81781. (function (BABYLON) {
  81782. /**
  81783. * This is a holder class for the physics joint created by the physics plugin.
  81784. * It holds a set of functions to control the underlying joint.
  81785. */
  81786. var PhysicsJoint = /** @class */ (function () {
  81787. function PhysicsJoint(type, jointData) {
  81788. this.type = type;
  81789. this.jointData = jointData;
  81790. jointData.nativeParams = jointData.nativeParams || {};
  81791. }
  81792. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81793. get: function () {
  81794. return this._physicsJoint;
  81795. },
  81796. set: function (newJoint) {
  81797. if (this._physicsJoint) {
  81798. //remove from the wolrd
  81799. }
  81800. this._physicsJoint = newJoint;
  81801. },
  81802. enumerable: true,
  81803. configurable: true
  81804. });
  81805. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81806. set: function (physicsPlugin) {
  81807. this._physicsPlugin = physicsPlugin;
  81808. },
  81809. enumerable: true,
  81810. configurable: true
  81811. });
  81812. /**
  81813. * Execute a function that is physics-plugin specific.
  81814. * @param {Function} func the function that will be executed.
  81815. * It accepts two parameters: the physics world and the physics joint.
  81816. */
  81817. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81818. func(this._physicsPlugin.world, this._physicsJoint);
  81819. };
  81820. //TODO check if the native joints are the same
  81821. //Joint Types
  81822. PhysicsJoint.DistanceJoint = 0;
  81823. PhysicsJoint.HingeJoint = 1;
  81824. PhysicsJoint.BallAndSocketJoint = 2;
  81825. PhysicsJoint.WheelJoint = 3;
  81826. PhysicsJoint.SliderJoint = 4;
  81827. //OIMO
  81828. PhysicsJoint.PrismaticJoint = 5;
  81829. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81830. PhysicsJoint.UniversalJoint = 6;
  81831. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81832. //Cannon
  81833. //Similar to a Ball-Joint. Different in params
  81834. PhysicsJoint.PointToPointJoint = 8;
  81835. //Cannon only at the moment
  81836. PhysicsJoint.SpringJoint = 9;
  81837. PhysicsJoint.LockJoint = 10;
  81838. return PhysicsJoint;
  81839. }());
  81840. BABYLON.PhysicsJoint = PhysicsJoint;
  81841. /**
  81842. * A class representing a physics distance joint.
  81843. */
  81844. var DistanceJoint = /** @class */ (function (_super) {
  81845. __extends(DistanceJoint, _super);
  81846. function DistanceJoint(jointData) {
  81847. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81848. }
  81849. /**
  81850. * Update the predefined distance.
  81851. */
  81852. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81853. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81854. };
  81855. return DistanceJoint;
  81856. }(PhysicsJoint));
  81857. BABYLON.DistanceJoint = DistanceJoint;
  81858. var MotorEnabledJoint = /** @class */ (function (_super) {
  81859. __extends(MotorEnabledJoint, _super);
  81860. function MotorEnabledJoint(type, jointData) {
  81861. return _super.call(this, type, jointData) || this;
  81862. }
  81863. /**
  81864. * Set the motor values.
  81865. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81866. * @param {number} force the force to apply
  81867. * @param {number} maxForce max force for this motor.
  81868. */
  81869. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81870. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81871. };
  81872. /**
  81873. * Set the motor's limits.
  81874. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81875. */
  81876. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81877. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81878. };
  81879. return MotorEnabledJoint;
  81880. }(PhysicsJoint));
  81881. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81882. /**
  81883. * This class represents a single hinge physics joint
  81884. */
  81885. var HingeJoint = /** @class */ (function (_super) {
  81886. __extends(HingeJoint, _super);
  81887. function HingeJoint(jointData) {
  81888. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81889. }
  81890. /**
  81891. * Set the motor values.
  81892. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81893. * @param {number} force the force to apply
  81894. * @param {number} maxForce max force for this motor.
  81895. */
  81896. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81897. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81898. };
  81899. /**
  81900. * Set the motor's limits.
  81901. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81902. */
  81903. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81904. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81905. };
  81906. return HingeJoint;
  81907. }(MotorEnabledJoint));
  81908. BABYLON.HingeJoint = HingeJoint;
  81909. /**
  81910. * This class represents a dual hinge physics joint (same as wheel joint)
  81911. */
  81912. var Hinge2Joint = /** @class */ (function (_super) {
  81913. __extends(Hinge2Joint, _super);
  81914. function Hinge2Joint(jointData) {
  81915. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81916. }
  81917. /**
  81918. * Set the motor values.
  81919. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81920. * @param {number} force the force to apply
  81921. * @param {number} maxForce max force for this motor.
  81922. * @param {motorIndex} the motor's index, 0 or 1.
  81923. */
  81924. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81925. if (motorIndex === void 0) { motorIndex = 0; }
  81926. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81927. };
  81928. /**
  81929. * Set the motor limits.
  81930. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81931. * @param {number} upperLimit the upper limit
  81932. * @param {number} lowerLimit lower limit
  81933. * @param {motorIndex} the motor's index, 0 or 1.
  81934. */
  81935. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81936. if (motorIndex === void 0) { motorIndex = 0; }
  81937. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81938. };
  81939. return Hinge2Joint;
  81940. }(MotorEnabledJoint));
  81941. BABYLON.Hinge2Joint = Hinge2Joint;
  81942. })(BABYLON || (BABYLON = {}));
  81943. //# sourceMappingURL=babylon.physicsJoint.js.map
  81944. var BABYLON;
  81945. (function (BABYLON) {
  81946. var PhysicsImpostor = /** @class */ (function () {
  81947. function PhysicsImpostor(object, type, _options, _scene) {
  81948. if (_options === void 0) { _options = { mass: 0 }; }
  81949. var _this = this;
  81950. this.object = object;
  81951. this.type = type;
  81952. this._options = _options;
  81953. this._scene = _scene;
  81954. this._bodyUpdateRequired = false;
  81955. this._onBeforePhysicsStepCallbacks = new Array();
  81956. this._onAfterPhysicsStepCallbacks = new Array();
  81957. this._onPhysicsCollideCallbacks = [];
  81958. this._deltaPosition = BABYLON.Vector3.Zero();
  81959. this._isDisposed = false;
  81960. //temp variables for parent rotation calculations
  81961. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81962. this._tmpQuat = new BABYLON.Quaternion();
  81963. this._tmpQuat2 = new BABYLON.Quaternion();
  81964. /**
  81965. * this function is executed by the physics engine.
  81966. */
  81967. this.beforeStep = function () {
  81968. if (!_this._physicsEngine) {
  81969. return;
  81970. }
  81971. _this.object.translate(_this._deltaPosition, -1);
  81972. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81973. _this.object.computeWorldMatrix(false);
  81974. if (_this.object.parent && _this.object.rotationQuaternion) {
  81975. _this.getParentsRotation();
  81976. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81977. }
  81978. else {
  81979. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81980. }
  81981. if (!_this._options.disableBidirectionalTransformation) {
  81982. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81983. }
  81984. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81985. func(_this);
  81986. });
  81987. };
  81988. /**
  81989. * this function is executed by the physics engine.
  81990. */
  81991. this.afterStep = function () {
  81992. if (!_this._physicsEngine) {
  81993. return;
  81994. }
  81995. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81996. func(_this);
  81997. });
  81998. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81999. // object has now its world rotation. needs to be converted to local.
  82000. if (_this.object.parent && _this.object.rotationQuaternion) {
  82001. _this.getParentsRotation();
  82002. _this._tmpQuat.conjugateInPlace();
  82003. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  82004. }
  82005. // take the position set and make it the absolute position of this object.
  82006. _this.object.setAbsolutePosition(_this.object.position);
  82007. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  82008. _this.object.translate(_this._deltaPosition, 1);
  82009. };
  82010. /**
  82011. * Legacy collision detection event support
  82012. */
  82013. this.onCollideEvent = null;
  82014. //event and body object due to cannon's event-based architecture.
  82015. this.onCollide = function (e) {
  82016. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  82017. return;
  82018. }
  82019. if (!_this._physicsEngine) {
  82020. return;
  82021. }
  82022. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  82023. if (otherImpostor) {
  82024. // Legacy collision detection event support
  82025. if (_this.onCollideEvent) {
  82026. _this.onCollideEvent(_this, otherImpostor);
  82027. }
  82028. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  82029. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  82030. }).forEach(function (obj) {
  82031. obj.callback(_this, otherImpostor);
  82032. });
  82033. }
  82034. };
  82035. //sanity check!
  82036. if (!this.object) {
  82037. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  82038. return;
  82039. }
  82040. //legacy support for old syntax.
  82041. if (!this._scene && object.getScene) {
  82042. this._scene = object.getScene();
  82043. }
  82044. if (!this._scene) {
  82045. return;
  82046. }
  82047. this._physicsEngine = this._scene.getPhysicsEngine();
  82048. if (!this._physicsEngine) {
  82049. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  82050. }
  82051. else {
  82052. //set the object's quaternion, if not set
  82053. if (!this.object.rotationQuaternion) {
  82054. if (this.object.rotation) {
  82055. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  82056. }
  82057. else {
  82058. this.object.rotationQuaternion = new BABYLON.Quaternion();
  82059. }
  82060. }
  82061. //default options params
  82062. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  82063. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  82064. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  82065. this._joints = [];
  82066. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  82067. if (!this.object.parent || this._options.ignoreParent) {
  82068. this._init();
  82069. }
  82070. else if (this.object.parent.physicsImpostor) {
  82071. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  82072. }
  82073. }
  82074. }
  82075. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  82076. get: function () {
  82077. return this._isDisposed;
  82078. },
  82079. enumerable: true,
  82080. configurable: true
  82081. });
  82082. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  82083. get: function () {
  82084. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  82085. },
  82086. set: function (value) {
  82087. this.setMass(value);
  82088. },
  82089. enumerable: true,
  82090. configurable: true
  82091. });
  82092. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  82093. get: function () {
  82094. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  82095. },
  82096. set: function (value) {
  82097. if (!this._physicsEngine) {
  82098. return;
  82099. }
  82100. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  82101. },
  82102. enumerable: true,
  82103. configurable: true
  82104. });
  82105. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  82106. get: function () {
  82107. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  82108. },
  82109. set: function (value) {
  82110. if (!this._physicsEngine) {
  82111. return;
  82112. }
  82113. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  82114. },
  82115. enumerable: true,
  82116. configurable: true
  82117. });
  82118. /**
  82119. * This function will completly initialize this impostor.
  82120. * It will create a new body - but only if this mesh has no parent.
  82121. * If it has, this impostor will not be used other than to define the impostor
  82122. * of the child mesh.
  82123. */
  82124. PhysicsImpostor.prototype._init = function () {
  82125. if (!this._physicsEngine) {
  82126. return;
  82127. }
  82128. this._physicsEngine.removeImpostor(this);
  82129. this.physicsBody = null;
  82130. this._parent = this._parent || this._getPhysicsParent();
  82131. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  82132. this._physicsEngine.addImpostor(this);
  82133. }
  82134. };
  82135. PhysicsImpostor.prototype._getPhysicsParent = function () {
  82136. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  82137. var parentMesh = this.object.parent;
  82138. return parentMesh.physicsImpostor;
  82139. }
  82140. return null;
  82141. };
  82142. /**
  82143. * Should a new body be generated.
  82144. */
  82145. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  82146. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  82147. };
  82148. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  82149. this.forceUpdate();
  82150. };
  82151. /**
  82152. * Force a regeneration of this or the parent's impostor's body.
  82153. * Use under cautious - This will remove all joints already implemented.
  82154. */
  82155. PhysicsImpostor.prototype.forceUpdate = function () {
  82156. this._init();
  82157. if (this.parent && !this._options.ignoreParent) {
  82158. this.parent.forceUpdate();
  82159. }
  82160. };
  82161. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  82162. /*public get mesh(): AbstractMesh {
  82163. return this._mesh;
  82164. }*/
  82165. /**
  82166. * Gets the body that holds this impostor. Either its own, or its parent.
  82167. */
  82168. get: function () {
  82169. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  82170. },
  82171. /**
  82172. * Set the physics body. Used mainly by the physics engine/plugin
  82173. */
  82174. set: function (physicsBody) {
  82175. if (this._physicsBody && this._physicsEngine) {
  82176. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  82177. }
  82178. this._physicsBody = physicsBody;
  82179. this.resetUpdateFlags();
  82180. },
  82181. enumerable: true,
  82182. configurable: true
  82183. });
  82184. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  82185. get: function () {
  82186. return !this._options.ignoreParent && this._parent ? this._parent : null;
  82187. },
  82188. set: function (value) {
  82189. this._parent = value;
  82190. },
  82191. enumerable: true,
  82192. configurable: true
  82193. });
  82194. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  82195. this._bodyUpdateRequired = false;
  82196. };
  82197. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  82198. if (this.object.getBoundingInfo) {
  82199. var q = this.object.rotationQuaternion;
  82200. //reset rotation
  82201. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  82202. //calculate the world matrix with no rotation
  82203. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82204. var boundingInfo = this.object.getBoundingInfo();
  82205. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  82206. //bring back the rotation
  82207. this.object.rotationQuaternion = q;
  82208. //calculate the world matrix with the new rotation
  82209. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82210. return size;
  82211. }
  82212. else {
  82213. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  82214. }
  82215. };
  82216. PhysicsImpostor.prototype.getObjectCenter = function () {
  82217. if (this.object.getBoundingInfo) {
  82218. var boundingInfo = this.object.getBoundingInfo();
  82219. return boundingInfo.boundingBox.centerWorld;
  82220. }
  82221. else {
  82222. return this.object.position;
  82223. }
  82224. };
  82225. /**
  82226. * Get a specific parametes from the options parameter.
  82227. */
  82228. PhysicsImpostor.prototype.getParam = function (paramName) {
  82229. return this._options[paramName];
  82230. };
  82231. /**
  82232. * Sets a specific parameter in the options given to the physics plugin
  82233. */
  82234. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  82235. this._options[paramName] = value;
  82236. this._bodyUpdateRequired = true;
  82237. };
  82238. /**
  82239. * Specifically change the body's mass option. Won't recreate the physics body object
  82240. */
  82241. PhysicsImpostor.prototype.setMass = function (mass) {
  82242. if (this.getParam("mass") !== mass) {
  82243. this.setParam("mass", mass);
  82244. }
  82245. if (this._physicsEngine) {
  82246. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82247. }
  82248. };
  82249. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82250. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82251. };
  82252. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82253. if (this._physicsEngine) {
  82254. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82255. }
  82256. };
  82257. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82258. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82259. };
  82260. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82261. if (this._physicsEngine) {
  82262. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82263. }
  82264. };
  82265. /**
  82266. * Execute a function with the physics plugin native code.
  82267. * Provide a function the will have two variables - the world object and the physics body object.
  82268. */
  82269. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82270. if (this._physicsEngine) {
  82271. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82272. }
  82273. };
  82274. /**
  82275. * Register a function that will be executed before the physics world is stepping forward.
  82276. */
  82277. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82278. this._onBeforePhysicsStepCallbacks.push(func);
  82279. };
  82280. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82281. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82282. if (index > -1) {
  82283. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82284. }
  82285. else {
  82286. BABYLON.Tools.Warn("Function to remove was not found");
  82287. }
  82288. };
  82289. /**
  82290. * Register a function that will be executed after the physics step
  82291. */
  82292. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82293. this._onAfterPhysicsStepCallbacks.push(func);
  82294. };
  82295. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82296. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82297. if (index > -1) {
  82298. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82299. }
  82300. else {
  82301. BABYLON.Tools.Warn("Function to remove was not found");
  82302. }
  82303. };
  82304. /**
  82305. * register a function that will be executed when this impostor collides against a different body.
  82306. */
  82307. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82308. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82309. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82310. };
  82311. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82312. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82313. var index = -1;
  82314. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  82315. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  82316. // chcek the arrays match
  82317. var sameList = cbDef.otherImpostors.every(function (impostor) {
  82318. return collidedAgainstList.indexOf(impostor) > -1;
  82319. });
  82320. if (sameList) {
  82321. index = idx;
  82322. }
  82323. return sameList;
  82324. }
  82325. return false;
  82326. });
  82327. if (found) {
  82328. this._onPhysicsCollideCallbacks.splice(index, 1);
  82329. }
  82330. else {
  82331. BABYLON.Tools.Warn("Function to remove was not found");
  82332. }
  82333. };
  82334. PhysicsImpostor.prototype.getParentsRotation = function () {
  82335. var parent = this.object.parent;
  82336. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82337. while (parent) {
  82338. if (parent.rotationQuaternion) {
  82339. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82340. }
  82341. else {
  82342. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82343. }
  82344. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82345. parent = parent.parent;
  82346. }
  82347. return this._tmpQuat;
  82348. };
  82349. /**
  82350. * Apply a force
  82351. */
  82352. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82353. if (this._physicsEngine) {
  82354. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82355. }
  82356. return this;
  82357. };
  82358. /**
  82359. * Apply an impulse
  82360. */
  82361. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82362. if (this._physicsEngine) {
  82363. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82364. }
  82365. return this;
  82366. };
  82367. /**
  82368. * A help function to create a joint.
  82369. */
  82370. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82371. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82372. this.addJoint(otherImpostor, joint);
  82373. return this;
  82374. };
  82375. /**
  82376. * Add a joint to this impostor with a different impostor.
  82377. */
  82378. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82379. this._joints.push({
  82380. otherImpostor: otherImpostor,
  82381. joint: joint
  82382. });
  82383. if (this._physicsEngine) {
  82384. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82385. }
  82386. return this;
  82387. };
  82388. /**
  82389. * Will keep this body still, in a sleep mode.
  82390. */
  82391. PhysicsImpostor.prototype.sleep = function () {
  82392. if (this._physicsEngine) {
  82393. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82394. }
  82395. return this;
  82396. };
  82397. /**
  82398. * Wake the body up.
  82399. */
  82400. PhysicsImpostor.prototype.wakeUp = function () {
  82401. if (this._physicsEngine) {
  82402. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82403. }
  82404. return this;
  82405. };
  82406. PhysicsImpostor.prototype.clone = function (newObject) {
  82407. if (!newObject)
  82408. return null;
  82409. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82410. };
  82411. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82412. var _this = this;
  82413. //no dispose if no physics engine is available.
  82414. if (!this._physicsEngine) {
  82415. return;
  82416. }
  82417. this._joints.forEach(function (j) {
  82418. if (_this._physicsEngine) {
  82419. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82420. }
  82421. });
  82422. //dispose the physics body
  82423. this._physicsEngine.removeImpostor(this);
  82424. if (this.parent) {
  82425. this.parent.forceUpdate();
  82426. }
  82427. else {
  82428. /*this._object.getChildMeshes().forEach(function(mesh) {
  82429. if (mesh.physicsImpostor) {
  82430. if (disposeChildren) {
  82431. mesh.physicsImpostor.dispose();
  82432. mesh.physicsImpostor = null;
  82433. }
  82434. }
  82435. })*/
  82436. }
  82437. this._isDisposed = true;
  82438. };
  82439. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82440. this._deltaPosition.copyFrom(position);
  82441. };
  82442. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82443. if (!this._deltaRotation) {
  82444. this._deltaRotation = new BABYLON.Quaternion();
  82445. }
  82446. this._deltaRotation.copyFrom(rotation);
  82447. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82448. };
  82449. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82450. if (this._physicsEngine) {
  82451. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82452. }
  82453. return this;
  82454. };
  82455. PhysicsImpostor.prototype.getRadius = function () {
  82456. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82457. };
  82458. /**
  82459. * Sync a bone with this impostor
  82460. * @param bone The bone to sync to the impostor.
  82461. * @param boneMesh The mesh that the bone is influencing.
  82462. * @param jointPivot The pivot of the joint / bone in local space.
  82463. * @param distToJoint Optional distance from the impostor to the joint.
  82464. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82465. */
  82466. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82467. var tempVec = PhysicsImpostor._tmpVecs[0];
  82468. var mesh = this.object;
  82469. if (mesh.rotationQuaternion) {
  82470. if (adjustRotation) {
  82471. var tempQuat = PhysicsImpostor._tmpQuat;
  82472. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82473. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82474. }
  82475. else {
  82476. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82477. }
  82478. }
  82479. tempVec.x = 0;
  82480. tempVec.y = 0;
  82481. tempVec.z = 0;
  82482. if (jointPivot) {
  82483. tempVec.x = jointPivot.x;
  82484. tempVec.y = jointPivot.y;
  82485. tempVec.z = jointPivot.z;
  82486. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82487. if (distToJoint === undefined || distToJoint === null) {
  82488. distToJoint = jointPivot.length();
  82489. }
  82490. tempVec.x *= distToJoint;
  82491. tempVec.y *= distToJoint;
  82492. tempVec.z *= distToJoint;
  82493. }
  82494. if (bone.getParent()) {
  82495. tempVec.addInPlace(mesh.getAbsolutePosition());
  82496. bone.setAbsolutePosition(tempVec, boneMesh);
  82497. }
  82498. else {
  82499. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82500. boneMesh.position.x -= tempVec.x;
  82501. boneMesh.position.y -= tempVec.y;
  82502. boneMesh.position.z -= tempVec.z;
  82503. }
  82504. };
  82505. /**
  82506. * Sync impostor to a bone
  82507. * @param bone The bone that the impostor will be synced to.
  82508. * @param boneMesh The mesh that the bone is influencing.
  82509. * @param jointPivot The pivot of the joint / bone in local space.
  82510. * @param distToJoint Optional distance from the impostor to the joint.
  82511. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82512. * @param boneAxis Optional vector3 axis the bone is aligned with
  82513. */
  82514. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82515. var mesh = this.object;
  82516. if (mesh.rotationQuaternion) {
  82517. if (adjustRotation) {
  82518. var tempQuat = PhysicsImpostor._tmpQuat;
  82519. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82520. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82521. }
  82522. else {
  82523. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82524. }
  82525. }
  82526. var pos = PhysicsImpostor._tmpVecs[0];
  82527. var boneDir = PhysicsImpostor._tmpVecs[1];
  82528. if (!boneAxis) {
  82529. boneAxis = PhysicsImpostor._tmpVecs[2];
  82530. boneAxis.x = 0;
  82531. boneAxis.y = 1;
  82532. boneAxis.z = 0;
  82533. }
  82534. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82535. bone.getAbsolutePositionToRef(boneMesh, pos);
  82536. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82537. distToJoint = jointPivot.length();
  82538. }
  82539. if (distToJoint !== undefined && distToJoint !== null) {
  82540. pos.x += boneDir.x * distToJoint;
  82541. pos.y += boneDir.y * distToJoint;
  82542. pos.z += boneDir.z * distToJoint;
  82543. }
  82544. mesh.setAbsolutePosition(pos);
  82545. };
  82546. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82547. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82548. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82549. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82550. //Impostor types
  82551. PhysicsImpostor.NoImpostor = 0;
  82552. PhysicsImpostor.SphereImpostor = 1;
  82553. PhysicsImpostor.BoxImpostor = 2;
  82554. PhysicsImpostor.PlaneImpostor = 3;
  82555. PhysicsImpostor.MeshImpostor = 4;
  82556. PhysicsImpostor.CylinderImpostor = 7;
  82557. PhysicsImpostor.ParticleImpostor = 8;
  82558. PhysicsImpostor.HeightmapImpostor = 9;
  82559. return PhysicsImpostor;
  82560. }());
  82561. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82562. })(BABYLON || (BABYLON = {}));
  82563. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82564. var BABYLON;
  82565. (function (BABYLON) {
  82566. var PhysicsEngine = /** @class */ (function () {
  82567. function PhysicsEngine(gravity, _physicsPlugin) {
  82568. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82569. this._physicsPlugin = _physicsPlugin;
  82570. //new methods and parameters
  82571. this._impostors = [];
  82572. this._joints = [];
  82573. if (!this._physicsPlugin.isSupported()) {
  82574. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82575. + "Please make sure it is included.");
  82576. }
  82577. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82578. this.setGravity(gravity);
  82579. this.setTimeStep();
  82580. }
  82581. PhysicsEngine.prototype.setGravity = function (gravity) {
  82582. this.gravity = gravity;
  82583. this._physicsPlugin.setGravity(this.gravity);
  82584. };
  82585. /**
  82586. * Set the time step of the physics engine.
  82587. * default is 1/60.
  82588. * To slow it down, enter 1/600 for example.
  82589. * To speed it up, 1/30
  82590. * @param {number} newTimeStep the new timestep to apply to this world.
  82591. */
  82592. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82593. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82594. this._physicsPlugin.setTimeStep(newTimeStep);
  82595. };
  82596. /**
  82597. * Get the time step of the physics engine.
  82598. */
  82599. PhysicsEngine.prototype.getTimeStep = function () {
  82600. return this._physicsPlugin.getTimeStep();
  82601. };
  82602. PhysicsEngine.prototype.dispose = function () {
  82603. this._impostors.forEach(function (impostor) {
  82604. impostor.dispose();
  82605. });
  82606. this._physicsPlugin.dispose();
  82607. };
  82608. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82609. return this._physicsPlugin.name;
  82610. };
  82611. /**
  82612. * Adding a new impostor for the impostor tracking.
  82613. * This will be done by the impostor itself.
  82614. * @param {PhysicsImpostor} impostor the impostor to add
  82615. */
  82616. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82617. impostor.uniqueId = this._impostors.push(impostor);
  82618. //if no parent, generate the body
  82619. if (!impostor.parent) {
  82620. this._physicsPlugin.generatePhysicsBody(impostor);
  82621. }
  82622. };
  82623. /**
  82624. * Remove an impostor from the engine.
  82625. * This impostor and its mesh will not longer be updated by the physics engine.
  82626. * @param {PhysicsImpostor} impostor the impostor to remove
  82627. */
  82628. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82629. var index = this._impostors.indexOf(impostor);
  82630. if (index > -1) {
  82631. var removed = this._impostors.splice(index, 1);
  82632. //Is it needed?
  82633. if (removed.length) {
  82634. //this will also remove it from the world.
  82635. removed[0].physicsBody = null;
  82636. }
  82637. }
  82638. };
  82639. /**
  82640. * Add a joint to the physics engine
  82641. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82642. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82643. * @param {PhysicsJoint} the joint that will connect both impostors.
  82644. */
  82645. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82646. var impostorJoint = {
  82647. mainImpostor: mainImpostor,
  82648. connectedImpostor: connectedImpostor,
  82649. joint: joint
  82650. };
  82651. joint.physicsPlugin = this._physicsPlugin;
  82652. this._joints.push(impostorJoint);
  82653. this._physicsPlugin.generateJoint(impostorJoint);
  82654. };
  82655. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82656. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82657. return (impostorJoint.connectedImpostor === connectedImpostor
  82658. && impostorJoint.joint === joint
  82659. && impostorJoint.mainImpostor === mainImpostor);
  82660. });
  82661. if (matchingJoints.length) {
  82662. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82663. //TODO remove it from the list as well
  82664. }
  82665. };
  82666. /**
  82667. * Called by the scene. no need to call it.
  82668. */
  82669. PhysicsEngine.prototype._step = function (delta) {
  82670. var _this = this;
  82671. //check if any mesh has no body / requires an update
  82672. this._impostors.forEach(function (impostor) {
  82673. if (impostor.isBodyInitRequired()) {
  82674. _this._physicsPlugin.generatePhysicsBody(impostor);
  82675. }
  82676. });
  82677. if (delta > 0.1) {
  82678. delta = 0.1;
  82679. }
  82680. else if (delta <= 0) {
  82681. delta = 1.0 / 60.0;
  82682. }
  82683. this._physicsPlugin.executeStep(delta, this._impostors);
  82684. };
  82685. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82686. return this._physicsPlugin;
  82687. };
  82688. PhysicsEngine.prototype.getImpostors = function () {
  82689. return this._impostors;
  82690. };
  82691. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82692. for (var i = 0; i < this._impostors.length; ++i) {
  82693. if (this._impostors[i].object === object) {
  82694. return this._impostors[i];
  82695. }
  82696. }
  82697. return null;
  82698. };
  82699. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82700. for (var i = 0; i < this._impostors.length; ++i) {
  82701. if (this._impostors[i].physicsBody === body) {
  82702. return this._impostors[i];
  82703. }
  82704. }
  82705. return null;
  82706. };
  82707. // Statics
  82708. PhysicsEngine.Epsilon = 0.001;
  82709. return PhysicsEngine;
  82710. }());
  82711. BABYLON.PhysicsEngine = PhysicsEngine;
  82712. })(BABYLON || (BABYLON = {}));
  82713. //# sourceMappingURL=babylon.physicsEngine.js.map
  82714. var BABYLON;
  82715. (function (BABYLON) {
  82716. var PhysicsHelper = /** @class */ (function () {
  82717. function PhysicsHelper(scene) {
  82718. this._scene = scene;
  82719. this._physicsEngine = this._scene.getPhysicsEngine();
  82720. if (!this._physicsEngine) {
  82721. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82722. }
  82723. }
  82724. /**
  82725. * @param {Vector3} origin the origin of the explosion
  82726. * @param {number} radius the explosion radius
  82727. * @param {number} strength the explosion strength
  82728. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82729. */
  82730. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82731. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82732. if (!this._physicsEngine) {
  82733. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82734. return null;
  82735. }
  82736. var impostors = this._physicsEngine.getImpostors();
  82737. if (impostors.length === 0) {
  82738. return null;
  82739. }
  82740. var event = new PhysicsRadialExplosionEvent(this._scene);
  82741. impostors.forEach(function (impostor) {
  82742. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82743. if (!impostorForceAndContactPoint) {
  82744. return;
  82745. }
  82746. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82747. });
  82748. event.dispose(false);
  82749. return event;
  82750. };
  82751. /**
  82752. * @param {Vector3} origin the origin of the explosion
  82753. * @param {number} radius the explosion radius
  82754. * @param {number} strength the explosion strength
  82755. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82756. */
  82757. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82758. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82759. if (!this._physicsEngine) {
  82760. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82761. return null;
  82762. }
  82763. var impostors = this._physicsEngine.getImpostors();
  82764. if (impostors.length === 0) {
  82765. return null;
  82766. }
  82767. var event = new PhysicsRadialExplosionEvent(this._scene);
  82768. impostors.forEach(function (impostor) {
  82769. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82770. if (!impostorForceAndContactPoint) {
  82771. return;
  82772. }
  82773. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82774. });
  82775. event.dispose(false);
  82776. return event;
  82777. };
  82778. /**
  82779. * @param {Vector3} origin the origin of the explosion
  82780. * @param {number} radius the explosion radius
  82781. * @param {number} strength the explosion strength
  82782. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82783. */
  82784. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82785. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82786. if (!this._physicsEngine) {
  82787. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82788. return null;
  82789. }
  82790. var impostors = this._physicsEngine.getImpostors();
  82791. if (impostors.length === 0) {
  82792. return null;
  82793. }
  82794. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82795. event.dispose(false);
  82796. return event;
  82797. };
  82798. /**
  82799. * @param {Vector3} origin the origin of the updraft
  82800. * @param {number} radius the radius of the updraft
  82801. * @param {number} strength the strength of the updraft
  82802. * @param {number} height the height of the updraft
  82803. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82804. */
  82805. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82806. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82807. if (!this._physicsEngine) {
  82808. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82809. return null;
  82810. }
  82811. if (this._physicsEngine.getImpostors().length === 0) {
  82812. return null;
  82813. }
  82814. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82815. event.dispose(false);
  82816. return event;
  82817. };
  82818. /**
  82819. * @param {Vector3} origin the of the vortex
  82820. * @param {number} radius the radius of the vortex
  82821. * @param {number} strength the strength of the vortex
  82822. * @param {number} height the height of the vortex
  82823. */
  82824. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82825. if (!this._physicsEngine) {
  82826. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82827. return null;
  82828. }
  82829. if (this._physicsEngine.getImpostors().length === 0) {
  82830. return null;
  82831. }
  82832. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82833. event.dispose(false);
  82834. return event;
  82835. };
  82836. return PhysicsHelper;
  82837. }());
  82838. BABYLON.PhysicsHelper = PhysicsHelper;
  82839. /***** Radial explosion *****/
  82840. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82841. function PhysicsRadialExplosionEvent(scene) {
  82842. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82843. this._rays = [];
  82844. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82845. this._scene = scene;
  82846. }
  82847. /**
  82848. * Returns the data related to the radial explosion event (sphere & rays).
  82849. * @returns {PhysicsRadialExplosionEventData}
  82850. */
  82851. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82852. this._dataFetched = true;
  82853. return {
  82854. sphere: this._sphere,
  82855. rays: this._rays,
  82856. };
  82857. };
  82858. /**
  82859. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82860. * @param impostor
  82861. * @param {Vector3} origin the origin of the explosion
  82862. * @param {number} radius the explosion radius
  82863. * @param {number} strength the explosion strength
  82864. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82865. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82866. */
  82867. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82868. if (impostor.mass === 0) {
  82869. return null;
  82870. }
  82871. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82872. return null;
  82873. }
  82874. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82875. return null;
  82876. }
  82877. var impostorObjectCenter = impostor.getObjectCenter();
  82878. var direction = impostorObjectCenter.subtract(origin);
  82879. var ray = new BABYLON.Ray(origin, direction, radius);
  82880. this._rays.push(ray);
  82881. var hit = ray.intersectsMesh(impostor.object);
  82882. var contactPoint = hit.pickedPoint;
  82883. if (!contactPoint) {
  82884. return null;
  82885. }
  82886. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82887. if (distanceFromOrigin > radius) {
  82888. return null;
  82889. }
  82890. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82891. ? strength
  82892. : strength * (1 - (distanceFromOrigin / radius));
  82893. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82894. return { force: force, contactPoint: contactPoint };
  82895. };
  82896. /**
  82897. * Disposes the sphere.
  82898. * @param {bolean} force
  82899. */
  82900. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82901. var _this = this;
  82902. if (force === void 0) { force = true; }
  82903. if (force) {
  82904. this._sphere.dispose();
  82905. }
  82906. else {
  82907. setTimeout(function () {
  82908. if (!_this._dataFetched) {
  82909. _this._sphere.dispose();
  82910. }
  82911. }, 0);
  82912. }
  82913. };
  82914. /*** Helpers ***/
  82915. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82916. if (!this._sphere) {
  82917. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82918. this._sphere.isVisible = false;
  82919. }
  82920. };
  82921. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82922. var impostorObject = impostor.object;
  82923. this._prepareSphere();
  82924. this._sphere.position = origin;
  82925. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82926. this._sphere._updateBoundingInfo();
  82927. this._sphere.computeWorldMatrix(true);
  82928. return this._sphere.intersectsMesh(impostorObject, true);
  82929. };
  82930. return PhysicsRadialExplosionEvent;
  82931. }());
  82932. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82933. /***** Gravitational Field *****/
  82934. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82935. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82936. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82937. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82938. this._physicsHelper = physicsHelper;
  82939. this._scene = scene;
  82940. this._origin = origin;
  82941. this._radius = radius;
  82942. this._strength = strength;
  82943. this._falloff = falloff;
  82944. this._tickCallback = this._tick.bind(this);
  82945. }
  82946. /**
  82947. * Returns the data related to the gravitational field event (sphere).
  82948. * @returns {PhysicsGravitationalFieldEventData}
  82949. */
  82950. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82951. this._dataFetched = true;
  82952. return {
  82953. sphere: this._sphere,
  82954. };
  82955. };
  82956. /**
  82957. * Enables the gravitational field.
  82958. */
  82959. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82960. this._tickCallback.call(this);
  82961. this._scene.registerBeforeRender(this._tickCallback);
  82962. };
  82963. /**
  82964. * Disables the gravitational field.
  82965. */
  82966. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82967. this._scene.unregisterBeforeRender(this._tickCallback);
  82968. };
  82969. /**
  82970. * Disposes the sphere.
  82971. * @param {bolean} force
  82972. */
  82973. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82974. var _this = this;
  82975. if (force === void 0) { force = true; }
  82976. if (force) {
  82977. this._sphere.dispose();
  82978. }
  82979. else {
  82980. setTimeout(function () {
  82981. if (!_this._dataFetched) {
  82982. _this._sphere.dispose();
  82983. }
  82984. }, 0);
  82985. }
  82986. };
  82987. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82988. // Since the params won't change, we fetch the event only once
  82989. if (this._sphere) {
  82990. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82991. }
  82992. else {
  82993. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82994. if (radialExplosionEvent) {
  82995. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82996. }
  82997. }
  82998. };
  82999. return PhysicsGravitationalFieldEvent;
  83000. }());
  83001. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  83002. /***** Updraft *****/
  83003. var PhysicsUpdraftEvent = /** @class */ (function () {
  83004. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  83005. this._scene = _scene;
  83006. this._origin = _origin;
  83007. this._radius = _radius;
  83008. this._strength = _strength;
  83009. this._height = _height;
  83010. this._updraftMode = _updraftMode;
  83011. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83012. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  83013. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83014. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83015. this._physicsEngine = this._scene.getPhysicsEngine();
  83016. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83017. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83018. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83019. this._originDirection = this._origin.subtract(this._originTop).normalize();
  83020. }
  83021. this._tickCallback = this._tick.bind(this);
  83022. }
  83023. /**
  83024. * Returns the data related to the updraft event (cylinder).
  83025. * @returns {PhysicsUpdraftEventData}
  83026. */
  83027. PhysicsUpdraftEvent.prototype.getData = function () {
  83028. this._dataFetched = true;
  83029. return {
  83030. cylinder: this._cylinder,
  83031. };
  83032. };
  83033. /**
  83034. * Enables the updraft.
  83035. */
  83036. PhysicsUpdraftEvent.prototype.enable = function () {
  83037. this._tickCallback.call(this);
  83038. this._scene.registerBeforeRender(this._tickCallback);
  83039. };
  83040. /**
  83041. * Disables the cortex.
  83042. */
  83043. PhysicsUpdraftEvent.prototype.disable = function () {
  83044. this._scene.unregisterBeforeRender(this._tickCallback);
  83045. };
  83046. /**
  83047. * Disposes the sphere.
  83048. * @param {bolean} force
  83049. */
  83050. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  83051. var _this = this;
  83052. if (force === void 0) { force = true; }
  83053. if (force) {
  83054. this._cylinder.dispose();
  83055. }
  83056. else {
  83057. setTimeout(function () {
  83058. if (!_this._dataFetched) {
  83059. _this._cylinder.dispose();
  83060. }
  83061. }, 0);
  83062. }
  83063. };
  83064. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83065. if (impostor.mass === 0) {
  83066. return null;
  83067. }
  83068. if (!this._intersectsWithCylinder(impostor)) {
  83069. return null;
  83070. }
  83071. var impostorObjectCenter = impostor.getObjectCenter();
  83072. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83073. var direction = this._originDirection;
  83074. }
  83075. else {
  83076. var direction = impostorObjectCenter.subtract(this._originTop);
  83077. }
  83078. var multiplier = this._strength * -1;
  83079. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83080. return { force: force, contactPoint: impostorObjectCenter };
  83081. };
  83082. PhysicsUpdraftEvent.prototype._tick = function () {
  83083. var _this = this;
  83084. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83085. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83086. if (!impostorForceAndContactPoint) {
  83087. return;
  83088. }
  83089. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83090. });
  83091. };
  83092. /*** Helpers ***/
  83093. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  83094. if (!this._cylinder) {
  83095. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  83096. height: this._height,
  83097. diameter: this._radius * 2,
  83098. }, this._scene);
  83099. this._cylinder.isVisible = false;
  83100. }
  83101. };
  83102. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  83103. var impostorObject = impostor.object;
  83104. this._prepareCylinder();
  83105. this._cylinder.position = this._cylinderPosition;
  83106. return this._cylinder.intersectsMesh(impostorObject, true);
  83107. };
  83108. return PhysicsUpdraftEvent;
  83109. }());
  83110. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  83111. /***** Vortex *****/
  83112. var PhysicsVortexEvent = /** @class */ (function () {
  83113. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  83114. this._scene = _scene;
  83115. this._origin = _origin;
  83116. this._radius = _radius;
  83117. this._strength = _strength;
  83118. this._height = _height;
  83119. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83120. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  83121. this._updraftMultiplier = 0.02;
  83122. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83123. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83124. this._physicsEngine = this._scene.getPhysicsEngine();
  83125. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83126. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83127. this._tickCallback = this._tick.bind(this);
  83128. }
  83129. /**
  83130. * Returns the data related to the vortex event (cylinder).
  83131. * @returns {PhysicsVortexEventData}
  83132. */
  83133. PhysicsVortexEvent.prototype.getData = function () {
  83134. this._dataFetched = true;
  83135. return {
  83136. cylinder: this._cylinder,
  83137. };
  83138. };
  83139. /**
  83140. * Enables the vortex.
  83141. */
  83142. PhysicsVortexEvent.prototype.enable = function () {
  83143. this._tickCallback.call(this);
  83144. this._scene.registerBeforeRender(this._tickCallback);
  83145. };
  83146. /**
  83147. * Disables the cortex.
  83148. */
  83149. PhysicsVortexEvent.prototype.disable = function () {
  83150. this._scene.unregisterBeforeRender(this._tickCallback);
  83151. };
  83152. /**
  83153. * Disposes the sphere.
  83154. * @param {bolean} force
  83155. */
  83156. PhysicsVortexEvent.prototype.dispose = function (force) {
  83157. var _this = this;
  83158. if (force === void 0) { force = true; }
  83159. if (force) {
  83160. this._cylinder.dispose();
  83161. }
  83162. else {
  83163. setTimeout(function () {
  83164. if (!_this._dataFetched) {
  83165. _this._cylinder.dispose();
  83166. }
  83167. }, 0);
  83168. }
  83169. };
  83170. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83171. if (impostor.mass === 0) {
  83172. return null;
  83173. }
  83174. if (!this._intersectsWithCylinder(impostor)) {
  83175. return null;
  83176. }
  83177. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83178. return null;
  83179. }
  83180. var impostorObjectCenter = impostor.getObjectCenter();
  83181. 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)
  83182. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  83183. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  83184. var hit = ray.intersectsMesh(impostor.object);
  83185. var contactPoint = hit.pickedPoint;
  83186. if (!contactPoint) {
  83187. return null;
  83188. }
  83189. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  83190. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  83191. var directionToOrigin = contactPoint.normalize();
  83192. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83193. directionToOrigin = directionToOrigin.negate();
  83194. }
  83195. // TODO: find a more physically based solution
  83196. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83197. var forceX = directionToOrigin.x * this._strength / 8;
  83198. var forceY = directionToOrigin.y * this._updraftMultiplier;
  83199. var forceZ = directionToOrigin.z * this._strength / 8;
  83200. }
  83201. else {
  83202. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  83203. var forceY = this._originTop.y * this._updraftMultiplier;
  83204. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  83205. }
  83206. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  83207. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  83208. return { force: force, contactPoint: impostorObjectCenter };
  83209. };
  83210. PhysicsVortexEvent.prototype._tick = function () {
  83211. var _this = this;
  83212. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83213. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83214. if (!impostorForceAndContactPoint) {
  83215. return;
  83216. }
  83217. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83218. });
  83219. };
  83220. /*** Helpers ***/
  83221. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  83222. if (!this._cylinder) {
  83223. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  83224. height: this._height,
  83225. diameter: this._radius * 2,
  83226. }, this._scene);
  83227. this._cylinder.isVisible = false;
  83228. }
  83229. };
  83230. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  83231. var impostorObject = impostor.object;
  83232. this._prepareCylinder();
  83233. this._cylinder.position = this._cylinderPosition;
  83234. return this._cylinder.intersectsMesh(impostorObject, true);
  83235. };
  83236. return PhysicsVortexEvent;
  83237. }());
  83238. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  83239. /***** Enums *****/
  83240. /**
  83241. * The strenght of the force in correspondence to the distance of the affected object
  83242. */
  83243. var PhysicsRadialImpulseFalloff;
  83244. (function (PhysicsRadialImpulseFalloff) {
  83245. /** Defines that impulse is constant in strength across it's whole radius */
  83246. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  83247. /** DEfines that impulse gets weaker if it's further from the origin */
  83248. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  83249. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  83250. /**
  83251. * The strenght of the force in correspondence to the distance of the affected object
  83252. */
  83253. var PhysicsUpdraftMode;
  83254. (function (PhysicsUpdraftMode) {
  83255. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  83256. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  83257. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  83258. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83259. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83260. })(BABYLON || (BABYLON = {}));
  83261. //# sourceMappingURL=babylon.physicsHelper.js.map
  83262. var BABYLON;
  83263. (function (BABYLON) {
  83264. var CannonJSPlugin = /** @class */ (function () {
  83265. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83266. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83267. if (iterations === void 0) { iterations = 10; }
  83268. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83269. this.name = "CannonJSPlugin";
  83270. this._physicsMaterials = new Array();
  83271. this._fixedTimeStep = 1 / 60;
  83272. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83273. this.BJSCANNON = CANNON;
  83274. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83275. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83276. this._tmpPosition = BABYLON.Vector3.Zero();
  83277. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83278. this._tmpUnityRotation = new BABYLON.Quaternion();
  83279. if (!this.isSupported()) {
  83280. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83281. return;
  83282. }
  83283. this._extendNamespace();
  83284. this.world = new this.BJSCANNON.World();
  83285. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83286. this.world.solver.iterations = iterations;
  83287. }
  83288. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83289. this.world.gravity.copy(gravity);
  83290. };
  83291. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83292. this._fixedTimeStep = timeStep;
  83293. };
  83294. CannonJSPlugin.prototype.getTimeStep = function () {
  83295. return this._fixedTimeStep;
  83296. };
  83297. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83298. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83299. };
  83300. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83301. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83302. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83303. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83304. };
  83305. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83306. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83307. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83308. impostor.physicsBody.applyForce(impulse, worldPoint);
  83309. };
  83310. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83311. //parent-child relationship. Does this impostor has a parent impostor?
  83312. if (impostor.parent) {
  83313. if (impostor.physicsBody) {
  83314. this.removePhysicsBody(impostor);
  83315. //TODO is that needed?
  83316. impostor.forceUpdate();
  83317. }
  83318. return;
  83319. }
  83320. //should a new body be created for this impostor?
  83321. if (impostor.isBodyInitRequired()) {
  83322. var shape = this._createShape(impostor);
  83323. //unregister events, if body is being changed
  83324. var oldBody = impostor.physicsBody;
  83325. if (oldBody) {
  83326. this.removePhysicsBody(impostor);
  83327. }
  83328. //create the body and material
  83329. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83330. var bodyCreationObject = {
  83331. mass: impostor.getParam("mass"),
  83332. material: material
  83333. };
  83334. // A simple extend, in case native options were used.
  83335. var nativeOptions = impostor.getParam("nativeOptions");
  83336. for (var key in nativeOptions) {
  83337. if (nativeOptions.hasOwnProperty(key)) {
  83338. bodyCreationObject[key] = nativeOptions[key];
  83339. }
  83340. }
  83341. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83342. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83343. this.world.addEventListener("preStep", impostor.beforeStep);
  83344. this.world.addEventListener("postStep", impostor.afterStep);
  83345. impostor.physicsBody.addShape(shape);
  83346. this.world.add(impostor.physicsBody);
  83347. //try to keep the body moving in the right direction by taking old properties.
  83348. //Should be tested!
  83349. if (oldBody) {
  83350. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83351. impostor.physicsBody[param].copy(oldBody[param]);
  83352. });
  83353. }
  83354. this._processChildMeshes(impostor);
  83355. }
  83356. //now update the body's transformation
  83357. this._updatePhysicsBodyTransformation(impostor);
  83358. };
  83359. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83360. var _this = this;
  83361. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83362. var currentRotation = mainImpostor.object.rotationQuaternion;
  83363. if (meshChildren.length) {
  83364. var processMesh = function (localPosition, mesh) {
  83365. if (!currentRotation || !mesh.rotationQuaternion) {
  83366. return;
  83367. }
  83368. var childImpostor = mesh.getPhysicsImpostor();
  83369. if (childImpostor) {
  83370. var parent = childImpostor.parent;
  83371. if (parent !== mainImpostor) {
  83372. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83373. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83374. if (childImpostor.physicsBody) {
  83375. _this.removePhysicsBody(childImpostor);
  83376. childImpostor.physicsBody = null;
  83377. }
  83378. childImpostor.parent = mainImpostor;
  83379. childImpostor.resetUpdateFlags();
  83380. 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));
  83381. //Add the mass of the children.
  83382. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83383. }
  83384. }
  83385. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83386. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83387. };
  83388. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83389. }
  83390. };
  83391. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83392. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83393. this.world.removeEventListener("preStep", impostor.beforeStep);
  83394. this.world.removeEventListener("postStep", impostor.afterStep);
  83395. this.world.remove(impostor.physicsBody);
  83396. };
  83397. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83398. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83399. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83400. if (!mainBody || !connectedBody) {
  83401. return;
  83402. }
  83403. var constraint;
  83404. var jointData = impostorJoint.joint.jointData;
  83405. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83406. var constraintData = {
  83407. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83408. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83409. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83410. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83411. maxForce: jointData.nativeParams.maxForce,
  83412. collideConnected: !!jointData.collision
  83413. };
  83414. switch (impostorJoint.joint.type) {
  83415. case BABYLON.PhysicsJoint.HingeJoint:
  83416. case BABYLON.PhysicsJoint.Hinge2Joint:
  83417. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83418. break;
  83419. case BABYLON.PhysicsJoint.DistanceJoint:
  83420. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83421. break;
  83422. case BABYLON.PhysicsJoint.SpringJoint:
  83423. var springData = jointData;
  83424. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83425. restLength: springData.length,
  83426. stiffness: springData.stiffness,
  83427. damping: springData.damping,
  83428. localAnchorA: constraintData.pivotA,
  83429. localAnchorB: constraintData.pivotB
  83430. });
  83431. break;
  83432. case BABYLON.PhysicsJoint.LockJoint:
  83433. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83434. break;
  83435. case BABYLON.PhysicsJoint.PointToPointJoint:
  83436. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83437. default:
  83438. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83439. break;
  83440. }
  83441. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83442. constraint.collideConnected = !!jointData.collision;
  83443. impostorJoint.joint.physicsJoint = constraint;
  83444. //don't add spring as constraint, as it is not one.
  83445. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83446. this.world.addConstraint(constraint);
  83447. }
  83448. else {
  83449. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83450. constraint.applyForce();
  83451. });
  83452. }
  83453. };
  83454. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83455. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83456. };
  83457. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83458. var index;
  83459. var mat;
  83460. for (index = 0; index < this._physicsMaterials.length; index++) {
  83461. mat = this._physicsMaterials[index];
  83462. if (mat.friction === friction && mat.restitution === restitution) {
  83463. return mat;
  83464. }
  83465. }
  83466. var currentMat = new this.BJSCANNON.Material(name);
  83467. currentMat.friction = friction;
  83468. currentMat.restitution = restitution;
  83469. this._physicsMaterials.push(currentMat);
  83470. return currentMat;
  83471. };
  83472. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83473. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83474. };
  83475. CannonJSPlugin.prototype._createShape = function (impostor) {
  83476. var object = impostor.object;
  83477. var returnValue;
  83478. var extendSize = impostor.getObjectExtendSize();
  83479. switch (impostor.type) {
  83480. case BABYLON.PhysicsImpostor.SphereImpostor:
  83481. var radiusX = extendSize.x;
  83482. var radiusY = extendSize.y;
  83483. var radiusZ = extendSize.z;
  83484. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83485. break;
  83486. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83487. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83488. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83489. break;
  83490. case BABYLON.PhysicsImpostor.BoxImpostor:
  83491. var box = extendSize.scale(0.5);
  83492. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83493. break;
  83494. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83495. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83496. returnValue = new this.BJSCANNON.Plane();
  83497. break;
  83498. case BABYLON.PhysicsImpostor.MeshImpostor:
  83499. // should transform the vertex data to world coordinates!!
  83500. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83501. var rawFaces = object.getIndices ? object.getIndices() : [];
  83502. if (!rawVerts)
  83503. return;
  83504. // get only scale! so the object could transform correctly.
  83505. var oldPosition = object.position.clone();
  83506. var oldRotation = object.rotation && object.rotation.clone();
  83507. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83508. object.position.copyFromFloats(0, 0, 0);
  83509. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83510. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83511. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83512. var transform = object.computeWorldMatrix(true);
  83513. // convert rawVerts to object space
  83514. var temp = new Array();
  83515. var index;
  83516. for (index = 0; index < rawVerts.length; index += 3) {
  83517. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83518. }
  83519. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83520. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83521. //now set back the transformation!
  83522. object.position.copyFrom(oldPosition);
  83523. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83524. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83525. break;
  83526. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83527. var oldPosition2 = object.position.clone();
  83528. var oldRotation2 = object.rotation && object.rotation.clone();
  83529. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83530. object.position.copyFromFloats(0, 0, 0);
  83531. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83532. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83533. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83534. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83535. returnValue = this._createHeightmap(object);
  83536. object.position.copyFrom(oldPosition2);
  83537. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83538. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83539. object.computeWorldMatrix(true);
  83540. break;
  83541. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83542. returnValue = new this.BJSCANNON.Particle();
  83543. break;
  83544. }
  83545. return returnValue;
  83546. };
  83547. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83548. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83549. var transform = object.computeWorldMatrix(true);
  83550. // convert rawVerts to object space
  83551. var temp = new Array();
  83552. var index;
  83553. for (index = 0; index < pos.length; index += 3) {
  83554. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83555. }
  83556. pos = temp;
  83557. var matrix = new Array();
  83558. //For now pointDepth will not be used and will be automatically calculated.
  83559. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83560. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83561. var boundingInfo = object.getBoundingInfo();
  83562. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83563. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83564. var elementSize = dim * 2 / arraySize;
  83565. for (var i = 0; i < pos.length; i = i + 3) {
  83566. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83567. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83568. var y = -pos[i + 2] + minY;
  83569. if (!matrix[x]) {
  83570. matrix[x] = [];
  83571. }
  83572. if (!matrix[x][z]) {
  83573. matrix[x][z] = y;
  83574. }
  83575. matrix[x][z] = Math.max(y, matrix[x][z]);
  83576. }
  83577. for (var x = 0; x <= arraySize; ++x) {
  83578. if (!matrix[x]) {
  83579. var loc = 1;
  83580. while (!matrix[(x + loc) % arraySize]) {
  83581. loc++;
  83582. }
  83583. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83584. //console.log("missing x", x);
  83585. }
  83586. for (var z = 0; z <= arraySize; ++z) {
  83587. if (!matrix[x][z]) {
  83588. var loc = 1;
  83589. var newValue;
  83590. while (newValue === undefined) {
  83591. newValue = matrix[x][(z + loc++) % arraySize];
  83592. }
  83593. matrix[x][z] = newValue;
  83594. }
  83595. }
  83596. }
  83597. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83598. elementSize: elementSize
  83599. });
  83600. //For future reference, needed for body transformation
  83601. shape.minY = minY;
  83602. return shape;
  83603. };
  83604. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83605. var object = impostor.object;
  83606. //make sure it is updated...
  83607. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83608. // The delta between the mesh position and the mesh bounding box center
  83609. var bInfo = object.getBoundingInfo();
  83610. if (!bInfo)
  83611. return;
  83612. var center = impostor.getObjectCenter();
  83613. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83614. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83615. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83616. this._tmpPosition.copyFrom(center);
  83617. var quaternion = object.rotationQuaternion;
  83618. if (!quaternion) {
  83619. return;
  83620. }
  83621. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83622. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83623. //-90 DEG in X, precalculated
  83624. quaternion = quaternion.multiply(this._minus90X);
  83625. //Invert! (Precalculated, 90 deg in X)
  83626. //No need to clone. this will never change.
  83627. impostor.setDeltaRotation(this._plus90X);
  83628. }
  83629. //If it is a heightfield, if should be centered.
  83630. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83631. var mesh = object;
  83632. var boundingInfo = mesh.getBoundingInfo();
  83633. //calculate the correct body position:
  83634. var rotationQuaternion = mesh.rotationQuaternion;
  83635. mesh.rotationQuaternion = this._tmpUnityRotation;
  83636. mesh.computeWorldMatrix(true);
  83637. //get original center with no rotation
  83638. var c = center.clone();
  83639. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83640. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83641. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83642. mesh.setPreTransformMatrix(p);
  83643. mesh.computeWorldMatrix(true);
  83644. //calculate the translation
  83645. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83646. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83647. //add it inverted to the delta
  83648. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83649. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83650. //rotation is back
  83651. mesh.rotationQuaternion = rotationQuaternion;
  83652. mesh.setPreTransformMatrix(oldPivot);
  83653. mesh.computeWorldMatrix(true);
  83654. }
  83655. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83656. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83657. //this._tmpPosition.copyFrom(object.position);
  83658. }
  83659. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83660. //Now update the impostor object
  83661. impostor.physicsBody.position.copy(this._tmpPosition);
  83662. impostor.physicsBody.quaternion.copy(quaternion);
  83663. };
  83664. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83665. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83666. if (impostor.object.rotationQuaternion) {
  83667. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83668. }
  83669. };
  83670. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83671. impostor.physicsBody.position.copy(newPosition);
  83672. impostor.physicsBody.quaternion.copy(newRotation);
  83673. };
  83674. CannonJSPlugin.prototype.isSupported = function () {
  83675. return this.BJSCANNON !== undefined;
  83676. };
  83677. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83678. impostor.physicsBody.velocity.copy(velocity);
  83679. };
  83680. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83681. impostor.physicsBody.angularVelocity.copy(velocity);
  83682. };
  83683. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83684. var v = impostor.physicsBody.velocity;
  83685. if (!v) {
  83686. return null;
  83687. }
  83688. return new BABYLON.Vector3(v.x, v.y, v.z);
  83689. };
  83690. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83691. var v = impostor.physicsBody.angularVelocity;
  83692. if (!v) {
  83693. return null;
  83694. }
  83695. return new BABYLON.Vector3(v.x, v.y, v.z);
  83696. };
  83697. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83698. impostor.physicsBody.mass = mass;
  83699. impostor.physicsBody.updateMassProperties();
  83700. };
  83701. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83702. return impostor.physicsBody.mass;
  83703. };
  83704. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83705. return impostor.physicsBody.material.friction;
  83706. };
  83707. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83708. impostor.physicsBody.material.friction = friction;
  83709. };
  83710. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83711. return impostor.physicsBody.material.restitution;
  83712. };
  83713. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83714. impostor.physicsBody.material.restitution = restitution;
  83715. };
  83716. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83717. impostor.physicsBody.sleep();
  83718. };
  83719. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83720. impostor.physicsBody.wakeUp();
  83721. };
  83722. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83723. joint.physicsJoint.distance = maxDistance;
  83724. };
  83725. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83726. // if (!motorIndex) {
  83727. // joint.physicsJoint.enableMotor();
  83728. // }
  83729. // }
  83730. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83731. // if (!motorIndex) {
  83732. // joint.physicsJoint.disableMotor();
  83733. // }
  83734. // }
  83735. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83736. if (!motorIndex) {
  83737. joint.physicsJoint.enableMotor();
  83738. joint.physicsJoint.setMotorSpeed(speed);
  83739. if (maxForce) {
  83740. this.setLimit(joint, maxForce);
  83741. }
  83742. }
  83743. };
  83744. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83745. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83746. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83747. };
  83748. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83749. var body = impostor.physicsBody;
  83750. mesh.position.x = body.position.x;
  83751. mesh.position.y = body.position.y;
  83752. mesh.position.z = body.position.z;
  83753. if (mesh.rotationQuaternion) {
  83754. mesh.rotationQuaternion.x = body.quaternion.x;
  83755. mesh.rotationQuaternion.y = body.quaternion.y;
  83756. mesh.rotationQuaternion.z = body.quaternion.z;
  83757. mesh.rotationQuaternion.w = body.quaternion.w;
  83758. }
  83759. };
  83760. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83761. var shape = impostor.physicsBody.shapes[0];
  83762. return shape.boundingSphereRadius;
  83763. };
  83764. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83765. var shape = impostor.physicsBody.shapes[0];
  83766. result.x = shape.halfExtents.x * 2;
  83767. result.y = shape.halfExtents.y * 2;
  83768. result.z = shape.halfExtents.z * 2;
  83769. };
  83770. CannonJSPlugin.prototype.dispose = function () {
  83771. };
  83772. CannonJSPlugin.prototype._extendNamespace = function () {
  83773. //this will force cannon to execute at least one step when using interpolation
  83774. var step_tmp1 = new this.BJSCANNON.Vec3();
  83775. var Engine = this.BJSCANNON;
  83776. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83777. maxSubSteps = maxSubSteps || 10;
  83778. timeSinceLastCalled = timeSinceLastCalled || 0;
  83779. if (timeSinceLastCalled === 0) {
  83780. this.internalStep(dt);
  83781. this.time += dt;
  83782. }
  83783. else {
  83784. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83785. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83786. var t0 = performance.now();
  83787. for (var i = 0; i !== internalSteps; i++) {
  83788. this.internalStep(dt);
  83789. if (performance.now() - t0 > dt * 1000) {
  83790. break;
  83791. }
  83792. }
  83793. this.time += timeSinceLastCalled;
  83794. var h = this.time % dt;
  83795. var h_div_dt = h / dt;
  83796. var interpvelo = step_tmp1;
  83797. var bodies = this.bodies;
  83798. for (var j = 0; j !== bodies.length; j++) {
  83799. var b = bodies[j];
  83800. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83801. b.position.vsub(b.previousPosition, interpvelo);
  83802. interpvelo.scale(h_div_dt, interpvelo);
  83803. b.position.vadd(interpvelo, b.interpolatedPosition);
  83804. }
  83805. else {
  83806. b.interpolatedPosition.copy(b.position);
  83807. b.interpolatedQuaternion.copy(b.quaternion);
  83808. }
  83809. }
  83810. }
  83811. };
  83812. };
  83813. return CannonJSPlugin;
  83814. }());
  83815. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83816. })(BABYLON || (BABYLON = {}));
  83817. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83818. var BABYLON;
  83819. (function (BABYLON) {
  83820. var OimoJSPlugin = /** @class */ (function () {
  83821. function OimoJSPlugin(iterations) {
  83822. this.name = "OimoJSPlugin";
  83823. this._tmpImpostorsArray = [];
  83824. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83825. this.BJSOIMO = OIMO;
  83826. this.world = new this.BJSOIMO.World({
  83827. iterations: iterations
  83828. });
  83829. this.world.clear();
  83830. }
  83831. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83832. this.world.gravity.copy(gravity);
  83833. };
  83834. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83835. this.world.timeStep = timeStep;
  83836. };
  83837. OimoJSPlugin.prototype.getTimeStep = function () {
  83838. return this.world.timeStep;
  83839. };
  83840. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83841. var _this = this;
  83842. impostors.forEach(function (impostor) {
  83843. impostor.beforeStep();
  83844. });
  83845. this.world.step();
  83846. impostors.forEach(function (impostor) {
  83847. impostor.afterStep();
  83848. //update the ordered impostors array
  83849. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83850. });
  83851. //check for collisions
  83852. var contact = this.world.contacts;
  83853. while (contact !== null) {
  83854. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83855. contact = contact.next;
  83856. continue;
  83857. }
  83858. //is this body colliding with any other? get the impostor
  83859. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83860. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83861. if (!mainImpostor || !collidingImpostor) {
  83862. contact = contact.next;
  83863. continue;
  83864. }
  83865. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83866. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83867. contact = contact.next;
  83868. }
  83869. };
  83870. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83871. var mass = impostor.physicsBody.mass;
  83872. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83873. };
  83874. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83875. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83876. this.applyImpulse(impostor, force, contactPoint);
  83877. };
  83878. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83879. var _this = this;
  83880. //parent-child relationship. Does this impostor has a parent impostor?
  83881. if (impostor.parent) {
  83882. if (impostor.physicsBody) {
  83883. this.removePhysicsBody(impostor);
  83884. //TODO is that needed?
  83885. impostor.forceUpdate();
  83886. }
  83887. return;
  83888. }
  83889. if (impostor.isBodyInitRequired()) {
  83890. var bodyConfig = {
  83891. name: impostor.uniqueId,
  83892. //Oimo must have mass, also for static objects.
  83893. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83894. size: [],
  83895. type: [],
  83896. pos: [],
  83897. posShape: [],
  83898. rot: [],
  83899. rotShape: [],
  83900. move: impostor.getParam("mass") !== 0,
  83901. density: impostor.getParam("mass"),
  83902. friction: impostor.getParam("friction"),
  83903. restitution: impostor.getParam("restitution"),
  83904. //Supporting older versions of Oimo
  83905. world: this.world
  83906. };
  83907. var impostors = [impostor];
  83908. var addToArray = function (parent) {
  83909. if (!parent.getChildMeshes)
  83910. return;
  83911. parent.getChildMeshes().forEach(function (m) {
  83912. if (m.physicsImpostor) {
  83913. impostors.push(m.physicsImpostor);
  83914. //m.physicsImpostor._init();
  83915. }
  83916. });
  83917. };
  83918. addToArray(impostor.object);
  83919. var checkWithEpsilon_1 = function (value) {
  83920. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83921. };
  83922. impostors.forEach(function (i) {
  83923. if (!i.object.rotationQuaternion) {
  83924. return;
  83925. }
  83926. //get the correct bounding box
  83927. var oldQuaternion = i.object.rotationQuaternion;
  83928. var rot = oldQuaternion.toEulerAngles();
  83929. var extendSize = i.getObjectExtendSize();
  83930. var radToDeg = 57.295779513082320876;
  83931. if (i === impostor) {
  83932. var center = impostor.getObjectCenter();
  83933. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83934. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83935. //Can also use Array.prototype.push.apply
  83936. bodyConfig.pos.push(center.x);
  83937. bodyConfig.pos.push(center.y);
  83938. bodyConfig.pos.push(center.z);
  83939. bodyConfig.posShape.push(0, 0, 0);
  83940. //tmp solution
  83941. bodyConfig.rot.push(rot.x * radToDeg);
  83942. bodyConfig.rot.push(rot.y * radToDeg);
  83943. bodyConfig.rot.push(rot.z * radToDeg);
  83944. bodyConfig.rotShape.push(0, 0, 0);
  83945. }
  83946. else {
  83947. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83948. bodyConfig.posShape.push(localPosition.x);
  83949. bodyConfig.posShape.push(localPosition.y);
  83950. bodyConfig.posShape.push(localPosition.z);
  83951. bodyConfig.pos.push(0, 0, 0);
  83952. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83953. bodyConfig.rot.push(0);
  83954. bodyConfig.rot.push(0);
  83955. bodyConfig.rot.push(0);
  83956. bodyConfig.rotShape.push(rot.x * radToDeg);
  83957. bodyConfig.rotShape.push(rot.y * radToDeg);
  83958. bodyConfig.rotShape.push(rot.z * radToDeg);
  83959. }
  83960. // register mesh
  83961. switch (i.type) {
  83962. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83963. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83964. case BABYLON.PhysicsImpostor.SphereImpostor:
  83965. var radiusX = extendSize.x;
  83966. var radiusY = extendSize.y;
  83967. var radiusZ = extendSize.z;
  83968. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83969. bodyConfig.type.push('sphere');
  83970. //due to the way oimo works with compounds, add 3 times
  83971. bodyConfig.size.push(size);
  83972. bodyConfig.size.push(size);
  83973. bodyConfig.size.push(size);
  83974. break;
  83975. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83976. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83977. var sizeY = checkWithEpsilon_1(extendSize.y);
  83978. bodyConfig.type.push('cylinder');
  83979. bodyConfig.size.push(sizeX);
  83980. bodyConfig.size.push(sizeY);
  83981. //due to the way oimo works with compounds, add one more value.
  83982. bodyConfig.size.push(sizeY);
  83983. break;
  83984. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83985. case BABYLON.PhysicsImpostor.BoxImpostor:
  83986. default:
  83987. var sizeX = checkWithEpsilon_1(extendSize.x);
  83988. var sizeY = checkWithEpsilon_1(extendSize.y);
  83989. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83990. bodyConfig.type.push('box');
  83991. //if (i === impostor) {
  83992. bodyConfig.size.push(sizeX);
  83993. bodyConfig.size.push(sizeY);
  83994. bodyConfig.size.push(sizeZ);
  83995. //} else {
  83996. // bodyConfig.size.push(0,0,0);
  83997. //}
  83998. break;
  83999. }
  84000. //actually not needed, but hey...
  84001. i.object.rotationQuaternion = oldQuaternion;
  84002. });
  84003. impostor.physicsBody = this.world.add(bodyConfig);
  84004. }
  84005. else {
  84006. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  84007. }
  84008. impostor.setDeltaPosition(this._tmpPositionVector);
  84009. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  84010. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  84011. };
  84012. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84013. //impostor.physicsBody.dispose();
  84014. //Same as : (older oimo versions)
  84015. this.world.removeRigidBody(impostor.physicsBody);
  84016. };
  84017. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84018. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84019. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84020. if (!mainBody || !connectedBody) {
  84021. return;
  84022. }
  84023. var jointData = impostorJoint.joint.jointData;
  84024. var options = jointData.nativeParams || {};
  84025. var type;
  84026. var nativeJointData = {
  84027. body1: mainBody,
  84028. body2: connectedBody,
  84029. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  84030. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  84031. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  84032. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  84033. min: options.min,
  84034. max: options.max,
  84035. collision: options.collision || jointData.collision,
  84036. spring: options.spring,
  84037. //supporting older version of Oimo
  84038. world: this.world
  84039. };
  84040. switch (impostorJoint.joint.type) {
  84041. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84042. type = "jointBall";
  84043. break;
  84044. case BABYLON.PhysicsJoint.SpringJoint:
  84045. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  84046. var springData = jointData;
  84047. nativeJointData.min = springData.length || nativeJointData.min;
  84048. //Max should also be set, just make sure it is at least min
  84049. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  84050. case BABYLON.PhysicsJoint.DistanceJoint:
  84051. type = "jointDistance";
  84052. nativeJointData.max = jointData.maxDistance;
  84053. break;
  84054. case BABYLON.PhysicsJoint.PrismaticJoint:
  84055. type = "jointPrisme";
  84056. break;
  84057. case BABYLON.PhysicsJoint.SliderJoint:
  84058. type = "jointSlide";
  84059. break;
  84060. case BABYLON.PhysicsJoint.WheelJoint:
  84061. type = "jointWheel";
  84062. break;
  84063. case BABYLON.PhysicsJoint.HingeJoint:
  84064. default:
  84065. type = "jointHinge";
  84066. break;
  84067. }
  84068. nativeJointData.type = type;
  84069. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  84070. };
  84071. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84072. //Bug in Oimo prevents us from disposing a joint in the playground
  84073. //joint.joint.physicsJoint.dispose();
  84074. //So we will bruteforce it!
  84075. try {
  84076. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  84077. }
  84078. catch (e) {
  84079. BABYLON.Tools.Warn(e);
  84080. }
  84081. };
  84082. OimoJSPlugin.prototype.isSupported = function () {
  84083. return this.BJSOIMO !== undefined;
  84084. };
  84085. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84086. if (!impostor.physicsBody.sleeping) {
  84087. //TODO check that
  84088. /*if (impostor.physicsBody.shapes.next) {
  84089. var parentShape = this._getLastShape(impostor.physicsBody);
  84090. impostor.object.position.copyFrom(parentShape.position);
  84091. console.log(parentShape.position);
  84092. } else {*/
  84093. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  84094. //}
  84095. if (impostor.object.rotationQuaternion) {
  84096. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  84097. }
  84098. }
  84099. };
  84100. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84101. var body = impostor.physicsBody;
  84102. body.position.copy(newPosition);
  84103. body.orientation.copy(newRotation);
  84104. body.syncShapes();
  84105. body.awake();
  84106. };
  84107. /*private _getLastShape(body: any): any {
  84108. var lastShape = body.shapes;
  84109. while (lastShape.next) {
  84110. lastShape = lastShape.next;
  84111. }
  84112. return lastShape;
  84113. }*/
  84114. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84115. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  84116. };
  84117. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84118. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  84119. };
  84120. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84121. var v = impostor.physicsBody.linearVelocity;
  84122. if (!v) {
  84123. return null;
  84124. }
  84125. return new BABYLON.Vector3(v.x, v.y, v.z);
  84126. };
  84127. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84128. var v = impostor.physicsBody.angularVelocity;
  84129. if (!v) {
  84130. return null;
  84131. }
  84132. return new BABYLON.Vector3(v.x, v.y, v.z);
  84133. };
  84134. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84135. var staticBody = mass === 0;
  84136. //this will actually set the body's density and not its mass.
  84137. //But this is how oimo treats the mass variable.
  84138. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  84139. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  84140. };
  84141. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  84142. return impostor.physicsBody.shapes.density;
  84143. };
  84144. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  84145. return impostor.physicsBody.shapes.friction;
  84146. };
  84147. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84148. impostor.physicsBody.shapes.friction = friction;
  84149. };
  84150. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84151. return impostor.physicsBody.shapes.restitution;
  84152. };
  84153. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84154. impostor.physicsBody.shapes.restitution = restitution;
  84155. };
  84156. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  84157. impostor.physicsBody.sleep();
  84158. };
  84159. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  84160. impostor.physicsBody.awake();
  84161. };
  84162. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84163. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  84164. if (minDistance !== void 0) {
  84165. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  84166. }
  84167. };
  84168. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84169. //TODO separate rotational and transational motors.
  84170. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84171. if (motor) {
  84172. motor.setMotor(speed, maxForce);
  84173. }
  84174. };
  84175. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  84176. //TODO separate rotational and transational motors.
  84177. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84178. if (motor) {
  84179. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  84180. }
  84181. };
  84182. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84183. var body = impostor.physicsBody;
  84184. mesh.position.x = body.position.x;
  84185. mesh.position.y = body.position.y;
  84186. mesh.position.z = body.position.z;
  84187. if (mesh.rotationQuaternion) {
  84188. mesh.rotationQuaternion.x = body.orientation.x;
  84189. mesh.rotationQuaternion.y = body.orientation.y;
  84190. mesh.rotationQuaternion.z = body.orientation.z;
  84191. mesh.rotationQuaternion.w = body.orientation.s;
  84192. }
  84193. };
  84194. OimoJSPlugin.prototype.getRadius = function (impostor) {
  84195. return impostor.physicsBody.shapes.radius;
  84196. };
  84197. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84198. var shape = impostor.physicsBody.shapes;
  84199. result.x = shape.halfWidth * 2;
  84200. result.y = shape.halfHeight * 2;
  84201. result.z = shape.halfDepth * 2;
  84202. };
  84203. OimoJSPlugin.prototype.dispose = function () {
  84204. this.world.clear();
  84205. };
  84206. return OimoJSPlugin;
  84207. }());
  84208. BABYLON.OimoJSPlugin = OimoJSPlugin;
  84209. })(BABYLON || (BABYLON = {}));
  84210. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  84211. var BABYLON;
  84212. (function (BABYLON) {
  84213. /*
  84214. * Based on jsTGALoader - Javascript loader for TGA file
  84215. * By Vincent Thibault
  84216. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  84217. */
  84218. var TGATools = /** @class */ (function () {
  84219. function TGATools() {
  84220. }
  84221. TGATools.GetTGAHeader = function (data) {
  84222. var offset = 0;
  84223. var header = {
  84224. id_length: data[offset++],
  84225. colormap_type: data[offset++],
  84226. image_type: data[offset++],
  84227. colormap_index: data[offset++] | data[offset++] << 8,
  84228. colormap_length: data[offset++] | data[offset++] << 8,
  84229. colormap_size: data[offset++],
  84230. origin: [
  84231. data[offset++] | data[offset++] << 8,
  84232. data[offset++] | data[offset++] << 8
  84233. ],
  84234. width: data[offset++] | data[offset++] << 8,
  84235. height: data[offset++] | data[offset++] << 8,
  84236. pixel_size: data[offset++],
  84237. flags: data[offset++]
  84238. };
  84239. return header;
  84240. };
  84241. TGATools.UploadContent = function (gl, data) {
  84242. // Not enough data to contain header ?
  84243. if (data.length < 19) {
  84244. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  84245. return;
  84246. }
  84247. // Read Header
  84248. var offset = 18;
  84249. var header = TGATools.GetTGAHeader(data);
  84250. // Assume it's a valid Targa file.
  84251. if (header.id_length + offset > data.length) {
  84252. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  84253. return;
  84254. }
  84255. // Skip not needed data
  84256. offset += header.id_length;
  84257. var use_rle = false;
  84258. var use_pal = false;
  84259. var use_grey = false;
  84260. // Get some informations.
  84261. switch (header.image_type) {
  84262. case TGATools._TYPE_RLE_INDEXED:
  84263. use_rle = true;
  84264. case TGATools._TYPE_INDEXED:
  84265. use_pal = true;
  84266. break;
  84267. case TGATools._TYPE_RLE_RGB:
  84268. use_rle = true;
  84269. case TGATools._TYPE_RGB:
  84270. // use_rgb = true;
  84271. break;
  84272. case TGATools._TYPE_RLE_GREY:
  84273. use_rle = true;
  84274. case TGATools._TYPE_GREY:
  84275. use_grey = true;
  84276. break;
  84277. }
  84278. var pixel_data;
  84279. // var numAlphaBits = header.flags & 0xf;
  84280. var pixel_size = header.pixel_size >> 3;
  84281. var pixel_total = header.width * header.height * pixel_size;
  84282. // Read palettes
  84283. var palettes;
  84284. if (use_pal) {
  84285. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84286. }
  84287. // Read LRE
  84288. if (use_rle) {
  84289. pixel_data = new Uint8Array(pixel_total);
  84290. var c, count, i;
  84291. var localOffset = 0;
  84292. var pixels = new Uint8Array(pixel_size);
  84293. while (offset < pixel_total && localOffset < pixel_total) {
  84294. c = data[offset++];
  84295. count = (c & 0x7f) + 1;
  84296. // RLE pixels
  84297. if (c & 0x80) {
  84298. // Bind pixel tmp array
  84299. for (i = 0; i < pixel_size; ++i) {
  84300. pixels[i] = data[offset++];
  84301. }
  84302. // Copy pixel array
  84303. for (i = 0; i < count; ++i) {
  84304. pixel_data.set(pixels, localOffset + i * pixel_size);
  84305. }
  84306. localOffset += pixel_size * count;
  84307. }
  84308. // Raw pixels
  84309. else {
  84310. count *= pixel_size;
  84311. for (i = 0; i < count; ++i) {
  84312. pixel_data[localOffset + i] = data[offset++];
  84313. }
  84314. localOffset += count;
  84315. }
  84316. }
  84317. }
  84318. // RAW Pixels
  84319. else {
  84320. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84321. }
  84322. // Load to texture
  84323. var x_start, y_start, x_step, y_step, y_end, x_end;
  84324. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84325. default:
  84326. case TGATools._ORIGIN_UL:
  84327. x_start = 0;
  84328. x_step = 1;
  84329. x_end = header.width;
  84330. y_start = 0;
  84331. y_step = 1;
  84332. y_end = header.height;
  84333. break;
  84334. case TGATools._ORIGIN_BL:
  84335. x_start = 0;
  84336. x_step = 1;
  84337. x_end = header.width;
  84338. y_start = header.height - 1;
  84339. y_step = -1;
  84340. y_end = -1;
  84341. break;
  84342. case TGATools._ORIGIN_UR:
  84343. x_start = header.width - 1;
  84344. x_step = -1;
  84345. x_end = -1;
  84346. y_start = 0;
  84347. y_step = 1;
  84348. y_end = header.height;
  84349. break;
  84350. case TGATools._ORIGIN_BR:
  84351. x_start = header.width - 1;
  84352. x_step = -1;
  84353. x_end = -1;
  84354. y_start = header.height - 1;
  84355. y_step = -1;
  84356. y_end = -1;
  84357. break;
  84358. }
  84359. // Load the specify method
  84360. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84361. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84362. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84363. };
  84364. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84365. var image = pixel_data, colormap = palettes;
  84366. var width = header.width, height = header.height;
  84367. var color, i = 0, x, y;
  84368. var imageData = new Uint8Array(width * height * 4);
  84369. for (y = y_start; y !== y_end; y += y_step) {
  84370. for (x = x_start; x !== x_end; x += x_step, i++) {
  84371. color = image[i];
  84372. imageData[(x + width * y) * 4 + 3] = 255;
  84373. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84374. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84375. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84376. }
  84377. }
  84378. return imageData;
  84379. };
  84380. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84381. var image = pixel_data;
  84382. var width = header.width, height = header.height;
  84383. var color, i = 0, x, y;
  84384. var imageData = new Uint8Array(width * height * 4);
  84385. for (y = y_start; y !== y_end; y += y_step) {
  84386. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84387. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84388. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84389. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84390. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84391. imageData[(x + width * y) * 4 + 0] = r;
  84392. imageData[(x + width * y) * 4 + 1] = g;
  84393. imageData[(x + width * y) * 4 + 2] = b;
  84394. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84395. }
  84396. }
  84397. return imageData;
  84398. };
  84399. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84400. var image = pixel_data;
  84401. var width = header.width, height = header.height;
  84402. var i = 0, x, y;
  84403. var imageData = new Uint8Array(width * height * 4);
  84404. for (y = y_start; y !== y_end; y += y_step) {
  84405. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84406. imageData[(x + width * y) * 4 + 3] = 255;
  84407. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84408. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84409. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84410. }
  84411. }
  84412. return imageData;
  84413. };
  84414. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84415. var image = pixel_data;
  84416. var width = header.width, height = header.height;
  84417. var i = 0, x, y;
  84418. var imageData = new Uint8Array(width * height * 4);
  84419. for (y = y_start; y !== y_end; y += y_step) {
  84420. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84421. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84422. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84423. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84424. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84425. }
  84426. }
  84427. return imageData;
  84428. };
  84429. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84430. var image = pixel_data;
  84431. var width = header.width, height = header.height;
  84432. var color, i = 0, x, y;
  84433. var imageData = new Uint8Array(width * height * 4);
  84434. for (y = y_start; y !== y_end; y += y_step) {
  84435. for (x = x_start; x !== x_end; x += x_step, i++) {
  84436. color = image[i];
  84437. imageData[(x + width * y) * 4 + 0] = color;
  84438. imageData[(x + width * y) * 4 + 1] = color;
  84439. imageData[(x + width * y) * 4 + 2] = color;
  84440. imageData[(x + width * y) * 4 + 3] = 255;
  84441. }
  84442. }
  84443. return imageData;
  84444. };
  84445. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84446. var image = pixel_data;
  84447. var width = header.width, height = header.height;
  84448. var i = 0, x, y;
  84449. var imageData = new Uint8Array(width * height * 4);
  84450. for (y = y_start; y !== y_end; y += y_step) {
  84451. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84452. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84453. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84454. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84455. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84456. }
  84457. }
  84458. return imageData;
  84459. };
  84460. //private static _TYPE_NO_DATA = 0;
  84461. TGATools._TYPE_INDEXED = 1;
  84462. TGATools._TYPE_RGB = 2;
  84463. TGATools._TYPE_GREY = 3;
  84464. TGATools._TYPE_RLE_INDEXED = 9;
  84465. TGATools._TYPE_RLE_RGB = 10;
  84466. TGATools._TYPE_RLE_GREY = 11;
  84467. TGATools._ORIGIN_MASK = 0x30;
  84468. TGATools._ORIGIN_SHIFT = 0x04;
  84469. TGATools._ORIGIN_BL = 0x00;
  84470. TGATools._ORIGIN_BR = 0x01;
  84471. TGATools._ORIGIN_UL = 0x02;
  84472. TGATools._ORIGIN_UR = 0x03;
  84473. return TGATools;
  84474. }());
  84475. BABYLON.TGATools = TGATools;
  84476. })(BABYLON || (BABYLON = {}));
  84477. //# sourceMappingURL=babylon.tga.js.map
  84478. var BABYLON;
  84479. (function (BABYLON) {
  84480. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84481. // All values and structures referenced from:
  84482. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84483. var DDS_MAGIC = 0x20534444;
  84484. var
  84485. //DDSD_CAPS = 0x1,
  84486. //DDSD_HEIGHT = 0x2,
  84487. //DDSD_WIDTH = 0x4,
  84488. //DDSD_PITCH = 0x8,
  84489. //DDSD_PIXELFORMAT = 0x1000,
  84490. DDSD_MIPMAPCOUNT = 0x20000;
  84491. //DDSD_LINEARSIZE = 0x80000,
  84492. //DDSD_DEPTH = 0x800000;
  84493. // var DDSCAPS_COMPLEX = 0x8,
  84494. // DDSCAPS_MIPMAP = 0x400000,
  84495. // DDSCAPS_TEXTURE = 0x1000;
  84496. var DDSCAPS2_CUBEMAP = 0x200;
  84497. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84498. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84499. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84500. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84501. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84502. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84503. // DDSCAPS2_VOLUME = 0x200000;
  84504. var
  84505. //DDPF_ALPHAPIXELS = 0x1,
  84506. //DDPF_ALPHA = 0x2,
  84507. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84508. //DDPF_YUV = 0x200,
  84509. DDPF_LUMINANCE = 0x20000;
  84510. function FourCCToInt32(value) {
  84511. return value.charCodeAt(0) +
  84512. (value.charCodeAt(1) << 8) +
  84513. (value.charCodeAt(2) << 16) +
  84514. (value.charCodeAt(3) << 24);
  84515. }
  84516. function Int32ToFourCC(value) {
  84517. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84518. }
  84519. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84520. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84521. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84522. var FOURCC_DX10 = FourCCToInt32("DX10");
  84523. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84524. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84525. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84526. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84527. var headerLengthInt = 31; // The header length in 32 bit ints
  84528. // Offsets into the header array
  84529. var off_magic = 0;
  84530. var off_size = 1;
  84531. var off_flags = 2;
  84532. var off_height = 3;
  84533. var off_width = 4;
  84534. var off_mipmapCount = 7;
  84535. var off_pfFlags = 20;
  84536. var off_pfFourCC = 21;
  84537. var off_RGBbpp = 22;
  84538. var off_RMask = 23;
  84539. var off_GMask = 24;
  84540. var off_BMask = 25;
  84541. var off_AMask = 26;
  84542. // var off_caps1 = 27;
  84543. var off_caps2 = 28;
  84544. // var off_caps3 = 29;
  84545. // var off_caps4 = 30;
  84546. var off_dxgiFormat = 32;
  84547. ;
  84548. var DDSTools = /** @class */ (function () {
  84549. function DDSTools() {
  84550. }
  84551. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84552. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84553. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84554. var mipmapCount = 1;
  84555. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84556. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84557. }
  84558. var fourCC = header[off_pfFourCC];
  84559. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84560. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84561. switch (fourCC) {
  84562. case FOURCC_D3DFMT_R16G16B16A16F:
  84563. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84564. break;
  84565. case FOURCC_D3DFMT_R32G32B32A32F:
  84566. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84567. break;
  84568. case FOURCC_DX10:
  84569. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84570. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84571. break;
  84572. }
  84573. }
  84574. return {
  84575. width: header[off_width],
  84576. height: header[off_height],
  84577. mipmapCount: mipmapCount,
  84578. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84579. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84580. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84581. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84582. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84583. dxgiFormat: dxgiFormat,
  84584. textureType: textureType
  84585. };
  84586. };
  84587. DDSTools._ToHalfFloat = function (value) {
  84588. if (!DDSTools._FloatView) {
  84589. DDSTools._FloatView = new Float32Array(1);
  84590. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84591. }
  84592. DDSTools._FloatView[0] = value;
  84593. var x = DDSTools._Int32View[0];
  84594. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84595. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84596. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84597. /* If zero, or denormal, or exponent underflows too much for a denormal
  84598. * half, return signed zero. */
  84599. if (e < 103) {
  84600. return bits;
  84601. }
  84602. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84603. if (e > 142) {
  84604. bits |= 0x7c00;
  84605. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84606. * not Inf, so make sure we set one mantissa bit too. */
  84607. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84608. return bits;
  84609. }
  84610. /* If exponent underflows but not too much, return a denormal */
  84611. if (e < 113) {
  84612. m |= 0x0800;
  84613. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84614. * to 1, which is OK. */
  84615. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84616. return bits;
  84617. }
  84618. bits |= ((e - 112) << 10) | (m >> 1);
  84619. bits += m & 1;
  84620. return bits;
  84621. };
  84622. DDSTools._FromHalfFloat = function (value) {
  84623. var s = (value & 0x8000) >> 15;
  84624. var e = (value & 0x7C00) >> 10;
  84625. var f = value & 0x03FF;
  84626. if (e === 0) {
  84627. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84628. }
  84629. else if (e == 0x1F) {
  84630. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84631. }
  84632. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84633. };
  84634. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84635. var destArray = new Float32Array(dataLength);
  84636. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84637. var index = 0;
  84638. for (var y = 0; y < height; y++) {
  84639. for (var x = 0; x < width; x++) {
  84640. var srcPos = (x + y * width) * 4;
  84641. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84642. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84643. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84644. if (DDSTools.StoreLODInAlphaChannel) {
  84645. destArray[index + 3] = lod;
  84646. }
  84647. else {
  84648. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84649. }
  84650. index += 4;
  84651. }
  84652. }
  84653. return destArray;
  84654. };
  84655. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84656. if (DDSTools.StoreLODInAlphaChannel) {
  84657. var destArray = new Uint16Array(dataLength);
  84658. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84659. var index = 0;
  84660. for (var y = 0; y < height; y++) {
  84661. for (var x = 0; x < width; x++) {
  84662. var srcPos = (x + y * width) * 4;
  84663. destArray[index] = srcData[srcPos];
  84664. destArray[index + 1] = srcData[srcPos + 1];
  84665. destArray[index + 2] = srcData[srcPos + 2];
  84666. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84667. index += 4;
  84668. }
  84669. }
  84670. return destArray;
  84671. }
  84672. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84673. };
  84674. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84675. if (DDSTools.StoreLODInAlphaChannel) {
  84676. var destArray = new Float32Array(dataLength);
  84677. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84678. var index = 0;
  84679. for (var y = 0; y < height; y++) {
  84680. for (var x = 0; x < width; x++) {
  84681. var srcPos = (x + y * width) * 4;
  84682. destArray[index] = srcData[srcPos];
  84683. destArray[index + 1] = srcData[srcPos + 1];
  84684. destArray[index + 2] = srcData[srcPos + 2];
  84685. destArray[index + 3] = lod;
  84686. index += 4;
  84687. }
  84688. }
  84689. return destArray;
  84690. }
  84691. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84692. };
  84693. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84694. var destArray = new Uint8Array(dataLength);
  84695. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84696. var index = 0;
  84697. for (var y = 0; y < height; y++) {
  84698. for (var x = 0; x < width; x++) {
  84699. var srcPos = (x + y * width) * 4;
  84700. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84701. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84702. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84703. if (DDSTools.StoreLODInAlphaChannel) {
  84704. destArray[index + 3] = lod;
  84705. }
  84706. else {
  84707. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84708. }
  84709. index += 4;
  84710. }
  84711. }
  84712. return destArray;
  84713. };
  84714. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84715. var destArray = new Uint8Array(dataLength);
  84716. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84717. var index = 0;
  84718. for (var y = 0; y < height; y++) {
  84719. for (var x = 0; x < width; x++) {
  84720. var srcPos = (x + y * width) * 4;
  84721. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84722. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84723. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84724. if (DDSTools.StoreLODInAlphaChannel) {
  84725. destArray[index + 3] = lod;
  84726. }
  84727. else {
  84728. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84729. }
  84730. index += 4;
  84731. }
  84732. }
  84733. return destArray;
  84734. };
  84735. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84736. var byteArray = new Uint8Array(dataLength);
  84737. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84738. var index = 0;
  84739. for (var y = 0; y < height; y++) {
  84740. for (var x = 0; x < width; x++) {
  84741. var srcPos = (x + y * width) * 4;
  84742. byteArray[index] = srcData[srcPos + rOffset];
  84743. byteArray[index + 1] = srcData[srcPos + gOffset];
  84744. byteArray[index + 2] = srcData[srcPos + bOffset];
  84745. byteArray[index + 3] = srcData[srcPos + aOffset];
  84746. index += 4;
  84747. }
  84748. }
  84749. return byteArray;
  84750. };
  84751. DDSTools._ExtractLongWordOrder = function (value) {
  84752. if (value === 0 || value === 255 || value === -16777216) {
  84753. return 0;
  84754. }
  84755. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84756. };
  84757. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84758. var byteArray = new Uint8Array(dataLength);
  84759. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84760. var index = 0;
  84761. for (var y = 0; y < height; y++) {
  84762. for (var x = 0; x < width; x++) {
  84763. var srcPos = (x + y * width) * 3;
  84764. byteArray[index] = srcData[srcPos + rOffset];
  84765. byteArray[index + 1] = srcData[srcPos + gOffset];
  84766. byteArray[index + 2] = srcData[srcPos + bOffset];
  84767. index += 3;
  84768. }
  84769. }
  84770. return byteArray;
  84771. };
  84772. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84773. var byteArray = new Uint8Array(dataLength);
  84774. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84775. var index = 0;
  84776. for (var y = 0; y < height; y++) {
  84777. for (var x = 0; x < width; x++) {
  84778. var srcPos = (x + y * width);
  84779. byteArray[index] = srcData[srcPos];
  84780. index++;
  84781. }
  84782. }
  84783. return byteArray;
  84784. };
  84785. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84786. if (lodIndex === void 0) { lodIndex = -1; }
  84787. var sphericalPolynomialFaces = null;
  84788. if (info.sphericalPolynomial) {
  84789. sphericalPolynomialFaces = new Array();
  84790. }
  84791. var ext = engine.getCaps().s3tc;
  84792. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84793. var fourCC, width, height, dataLength = 0, dataOffset;
  84794. var byteArray, mipmapCount, mip;
  84795. var internalFormat = 0;
  84796. var format = 0;
  84797. var blockBytes = 1;
  84798. if (header[off_magic] !== DDS_MAGIC) {
  84799. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84800. return;
  84801. }
  84802. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84803. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84804. return;
  84805. }
  84806. if (info.isCompressed && !ext) {
  84807. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84808. return;
  84809. }
  84810. var bpp = header[off_RGBbpp];
  84811. dataOffset = header[off_size] + 4;
  84812. var computeFormats = false;
  84813. if (info.isFourCC) {
  84814. fourCC = header[off_pfFourCC];
  84815. switch (fourCC) {
  84816. case FOURCC_DXT1:
  84817. blockBytes = 8;
  84818. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84819. break;
  84820. case FOURCC_DXT3:
  84821. blockBytes = 16;
  84822. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84823. break;
  84824. case FOURCC_DXT5:
  84825. blockBytes = 16;
  84826. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84827. break;
  84828. case FOURCC_D3DFMT_R16G16B16A16F:
  84829. computeFormats = true;
  84830. break;
  84831. case FOURCC_D3DFMT_R32G32B32A32F:
  84832. computeFormats = true;
  84833. break;
  84834. case FOURCC_DX10:
  84835. // There is an additionnal header so dataOffset need to be changed
  84836. dataOffset += 5 * 4; // 5 uints
  84837. var supported = false;
  84838. switch (info.dxgiFormat) {
  84839. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84840. computeFormats = true;
  84841. supported = true;
  84842. break;
  84843. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84844. info.isRGB = true;
  84845. info.isFourCC = false;
  84846. bpp = 32;
  84847. supported = true;
  84848. break;
  84849. }
  84850. if (supported) {
  84851. break;
  84852. }
  84853. default:
  84854. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84855. return;
  84856. }
  84857. }
  84858. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84859. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84860. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84861. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84862. if (computeFormats) {
  84863. format = engine._getWebGLTextureType(info.textureType);
  84864. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84865. }
  84866. mipmapCount = 1;
  84867. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84868. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84869. }
  84870. for (var face = 0; face < faces; face++) {
  84871. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84872. width = header[off_width];
  84873. height = header[off_height];
  84874. for (mip = 0; mip < mipmapCount; ++mip) {
  84875. if (lodIndex === -1 || lodIndex === mip) {
  84876. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84877. var i = (lodIndex === -1) ? mip : 0;
  84878. if (!info.isCompressed && info.isFourCC) {
  84879. dataLength = width * height * 4;
  84880. var floatArray = null;
  84881. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84882. if (bpp === 128) {
  84883. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84884. if (sphericalPolynomialFaces && i == 0) {
  84885. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84886. }
  84887. }
  84888. else if (bpp === 64) {
  84889. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84890. if (sphericalPolynomialFaces && i == 0) {
  84891. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84892. }
  84893. }
  84894. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84895. format = engine._getWebGLTextureType(info.textureType);
  84896. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84897. }
  84898. else {
  84899. if (bpp === 128) {
  84900. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84901. if (sphericalPolynomialFaces && i == 0) {
  84902. sphericalPolynomialFaces.push(floatArray);
  84903. }
  84904. }
  84905. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84906. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84907. if (sphericalPolynomialFaces && i == 0) {
  84908. sphericalPolynomialFaces.push(floatArray);
  84909. }
  84910. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84911. format = engine._getWebGLTextureType(info.textureType);
  84912. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84913. }
  84914. else { // 64
  84915. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84916. if (sphericalPolynomialFaces && i == 0) {
  84917. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84918. }
  84919. }
  84920. }
  84921. if (floatArray) {
  84922. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84923. }
  84924. }
  84925. else if (info.isRGB) {
  84926. if (bpp === 24) {
  84927. dataLength = width * height * 3;
  84928. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84929. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84930. }
  84931. else { // 32
  84932. dataLength = width * height * 4;
  84933. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84934. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84935. }
  84936. }
  84937. else if (info.isLuminance) {
  84938. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84939. var unpaddedRowSize = width;
  84940. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84941. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84942. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84943. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84944. }
  84945. else {
  84946. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84947. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84948. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84949. }
  84950. }
  84951. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84952. width *= 0.5;
  84953. height *= 0.5;
  84954. width = Math.max(1.0, width);
  84955. height = Math.max(1.0, height);
  84956. }
  84957. if (currentFace !== undefined) {
  84958. // Loading a single face
  84959. break;
  84960. }
  84961. }
  84962. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84963. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84964. size: header[off_width],
  84965. right: sphericalPolynomialFaces[0],
  84966. left: sphericalPolynomialFaces[1],
  84967. up: sphericalPolynomialFaces[2],
  84968. down: sphericalPolynomialFaces[3],
  84969. front: sphericalPolynomialFaces[4],
  84970. back: sphericalPolynomialFaces[5],
  84971. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84972. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84973. gammaSpace: false,
  84974. });
  84975. }
  84976. else {
  84977. info.sphericalPolynomial = undefined;
  84978. }
  84979. };
  84980. DDSTools.StoreLODInAlphaChannel = false;
  84981. return DDSTools;
  84982. }());
  84983. BABYLON.DDSTools = DDSTools;
  84984. })(BABYLON || (BABYLON = {}));
  84985. //# sourceMappingURL=babylon.dds.js.map
  84986. var BABYLON;
  84987. (function (BABYLON) {
  84988. /**
  84989. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84990. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84991. */
  84992. var KhronosTextureContainer = /** @class */ (function () {
  84993. /**
  84994. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84995. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84996. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84997. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84998. */
  84999. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  85000. this.arrayBuffer = arrayBuffer;
  85001. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  85002. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  85003. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  85004. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  85005. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  85006. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  85007. BABYLON.Tools.Error("texture missing KTX identifier");
  85008. return;
  85009. }
  85010. // load the reset of the header in native 32 bit int
  85011. var header = new Int32Array(this.arrayBuffer, 12, 13);
  85012. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  85013. var oppositeEndianess = header[0] === 0x01020304;
  85014. // read all the header elements in order they exist in the file, without modification (sans endainness)
  85015. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  85016. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  85017. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  85018. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  85019. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  85020. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  85021. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  85022. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  85023. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  85024. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  85025. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  85026. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  85027. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  85028. if (this.glType !== 0) {
  85029. BABYLON.Tools.Error("only compressed formats currently supported");
  85030. return;
  85031. }
  85032. else {
  85033. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  85034. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  85035. }
  85036. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  85037. BABYLON.Tools.Error("only 2D textures currently supported");
  85038. return;
  85039. }
  85040. if (this.numberOfArrayElements !== 0) {
  85041. BABYLON.Tools.Error("texture arrays not currently supported");
  85042. return;
  85043. }
  85044. if (this.numberOfFaces !== facesExpected) {
  85045. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  85046. return;
  85047. }
  85048. // we now have a completely validated file, so could use existence of loadType as success
  85049. // would need to make this more elaborate & adjust checks above to support more than one load type
  85050. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  85051. }
  85052. // not as fast hardware based, but will probably never need to use
  85053. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  85054. return ((val & 0xFF) << 24)
  85055. | ((val & 0xFF00) << 8)
  85056. | ((val >> 8) & 0xFF00)
  85057. | ((val >> 24) & 0xFF);
  85058. };
  85059. /**
  85060. * It is assumed that the texture has already been created & is currently bound
  85061. */
  85062. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  85063. switch (this.loadType) {
  85064. case KhronosTextureContainer.COMPRESSED_2D:
  85065. this._upload2DCompressedLevels(gl, loadMipmaps);
  85066. break;
  85067. case KhronosTextureContainer.TEX_2D:
  85068. case KhronosTextureContainer.COMPRESSED_3D:
  85069. case KhronosTextureContainer.TEX_3D:
  85070. }
  85071. };
  85072. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  85073. // initialize width & height for level 1
  85074. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  85075. var width = this.pixelWidth;
  85076. var height = this.pixelHeight;
  85077. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  85078. for (var level = 0; level < mipmapCount; level++) {
  85079. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  85080. for (var face = 0; face < this.numberOfFaces; face++) {
  85081. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  85082. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  85083. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  85084. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  85085. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  85086. }
  85087. width = Math.max(1.0, width * 0.5);
  85088. height = Math.max(1.0, height * 0.5);
  85089. }
  85090. };
  85091. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  85092. // load types
  85093. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  85094. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  85095. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  85096. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  85097. return KhronosTextureContainer;
  85098. }());
  85099. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  85100. })(BABYLON || (BABYLON = {}));
  85101. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  85102. var BABYLON;
  85103. (function (BABYLON) {
  85104. var Debug;
  85105. (function (Debug) {
  85106. /**
  85107. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  85108. */
  85109. var SkeletonViewer = /** @class */ (function () {
  85110. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  85111. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  85112. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  85113. this.skeleton = skeleton;
  85114. this.mesh = mesh;
  85115. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  85116. this.renderingGroupId = renderingGroupId;
  85117. this.color = BABYLON.Color3.White();
  85118. this._debugLines = new Array();
  85119. this._isEnabled = false;
  85120. this._scene = scene;
  85121. this.update();
  85122. this._renderFunction = this.update.bind(this);
  85123. }
  85124. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  85125. get: function () {
  85126. return this._isEnabled;
  85127. },
  85128. set: function (value) {
  85129. if (this._isEnabled === value) {
  85130. return;
  85131. }
  85132. this._isEnabled = value;
  85133. if (value) {
  85134. this._scene.registerBeforeRender(this._renderFunction);
  85135. }
  85136. else {
  85137. this._scene.unregisterBeforeRender(this._renderFunction);
  85138. }
  85139. },
  85140. enumerable: true,
  85141. configurable: true
  85142. });
  85143. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  85144. if (x === void 0) { x = 0; }
  85145. if (y === void 0) { y = 0; }
  85146. if (z === void 0) { z = 0; }
  85147. var tmat = BABYLON.Tmp.Matrix[0];
  85148. var parentBone = bone.getParent();
  85149. tmat.copyFrom(bone.getLocalMatrix());
  85150. if (x !== 0 || y !== 0 || z !== 0) {
  85151. var tmat2 = BABYLON.Tmp.Matrix[1];
  85152. BABYLON.Matrix.IdentityToRef(tmat2);
  85153. tmat2.m[12] = x;
  85154. tmat2.m[13] = y;
  85155. tmat2.m[14] = z;
  85156. tmat2.multiplyToRef(tmat, tmat);
  85157. }
  85158. if (parentBone) {
  85159. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  85160. }
  85161. tmat.multiplyToRef(meshMat, tmat);
  85162. position.x = tmat.m[12];
  85163. position.y = tmat.m[13];
  85164. position.z = tmat.m[14];
  85165. };
  85166. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  85167. var len = bones.length;
  85168. var meshPos = this.mesh.position;
  85169. for (var i = 0; i < len; i++) {
  85170. var bone = bones[i];
  85171. var points = this._debugLines[i];
  85172. if (!points) {
  85173. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85174. this._debugLines[i] = points;
  85175. }
  85176. this._getBonePosition(points[0], bone, meshMat);
  85177. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  85178. points[0].subtractInPlace(meshPos);
  85179. points[1].subtractInPlace(meshPos);
  85180. }
  85181. };
  85182. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  85183. var len = bones.length;
  85184. var boneNum = 0;
  85185. var meshPos = this.mesh.position;
  85186. for (var i = len - 1; i >= 0; i--) {
  85187. var childBone = bones[i];
  85188. var parentBone = childBone.getParent();
  85189. if (!parentBone) {
  85190. continue;
  85191. }
  85192. var points = this._debugLines[boneNum];
  85193. if (!points) {
  85194. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85195. this._debugLines[boneNum] = points;
  85196. }
  85197. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  85198. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  85199. points[0].subtractInPlace(meshPos);
  85200. points[1].subtractInPlace(meshPos);
  85201. boneNum++;
  85202. }
  85203. };
  85204. SkeletonViewer.prototype.update = function () {
  85205. if (this.autoUpdateBonesMatrices) {
  85206. this.skeleton.computeAbsoluteTransforms();
  85207. }
  85208. if (this.skeleton.bones[0].length === undefined) {
  85209. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85210. }
  85211. else {
  85212. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85213. }
  85214. if (!this._debugMesh) {
  85215. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  85216. this._debugMesh.renderingGroupId = this.renderingGroupId;
  85217. }
  85218. else {
  85219. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  85220. }
  85221. this._debugMesh.position.copyFrom(this.mesh.position);
  85222. this._debugMesh.color = this.color;
  85223. };
  85224. SkeletonViewer.prototype.dispose = function () {
  85225. if (this._debugMesh) {
  85226. this.isEnabled = false;
  85227. this._debugMesh.dispose();
  85228. this._debugMesh = null;
  85229. }
  85230. };
  85231. return SkeletonViewer;
  85232. }());
  85233. Debug.SkeletonViewer = SkeletonViewer;
  85234. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85235. })(BABYLON || (BABYLON = {}));
  85236. //# sourceMappingURL=babylon.skeletonViewer.js.map
  85237. /**
  85238. * Module Debug contains the (visual) components to debug a scene correctly
  85239. */
  85240. var BABYLON;
  85241. (function (BABYLON) {
  85242. var Debug;
  85243. (function (Debug) {
  85244. /**
  85245. * The Axes viewer will show 3 axes in a specific point in space
  85246. */
  85247. var AxesViewer = /** @class */ (function () {
  85248. function AxesViewer(scene, scaleLines) {
  85249. if (scaleLines === void 0) { scaleLines = 1; }
  85250. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85251. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85252. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85253. this.scaleLines = 1;
  85254. this.scaleLines = scaleLines;
  85255. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  85256. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  85257. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  85258. this._xmesh.renderingGroupId = 2;
  85259. this._ymesh.renderingGroupId = 2;
  85260. this._zmesh.renderingGroupId = 2;
  85261. this._xmesh.material.checkReadyOnlyOnce = true;
  85262. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85263. this._ymesh.material.checkReadyOnlyOnce = true;
  85264. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85265. this._zmesh.material.checkReadyOnlyOnce = true;
  85266. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85267. this.scene = scene;
  85268. }
  85269. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85270. var scaleLines = this.scaleLines;
  85271. if (this._xmesh) {
  85272. this._xmesh.position.copyFrom(position);
  85273. }
  85274. if (this._ymesh) {
  85275. this._ymesh.position.copyFrom(position);
  85276. }
  85277. if (this._zmesh) {
  85278. this._zmesh.position.copyFrom(position);
  85279. }
  85280. var point2 = this._xline[1];
  85281. point2.x = xaxis.x * scaleLines;
  85282. point2.y = xaxis.y * scaleLines;
  85283. point2.z = xaxis.z * scaleLines;
  85284. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85285. point2 = this._yline[1];
  85286. point2.x = yaxis.x * scaleLines;
  85287. point2.y = yaxis.y * scaleLines;
  85288. point2.z = yaxis.z * scaleLines;
  85289. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85290. point2 = this._zline[1];
  85291. point2.x = zaxis.x * scaleLines;
  85292. point2.y = zaxis.y * scaleLines;
  85293. point2.z = zaxis.z * scaleLines;
  85294. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85295. };
  85296. AxesViewer.prototype.dispose = function () {
  85297. if (this._xmesh) {
  85298. this._xmesh.dispose();
  85299. }
  85300. if (this._ymesh) {
  85301. this._ymesh.dispose();
  85302. }
  85303. if (this._zmesh) {
  85304. this._zmesh.dispose();
  85305. }
  85306. this._xmesh = null;
  85307. this._ymesh = null;
  85308. this._zmesh = null;
  85309. this.scene = null;
  85310. };
  85311. return AxesViewer;
  85312. }());
  85313. Debug.AxesViewer = AxesViewer;
  85314. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85315. })(BABYLON || (BABYLON = {}));
  85316. //# sourceMappingURL=babylon.axesViewer.js.map
  85317. var BABYLON;
  85318. (function (BABYLON) {
  85319. var Debug;
  85320. (function (Debug) {
  85321. /**
  85322. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85323. */
  85324. var BoneAxesViewer = /** @class */ (function (_super) {
  85325. __extends(BoneAxesViewer, _super);
  85326. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85327. if (scaleLines === void 0) { scaleLines = 1; }
  85328. var _this = _super.call(this, scene, scaleLines) || this;
  85329. _this.pos = BABYLON.Vector3.Zero();
  85330. _this.xaxis = BABYLON.Vector3.Zero();
  85331. _this.yaxis = BABYLON.Vector3.Zero();
  85332. _this.zaxis = BABYLON.Vector3.Zero();
  85333. _this.mesh = mesh;
  85334. _this.bone = bone;
  85335. return _this;
  85336. }
  85337. BoneAxesViewer.prototype.update = function () {
  85338. if (!this.mesh || !this.bone) {
  85339. return;
  85340. }
  85341. var bone = this.bone;
  85342. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85343. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85344. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85345. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85346. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85347. };
  85348. BoneAxesViewer.prototype.dispose = function () {
  85349. if (this.mesh) {
  85350. this.mesh = null;
  85351. this.bone = null;
  85352. _super.prototype.dispose.call(this);
  85353. }
  85354. };
  85355. return BoneAxesViewer;
  85356. }(Debug.AxesViewer));
  85357. Debug.BoneAxesViewer = BoneAxesViewer;
  85358. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85359. })(BABYLON || (BABYLON = {}));
  85360. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85361. var BABYLON;
  85362. (function (BABYLON) {
  85363. var RayHelper = /** @class */ (function () {
  85364. function RayHelper(ray) {
  85365. this.ray = ray;
  85366. }
  85367. RayHelper.CreateAndShow = function (ray, scene, color) {
  85368. var helper = new RayHelper(ray);
  85369. helper.show(scene, color);
  85370. return helper;
  85371. };
  85372. RayHelper.prototype.show = function (scene, color) {
  85373. if (!this._renderFunction && this.ray) {
  85374. var ray = this.ray;
  85375. this._renderFunction = this._render.bind(this);
  85376. this._scene = scene;
  85377. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85378. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85379. if (this._renderFunction) {
  85380. this._scene.registerBeforeRender(this._renderFunction);
  85381. }
  85382. }
  85383. if (color && this._renderLine) {
  85384. this._renderLine.color.copyFrom(color);
  85385. }
  85386. };
  85387. RayHelper.prototype.hide = function () {
  85388. if (this._renderFunction && this._scene) {
  85389. this._scene.unregisterBeforeRender(this._renderFunction);
  85390. this._scene = null;
  85391. this._renderFunction = null;
  85392. if (this._renderLine) {
  85393. this._renderLine.dispose();
  85394. this._renderLine = null;
  85395. }
  85396. this._renderPoints = [];
  85397. }
  85398. };
  85399. RayHelper.prototype._render = function () {
  85400. var ray = this.ray;
  85401. if (!ray) {
  85402. return;
  85403. }
  85404. var point = this._renderPoints[1];
  85405. var len = Math.min(ray.length, 1000000);
  85406. point.copyFrom(ray.direction);
  85407. point.scaleInPlace(len);
  85408. point.addInPlace(ray.origin);
  85409. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85410. };
  85411. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85412. this._attachedToMesh = mesh;
  85413. var ray = this.ray;
  85414. if (!ray) {
  85415. return;
  85416. }
  85417. if (!ray.direction) {
  85418. ray.direction = BABYLON.Vector3.Zero();
  85419. }
  85420. if (!ray.origin) {
  85421. ray.origin = BABYLON.Vector3.Zero();
  85422. }
  85423. if (length) {
  85424. ray.length = length;
  85425. }
  85426. if (!meshSpaceOrigin) {
  85427. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85428. }
  85429. if (!meshSpaceDirection) {
  85430. // -1 so that this will work with Mesh.lookAt
  85431. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85432. }
  85433. if (!this._meshSpaceDirection) {
  85434. this._meshSpaceDirection = meshSpaceDirection.clone();
  85435. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85436. }
  85437. else {
  85438. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85439. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85440. }
  85441. if (!this._updateToMeshFunction) {
  85442. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85443. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85444. }
  85445. this._updateToMesh();
  85446. };
  85447. RayHelper.prototype.detachFromMesh = function () {
  85448. if (this._attachedToMesh) {
  85449. if (this._updateToMeshFunction) {
  85450. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85451. }
  85452. this._attachedToMesh = null;
  85453. this._updateToMeshFunction = null;
  85454. }
  85455. };
  85456. RayHelper.prototype._updateToMesh = function () {
  85457. var ray = this.ray;
  85458. if (!this._attachedToMesh || !ray) {
  85459. return;
  85460. }
  85461. if (this._attachedToMesh._isDisposed) {
  85462. this.detachFromMesh();
  85463. return;
  85464. }
  85465. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85466. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85467. };
  85468. RayHelper.prototype.dispose = function () {
  85469. this.hide();
  85470. this.detachFromMesh();
  85471. this.ray = null;
  85472. };
  85473. return RayHelper;
  85474. }());
  85475. BABYLON.RayHelper = RayHelper;
  85476. })(BABYLON || (BABYLON = {}));
  85477. //# sourceMappingURL=babylon.rayHelper.js.map
  85478. var BABYLON;
  85479. (function (BABYLON) {
  85480. // load the inspector using require, if not present in the global namespace.
  85481. var DebugLayer = /** @class */ (function () {
  85482. function DebugLayer(scene) {
  85483. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85484. this._scene = scene;
  85485. // load inspector using require, if it doesn't exist on the global namespace.
  85486. }
  85487. /** Creates the inspector window. */
  85488. DebugLayer.prototype._createInspector = function (config) {
  85489. if (config === void 0) { config = {}; }
  85490. var popup = config.popup || false;
  85491. var initialTab = config.initialTab || 0;
  85492. var parentElement = config.parentElement || null;
  85493. if (!this._inspector) {
  85494. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85495. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85496. } // else nothing to do,; instance is already existing
  85497. };
  85498. DebugLayer.prototype.isVisible = function () {
  85499. if (!this._inspector) {
  85500. return false;
  85501. }
  85502. return true;
  85503. };
  85504. DebugLayer.prototype.hide = function () {
  85505. if (this._inspector) {
  85506. try {
  85507. this._inspector.dispose();
  85508. }
  85509. catch (e) {
  85510. // If the inspector has been removed directly from the inspector tool
  85511. }
  85512. this._inspector = null;
  85513. }
  85514. };
  85515. DebugLayer.prototype.show = function (config) {
  85516. if (config === void 0) { config = {}; }
  85517. if (typeof this.BJSINSPECTOR == 'undefined') {
  85518. // Load inspector and add it to the DOM
  85519. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85520. }
  85521. else {
  85522. // Otherwise creates the inspector
  85523. this._createInspector(config);
  85524. }
  85525. };
  85526. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85527. return DebugLayer;
  85528. }());
  85529. BABYLON.DebugLayer = DebugLayer;
  85530. })(BABYLON || (BABYLON = {}));
  85531. //# sourceMappingURL=babylon.debugLayer.js.map
  85532. var BABYLON;
  85533. (function (BABYLON) {
  85534. var Debug;
  85535. (function (Debug) {
  85536. /**
  85537. * Used to show the physics impostor around the specific mesh.
  85538. */
  85539. var PhysicsViewer = /** @class */ (function () {
  85540. function PhysicsViewer(scene) {
  85541. this._impostors = [];
  85542. this._meshes = [];
  85543. this._numMeshes = 0;
  85544. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85545. var physicEngine = this._scene.getPhysicsEngine();
  85546. if (physicEngine) {
  85547. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85548. }
  85549. }
  85550. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85551. var plugin = this._physicsEnginePlugin;
  85552. for (var i = 0; i < this._numMeshes; i++) {
  85553. var impostor = this._impostors[i];
  85554. if (!impostor) {
  85555. continue;
  85556. }
  85557. if (impostor.isDisposed) {
  85558. this.hideImpostor(this._impostors[i--]);
  85559. }
  85560. else {
  85561. var mesh = this._meshes[i];
  85562. if (mesh && plugin) {
  85563. plugin.syncMeshWithImpostor(mesh, impostor);
  85564. }
  85565. }
  85566. }
  85567. };
  85568. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85569. if (!this._scene) {
  85570. return;
  85571. }
  85572. for (var i = 0; i < this._numMeshes; i++) {
  85573. if (this._impostors[i] == impostor) {
  85574. return;
  85575. }
  85576. }
  85577. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85578. if (debugMesh) {
  85579. this._impostors[this._numMeshes] = impostor;
  85580. this._meshes[this._numMeshes] = debugMesh;
  85581. if (this._numMeshes === 0) {
  85582. this._renderFunction = this._updateDebugMeshes.bind(this);
  85583. this._scene.registerBeforeRender(this._renderFunction);
  85584. }
  85585. this._numMeshes++;
  85586. }
  85587. };
  85588. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85589. if (!impostor || !this._scene) {
  85590. return;
  85591. }
  85592. var removed = false;
  85593. for (var i = 0; i < this._numMeshes; i++) {
  85594. if (this._impostors[i] == impostor) {
  85595. var mesh = this._meshes[i];
  85596. if (!mesh) {
  85597. continue;
  85598. }
  85599. this._scene.removeMesh(mesh);
  85600. mesh.dispose();
  85601. this._numMeshes--;
  85602. if (this._numMeshes > 0) {
  85603. this._meshes[i] = this._meshes[this._numMeshes];
  85604. this._impostors[i] = this._impostors[this._numMeshes];
  85605. this._meshes[this._numMeshes] = null;
  85606. this._impostors[this._numMeshes] = null;
  85607. }
  85608. else {
  85609. this._meshes[0] = null;
  85610. this._impostors[0] = null;
  85611. }
  85612. removed = true;
  85613. break;
  85614. }
  85615. }
  85616. if (removed && this._numMeshes === 0) {
  85617. this._scene.unregisterBeforeRender(this._renderFunction);
  85618. }
  85619. };
  85620. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85621. if (!this._debugMaterial) {
  85622. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85623. this._debugMaterial.wireframe = true;
  85624. }
  85625. return this._debugMaterial;
  85626. };
  85627. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85628. if (!this._debugBoxMesh) {
  85629. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85630. this._debugBoxMesh.renderingGroupId = 1;
  85631. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85632. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85633. scene.removeMesh(this._debugBoxMesh);
  85634. }
  85635. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85636. };
  85637. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85638. if (!this._debugSphereMesh) {
  85639. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85640. this._debugSphereMesh.renderingGroupId = 1;
  85641. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85642. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85643. scene.removeMesh(this._debugSphereMesh);
  85644. }
  85645. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85646. };
  85647. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85648. var mesh = null;
  85649. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85650. mesh = this._getDebugBoxMesh(scene);
  85651. impostor.getBoxSizeToRef(mesh.scaling);
  85652. }
  85653. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85654. mesh = this._getDebugSphereMesh(scene);
  85655. var radius = impostor.getRadius();
  85656. mesh.scaling.x = radius * 2;
  85657. mesh.scaling.y = radius * 2;
  85658. mesh.scaling.z = radius * 2;
  85659. }
  85660. return mesh;
  85661. };
  85662. PhysicsViewer.prototype.dispose = function () {
  85663. for (var i = 0; i < this._numMeshes; i++) {
  85664. this.hideImpostor(this._impostors[i]);
  85665. }
  85666. if (this._debugBoxMesh) {
  85667. this._debugBoxMesh.dispose();
  85668. }
  85669. if (this._debugSphereMesh) {
  85670. this._debugSphereMesh.dispose();
  85671. }
  85672. if (this._debugMaterial) {
  85673. this._debugMaterial.dispose();
  85674. }
  85675. this._impostors.length = 0;
  85676. this._scene = null;
  85677. this._physicsEnginePlugin = null;
  85678. };
  85679. return PhysicsViewer;
  85680. }());
  85681. Debug.PhysicsViewer = PhysicsViewer;
  85682. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85683. })(BABYLON || (BABYLON = {}));
  85684. //# sourceMappingURL=babylon.physicsViewer.js.map
  85685. var BABYLON;
  85686. (function (BABYLON) {
  85687. var BoundingBoxRenderer = /** @class */ (function () {
  85688. function BoundingBoxRenderer(scene) {
  85689. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85690. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85691. this.showBackLines = true;
  85692. this.renderList = new BABYLON.SmartArray(32);
  85693. this._vertexBuffers = {};
  85694. this._scene = scene;
  85695. }
  85696. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85697. if (this._colorShader) {
  85698. return;
  85699. }
  85700. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85701. attributes: [BABYLON.VertexBuffer.PositionKind],
  85702. uniforms: ["world", "viewProjection", "color"]
  85703. });
  85704. var engine = this._scene.getEngine();
  85705. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85706. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85707. this._createIndexBuffer();
  85708. };
  85709. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85710. var engine = this._scene.getEngine();
  85711. 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]);
  85712. };
  85713. BoundingBoxRenderer.prototype._rebuild = function () {
  85714. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85715. if (vb) {
  85716. vb._rebuild();
  85717. }
  85718. this._createIndexBuffer();
  85719. };
  85720. BoundingBoxRenderer.prototype.reset = function () {
  85721. this.renderList.reset();
  85722. };
  85723. BoundingBoxRenderer.prototype.render = function () {
  85724. if (this.renderList.length === 0) {
  85725. return;
  85726. }
  85727. this._prepareRessources();
  85728. if (!this._colorShader.isReady()) {
  85729. return;
  85730. }
  85731. var engine = this._scene.getEngine();
  85732. engine.setDepthWrite(false);
  85733. this._colorShader._preBind();
  85734. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85735. var boundingBox = this.renderList.data[boundingBoxIndex];
  85736. var min = boundingBox.minimum;
  85737. var max = boundingBox.maximum;
  85738. var diff = max.subtract(min);
  85739. var median = min.add(diff.scale(0.5));
  85740. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85741. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85742. .multiply(boundingBox.getWorldMatrix());
  85743. // VBOs
  85744. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85745. if (this.showBackLines) {
  85746. // Back
  85747. engine.setDepthFunctionToGreaterOrEqual();
  85748. this._scene.resetCachedMaterial();
  85749. this._colorShader.setColor4("color", this.backColor.toColor4());
  85750. this._colorShader.bind(worldMatrix);
  85751. // Draw order
  85752. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85753. }
  85754. // Front
  85755. engine.setDepthFunctionToLess();
  85756. this._scene.resetCachedMaterial();
  85757. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85758. this._colorShader.bind(worldMatrix);
  85759. // Draw order
  85760. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85761. }
  85762. this._colorShader.unbind();
  85763. engine.setDepthFunctionToLessOrEqual();
  85764. engine.setDepthWrite(true);
  85765. };
  85766. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85767. this._prepareRessources();
  85768. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85769. return;
  85770. }
  85771. var engine = this._scene.getEngine();
  85772. engine.setDepthWrite(false);
  85773. engine.setColorWrite(false);
  85774. this._colorShader._preBind();
  85775. var boundingBox = mesh._boundingInfo.boundingBox;
  85776. var min = boundingBox.minimum;
  85777. var max = boundingBox.maximum;
  85778. var diff = max.subtract(min);
  85779. var median = min.add(diff.scale(0.5));
  85780. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85781. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85782. .multiply(boundingBox.getWorldMatrix());
  85783. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85784. engine.setDepthFunctionToLess();
  85785. this._scene.resetCachedMaterial();
  85786. this._colorShader.bind(worldMatrix);
  85787. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85788. this._colorShader.unbind();
  85789. engine.setDepthFunctionToLessOrEqual();
  85790. engine.setDepthWrite(true);
  85791. engine.setColorWrite(true);
  85792. };
  85793. BoundingBoxRenderer.prototype.dispose = function () {
  85794. if (!this._colorShader) {
  85795. return;
  85796. }
  85797. this.renderList.dispose();
  85798. this._colorShader.dispose();
  85799. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85800. if (buffer) {
  85801. buffer.dispose();
  85802. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85803. }
  85804. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85805. };
  85806. return BoundingBoxRenderer;
  85807. }());
  85808. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85809. })(BABYLON || (BABYLON = {}));
  85810. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85811. var BABYLON;
  85812. (function (BABYLON) {
  85813. /**
  85814. * Defines a target to use with MorphTargetManager
  85815. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85816. */
  85817. var MorphTarget = /** @class */ (function () {
  85818. /**
  85819. * Creates a new MorphTarget
  85820. * @param name defines the name of the target
  85821. * @param influence defines the influence to use
  85822. */
  85823. function MorphTarget(
  85824. /** defines the name of the target */
  85825. name, influence, scene) {
  85826. if (influence === void 0) { influence = 0; }
  85827. if (scene === void 0) { scene = null; }
  85828. this.name = name;
  85829. /**
  85830. * Gets or sets the list of animations
  85831. */
  85832. this.animations = new Array();
  85833. this._positions = null;
  85834. this._normals = null;
  85835. this._tangents = null;
  85836. /**
  85837. * Observable raised when the influence changes
  85838. */
  85839. this.onInfluenceChanged = new BABYLON.Observable();
  85840. this._animationPropertiesOverride = null;
  85841. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85842. this.influence = influence;
  85843. }
  85844. Object.defineProperty(MorphTarget.prototype, "influence", {
  85845. /**
  85846. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85847. */
  85848. get: function () {
  85849. return this._influence;
  85850. },
  85851. set: function (influence) {
  85852. if (this._influence === influence) {
  85853. return;
  85854. }
  85855. var previous = this._influence;
  85856. this._influence = influence;
  85857. if (this.onInfluenceChanged.hasObservers) {
  85858. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85859. }
  85860. },
  85861. enumerable: true,
  85862. configurable: true
  85863. });
  85864. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  85865. /**
  85866. * Gets or sets the animation properties override
  85867. */
  85868. get: function () {
  85869. if (!this._animationPropertiesOverride && this._scene) {
  85870. return this._scene.animationPropertiesOverride;
  85871. }
  85872. return this._animationPropertiesOverride;
  85873. },
  85874. set: function (value) {
  85875. this._animationPropertiesOverride = value;
  85876. },
  85877. enumerable: true,
  85878. configurable: true
  85879. });
  85880. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85881. /**
  85882. * Gets a boolean defining if the target contains position data
  85883. */
  85884. get: function () {
  85885. return !!this._positions;
  85886. },
  85887. enumerable: true,
  85888. configurable: true
  85889. });
  85890. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85891. /**
  85892. * Gets a boolean defining if the target contains normal data
  85893. */
  85894. get: function () {
  85895. return !!this._normals;
  85896. },
  85897. enumerable: true,
  85898. configurable: true
  85899. });
  85900. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85901. /**
  85902. * Gets a boolean defining if the target contains tangent data
  85903. */
  85904. get: function () {
  85905. return !!this._tangents;
  85906. },
  85907. enumerable: true,
  85908. configurable: true
  85909. });
  85910. /**
  85911. * Affects position data to this target
  85912. * @param data defines the position data to use
  85913. */
  85914. MorphTarget.prototype.setPositions = function (data) {
  85915. this._positions = data;
  85916. };
  85917. /**
  85918. * Gets the position data stored in this target
  85919. * @returns a FloatArray containing the position data (or null if not present)
  85920. */
  85921. MorphTarget.prototype.getPositions = function () {
  85922. return this._positions;
  85923. };
  85924. /**
  85925. * Affects normal data to this target
  85926. * @param data defines the normal data to use
  85927. */
  85928. MorphTarget.prototype.setNormals = function (data) {
  85929. this._normals = data;
  85930. };
  85931. /**
  85932. * Gets the normal data stored in this target
  85933. * @returns a FloatArray containing the normal data (or null if not present)
  85934. */
  85935. MorphTarget.prototype.getNormals = function () {
  85936. return this._normals;
  85937. };
  85938. /**
  85939. * Affects tangent data to this target
  85940. * @param data defines the tangent data to use
  85941. */
  85942. MorphTarget.prototype.setTangents = function (data) {
  85943. this._tangents = data;
  85944. };
  85945. /**
  85946. * Gets the tangent data stored in this target
  85947. * @returns a FloatArray containing the tangent data (or null if not present)
  85948. */
  85949. MorphTarget.prototype.getTangents = function () {
  85950. return this._tangents;
  85951. };
  85952. /**
  85953. * Serializes the current target into a Serialization object
  85954. * @returns the serialized object
  85955. */
  85956. MorphTarget.prototype.serialize = function () {
  85957. var serializationObject = {};
  85958. serializationObject.name = this.name;
  85959. serializationObject.influence = this.influence;
  85960. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85961. if (this.hasNormals) {
  85962. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85963. }
  85964. if (this.hasTangents) {
  85965. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85966. }
  85967. // Animations
  85968. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85969. return serializationObject;
  85970. };
  85971. // Statics
  85972. /**
  85973. * Creates a new target from serialized data
  85974. * @param serializationObject defines the serialized data to use
  85975. * @returns a new MorphTarget
  85976. */
  85977. MorphTarget.Parse = function (serializationObject) {
  85978. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85979. result.setPositions(serializationObject.positions);
  85980. if (serializationObject.normals) {
  85981. result.setNormals(serializationObject.normals);
  85982. }
  85983. if (serializationObject.tangents) {
  85984. result.setTangents(serializationObject.tangents);
  85985. }
  85986. // Animations
  85987. if (serializationObject.animations) {
  85988. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85989. var parsedAnimation = serializationObject.animations[animationIndex];
  85990. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85991. }
  85992. }
  85993. return result;
  85994. };
  85995. /**
  85996. * Creates a MorphTarget from mesh data
  85997. * @param mesh defines the source mesh
  85998. * @param name defines the name to use for the new target
  85999. * @param influence defines the influence to attach to the target
  86000. * @returns a new MorphTarget
  86001. */
  86002. MorphTarget.FromMesh = function (mesh, name, influence) {
  86003. if (!name) {
  86004. name = mesh.name;
  86005. }
  86006. var result = new MorphTarget(name, influence, mesh.getScene());
  86007. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86008. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  86009. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  86010. }
  86011. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  86012. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  86013. }
  86014. return result;
  86015. };
  86016. return MorphTarget;
  86017. }());
  86018. BABYLON.MorphTarget = MorphTarget;
  86019. })(BABYLON || (BABYLON = {}));
  86020. //# sourceMappingURL=babylon.morphTarget.js.map
  86021. var BABYLON;
  86022. (function (BABYLON) {
  86023. /**
  86024. * This class is used to deform meshes using morphing between different targets
  86025. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  86026. */
  86027. var MorphTargetManager = /** @class */ (function () {
  86028. /**
  86029. * Creates a new MorphTargetManager
  86030. * @param scene defines the current scene
  86031. */
  86032. function MorphTargetManager(scene) {
  86033. if (scene === void 0) { scene = null; }
  86034. this._targets = new Array();
  86035. this._targetObservable = new Array();
  86036. this._activeTargets = new BABYLON.SmartArray(16);
  86037. this._supportsNormals = false;
  86038. this._supportsTangents = false;
  86039. this._vertexCount = 0;
  86040. this._uniqueId = 0;
  86041. this._tempInfluences = new Array();
  86042. if (!scene) {
  86043. scene = BABYLON.Engine.LastCreatedScene;
  86044. }
  86045. this._scene = scene;
  86046. if (this._scene) {
  86047. this._scene.morphTargetManagers.push(this);
  86048. this._uniqueId = this._scene.getUniqueId();
  86049. }
  86050. }
  86051. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  86052. /**
  86053. * Gets the unique ID of this manager
  86054. */
  86055. get: function () {
  86056. return this._uniqueId;
  86057. },
  86058. enumerable: true,
  86059. configurable: true
  86060. });
  86061. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  86062. /**
  86063. * Gets the number of vertices handled by this manager
  86064. */
  86065. get: function () {
  86066. return this._vertexCount;
  86067. },
  86068. enumerable: true,
  86069. configurable: true
  86070. });
  86071. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  86072. /**
  86073. * Gets a boolean indicating if this manager supports morphing of normals
  86074. */
  86075. get: function () {
  86076. return this._supportsNormals;
  86077. },
  86078. enumerable: true,
  86079. configurable: true
  86080. });
  86081. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  86082. /**
  86083. * Gets a boolean indicating if this manager supports morphing of tangents
  86084. */
  86085. get: function () {
  86086. return this._supportsTangents;
  86087. },
  86088. enumerable: true,
  86089. configurable: true
  86090. });
  86091. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  86092. /**
  86093. * Gets the number of targets stored in this manager
  86094. */
  86095. get: function () {
  86096. return this._targets.length;
  86097. },
  86098. enumerable: true,
  86099. configurable: true
  86100. });
  86101. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  86102. /**
  86103. * Gets the number of influencers (ie. the number of targets with influences > 0)
  86104. */
  86105. get: function () {
  86106. return this._activeTargets.length;
  86107. },
  86108. enumerable: true,
  86109. configurable: true
  86110. });
  86111. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  86112. /**
  86113. * Gets the list of influences (one per target)
  86114. */
  86115. get: function () {
  86116. return this._influences;
  86117. },
  86118. enumerable: true,
  86119. configurable: true
  86120. });
  86121. /**
  86122. * Gets the active target at specified index. An active target is a target with an influence > 0
  86123. * @param index defines the index to check
  86124. * @returns the requested target
  86125. */
  86126. MorphTargetManager.prototype.getActiveTarget = function (index) {
  86127. return this._activeTargets.data[index];
  86128. };
  86129. /**
  86130. * Gets the target at specified index
  86131. * @param index defines the index to check
  86132. * @returns the requested target
  86133. */
  86134. MorphTargetManager.prototype.getTarget = function (index) {
  86135. return this._targets[index];
  86136. };
  86137. /**
  86138. * Add a new target to this manager
  86139. * @param target defines the target to add
  86140. */
  86141. MorphTargetManager.prototype.addTarget = function (target) {
  86142. var _this = this;
  86143. this._targets.push(target);
  86144. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  86145. _this._syncActiveTargets(needUpdate);
  86146. }));
  86147. this._syncActiveTargets(true);
  86148. };
  86149. /**
  86150. * Removes a target from the manager
  86151. * @param target defines the target to remove
  86152. */
  86153. MorphTargetManager.prototype.removeTarget = function (target) {
  86154. var index = this._targets.indexOf(target);
  86155. if (index >= 0) {
  86156. this._targets.splice(index, 1);
  86157. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  86158. this._syncActiveTargets(true);
  86159. }
  86160. };
  86161. /**
  86162. * Serializes the current manager into a Serialization object
  86163. * @returns the serialized object
  86164. */
  86165. MorphTargetManager.prototype.serialize = function () {
  86166. var serializationObject = {};
  86167. serializationObject.id = this.uniqueId;
  86168. serializationObject.targets = [];
  86169. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86170. var target = _a[_i];
  86171. serializationObject.targets.push(target.serialize());
  86172. }
  86173. return serializationObject;
  86174. };
  86175. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  86176. var influenceCount = 0;
  86177. this._activeTargets.reset();
  86178. this._supportsNormals = true;
  86179. this._supportsTangents = true;
  86180. this._vertexCount = 0;
  86181. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86182. var target = _a[_i];
  86183. this._activeTargets.push(target);
  86184. this._tempInfluences[influenceCount++] = target.influence;
  86185. var positions = target.getPositions();
  86186. if (positions) {
  86187. this._supportsNormals = this._supportsNormals && target.hasNormals;
  86188. this._supportsTangents = this._supportsTangents && target.hasTangents;
  86189. var vertexCount = positions.length / 3;
  86190. if (this._vertexCount === 0) {
  86191. this._vertexCount = vertexCount;
  86192. }
  86193. else if (this._vertexCount !== vertexCount) {
  86194. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  86195. return;
  86196. }
  86197. }
  86198. }
  86199. if (!this._influences || this._influences.length !== influenceCount) {
  86200. this._influences = new Float32Array(influenceCount);
  86201. }
  86202. for (var index = 0; index < influenceCount; index++) {
  86203. this._influences[index] = this._tempInfluences[index];
  86204. }
  86205. if (needUpdate) {
  86206. this.synchronize();
  86207. }
  86208. };
  86209. /**
  86210. * Syncrhonize the targets with all the meshes using this morph target manager
  86211. */
  86212. MorphTargetManager.prototype.synchronize = function () {
  86213. if (!this._scene) {
  86214. return;
  86215. }
  86216. // Flag meshes as dirty to resync with the active targets
  86217. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  86218. var mesh = _a[_i];
  86219. if (mesh.morphTargetManager === this) {
  86220. mesh._syncGeometryWithMorphTargetManager();
  86221. }
  86222. }
  86223. };
  86224. // Statics
  86225. /**
  86226. * Creates a new MorphTargetManager from serialized data
  86227. * @param serializationObject defines the serialized data
  86228. * @param scene defines the hosting scene
  86229. * @returns the new MorphTargetManager
  86230. */
  86231. MorphTargetManager.Parse = function (serializationObject, scene) {
  86232. var result = new MorphTargetManager(scene);
  86233. result._uniqueId = serializationObject.id;
  86234. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  86235. var targetData = _a[_i];
  86236. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  86237. }
  86238. return result;
  86239. };
  86240. return MorphTargetManager;
  86241. }());
  86242. BABYLON.MorphTargetManager = MorphTargetManager;
  86243. })(BABYLON || (BABYLON = {}));
  86244. //# sourceMappingURL=babylon.morphTargetManager.js.map
  86245. var BABYLON;
  86246. (function (BABYLON) {
  86247. var Octree = /** @class */ (function () {
  86248. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  86249. if (maxDepth === void 0) { maxDepth = 2; }
  86250. this.maxDepth = maxDepth;
  86251. this.dynamicContent = new Array();
  86252. this._maxBlockCapacity = maxBlockCapacity || 64;
  86253. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  86254. this._creationFunc = creationFunc;
  86255. }
  86256. // Methods
  86257. Octree.prototype.update = function (worldMin, worldMax, entries) {
  86258. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  86259. };
  86260. Octree.prototype.addMesh = function (entry) {
  86261. for (var index = 0; index < this.blocks.length; index++) {
  86262. var block = this.blocks[index];
  86263. block.addEntry(entry);
  86264. }
  86265. };
  86266. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  86267. this._selectionContent.reset();
  86268. for (var index = 0; index < this.blocks.length; index++) {
  86269. var block = this.blocks[index];
  86270. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  86271. }
  86272. if (allowDuplicate) {
  86273. this._selectionContent.concat(this.dynamicContent);
  86274. }
  86275. else {
  86276. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86277. }
  86278. return this._selectionContent;
  86279. };
  86280. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  86281. this._selectionContent.reset();
  86282. for (var index = 0; index < this.blocks.length; index++) {
  86283. var block = this.blocks[index];
  86284. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  86285. }
  86286. if (allowDuplicate) {
  86287. this._selectionContent.concat(this.dynamicContent);
  86288. }
  86289. else {
  86290. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86291. }
  86292. return this._selectionContent;
  86293. };
  86294. Octree.prototype.intersectsRay = function (ray) {
  86295. this._selectionContent.reset();
  86296. for (var index = 0; index < this.blocks.length; index++) {
  86297. var block = this.blocks[index];
  86298. block.intersectsRay(ray, this._selectionContent);
  86299. }
  86300. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86301. return this._selectionContent;
  86302. };
  86303. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  86304. target.blocks = new Array();
  86305. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  86306. // Segmenting space
  86307. for (var x = 0; x < 2; x++) {
  86308. for (var y = 0; y < 2; y++) {
  86309. for (var z = 0; z < 2; z++) {
  86310. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  86311. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86312. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86313. block.addEntries(entries);
  86314. target.blocks.push(block);
  86315. }
  86316. }
  86317. }
  86318. };
  86319. Octree.CreationFuncForMeshes = function (entry, block) {
  86320. var boundingInfo = entry.getBoundingInfo();
  86321. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86322. block.entries.push(entry);
  86323. }
  86324. };
  86325. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86326. var boundingInfo = entry.getBoundingInfo();
  86327. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86328. block.entries.push(entry);
  86329. }
  86330. };
  86331. return Octree;
  86332. }());
  86333. BABYLON.Octree = Octree;
  86334. })(BABYLON || (BABYLON = {}));
  86335. //# sourceMappingURL=babylon.octree.js.map
  86336. var BABYLON;
  86337. (function (BABYLON) {
  86338. var OctreeBlock = /** @class */ (function () {
  86339. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86340. this.entries = new Array();
  86341. this._boundingVectors = new Array();
  86342. this._capacity = capacity;
  86343. this._depth = depth;
  86344. this._maxDepth = maxDepth;
  86345. this._creationFunc = creationFunc;
  86346. this._minPoint = minPoint;
  86347. this._maxPoint = maxPoint;
  86348. this._boundingVectors.push(minPoint.clone());
  86349. this._boundingVectors.push(maxPoint.clone());
  86350. this._boundingVectors.push(minPoint.clone());
  86351. this._boundingVectors[2].x = maxPoint.x;
  86352. this._boundingVectors.push(minPoint.clone());
  86353. this._boundingVectors[3].y = maxPoint.y;
  86354. this._boundingVectors.push(minPoint.clone());
  86355. this._boundingVectors[4].z = maxPoint.z;
  86356. this._boundingVectors.push(maxPoint.clone());
  86357. this._boundingVectors[5].z = minPoint.z;
  86358. this._boundingVectors.push(maxPoint.clone());
  86359. this._boundingVectors[6].x = minPoint.x;
  86360. this._boundingVectors.push(maxPoint.clone());
  86361. this._boundingVectors[7].y = minPoint.y;
  86362. }
  86363. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86364. // Property
  86365. get: function () {
  86366. return this._capacity;
  86367. },
  86368. enumerable: true,
  86369. configurable: true
  86370. });
  86371. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86372. get: function () {
  86373. return this._minPoint;
  86374. },
  86375. enumerable: true,
  86376. configurable: true
  86377. });
  86378. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86379. get: function () {
  86380. return this._maxPoint;
  86381. },
  86382. enumerable: true,
  86383. configurable: true
  86384. });
  86385. // Methods
  86386. OctreeBlock.prototype.addEntry = function (entry) {
  86387. if (this.blocks) {
  86388. for (var index = 0; index < this.blocks.length; index++) {
  86389. var block = this.blocks[index];
  86390. block.addEntry(entry);
  86391. }
  86392. return;
  86393. }
  86394. this._creationFunc(entry, this);
  86395. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86396. this.createInnerBlocks();
  86397. }
  86398. };
  86399. OctreeBlock.prototype.addEntries = function (entries) {
  86400. for (var index = 0; index < entries.length; index++) {
  86401. var mesh = entries[index];
  86402. this.addEntry(mesh);
  86403. }
  86404. };
  86405. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86406. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86407. if (this.blocks) {
  86408. for (var index = 0; index < this.blocks.length; index++) {
  86409. var block = this.blocks[index];
  86410. block.select(frustumPlanes, selection, allowDuplicate);
  86411. }
  86412. return;
  86413. }
  86414. if (allowDuplicate) {
  86415. selection.concat(this.entries);
  86416. }
  86417. else {
  86418. selection.concatWithNoDuplicate(this.entries);
  86419. }
  86420. }
  86421. };
  86422. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86423. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86424. if (this.blocks) {
  86425. for (var index = 0; index < this.blocks.length; index++) {
  86426. var block = this.blocks[index];
  86427. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86428. }
  86429. return;
  86430. }
  86431. if (allowDuplicate) {
  86432. selection.concat(this.entries);
  86433. }
  86434. else {
  86435. selection.concatWithNoDuplicate(this.entries);
  86436. }
  86437. }
  86438. };
  86439. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86440. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86441. if (this.blocks) {
  86442. for (var index = 0; index < this.blocks.length; index++) {
  86443. var block = this.blocks[index];
  86444. block.intersectsRay(ray, selection);
  86445. }
  86446. return;
  86447. }
  86448. selection.concatWithNoDuplicate(this.entries);
  86449. }
  86450. };
  86451. OctreeBlock.prototype.createInnerBlocks = function () {
  86452. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86453. };
  86454. return OctreeBlock;
  86455. }());
  86456. BABYLON.OctreeBlock = OctreeBlock;
  86457. })(BABYLON || (BABYLON = {}));
  86458. //# sourceMappingURL=babylon.octreeBlock.js.map
  86459. var BABYLON;
  86460. (function (BABYLON) {
  86461. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86462. __extends(VRDistortionCorrectionPostProcess, _super);
  86463. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86464. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86465. 'LensCenter',
  86466. 'Scale',
  86467. 'ScaleIn',
  86468. 'HmdWarpParam'
  86469. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86470. _this._isRightEye = isRightEye;
  86471. _this._distortionFactors = vrMetrics.distortionK;
  86472. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86473. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86474. _this.adaptScaleToCurrentViewport = true;
  86475. _this.onSizeChangedObservable.add(function () {
  86476. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86477. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86478. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86479. });
  86480. _this.onApplyObservable.add(function (effect) {
  86481. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86482. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86483. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86484. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86485. });
  86486. return _this;
  86487. }
  86488. return VRDistortionCorrectionPostProcess;
  86489. }(BABYLON.PostProcess));
  86490. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86491. })(BABYLON || (BABYLON = {}));
  86492. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86493. var BABYLON;
  86494. (function (BABYLON) {
  86495. /**
  86496. * Postprocess used to generate anaglyphic rendering
  86497. */
  86498. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86499. __extends(AnaglyphPostProcess, _super);
  86500. /**
  86501. * Creates a new AnaglyphPostProcess
  86502. * @param name defines postprocess name
  86503. * @param options defines creation options or target ratio scale
  86504. * @param rigCameras defines cameras using this postprocess
  86505. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86506. * @param engine defines hosting engine
  86507. * @param reusable defines if the postprocess will be reused multiple times per frame
  86508. */
  86509. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86510. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86511. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86512. _this.onApplyObservable.add(function (effect) {
  86513. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86514. });
  86515. return _this;
  86516. }
  86517. return AnaglyphPostProcess;
  86518. }(BABYLON.PostProcess));
  86519. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86520. })(BABYLON || (BABYLON = {}));
  86521. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86522. var BABYLON;
  86523. (function (BABYLON) {
  86524. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86525. __extends(StereoscopicInterlacePostProcess, _super);
  86526. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86527. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86528. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86529. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86530. _this.onSizeChangedObservable.add(function () {
  86531. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86532. });
  86533. _this.onApplyObservable.add(function (effect) {
  86534. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86535. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86536. });
  86537. return _this;
  86538. }
  86539. return StereoscopicInterlacePostProcess;
  86540. }(BABYLON.PostProcess));
  86541. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86542. })(BABYLON || (BABYLON = {}));
  86543. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86544. var BABYLON;
  86545. (function (BABYLON) {
  86546. /**
  86547. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86548. * Screen rotation is taken into account.
  86549. */
  86550. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86551. function FreeCameraDeviceOrientationInput() {
  86552. var _this = this;
  86553. this._screenOrientationAngle = 0;
  86554. this._screenQuaternion = new BABYLON.Quaternion();
  86555. this._alpha = 0;
  86556. this._beta = 0;
  86557. this._gamma = 0;
  86558. this._orientationChanged = function () {
  86559. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86560. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86561. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86562. };
  86563. this._deviceOrientation = function (evt) {
  86564. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86565. _this._beta = evt.beta !== null ? evt.beta : 0;
  86566. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86567. };
  86568. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86569. this._orientationChanged();
  86570. }
  86571. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86572. get: function () {
  86573. return this._camera;
  86574. },
  86575. set: function (camera) {
  86576. this._camera = camera;
  86577. if (this._camera != null && !this._camera.rotationQuaternion) {
  86578. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86579. }
  86580. },
  86581. enumerable: true,
  86582. configurable: true
  86583. });
  86584. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86585. window.addEventListener("orientationchange", this._orientationChanged);
  86586. window.addEventListener("deviceorientation", this._deviceOrientation);
  86587. //In certain cases, the attach control is called AFTER orientation was changed,
  86588. //So this is needed.
  86589. this._orientationChanged();
  86590. };
  86591. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86592. window.removeEventListener("orientationchange", this._orientationChanged);
  86593. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86594. };
  86595. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86596. //if no device orientation provided, don't update the rotation.
  86597. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86598. if (!this._alpha)
  86599. return;
  86600. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86601. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86602. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86603. //Mirror on XY Plane
  86604. this._camera.rotationQuaternion.z *= -1;
  86605. this._camera.rotationQuaternion.w *= -1;
  86606. };
  86607. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86608. return "FreeCameraDeviceOrientationInput";
  86609. };
  86610. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86611. return "deviceOrientation";
  86612. };
  86613. return FreeCameraDeviceOrientationInput;
  86614. }());
  86615. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86616. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86617. })(BABYLON || (BABYLON = {}));
  86618. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86619. var BABYLON;
  86620. (function (BABYLON) {
  86621. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86622. function ArcRotateCameraVRDeviceOrientationInput() {
  86623. this.alphaCorrection = 1;
  86624. this.betaCorrection = 1;
  86625. this.gammaCorrection = 1;
  86626. this._alpha = 0;
  86627. this._gamma = 0;
  86628. this._dirty = false;
  86629. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86630. }
  86631. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86632. this.camera.attachControl(element, noPreventDefault);
  86633. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86634. };
  86635. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86636. if (evt.alpha !== null) {
  86637. this._alpha = +evt.alpha | 0;
  86638. }
  86639. if (evt.gamma !== null) {
  86640. this._gamma = +evt.gamma | 0;
  86641. }
  86642. this._dirty = true;
  86643. };
  86644. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86645. if (this._dirty) {
  86646. this._dirty = false;
  86647. if (this._gamma < 0) {
  86648. this._gamma = 180 + this._gamma;
  86649. }
  86650. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86651. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86652. }
  86653. };
  86654. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86655. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86656. };
  86657. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86658. return "ArcRotateCameraVRDeviceOrientationInput";
  86659. };
  86660. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86661. return "VRDeviceOrientation";
  86662. };
  86663. return ArcRotateCameraVRDeviceOrientationInput;
  86664. }());
  86665. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86666. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86667. })(BABYLON || (BABYLON = {}));
  86668. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86669. var BABYLON;
  86670. (function (BABYLON) {
  86671. var VRCameraMetrics = /** @class */ (function () {
  86672. function VRCameraMetrics() {
  86673. this.compensateDistortion = true;
  86674. }
  86675. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86676. get: function () {
  86677. return this.hResolution / (2 * this.vResolution);
  86678. },
  86679. enumerable: true,
  86680. configurable: true
  86681. });
  86682. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86683. get: function () {
  86684. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86685. },
  86686. enumerable: true,
  86687. configurable: true
  86688. });
  86689. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86690. get: function () {
  86691. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86692. var h = (4 * meters) / this.hScreenSize;
  86693. return BABYLON.Matrix.Translation(h, 0, 0);
  86694. },
  86695. enumerable: true,
  86696. configurable: true
  86697. });
  86698. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86699. get: function () {
  86700. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86701. var h = (4 * meters) / this.hScreenSize;
  86702. return BABYLON.Matrix.Translation(-h, 0, 0);
  86703. },
  86704. enumerable: true,
  86705. configurable: true
  86706. });
  86707. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86708. get: function () {
  86709. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86710. },
  86711. enumerable: true,
  86712. configurable: true
  86713. });
  86714. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86715. get: function () {
  86716. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86717. },
  86718. enumerable: true,
  86719. configurable: true
  86720. });
  86721. VRCameraMetrics.GetDefault = function () {
  86722. var result = new VRCameraMetrics();
  86723. result.hResolution = 1280;
  86724. result.vResolution = 800;
  86725. result.hScreenSize = 0.149759993;
  86726. result.vScreenSize = 0.0935999975;
  86727. result.vScreenCenter = 0.0467999987;
  86728. result.eyeToScreenDistance = 0.0410000011;
  86729. result.lensSeparationDistance = 0.0635000020;
  86730. result.interpupillaryDistance = 0.0640000030;
  86731. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86732. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86733. result.postProcessScaleFactor = 1.714605507808412;
  86734. result.lensCenterOffset = 0.151976421;
  86735. return result;
  86736. };
  86737. return VRCameraMetrics;
  86738. }());
  86739. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86740. })(BABYLON || (BABYLON = {}));
  86741. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86742. var BABYLON;
  86743. (function (BABYLON) {
  86744. /**
  86745. * This represents a WebVR camera.
  86746. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86747. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86748. */
  86749. var WebVRFreeCamera = /** @class */ (function (_super) {
  86750. __extends(WebVRFreeCamera, _super);
  86751. /**
  86752. * Instantiates a WebVRFreeCamera.
  86753. * @param name The name of the WebVRFreeCamera
  86754. * @param position The starting anchor position for the camera
  86755. * @param scene The scene the camera belongs to
  86756. * @param webVROptions a set of customizable options for the webVRCamera
  86757. */
  86758. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86759. if (webVROptions === void 0) { webVROptions = {}; }
  86760. var _this = _super.call(this, name, position, scene) || this;
  86761. _this.webVROptions = webVROptions;
  86762. /**
  86763. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86764. */
  86765. _this._vrDevice = null;
  86766. /**
  86767. * The rawPose of the vrDevice.
  86768. */
  86769. _this.rawPose = null;
  86770. _this._specsVersion = "1.1";
  86771. _this._attached = false;
  86772. _this._descendants = [];
  86773. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86774. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86775. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86776. _this._standingMatrix = null;
  86777. /**
  86778. * Represents device position in babylon space.
  86779. */
  86780. _this.devicePosition = BABYLON.Vector3.Zero();
  86781. /**
  86782. * Represents device rotation in babylon space.
  86783. */
  86784. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86785. /**
  86786. * The scale of the device to be used when translating from device space to babylon space.
  86787. */
  86788. _this.deviceScaleFactor = 1;
  86789. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86790. _this._worldToDevice = BABYLON.Matrix.Identity();
  86791. /**
  86792. * References to the webVR controllers for the vrDevice.
  86793. */
  86794. _this.controllers = [];
  86795. /**
  86796. * Emits an event when a controller is attached.
  86797. */
  86798. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86799. /**
  86800. * Emits an event when a controller's mesh has been loaded;
  86801. */
  86802. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86803. /**
  86804. * If the rig cameras be used as parent instead of this camera.
  86805. */
  86806. _this.rigParenting = true;
  86807. _this._defaultHeight = undefined;
  86808. _this._workingVector = BABYLON.Vector3.Zero();
  86809. _this._oneVector = BABYLON.Vector3.One();
  86810. _this._workingMatrix = BABYLON.Matrix.Identity();
  86811. _this._cache.position = BABYLON.Vector3.Zero();
  86812. if (webVROptions.defaultHeight) {
  86813. _this._defaultHeight = webVROptions.defaultHeight;
  86814. _this.position.y = _this._defaultHeight;
  86815. }
  86816. _this.minZ = 0.1;
  86817. //legacy support - the compensation boolean was removed.
  86818. if (arguments.length === 5) {
  86819. _this.webVROptions = arguments[4];
  86820. }
  86821. // default webVR options
  86822. if (_this.webVROptions.trackPosition == undefined) {
  86823. _this.webVROptions.trackPosition = true;
  86824. }
  86825. if (_this.webVROptions.controllerMeshes == undefined) {
  86826. _this.webVROptions.controllerMeshes = true;
  86827. }
  86828. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86829. _this.webVROptions.defaultLightingOnControllers = true;
  86830. }
  86831. _this.rotationQuaternion = new BABYLON.Quaternion();
  86832. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86833. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86834. }
  86835. //enable VR
  86836. var engine = _this.getEngine();
  86837. _this._onVREnabled = function (success) { if (success) {
  86838. _this.initControllers();
  86839. } };
  86840. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86841. engine.initWebVR().add(function (event) {
  86842. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86843. return;
  86844. }
  86845. _this._vrDevice = event.vrDisplay;
  86846. //reset the rig parameters.
  86847. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86848. if (_this._attached) {
  86849. _this.getEngine().enableVR();
  86850. }
  86851. });
  86852. if (typeof (VRFrameData) !== "undefined")
  86853. _this._frameData = new VRFrameData();
  86854. /**
  86855. * The idea behind the following lines:
  86856. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86857. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86858. * the second will not show it correctly.
  86859. *
  86860. * To solve this - each object that has the camera as parent will be added to a protected array.
  86861. * When the rig camera renders, it will take this array and set all of those to be its children.
  86862. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86863. * Amazing!
  86864. */
  86865. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86866. if (camera.parent === _this && _this.rigParenting) {
  86867. _this._descendants = _this.getDescendants(true, function (n) {
  86868. // don't take the cameras or the controllers!
  86869. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86870. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86871. return !isController && !isRigCamera;
  86872. });
  86873. _this._descendants.forEach(function (node) {
  86874. node.parent = camera;
  86875. });
  86876. }
  86877. });
  86878. scene.onAfterCameraRenderObservable.add(function (camera) {
  86879. if (camera.parent === _this && _this.rigParenting) {
  86880. _this._descendants.forEach(function (node) {
  86881. node.parent = _this;
  86882. });
  86883. }
  86884. });
  86885. return _this;
  86886. }
  86887. /**
  86888. * Gets the device distance from the ground in meters.
  86889. * @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.
  86890. */
  86891. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86892. if (this._standingMatrix) {
  86893. // Add standing matrix offset to get real offset from ground in room
  86894. this._standingMatrix.getTranslationToRef(this._workingVector);
  86895. return this._deviceRoomPosition.y + this._workingVector.y;
  86896. }
  86897. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86898. return this._defaultHeight || 0;
  86899. };
  86900. /**
  86901. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86902. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86903. */
  86904. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86905. var _this = this;
  86906. if (callback === void 0) { callback = function (bool) { }; }
  86907. // Use standing matrix if available
  86908. this.getEngine().initWebVRAsync().then(function (result) {
  86909. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86910. callback(false);
  86911. }
  86912. else {
  86913. _this._standingMatrix = new BABYLON.Matrix();
  86914. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86915. if (!_this.getScene().useRightHandedSystem) {
  86916. [2, 6, 8, 9, 14].forEach(function (num) {
  86917. if (_this._standingMatrix) {
  86918. _this._standingMatrix.m[num] *= -1;
  86919. }
  86920. });
  86921. }
  86922. callback(true);
  86923. }
  86924. });
  86925. };
  86926. /**
  86927. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86928. * @returns A promise with a boolean set to if the standing matrix is supported.
  86929. */
  86930. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86931. var _this = this;
  86932. return new Promise(function (res, rej) {
  86933. _this.useStandingMatrix(function (supported) {
  86934. res(supported);
  86935. });
  86936. });
  86937. };
  86938. /**
  86939. * Disposes the camera
  86940. */
  86941. WebVRFreeCamera.prototype.dispose = function () {
  86942. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86943. _super.prototype.dispose.call(this);
  86944. };
  86945. /**
  86946. * Gets a vrController by name.
  86947. * @param name The name of the controller to retreive
  86948. * @returns the controller matching the name specified or null if not found
  86949. */
  86950. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86951. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86952. var gp = _a[_i];
  86953. if (gp.hand === name) {
  86954. return gp;
  86955. }
  86956. }
  86957. return null;
  86958. };
  86959. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86960. /**
  86961. * The controller corrisponding to the users left hand.
  86962. */
  86963. get: function () {
  86964. if (!this._leftController) {
  86965. this._leftController = this.getControllerByName("left");
  86966. }
  86967. return this._leftController;
  86968. },
  86969. enumerable: true,
  86970. configurable: true
  86971. });
  86972. ;
  86973. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86974. /**
  86975. * The controller corrisponding to the users right hand.
  86976. */
  86977. get: function () {
  86978. if (!this._rightController) {
  86979. this._rightController = this.getControllerByName("right");
  86980. }
  86981. return this._rightController;
  86982. },
  86983. enumerable: true,
  86984. configurable: true
  86985. });
  86986. ;
  86987. /**
  86988. * Casts a ray forward from the vrCamera's gaze.
  86989. * @param length Length of the ray (default: 100)
  86990. * @returns the ray corrisponding to the gaze
  86991. */
  86992. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86993. if (length === void 0) { length = 100; }
  86994. if (this.leftCamera) {
  86995. // Use left eye to avoid computation to compute center on every call
  86996. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86997. }
  86998. else {
  86999. return _super.prototype.getForwardRay.call(this, length);
  87000. }
  87001. };
  87002. /**
  87003. * Updates the camera based on device's frame data
  87004. */
  87005. WebVRFreeCamera.prototype._checkInputs = function () {
  87006. if (this._vrDevice && this._vrDevice.isPresenting) {
  87007. this._vrDevice.getFrameData(this._frameData);
  87008. this.updateFromDevice(this._frameData.pose);
  87009. }
  87010. _super.prototype._checkInputs.call(this);
  87011. };
  87012. /**
  87013. * Updates the poseControlled values based on the input device pose.
  87014. * @param poseData Pose coming from the device
  87015. */
  87016. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  87017. if (poseData && poseData.orientation) {
  87018. this.rawPose = poseData;
  87019. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  87020. if (this.getScene().useRightHandedSystem) {
  87021. this._deviceRoomRotationQuaternion.z *= -1;
  87022. this._deviceRoomRotationQuaternion.w *= -1;
  87023. }
  87024. if (this.webVROptions.trackPosition && this.rawPose.position) {
  87025. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  87026. if (this.getScene().useRightHandedSystem) {
  87027. this._deviceRoomPosition.z *= -1;
  87028. }
  87029. }
  87030. }
  87031. };
  87032. /**
  87033. * WebVR's attach control will start broadcasting frames to the device.
  87034. * Note that in certain browsers (chrome for example) this function must be called
  87035. * within a user-interaction callback. Example:
  87036. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  87037. *
  87038. * @param element html element to attach the vrDevice to
  87039. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  87040. */
  87041. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  87042. _super.prototype.attachControl.call(this, element, noPreventDefault);
  87043. this._attached = true;
  87044. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  87045. if (this._vrDevice) {
  87046. this.getEngine().enableVR();
  87047. }
  87048. };
  87049. /**
  87050. * Detaches the camera from the html element and disables VR
  87051. *
  87052. * @param element html element to detach from
  87053. */
  87054. WebVRFreeCamera.prototype.detachControl = function (element) {
  87055. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  87056. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  87057. _super.prototype.detachControl.call(this, element);
  87058. this._attached = false;
  87059. this.getEngine().disableVR();
  87060. };
  87061. /**
  87062. * @returns the name of this class
  87063. */
  87064. WebVRFreeCamera.prototype.getClassName = function () {
  87065. return "WebVRFreeCamera";
  87066. };
  87067. /**
  87068. * Calls resetPose on the vrDisplay
  87069. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  87070. */
  87071. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  87072. //uses the vrDisplay's "resetPose()".
  87073. //pitch and roll won't be affected.
  87074. this._vrDevice.resetPose();
  87075. };
  87076. /**
  87077. * Updates the rig cameras (left and right eye)
  87078. */
  87079. WebVRFreeCamera.prototype._updateRigCameras = function () {
  87080. var camLeft = this._rigCameras[0];
  87081. var camRight = this._rigCameras[1];
  87082. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87083. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87084. camLeft.position.copyFrom(this._deviceRoomPosition);
  87085. camRight.position.copyFrom(this._deviceRoomPosition);
  87086. };
  87087. /**
  87088. * Updates the cached values of the camera
  87089. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  87090. */
  87091. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  87092. var _this = this;
  87093. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  87094. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  87095. if (!this.updateCacheCalled) {
  87096. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  87097. this.updateCacheCalled = true;
  87098. this.update();
  87099. }
  87100. // Set working vector to the device position in room space rotated by the new rotation
  87101. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  87102. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  87103. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  87104. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  87105. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  87106. // Add translation from anchor position
  87107. this._deviceToWorld.getTranslationToRef(this._workingVector);
  87108. this._workingVector.addInPlace(this.position);
  87109. this._workingVector.subtractInPlace(this._cache.position);
  87110. this._deviceToWorld.setTranslation(this._workingVector);
  87111. // Set an inverted matrix to be used when updating the camera
  87112. this._deviceToWorld.invertToRef(this._worldToDevice);
  87113. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  87114. this.controllers.forEach(function (controller) {
  87115. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  87116. controller.update();
  87117. });
  87118. }
  87119. if (!ignoreParentClass) {
  87120. _super.prototype._updateCache.call(this);
  87121. }
  87122. this.updateCacheCalled = false;
  87123. };
  87124. /**
  87125. * Updates the current device position and rotation in the babylon world
  87126. */
  87127. WebVRFreeCamera.prototype.update = function () {
  87128. // Get current device position in babylon world
  87129. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  87130. // Get current device rotation in babylon world
  87131. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  87132. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  87133. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  87134. _super.prototype.update.call(this);
  87135. };
  87136. /**
  87137. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  87138. * @returns an identity matrix
  87139. */
  87140. WebVRFreeCamera.prototype._getViewMatrix = function () {
  87141. return BABYLON.Matrix.Identity();
  87142. };
  87143. /**
  87144. * This function is called by the two RIG cameras.
  87145. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  87146. */
  87147. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  87148. var _this = this;
  87149. // Update the parent camera prior to using a child camera to avoid desynchronization
  87150. var parentCamera = this._cameraRigParams["parentCamera"];
  87151. parentCamera._updateCache();
  87152. //WebVR 1.1
  87153. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  87154. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  87155. if (!this.getScene().useRightHandedSystem) {
  87156. [2, 6, 8, 9, 14].forEach(function (num) {
  87157. _this._webvrViewMatrix.m[num] *= -1;
  87158. });
  87159. }
  87160. // update the camera rotation matrix
  87161. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  87162. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  87163. // Computing target and final matrix
  87164. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  87165. // should the view matrix be updated with scale and position offset?
  87166. if (parentCamera.deviceScaleFactor !== 1) {
  87167. this._webvrViewMatrix.invert();
  87168. // scale the position, if set
  87169. if (parentCamera.deviceScaleFactor) {
  87170. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  87171. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  87172. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  87173. }
  87174. this._webvrViewMatrix.invert();
  87175. }
  87176. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  87177. // Compute global position
  87178. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  87179. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  87180. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  87181. this._workingMatrix.getTranslationToRef(this._globalPosition);
  87182. this._markSyncedWithParent();
  87183. return this._webvrViewMatrix;
  87184. };
  87185. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  87186. var _this = this;
  87187. var parentCamera = this.parent;
  87188. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  87189. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  87190. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  87191. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  87192. //babylon compatible matrix
  87193. if (!this.getScene().useRightHandedSystem) {
  87194. [8, 9, 10, 11].forEach(function (num) {
  87195. _this._projectionMatrix.m[num] *= -1;
  87196. });
  87197. }
  87198. return this._projectionMatrix;
  87199. };
  87200. /**
  87201. * Initializes the controllers and their meshes
  87202. */
  87203. WebVRFreeCamera.prototype.initControllers = function () {
  87204. var _this = this;
  87205. this.controllers = [];
  87206. var manager = this.getScene().gamepadManager;
  87207. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  87208. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87209. var webVrController = gamepad;
  87210. if (webVrController.defaultModel) {
  87211. webVrController.defaultModel.setEnabled(false);
  87212. }
  87213. if (webVrController.hand === "right") {
  87214. _this._rightController = null;
  87215. }
  87216. if (webVrController.hand === "left") {
  87217. _this._leftController = null;
  87218. }
  87219. var controllerIndex = _this.controllers.indexOf(webVrController);
  87220. if (controllerIndex !== -1) {
  87221. _this.controllers.splice(controllerIndex, 1);
  87222. }
  87223. }
  87224. });
  87225. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  87226. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87227. var webVrController_1 = gamepad;
  87228. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  87229. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  87230. if (_this.webVROptions.controllerMeshes) {
  87231. if (webVrController_1.defaultModel) {
  87232. webVrController_1.defaultModel.setEnabled(true);
  87233. }
  87234. else {
  87235. // Load the meshes
  87236. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  87237. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  87238. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  87239. if (_this.webVROptions.defaultLightingOnControllers) {
  87240. if (!_this._lightOnControllers) {
  87241. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  87242. }
  87243. var activateLightOnSubMeshes_1 = function (mesh, light) {
  87244. var children = mesh.getChildren();
  87245. if (children.length !== 0) {
  87246. children.forEach(function (mesh) {
  87247. light.includedOnlyMeshes.push(mesh);
  87248. activateLightOnSubMeshes_1(mesh, light);
  87249. });
  87250. }
  87251. };
  87252. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  87253. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  87254. }
  87255. });
  87256. }
  87257. }
  87258. webVrController_1.attachToPoseControlledCamera(_this);
  87259. // since this is async - sanity check. Is the controller already stored?
  87260. if (_this.controllers.indexOf(webVrController_1) === -1) {
  87261. //add to the controllers array
  87262. _this.controllers.push(webVrController_1);
  87263. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  87264. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  87265. // So we're overriding setting left & right manually to be sure
  87266. var firstViveWandDetected = false;
  87267. for (var i = 0; i < _this.controllers.length; i++) {
  87268. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87269. if (!firstViveWandDetected) {
  87270. firstViveWandDetected = true;
  87271. _this.controllers[i].hand = "left";
  87272. }
  87273. else {
  87274. _this.controllers[i].hand = "right";
  87275. }
  87276. }
  87277. }
  87278. //did we find enough controllers? Great! let the developer know.
  87279. if (_this.controllers.length >= 2) {
  87280. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  87281. }
  87282. }
  87283. }
  87284. });
  87285. };
  87286. return WebVRFreeCamera;
  87287. }(BABYLON.FreeCamera));
  87288. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  87289. })(BABYLON || (BABYLON = {}));
  87290. //# sourceMappingURL=babylon.webVRCamera.js.map
  87291. var BABYLON;
  87292. (function (BABYLON) {
  87293. // We're mainly based on the logic defined into the FreeCamera code
  87294. /**
  87295. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  87296. * being tilted forward or back and left or right.
  87297. */
  87298. var DeviceOrientationCamera = /** @class */ (function (_super) {
  87299. __extends(DeviceOrientationCamera, _super);
  87300. /**
  87301. * Creates a new device orientation camera
  87302. * @param name The name of the camera
  87303. * @param position The start position camera
  87304. * @param scene The scene the camera belongs to
  87305. */
  87306. function DeviceOrientationCamera(name, position, scene) {
  87307. var _this = _super.call(this, name, position, scene) || this;
  87308. _this._quaternionCache = new BABYLON.Quaternion();
  87309. _this.inputs.addDeviceOrientation();
  87310. return _this;
  87311. }
  87312. /**
  87313. * Gets the current instance class name ("DeviceOrientationCamera").
  87314. * This helps avoiding instanceof at run time.
  87315. * @returns the class name
  87316. */
  87317. DeviceOrientationCamera.prototype.getClassName = function () {
  87318. return "DeviceOrientationCamera";
  87319. };
  87320. /**
  87321. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87322. */
  87323. DeviceOrientationCamera.prototype._checkInputs = function () {
  87324. _super.prototype._checkInputs.call(this);
  87325. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87326. if (this._initialQuaternion) {
  87327. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87328. }
  87329. };
  87330. /**
  87331. * Reset the camera to its default orientation on the specified axis only.
  87332. * @param axis The axis to reset
  87333. */
  87334. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87335. var _this = this;
  87336. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87337. //can only work if this camera has a rotation quaternion already.
  87338. if (!this.rotationQuaternion)
  87339. return;
  87340. if (!this._initialQuaternion) {
  87341. this._initialQuaternion = new BABYLON.Quaternion();
  87342. }
  87343. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87344. ['x', 'y', 'z'].forEach(function (axisName) {
  87345. if (!axis[axisName]) {
  87346. _this._initialQuaternion[axisName] = 0;
  87347. }
  87348. else {
  87349. _this._initialQuaternion[axisName] *= -1;
  87350. }
  87351. });
  87352. this._initialQuaternion.normalize();
  87353. //force rotation update
  87354. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87355. };
  87356. return DeviceOrientationCamera;
  87357. }(BABYLON.FreeCamera));
  87358. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87359. })(BABYLON || (BABYLON = {}));
  87360. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87361. var BABYLON;
  87362. (function (BABYLON) {
  87363. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87364. __extends(VRDeviceOrientationFreeCamera, _super);
  87365. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87366. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87367. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87368. var _this = _super.call(this, name, position, scene) || this;
  87369. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87370. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87371. return _this;
  87372. }
  87373. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87374. return "VRDeviceOrientationFreeCamera";
  87375. };
  87376. return VRDeviceOrientationFreeCamera;
  87377. }(BABYLON.DeviceOrientationCamera));
  87378. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87379. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87380. __extends(VRDeviceOrientationGamepadCamera, _super);
  87381. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87382. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87383. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87384. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87385. _this.inputs.addGamepad();
  87386. return _this;
  87387. }
  87388. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87389. return "VRDeviceOrientationGamepadCamera";
  87390. };
  87391. return VRDeviceOrientationGamepadCamera;
  87392. }(VRDeviceOrientationFreeCamera));
  87393. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87394. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87395. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87396. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87397. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87398. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87399. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87400. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87401. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87402. _this.inputs.addVRDeviceOrientation();
  87403. return _this;
  87404. }
  87405. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87406. return "VRDeviceOrientationArcRotateCamera";
  87407. };
  87408. return VRDeviceOrientationArcRotateCamera;
  87409. }(BABYLON.ArcRotateCamera));
  87410. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87411. })(BABYLON || (BABYLON = {}));
  87412. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87413. var BABYLON;
  87414. (function (BABYLON) {
  87415. /**
  87416. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87417. */
  87418. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87419. __extends(AnaglyphFreeCamera, _super);
  87420. /**
  87421. * Creates a new AnaglyphFreeCamera
  87422. * @param name defines camera name
  87423. * @param position defines initial position
  87424. * @param interaxialDistance defines distance between each color axis
  87425. * @param scene defines the hosting scene
  87426. */
  87427. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87428. var _this = _super.call(this, name, position, scene) || this;
  87429. _this.interaxialDistance = interaxialDistance;
  87430. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87431. return _this;
  87432. }
  87433. /**
  87434. * Gets camera class name
  87435. * @returns AnaglyphFreeCamera
  87436. */
  87437. AnaglyphFreeCamera.prototype.getClassName = function () {
  87438. return "AnaglyphFreeCamera";
  87439. };
  87440. return AnaglyphFreeCamera;
  87441. }(BABYLON.FreeCamera));
  87442. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87443. /**
  87444. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87445. */
  87446. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87447. __extends(AnaglyphArcRotateCamera, _super);
  87448. /**
  87449. * Creates a new AnaglyphArcRotateCamera
  87450. * @param name defines camera name
  87451. * @param alpha defines alpha angle (in radians)
  87452. * @param beta defines beta angle (in radians)
  87453. * @param radius defines radius
  87454. * @param target defines camera target
  87455. * @param interaxialDistance defines distance between each color axis
  87456. * @param scene defines the hosting scene
  87457. */
  87458. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87459. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87460. _this.interaxialDistance = interaxialDistance;
  87461. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87462. return _this;
  87463. }
  87464. /**
  87465. * Gets camera class name
  87466. * @returns AnaglyphArcRotateCamera
  87467. */
  87468. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87469. return "AnaglyphArcRotateCamera";
  87470. };
  87471. return AnaglyphArcRotateCamera;
  87472. }(BABYLON.ArcRotateCamera));
  87473. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87474. /**
  87475. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87476. */
  87477. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87478. __extends(AnaglyphGamepadCamera, _super);
  87479. /**
  87480. * Creates a new AnaglyphGamepadCamera
  87481. * @param name defines camera name
  87482. * @param position defines initial position
  87483. * @param interaxialDistance defines distance between each color axis
  87484. * @param scene defines the hosting scene
  87485. */
  87486. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87487. var _this = _super.call(this, name, position, scene) || this;
  87488. _this.interaxialDistance = interaxialDistance;
  87489. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87490. return _this;
  87491. }
  87492. /**
  87493. * Gets camera class name
  87494. * @returns AnaglyphGamepadCamera
  87495. */
  87496. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87497. return "AnaglyphGamepadCamera";
  87498. };
  87499. return AnaglyphGamepadCamera;
  87500. }(BABYLON.GamepadCamera));
  87501. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87502. /**
  87503. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87504. */
  87505. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87506. __extends(AnaglyphUniversalCamera, _super);
  87507. /**
  87508. * Creates a new AnaglyphUniversalCamera
  87509. * @param name defines camera name
  87510. * @param position defines initial position
  87511. * @param interaxialDistance defines distance between each color axis
  87512. * @param scene defines the hosting scene
  87513. */
  87514. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87515. var _this = _super.call(this, name, position, scene) || this;
  87516. _this.interaxialDistance = interaxialDistance;
  87517. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87518. return _this;
  87519. }
  87520. /**
  87521. * Gets camera class name
  87522. * @returns AnaglyphUniversalCamera
  87523. */
  87524. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87525. return "AnaglyphUniversalCamera";
  87526. };
  87527. return AnaglyphUniversalCamera;
  87528. }(BABYLON.UniversalCamera));
  87529. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87530. /**
  87531. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87532. */
  87533. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87534. __extends(StereoscopicFreeCamera, _super);
  87535. /**
  87536. * Creates a new StereoscopicFreeCamera
  87537. * @param name defines camera name
  87538. * @param position defines initial position
  87539. * @param interaxialDistance defines distance between each color axis
  87540. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87541. * @param scene defines the hosting scene
  87542. */
  87543. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87544. var _this = _super.call(this, name, position, scene) || this;
  87545. _this.interaxialDistance = interaxialDistance;
  87546. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87547. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87548. return _this;
  87549. }
  87550. /**
  87551. * Gets camera class name
  87552. * @returns StereoscopicFreeCamera
  87553. */
  87554. StereoscopicFreeCamera.prototype.getClassName = function () {
  87555. return "StereoscopicFreeCamera";
  87556. };
  87557. return StereoscopicFreeCamera;
  87558. }(BABYLON.FreeCamera));
  87559. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87560. /**
  87561. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87562. */
  87563. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87564. __extends(StereoscopicArcRotateCamera, _super);
  87565. /**
  87566. * Creates a new StereoscopicArcRotateCamera
  87567. * @param name defines camera name
  87568. * @param alpha defines alpha angle (in radians)
  87569. * @param beta defines beta angle (in radians)
  87570. * @param radius defines radius
  87571. * @param target defines camera target
  87572. * @param interaxialDistance defines distance between each color axis
  87573. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87574. * @param scene defines the hosting scene
  87575. */
  87576. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87577. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87578. _this.interaxialDistance = interaxialDistance;
  87579. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87580. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87581. return _this;
  87582. }
  87583. /**
  87584. * Gets camera class name
  87585. * @returns StereoscopicArcRotateCamera
  87586. */
  87587. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87588. return "StereoscopicArcRotateCamera";
  87589. };
  87590. return StereoscopicArcRotateCamera;
  87591. }(BABYLON.ArcRotateCamera));
  87592. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87593. /**
  87594. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87595. */
  87596. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87597. __extends(StereoscopicGamepadCamera, _super);
  87598. /**
  87599. * Creates a new StereoscopicGamepadCamera
  87600. * @param name defines camera name
  87601. * @param position defines initial position
  87602. * @param interaxialDistance defines distance between each color axis
  87603. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87604. * @param scene defines the hosting scene
  87605. */
  87606. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87607. var _this = _super.call(this, name, position, scene) || this;
  87608. _this.interaxialDistance = interaxialDistance;
  87609. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87610. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87611. return _this;
  87612. }
  87613. /**
  87614. * Gets camera class name
  87615. * @returns StereoscopicGamepadCamera
  87616. */
  87617. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87618. return "StereoscopicGamepadCamera";
  87619. };
  87620. return StereoscopicGamepadCamera;
  87621. }(BABYLON.GamepadCamera));
  87622. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87623. /**
  87624. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87625. */
  87626. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87627. __extends(StereoscopicUniversalCamera, _super);
  87628. /**
  87629. * Creates a new StereoscopicUniversalCamera
  87630. * @param name defines camera name
  87631. * @param position defines initial position
  87632. * @param interaxialDistance defines distance between each color axis
  87633. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87634. * @param scene defines the hosting scene
  87635. */
  87636. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87637. var _this = _super.call(this, name, position, scene) || this;
  87638. _this.interaxialDistance = interaxialDistance;
  87639. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87640. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87641. return _this;
  87642. }
  87643. /**
  87644. * Gets camera class name
  87645. * @returns StereoscopicUniversalCamera
  87646. */
  87647. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87648. return "StereoscopicUniversalCamera";
  87649. };
  87650. return StereoscopicUniversalCamera;
  87651. }(BABYLON.UniversalCamera));
  87652. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87653. })(BABYLON || (BABYLON = {}));
  87654. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87655. var BABYLON;
  87656. (function (BABYLON) {
  87657. var VRExperienceHelperGazer = /** @class */ (function () {
  87658. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87659. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87660. this.scene = scene;
  87661. this._pointerDownOnMeshAsked = false;
  87662. this._isActionableMesh = false;
  87663. this._teleportationRequestInitiated = false;
  87664. this._teleportationBackRequestInitiated = false;
  87665. this._rotationRightAsked = false;
  87666. this._rotationLeftAsked = false;
  87667. this._dpadPressed = true;
  87668. this._activePointer = false;
  87669. this._id = VRExperienceHelperGazer._idCounter++;
  87670. // Gaze tracker
  87671. if (!gazeTrackerToClone) {
  87672. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87673. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87674. this._gazeTracker.isPickable = false;
  87675. this._gazeTracker.isVisible = false;
  87676. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87677. targetMat.specularColor = BABYLON.Color3.Black();
  87678. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87679. targetMat.backFaceCulling = false;
  87680. this._gazeTracker.material = targetMat;
  87681. }
  87682. else {
  87683. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87684. }
  87685. }
  87686. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87687. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87688. };
  87689. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87690. this._pointerDownOnMeshAsked = true;
  87691. if (this._currentMeshSelected && this._currentHit) {
  87692. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87693. }
  87694. };
  87695. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87696. if (this._currentMeshSelected && this._currentHit) {
  87697. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87698. }
  87699. this._pointerDownOnMeshAsked = false;
  87700. };
  87701. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87702. this._activePointer = true;
  87703. };
  87704. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87705. this._activePointer = false;
  87706. };
  87707. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87708. if (distance === void 0) { distance = 100; }
  87709. };
  87710. VRExperienceHelperGazer.prototype.dispose = function () {
  87711. this._interactionsEnabled = false;
  87712. this._teleportationEnabled = false;
  87713. if (this._gazeTracker) {
  87714. this._gazeTracker.dispose();
  87715. }
  87716. };
  87717. VRExperienceHelperGazer._idCounter = 0;
  87718. return VRExperienceHelperGazer;
  87719. }());
  87720. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87721. __extends(VRExperienceHelperControllerGazer, _super);
  87722. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87723. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87724. _this.webVRController = webVRController;
  87725. // Laser pointer
  87726. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87727. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87728. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87729. laserPointerMaterial.alpha = 0.6;
  87730. _this._laserPointer.material = laserPointerMaterial;
  87731. _this._laserPointer.rotation.x = Math.PI / 2;
  87732. _this._laserPointer.position.z = -0.5;
  87733. _this._laserPointer.isVisible = false;
  87734. if (!webVRController.mesh) {
  87735. // Create an empty mesh that is used prior to loading the high quality model
  87736. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87737. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87738. preloadPointerPose.rotation.x = -0.7;
  87739. preloadMesh.addChild(preloadPointerPose);
  87740. webVRController.attachToMesh(preloadMesh);
  87741. }
  87742. _this._setLaserPointerParent(webVRController.mesh);
  87743. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  87744. _this._setLaserPointerParent(mesh);
  87745. });
  87746. return _this;
  87747. }
  87748. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87749. return this.webVRController.getForwardRay(length);
  87750. };
  87751. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87752. _super.prototype._activatePointer.call(this);
  87753. this._laserPointer.isVisible = true;
  87754. };
  87755. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87756. _super.prototype._deactivatePointer.call(this);
  87757. this._laserPointer.isVisible = false;
  87758. };
  87759. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87760. this._laserPointer.material.emissiveColor = color;
  87761. };
  87762. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87763. var makeNotPick = function (root) {
  87764. root.name += " laserPointer";
  87765. root.getChildMeshes().forEach(function (c) {
  87766. makeNotPick(c);
  87767. });
  87768. };
  87769. makeNotPick(mesh);
  87770. var childMeshes = mesh.getChildMeshes();
  87771. this.webVRController._pointingPoseNode = null;
  87772. for (var i = 0; i < childMeshes.length; i++) {
  87773. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87774. mesh = childMeshes[i];
  87775. this.webVRController._pointingPoseNode = mesh;
  87776. break;
  87777. }
  87778. }
  87779. this._laserPointer.parent = mesh;
  87780. };
  87781. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87782. if (distance === void 0) { distance = 100; }
  87783. this._laserPointer.scaling.y = distance;
  87784. this._laserPointer.position.z = -distance / 2;
  87785. };
  87786. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87787. _super.prototype.dispose.call(this);
  87788. this._laserPointer.dispose();
  87789. if (this._meshAttachedObserver) {
  87790. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  87791. }
  87792. };
  87793. return VRExperienceHelperControllerGazer;
  87794. }(VRExperienceHelperGazer));
  87795. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87796. __extends(VRExperienceHelperCameraGazer, _super);
  87797. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87798. var _this = _super.call(this, scene) || this;
  87799. _this.getCamera = getCamera;
  87800. return _this;
  87801. }
  87802. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87803. var camera = this.getCamera();
  87804. if (camera) {
  87805. return camera.getForwardRay(length);
  87806. }
  87807. else {
  87808. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87809. }
  87810. };
  87811. return VRExperienceHelperCameraGazer;
  87812. }(VRExperienceHelperGazer));
  87813. /**
  87814. * Helps to quickly add VR support to an existing scene.
  87815. * See http://doc.babylonjs.com/how_to/webvr_helper
  87816. */
  87817. var VRExperienceHelper = /** @class */ (function () {
  87818. /**
  87819. * Instantiates a VRExperienceHelper.
  87820. * Helps to quickly add VR support to an existing scene.
  87821. * @param scene The scene the VRExperienceHelper belongs to.
  87822. * @param webVROptions Options to modify the vr experience helper's behavior.
  87823. */
  87824. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87825. if (webVROptions === void 0) { webVROptions = {}; }
  87826. var _this = this;
  87827. this.webVROptions = webVROptions;
  87828. // Can the system support WebVR, even if a headset isn't plugged in?
  87829. this._webVRsupported = false;
  87830. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87831. this._webVRready = false;
  87832. // Are we waiting for the requestPresent callback to complete?
  87833. this._webVRrequesting = false;
  87834. // Are we presenting to the headset right now?
  87835. this._webVRpresenting = false;
  87836. // Are we presenting in the fullscreen fallback?
  87837. this._fullscreenVRpresenting = false;
  87838. /**
  87839. * Observable raised when entering VR.
  87840. */
  87841. this.onEnteringVRObservable = new BABYLON.Observable();
  87842. /**
  87843. * Observable raised when exiting VR.
  87844. */
  87845. this.onExitingVRObservable = new BABYLON.Observable();
  87846. /**
  87847. * Observable raised when controller mesh is loaded.
  87848. */
  87849. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87850. this._useCustomVRButton = false;
  87851. this._teleportationRequested = false;
  87852. this._teleportActive = false;
  87853. this._floorMeshesCollection = [];
  87854. this._rotationAllowed = true;
  87855. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87856. this._isDefaultTeleportationTarget = true;
  87857. this._teleportationFillColor = "#444444";
  87858. this._teleportationBorderColor = "#FFFFFF";
  87859. this._rotationAngle = 0;
  87860. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87861. this._padSensibilityUp = 0.65;
  87862. this._padSensibilityDown = 0.35;
  87863. this.leftController = null;
  87864. this.rightController = null;
  87865. /**
  87866. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87867. */
  87868. this.onNewMeshSelected = new BABYLON.Observable();
  87869. /**
  87870. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87871. */
  87872. this.onNewMeshPicked = new BABYLON.Observable();
  87873. /**
  87874. * Observable raised before camera teleportation
  87875. */
  87876. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87877. /**
  87878. * Observable raised after camera teleportation
  87879. */
  87880. this.onAfterCameraTeleport = new BABYLON.Observable();
  87881. /**
  87882. * Observable raised when current selected mesh gets unselected
  87883. */
  87884. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87885. /**
  87886. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87887. */
  87888. this.teleportationEnabled = true;
  87889. this._teleportationInitialized = false;
  87890. this._interactionsEnabled = false;
  87891. this._interactionsRequested = false;
  87892. this._displayGaze = true;
  87893. this._displayLaserPointer = true;
  87894. this._onResize = function () {
  87895. _this.moveButtonToBottomRight();
  87896. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87897. _this.exitVR();
  87898. }
  87899. };
  87900. this._onFullscreenChange = function () {
  87901. if (document.fullscreen !== undefined) {
  87902. _this._fullscreenVRpresenting = document.fullscreen;
  87903. }
  87904. else if (document.mozFullScreen !== undefined) {
  87905. _this._fullscreenVRpresenting = document.mozFullScreen;
  87906. }
  87907. else if (document.webkitIsFullScreen !== undefined) {
  87908. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87909. }
  87910. else if (document.msIsFullScreen !== undefined) {
  87911. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87912. }
  87913. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87914. _this.exitVR();
  87915. if (!_this._useCustomVRButton) {
  87916. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87917. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87918. }
  87919. }
  87920. };
  87921. this.beforeRender = function () {
  87922. if (_this.leftController && _this.leftController._activePointer) {
  87923. _this._castRayAndSelectObject(_this.leftController);
  87924. }
  87925. if (_this.rightController && _this.rightController._activePointer) {
  87926. _this._castRayAndSelectObject(_this.rightController);
  87927. }
  87928. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87929. _this._castRayAndSelectObject(_this._cameraGazer);
  87930. }
  87931. else {
  87932. _this._cameraGazer._gazeTracker.isVisible = false;
  87933. }
  87934. };
  87935. this._onNewGamepadConnected = function (gamepad) {
  87936. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87937. if (gamepad.leftStick) {
  87938. gamepad.onleftstickchanged(function (stickValues) {
  87939. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87940. // Listening to classic/xbox gamepad only if no VR controller is active
  87941. if ((!_this.leftController && !_this.rightController) ||
  87942. ((_this.leftController && !_this.leftController._activePointer) &&
  87943. (_this.rightController && !_this.rightController._activePointer))) {
  87944. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87945. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87946. }
  87947. }
  87948. });
  87949. }
  87950. if (gamepad.rightStick) {
  87951. gamepad.onrightstickchanged(function (stickValues) {
  87952. if (_this._teleportationInitialized) {
  87953. _this._checkRotate(stickValues, _this._cameraGazer);
  87954. }
  87955. });
  87956. }
  87957. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87958. gamepad.onbuttondown(function (buttonPressed) {
  87959. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87960. _this._cameraGazer._selectionPointerDown();
  87961. }
  87962. });
  87963. gamepad.onbuttonup(function (buttonPressed) {
  87964. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87965. _this._cameraGazer._selectionPointerUp();
  87966. }
  87967. });
  87968. }
  87969. }
  87970. else {
  87971. var webVRController = gamepad;
  87972. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87973. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87974. _this.rightController = controller;
  87975. }
  87976. else {
  87977. _this.leftController = controller;
  87978. }
  87979. _this._tryEnableInteractionOnController(controller);
  87980. }
  87981. };
  87982. // 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
  87983. this._tryEnableInteractionOnController = function (controller) {
  87984. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87985. _this._enableInteractionOnController(controller);
  87986. }
  87987. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87988. _this._enableTeleportationOnController(controller);
  87989. }
  87990. };
  87991. this._onNewGamepadDisconnected = function (gamepad) {
  87992. if (gamepad instanceof BABYLON.WebVRController) {
  87993. if (gamepad.hand === "left" && _this.leftController != null) {
  87994. _this.leftController.dispose();
  87995. _this.leftController = null;
  87996. }
  87997. if (gamepad.hand === "right" && _this.rightController != null) {
  87998. _this.rightController.dispose();
  87999. _this.rightController = null;
  88000. }
  88001. }
  88002. };
  88003. this._workingVector = BABYLON.Vector3.Zero();
  88004. this._workingQuaternion = BABYLON.Quaternion.Identity();
  88005. this._workingMatrix = BABYLON.Matrix.Identity();
  88006. this._scene = scene;
  88007. this._canvas = scene.getEngine().getRenderingCanvas();
  88008. // Parse options
  88009. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  88010. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  88011. }
  88012. if (webVROptions.createDeviceOrientationCamera === undefined) {
  88013. webVROptions.createDeviceOrientationCamera = true;
  88014. }
  88015. if (webVROptions.defaultHeight === undefined) {
  88016. webVROptions.defaultHeight = 1.7;
  88017. }
  88018. if (webVROptions.useCustomVRButton) {
  88019. this._useCustomVRButton = true;
  88020. if (webVROptions.customVRButton) {
  88021. this._btnVR = webVROptions.customVRButton;
  88022. }
  88023. }
  88024. if (webVROptions.rayLength) {
  88025. this._rayLength = webVROptions.rayLength;
  88026. }
  88027. this._defaultHeight = webVROptions.defaultHeight;
  88028. if (webVROptions.positionScale) {
  88029. this._rayLength *= webVROptions.positionScale;
  88030. this._defaultHeight *= webVROptions.positionScale;
  88031. }
  88032. // Set position
  88033. if (this._scene.activeCamera) {
  88034. this._position = this._scene.activeCamera.position.clone();
  88035. }
  88036. else {
  88037. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  88038. }
  88039. // Set non-vr camera
  88040. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  88041. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  88042. // Copy data from existing camera
  88043. if (this._scene.activeCamera) {
  88044. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88045. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  88046. // Set rotation from previous camera
  88047. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  88048. var targetCamera = this._scene.activeCamera;
  88049. if (targetCamera.rotationQuaternion) {
  88050. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  88051. }
  88052. else {
  88053. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  88054. }
  88055. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  88056. }
  88057. }
  88058. this._scene.activeCamera = this._deviceOrientationCamera;
  88059. if (this._canvas) {
  88060. this._scene.activeCamera.attachControl(this._canvas);
  88061. }
  88062. }
  88063. else {
  88064. this._existingCamera = this._scene.activeCamera;
  88065. }
  88066. // Create VR cameras
  88067. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88068. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  88069. }
  88070. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  88071. this._webVRCamera.useStandingMatrix();
  88072. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  88073. // Create default button
  88074. if (!this._useCustomVRButton) {
  88075. this._btnVR = document.createElement("BUTTON");
  88076. this._btnVR.className = "babylonVRicon";
  88077. this._btnVR.id = "babylonVRiconbtn";
  88078. this._btnVR.title = "Click to switch to VR";
  88079. 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) }";
  88080. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  88081. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  88082. // css += ".babylonVRicon.vrdisplaysupported { }";
  88083. // css += ".babylonVRicon.vrdisplayready { }";
  88084. // css += ".babylonVRicon.vrdisplayrequesting { }";
  88085. var style = document.createElement('style');
  88086. style.appendChild(document.createTextNode(css));
  88087. document.getElementsByTagName('head')[0].appendChild(style);
  88088. this.moveButtonToBottomRight();
  88089. }
  88090. // VR button click event
  88091. if (this._btnVR) {
  88092. this._btnVR.addEventListener("click", function () {
  88093. if (!_this.isInVRMode) {
  88094. _this.enterVR();
  88095. }
  88096. else {
  88097. _this.exitVR();
  88098. }
  88099. });
  88100. }
  88101. // Window events
  88102. window.addEventListener("resize", this._onResize);
  88103. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  88104. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  88105. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  88106. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  88107. // Display vr button when headset is connected
  88108. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88109. this.displayVRButton();
  88110. }
  88111. else {
  88112. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  88113. if (e.vrDisplay) {
  88114. _this.displayVRButton();
  88115. }
  88116. });
  88117. }
  88118. // Exiting VR mode using 'ESC' key on desktop
  88119. this._onKeyDown = function (event) {
  88120. if (event.keyCode === 27 && _this.isInVRMode) {
  88121. _this.exitVR();
  88122. }
  88123. };
  88124. document.addEventListener("keydown", this._onKeyDown);
  88125. // Exiting VR mode double tapping the touch screen
  88126. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  88127. if (_this.isInVRMode) {
  88128. _this.exitVR();
  88129. if (_this._fullscreenVRpresenting) {
  88130. _this._scene.getEngine().switchFullscreen(true);
  88131. }
  88132. }
  88133. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  88134. // Listen for WebVR display changes
  88135. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  88136. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  88137. this._onVRRequestPresentStart = function () {
  88138. _this._webVRrequesting = true;
  88139. _this.updateButtonVisibility();
  88140. };
  88141. this._onVRRequestPresentComplete = function (success) {
  88142. _this._webVRrequesting = false;
  88143. _this.updateButtonVisibility();
  88144. };
  88145. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  88146. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  88147. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  88148. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88149. scene.onDisposeObservable.add(function () {
  88150. _this.dispose();
  88151. });
  88152. // Gamepad connection events
  88153. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  88154. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  88155. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  88156. this.updateButtonVisibility();
  88157. //create easing functions
  88158. this._circleEase = new BABYLON.CircleEase();
  88159. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88160. }
  88161. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  88162. /** Return this.onEnteringVRObservable
  88163. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  88164. */
  88165. get: function () {
  88166. return this.onEnteringVRObservable;
  88167. },
  88168. enumerable: true,
  88169. configurable: true
  88170. });
  88171. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  88172. /** Return this.onExitingVRObservable
  88173. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  88174. */
  88175. get: function () {
  88176. return this.onExitingVRObservable;
  88177. },
  88178. enumerable: true,
  88179. configurable: true
  88180. });
  88181. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  88182. /** Return this.onControllerMeshLoadedObservable
  88183. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  88184. */
  88185. get: function () {
  88186. return this.onControllerMeshLoadedObservable;
  88187. },
  88188. enumerable: true,
  88189. configurable: true
  88190. });
  88191. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  88192. /**
  88193. * The mesh used to display where the user is going to teleport.
  88194. */
  88195. get: function () {
  88196. return this._teleportationTarget;
  88197. },
  88198. /**
  88199. * Sets the mesh to be used to display where the user is going to teleport.
  88200. */
  88201. set: function (value) {
  88202. if (value) {
  88203. value.name = "teleportationTarget";
  88204. this._isDefaultTeleportationTarget = false;
  88205. this._teleportationTarget = value;
  88206. }
  88207. },
  88208. enumerable: true,
  88209. configurable: true
  88210. });
  88211. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  88212. /**
  88213. * The mesh used to display where the user is selecting,
  88214. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  88215. * See http://doc.babylonjs.com/resources/baking_transformations
  88216. */
  88217. get: function () {
  88218. return this._cameraGazer._gazeTracker;
  88219. },
  88220. set: function (value) {
  88221. if (value) {
  88222. this._cameraGazer._gazeTracker = value;
  88223. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  88224. this._cameraGazer._gazeTracker.isPickable = false;
  88225. this._cameraGazer._gazeTracker.isVisible = false;
  88226. this._cameraGazer._gazeTracker.name = "gazeTracker";
  88227. if (this.leftController) {
  88228. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88229. }
  88230. if (this.rightController) {
  88231. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88232. }
  88233. }
  88234. },
  88235. enumerable: true,
  88236. configurable: true
  88237. });
  88238. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  88239. /**
  88240. * If the ray of the gaze should be displayed.
  88241. */
  88242. get: function () {
  88243. return this._displayGaze;
  88244. },
  88245. /**
  88246. * Sets if the ray of the gaze should be displayed.
  88247. */
  88248. set: function (value) {
  88249. this._displayGaze = value;
  88250. if (!value) {
  88251. this._cameraGazer._gazeTracker.isVisible = false;
  88252. if (this.leftController) {
  88253. this.leftController._gazeTracker.isVisible = false;
  88254. }
  88255. if (this.rightController) {
  88256. this.rightController._gazeTracker.isVisible = false;
  88257. }
  88258. }
  88259. },
  88260. enumerable: true,
  88261. configurable: true
  88262. });
  88263. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  88264. /**
  88265. * If the ray of the LaserPointer should be displayed.
  88266. */
  88267. get: function () {
  88268. return this._displayLaserPointer;
  88269. },
  88270. /**
  88271. * Sets if the ray of the LaserPointer should be displayed.
  88272. */
  88273. set: function (value) {
  88274. this._displayLaserPointer = value;
  88275. if (!value) {
  88276. if (this.rightController) {
  88277. this.rightController._deactivatePointer();
  88278. this.rightController._gazeTracker.isVisible = false;
  88279. }
  88280. if (this.leftController) {
  88281. this.leftController._deactivatePointer();
  88282. this.leftController._gazeTracker.isVisible = false;
  88283. }
  88284. }
  88285. else {
  88286. if (this.rightController) {
  88287. this.rightController._activatePointer();
  88288. }
  88289. if (this.leftController) {
  88290. this.leftController._activatePointer();
  88291. }
  88292. }
  88293. },
  88294. enumerable: true,
  88295. configurable: true
  88296. });
  88297. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  88298. /**
  88299. * The deviceOrientationCamera used as the camera when not in VR.
  88300. */
  88301. get: function () {
  88302. return this._deviceOrientationCamera;
  88303. },
  88304. enumerable: true,
  88305. configurable: true
  88306. });
  88307. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  88308. /**
  88309. * Based on the current WebVR support, returns the current VR camera used.
  88310. */
  88311. get: function () {
  88312. if (this._webVRready) {
  88313. return this._webVRCamera;
  88314. }
  88315. else {
  88316. return this._scene.activeCamera;
  88317. }
  88318. },
  88319. enumerable: true,
  88320. configurable: true
  88321. });
  88322. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88323. /**
  88324. * The webVRCamera which is used when in VR.
  88325. */
  88326. get: function () {
  88327. return this._webVRCamera;
  88328. },
  88329. enumerable: true,
  88330. configurable: true
  88331. });
  88332. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88333. /**
  88334. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88335. */
  88336. get: function () {
  88337. return this._vrDeviceOrientationCamera;
  88338. },
  88339. enumerable: true,
  88340. configurable: true
  88341. });
  88342. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88343. get: function () {
  88344. var result = this._cameraGazer._teleportationRequestInitiated
  88345. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88346. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88347. return result;
  88348. },
  88349. enumerable: true,
  88350. configurable: true
  88351. });
  88352. // Raised when one of the controller has loaded successfully its associated default mesh
  88353. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88354. if (this.leftController && this.leftController.webVRController == webVRController) {
  88355. if (webVRController.mesh) {
  88356. this.leftController._setLaserPointerParent(webVRController.mesh);
  88357. }
  88358. }
  88359. if (this.rightController && this.rightController.webVRController == webVRController) {
  88360. if (webVRController.mesh) {
  88361. this.rightController._setLaserPointerParent(webVRController.mesh);
  88362. }
  88363. }
  88364. try {
  88365. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88366. }
  88367. catch (err) {
  88368. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88369. }
  88370. };
  88371. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88372. /**
  88373. * Gets a value indicating if we are currently in VR mode.
  88374. */
  88375. get: function () {
  88376. return this._webVRpresenting || this._fullscreenVRpresenting;
  88377. },
  88378. enumerable: true,
  88379. configurable: true
  88380. });
  88381. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88382. var vrDisplay = this._scene.getEngine().getVRDevice();
  88383. if (vrDisplay) {
  88384. var wasPresenting = this._webVRpresenting;
  88385. // A VR display is connected
  88386. this._webVRpresenting = vrDisplay.isPresenting;
  88387. if (wasPresenting && !this._webVRpresenting)
  88388. this.exitVR();
  88389. }
  88390. else {
  88391. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88392. }
  88393. this.updateButtonVisibility();
  88394. };
  88395. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88396. this._webVRsupported = eventArgs.vrSupported;
  88397. this._webVRready = !!eventArgs.vrDisplay;
  88398. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88399. this.updateButtonVisibility();
  88400. };
  88401. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88402. if (this._canvas && !this._useCustomVRButton) {
  88403. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88404. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88405. }
  88406. };
  88407. VRExperienceHelper.prototype.displayVRButton = function () {
  88408. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88409. document.body.appendChild(this._btnVR);
  88410. this._btnVRDisplayed = true;
  88411. }
  88412. };
  88413. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88414. if (!this._btnVR || this._useCustomVRButton) {
  88415. return;
  88416. }
  88417. this._btnVR.className = "babylonVRicon";
  88418. if (this.isInVRMode) {
  88419. this._btnVR.className += " vrdisplaypresenting";
  88420. }
  88421. else {
  88422. if (this._webVRready)
  88423. this._btnVR.className += " vrdisplayready";
  88424. if (this._webVRsupported)
  88425. this._btnVR.className += " vrdisplaysupported";
  88426. if (this._webVRrequesting)
  88427. this._btnVR.className += " vrdisplayrequesting";
  88428. }
  88429. };
  88430. /**
  88431. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88432. * Otherwise, will use the fullscreen API.
  88433. */
  88434. VRExperienceHelper.prototype.enterVR = function () {
  88435. if (this.onEnteringVRObservable) {
  88436. try {
  88437. this.onEnteringVRObservable.notifyObservers(this);
  88438. }
  88439. catch (err) {
  88440. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88441. }
  88442. }
  88443. if (this._scene.activeCamera) {
  88444. this._position = this._scene.activeCamera.position.clone();
  88445. // make sure that we return to the last active camera
  88446. this._existingCamera = this._scene.activeCamera;
  88447. }
  88448. if (this._webVRrequesting)
  88449. return;
  88450. // If WebVR is supported and a headset is connected
  88451. if (this._webVRready) {
  88452. if (!this._webVRpresenting) {
  88453. this._webVRCamera.position = this._position;
  88454. this._scene.activeCamera = this._webVRCamera;
  88455. }
  88456. }
  88457. else if (this._vrDeviceOrientationCamera) {
  88458. this._vrDeviceOrientationCamera.position = this._position;
  88459. if (this._scene.activeCamera) {
  88460. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88461. }
  88462. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88463. this._scene.getEngine().switchFullscreen(true);
  88464. this.updateButtonVisibility();
  88465. }
  88466. if (this._scene.activeCamera && this._canvas) {
  88467. this._scene.activeCamera.attachControl(this._canvas);
  88468. }
  88469. if (this._interactionsEnabled) {
  88470. this._scene.registerBeforeRender(this.beforeRender);
  88471. }
  88472. };
  88473. /**
  88474. * Attempt to exit VR, or fullscreen.
  88475. */
  88476. VRExperienceHelper.prototype.exitVR = function () {
  88477. if (this.onExitingVRObservable) {
  88478. try {
  88479. this.onExitingVRObservable.notifyObservers(this);
  88480. }
  88481. catch (err) {
  88482. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88483. }
  88484. }
  88485. if (this._webVRpresenting) {
  88486. this._scene.getEngine().disableVR();
  88487. }
  88488. if (this._scene.activeCamera) {
  88489. this._position = this._scene.activeCamera.position.clone();
  88490. }
  88491. if (this._deviceOrientationCamera) {
  88492. this._deviceOrientationCamera.position = this._position;
  88493. this._scene.activeCamera = this._deviceOrientationCamera;
  88494. if (this._canvas) {
  88495. this._scene.activeCamera.attachControl(this._canvas);
  88496. }
  88497. }
  88498. else if (this._existingCamera) {
  88499. this._existingCamera.position = this._position;
  88500. this._scene.activeCamera = this._existingCamera;
  88501. }
  88502. this.updateButtonVisibility();
  88503. if (this._interactionsEnabled) {
  88504. this._scene.unregisterBeforeRender(this.beforeRender);
  88505. }
  88506. // resize to update width and height when exiting vr exits fullscreen
  88507. this._scene.getEngine().resize();
  88508. };
  88509. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88510. /**
  88511. * The position of the vr experience helper.
  88512. */
  88513. get: function () {
  88514. return this._position;
  88515. },
  88516. /**
  88517. * Sets the position of the vr experience helper.
  88518. */
  88519. set: function (value) {
  88520. this._position = value;
  88521. if (this._scene.activeCamera) {
  88522. this._scene.activeCamera.position = value;
  88523. }
  88524. },
  88525. enumerable: true,
  88526. configurable: true
  88527. });
  88528. /**
  88529. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88530. */
  88531. VRExperienceHelper.prototype.enableInteractions = function () {
  88532. var _this = this;
  88533. if (!this._interactionsEnabled) {
  88534. this._interactionsRequested = true;
  88535. if (this.leftController) {
  88536. this._enableInteractionOnController(this.leftController);
  88537. }
  88538. if (this.rightController) {
  88539. this._enableInteractionOnController(this.rightController);
  88540. }
  88541. this.raySelectionPredicate = function (mesh) {
  88542. return mesh.isVisible;
  88543. };
  88544. this.meshSelectionPredicate = function (mesh) {
  88545. return true;
  88546. };
  88547. this._raySelectionPredicate = function (mesh) {
  88548. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88549. && mesh.name.indexOf("teleportationTarget") === -1
  88550. && mesh.name.indexOf("torusTeleportation") === -1
  88551. && mesh.name.indexOf("laserPointer") === -1)) {
  88552. return _this.raySelectionPredicate(mesh);
  88553. }
  88554. return false;
  88555. };
  88556. this._interactionsEnabled = true;
  88557. }
  88558. };
  88559. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88560. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88561. if (this._floorMeshesCollection[i].id === mesh.id) {
  88562. return true;
  88563. }
  88564. }
  88565. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88566. return true;
  88567. }
  88568. return false;
  88569. };
  88570. /**
  88571. * Adds a floor mesh to be used for teleportation.
  88572. * @param floorMesh the mesh to be used for teleportation.
  88573. */
  88574. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88575. if (!this._floorMeshesCollection) {
  88576. return;
  88577. }
  88578. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88579. return;
  88580. }
  88581. this._floorMeshesCollection.push(floorMesh);
  88582. };
  88583. /**
  88584. * Removes a floor mesh from being used for teleportation.
  88585. * @param floorMesh the mesh to be removed.
  88586. */
  88587. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88588. if (!this._floorMeshesCollection) {
  88589. return;
  88590. }
  88591. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88592. if (meshIndex !== -1) {
  88593. this._floorMeshesCollection.splice(meshIndex, 1);
  88594. }
  88595. };
  88596. /**
  88597. * Enables interactions and teleportation using the VR controllers and gaze.
  88598. * @param vrTeleportationOptions options to modify teleportation behavior.
  88599. */
  88600. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88601. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88602. if (!this._teleportationInitialized) {
  88603. this._teleportationRequested = true;
  88604. this.enableInteractions();
  88605. if (vrTeleportationOptions.floorMeshName) {
  88606. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88607. }
  88608. if (vrTeleportationOptions.floorMeshes) {
  88609. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88610. }
  88611. if (this.leftController != null) {
  88612. this._enableTeleportationOnController(this.leftController);
  88613. }
  88614. if (this.rightController != null) {
  88615. this._enableTeleportationOnController(this.rightController);
  88616. }
  88617. // Creates an image processing post process for the vignette not relying
  88618. // on the main scene configuration for image processing to reduce setup and spaces
  88619. // (gamma/linear) conflicts.
  88620. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88621. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88622. imageProcessingConfiguration.vignetteEnabled = true;
  88623. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88624. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88625. this._teleportationInitialized = true;
  88626. if (this._isDefaultTeleportationTarget) {
  88627. this._createTeleportationCircles();
  88628. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88629. }
  88630. }
  88631. };
  88632. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88633. var _this = this;
  88634. var controllerMesh = controller.webVRController.mesh;
  88635. if (controllerMesh) {
  88636. controller._interactionsEnabled = true;
  88637. controller._activatePointer();
  88638. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88639. // Enabling / disabling laserPointer
  88640. if (_this._displayLaserPointer && stateObject.value === 1) {
  88641. if (controller._activePointer) {
  88642. controller._deactivatePointer();
  88643. }
  88644. else {
  88645. controller._activatePointer();
  88646. }
  88647. if (_this.displayGaze) {
  88648. controller._gazeTracker.isVisible = controller._activePointer;
  88649. }
  88650. }
  88651. });
  88652. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88653. if (!controller._pointerDownOnMeshAsked) {
  88654. if (stateObject.value > _this._padSensibilityUp) {
  88655. controller._selectionPointerDown();
  88656. }
  88657. }
  88658. else if (stateObject.value < _this._padSensibilityDown) {
  88659. controller._selectionPointerUp();
  88660. }
  88661. });
  88662. }
  88663. };
  88664. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88665. // Dont teleport if another gaze already requested teleportation
  88666. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88667. return;
  88668. }
  88669. if (!gazer._teleportationRequestInitiated) {
  88670. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88671. gazer._activatePointer();
  88672. gazer._teleportationRequestInitiated = true;
  88673. }
  88674. }
  88675. else {
  88676. // Listening to the proper controller values changes to confirm teleportation
  88677. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88678. if (this._teleportActive) {
  88679. this._teleportCamera(this._haloCenter);
  88680. }
  88681. gazer._teleportationRequestInitiated = false;
  88682. }
  88683. }
  88684. };
  88685. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88686. // Only rotate when user is not currently selecting a teleportation location
  88687. if (gazer._teleportationRequestInitiated) {
  88688. return;
  88689. }
  88690. if (!gazer._rotationLeftAsked) {
  88691. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88692. gazer._rotationLeftAsked = true;
  88693. if (this._rotationAllowed) {
  88694. this._rotateCamera(false);
  88695. }
  88696. }
  88697. }
  88698. else {
  88699. if (stateObject.x > -this._padSensibilityDown) {
  88700. gazer._rotationLeftAsked = false;
  88701. }
  88702. }
  88703. if (!gazer._rotationRightAsked) {
  88704. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88705. gazer._rotationRightAsked = true;
  88706. if (this._rotationAllowed) {
  88707. this._rotateCamera(true);
  88708. }
  88709. }
  88710. }
  88711. else {
  88712. if (stateObject.x < this._padSensibilityDown) {
  88713. gazer._rotationRightAsked = false;
  88714. }
  88715. }
  88716. };
  88717. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88718. // Only teleport backwards when user is not currently selecting a teleportation location
  88719. if (gazer._teleportationRequestInitiated) {
  88720. return;
  88721. }
  88722. // Teleport backwards
  88723. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88724. if (!gazer._teleportationBackRequestInitiated) {
  88725. if (!this.currentVRCamera) {
  88726. return;
  88727. }
  88728. // Get rotation and position of the current camera
  88729. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88730. var position = this.currentVRCamera.position;
  88731. // If the camera has device position, use that instead
  88732. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88733. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88734. position = this.currentVRCamera.devicePosition;
  88735. }
  88736. // Get matrix with only the y rotation of the device rotation
  88737. rotation.toEulerAnglesToRef(this._workingVector);
  88738. this._workingVector.z = 0;
  88739. this._workingVector.x = 0;
  88740. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88741. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88742. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88743. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88744. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88745. var ray = new BABYLON.Ray(position, this._workingVector);
  88746. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88747. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88748. this._teleportCamera(hit.pickedPoint);
  88749. }
  88750. gazer._teleportationBackRequestInitiated = true;
  88751. }
  88752. }
  88753. else {
  88754. gazer._teleportationBackRequestInitiated = false;
  88755. }
  88756. };
  88757. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88758. var _this = this;
  88759. var controllerMesh = controller.webVRController.mesh;
  88760. if (controllerMesh) {
  88761. if (!controller._interactionsEnabled) {
  88762. this._enableInteractionOnController(controller);
  88763. }
  88764. controller._interactionsEnabled = true;
  88765. controller._teleportationEnabled = true;
  88766. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88767. controller._dpadPressed = false;
  88768. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88769. controller._dpadPressed = stateObject.pressed;
  88770. if (!controller._dpadPressed) {
  88771. controller._rotationLeftAsked = false;
  88772. controller._rotationRightAsked = false;
  88773. controller._teleportationBackRequestInitiated = false;
  88774. }
  88775. });
  88776. }
  88777. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88778. if (_this.teleportationEnabled) {
  88779. _this._checkTeleportBackwards(stateObject, controller);
  88780. _this._checkTeleportWithRay(stateObject, controller);
  88781. }
  88782. _this._checkRotate(stateObject, controller);
  88783. });
  88784. }
  88785. };
  88786. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88787. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88788. this._teleportationTarget.isPickable = false;
  88789. var length = 512;
  88790. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88791. dynamicTexture.hasAlpha = true;
  88792. var context = dynamicTexture.getContext();
  88793. var centerX = length / 2;
  88794. var centerY = length / 2;
  88795. var radius = 200;
  88796. context.beginPath();
  88797. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88798. context.fillStyle = this._teleportationFillColor;
  88799. context.fill();
  88800. context.lineWidth = 10;
  88801. context.strokeStyle = this._teleportationBorderColor;
  88802. context.stroke();
  88803. context.closePath();
  88804. dynamicTexture.update();
  88805. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88806. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88807. this._teleportationTarget.material = teleportationCircleMaterial;
  88808. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88809. torus.isPickable = false;
  88810. torus.parent = this._teleportationTarget;
  88811. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88812. var keys = [];
  88813. keys.push({
  88814. frame: 0,
  88815. value: 0
  88816. });
  88817. keys.push({
  88818. frame: 30,
  88819. value: 0.4
  88820. });
  88821. keys.push({
  88822. frame: 60,
  88823. value: 0
  88824. });
  88825. animationInnerCircle.setKeys(keys);
  88826. var easingFunction = new BABYLON.SineEase();
  88827. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88828. animationInnerCircle.setEasingFunction(easingFunction);
  88829. torus.animations = [];
  88830. torus.animations.push(animationInnerCircle);
  88831. this._scene.beginAnimation(torus, 0, 60, true);
  88832. this._hideTeleportationTarget();
  88833. };
  88834. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88835. this._teleportActive = true;
  88836. if (this._teleportationInitialized) {
  88837. this._teleportationTarget.isVisible = true;
  88838. if (this._isDefaultTeleportationTarget) {
  88839. this._teleportationTarget.getChildren()[0].isVisible = true;
  88840. }
  88841. }
  88842. };
  88843. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88844. this._teleportActive = false;
  88845. if (this._teleportationInitialized) {
  88846. this._teleportationTarget.isVisible = false;
  88847. if (this._isDefaultTeleportationTarget) {
  88848. this._teleportationTarget.getChildren()[0].isVisible = false;
  88849. }
  88850. }
  88851. };
  88852. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88853. var _this = this;
  88854. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88855. return;
  88856. }
  88857. if (right) {
  88858. this._rotationAngle++;
  88859. }
  88860. else {
  88861. this._rotationAngle--;
  88862. }
  88863. this.currentVRCamera.animations = [];
  88864. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88865. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88866. var animationRotationKeys = [];
  88867. animationRotationKeys.push({
  88868. frame: 0,
  88869. value: this.currentVRCamera.rotationQuaternion
  88870. });
  88871. animationRotationKeys.push({
  88872. frame: 6,
  88873. value: target
  88874. });
  88875. animationRotation.setKeys(animationRotationKeys);
  88876. animationRotation.setEasingFunction(this._circleEase);
  88877. this.currentVRCamera.animations.push(animationRotation);
  88878. this._postProcessMove.animations = [];
  88879. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88880. var vignetteWeightKeys = [];
  88881. vignetteWeightKeys.push({
  88882. frame: 0,
  88883. value: 0
  88884. });
  88885. vignetteWeightKeys.push({
  88886. frame: 3,
  88887. value: 4
  88888. });
  88889. vignetteWeightKeys.push({
  88890. frame: 6,
  88891. value: 0
  88892. });
  88893. animationPP.setKeys(vignetteWeightKeys);
  88894. animationPP.setEasingFunction(this._circleEase);
  88895. this._postProcessMove.animations.push(animationPP);
  88896. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88897. var vignetteStretchKeys = [];
  88898. vignetteStretchKeys.push({
  88899. frame: 0,
  88900. value: 0
  88901. });
  88902. vignetteStretchKeys.push({
  88903. frame: 3,
  88904. value: 10
  88905. });
  88906. vignetteStretchKeys.push({
  88907. frame: 6,
  88908. value: 0
  88909. });
  88910. animationPP2.setKeys(vignetteStretchKeys);
  88911. animationPP2.setEasingFunction(this._circleEase);
  88912. this._postProcessMove.animations.push(animationPP2);
  88913. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88914. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88915. this._postProcessMove.samples = 4;
  88916. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88917. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88918. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88919. });
  88920. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88921. };
  88922. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  88923. if (hit.pickedPoint) {
  88924. if (gazer._teleportationRequestInitiated) {
  88925. this._displayTeleportationTarget();
  88926. this._haloCenter.copyFrom(hit.pickedPoint);
  88927. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88928. }
  88929. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  88930. if (pickNormal) {
  88931. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88932. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88933. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88934. }
  88935. this._teleportationTarget.position.y += 0.1;
  88936. }
  88937. };
  88938. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88939. var _this = this;
  88940. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88941. return;
  88942. }
  88943. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88944. // offset of the headset from the anchor.
  88945. if (this.webVRCamera.leftCamera) {
  88946. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88947. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88948. location.subtractToRef(this._workingVector, this._workingVector);
  88949. }
  88950. else {
  88951. this._workingVector.copyFrom(location);
  88952. }
  88953. // Add height to account for user's height offset
  88954. if (this.isInVRMode) {
  88955. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88956. }
  88957. else {
  88958. this._workingVector.y += this._defaultHeight;
  88959. }
  88960. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88961. // Create animation from the camera's position to the new location
  88962. this.currentVRCamera.animations = [];
  88963. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88964. var animationCameraTeleportationKeys = [{
  88965. frame: 0,
  88966. value: this.currentVRCamera.position
  88967. },
  88968. {
  88969. frame: 11,
  88970. value: this._workingVector
  88971. }
  88972. ];
  88973. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88974. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88975. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88976. this._postProcessMove.animations = [];
  88977. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88978. var vignetteWeightKeys = [];
  88979. vignetteWeightKeys.push({
  88980. frame: 0,
  88981. value: 0
  88982. });
  88983. vignetteWeightKeys.push({
  88984. frame: 5,
  88985. value: 8
  88986. });
  88987. vignetteWeightKeys.push({
  88988. frame: 11,
  88989. value: 0
  88990. });
  88991. animationPP.setKeys(vignetteWeightKeys);
  88992. this._postProcessMove.animations.push(animationPP);
  88993. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88994. var vignetteStretchKeys = [];
  88995. vignetteStretchKeys.push({
  88996. frame: 0,
  88997. value: 0
  88998. });
  88999. vignetteStretchKeys.push({
  89000. frame: 5,
  89001. value: 10
  89002. });
  89003. vignetteStretchKeys.push({
  89004. frame: 11,
  89005. value: 0
  89006. });
  89007. animationPP2.setKeys(vignetteStretchKeys);
  89008. this._postProcessMove.animations.push(animationPP2);
  89009. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  89010. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  89011. this._webVRCamera.attachPostProcess(this._postProcessMove);
  89012. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  89013. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  89014. });
  89015. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  89016. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  89017. });
  89018. this._hideTeleportationTarget();
  89019. };
  89020. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  89021. if (normal) {
  89022. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  89023. if (angle < Math.PI / 2) {
  89024. normal.scaleInPlace(-1);
  89025. }
  89026. }
  89027. return normal;
  89028. };
  89029. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  89030. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89031. return;
  89032. }
  89033. var ray = gazer._getForwardRay(this._rayLength);
  89034. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  89035. // Moving the gazeTracker on the mesh face targetted
  89036. if (hit && hit.pickedPoint) {
  89037. if (this._displayGaze) {
  89038. var multiplier = 1;
  89039. gazer._gazeTracker.isVisible = true;
  89040. if (gazer._isActionableMesh) {
  89041. multiplier = 3;
  89042. }
  89043. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  89044. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  89045. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  89046. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  89047. // To avoid z-fighting
  89048. var deltaFighting = 0.002;
  89049. if (pickNormal) {
  89050. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  89051. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  89052. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  89053. }
  89054. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  89055. if (gazer._gazeTracker.position.x < 0) {
  89056. gazer._gazeTracker.position.x += deltaFighting;
  89057. }
  89058. else {
  89059. gazer._gazeTracker.position.x -= deltaFighting;
  89060. }
  89061. if (gazer._gazeTracker.position.y < 0) {
  89062. gazer._gazeTracker.position.y += deltaFighting;
  89063. }
  89064. else {
  89065. gazer._gazeTracker.position.y -= deltaFighting;
  89066. }
  89067. if (gazer._gazeTracker.position.z < 0) {
  89068. gazer._gazeTracker.position.z += deltaFighting;
  89069. }
  89070. else {
  89071. gazer._gazeTracker.position.z -= deltaFighting;
  89072. }
  89073. }
  89074. // Changing the size of the laser pointer based on the distance from the targetted point
  89075. gazer._updatePointerDistance(hit.distance);
  89076. }
  89077. else {
  89078. gazer._updatePointerDistance();
  89079. gazer._gazeTracker.isVisible = false;
  89080. }
  89081. if (hit && hit.pickedMesh) {
  89082. gazer._currentHit = hit;
  89083. if (gazer._pointerDownOnMeshAsked) {
  89084. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  89085. }
  89086. // The object selected is the floor, we're in a teleportation scenario
  89087. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  89088. // Moving the teleportation area to this targetted point
  89089. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  89090. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  89091. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89092. }
  89093. gazer._currentMeshSelected = null;
  89094. if (gazer._teleportationRequestInitiated) {
  89095. this._moveTeleportationSelectorTo(hit, gazer, ray);
  89096. }
  89097. return;
  89098. }
  89099. // If not, we're in a selection scenario
  89100. //this._teleportationAllowed = false;
  89101. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  89102. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  89103. this.onNewMeshPicked.notifyObservers(hit);
  89104. gazer._currentMeshSelected = hit.pickedMesh;
  89105. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  89106. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  89107. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  89108. gazer._isActionableMesh = true;
  89109. }
  89110. else {
  89111. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89112. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89113. gazer._isActionableMesh = false;
  89114. }
  89115. try {
  89116. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  89117. }
  89118. catch (err) {
  89119. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  89120. }
  89121. }
  89122. else {
  89123. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89124. gazer._currentMeshSelected = null;
  89125. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89126. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89127. }
  89128. }
  89129. }
  89130. else {
  89131. gazer._currentHit = null;
  89132. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89133. gazer._currentMeshSelected = null;
  89134. //this._teleportationAllowed = false;
  89135. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89136. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89137. }
  89138. };
  89139. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  89140. if (mesh) {
  89141. this.onSelectedMeshUnselected.notifyObservers(mesh);
  89142. }
  89143. };
  89144. /**
  89145. * Sets the color of the laser ray from the vr controllers.
  89146. * @param color new color for the ray.
  89147. */
  89148. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  89149. if (this.leftController) {
  89150. this.leftController._setLaserPointerColor(color);
  89151. }
  89152. if (this.rightController) {
  89153. this.rightController._setLaserPointerColor(color);
  89154. }
  89155. };
  89156. /**
  89157. * Sets the color of the ray from the vr headsets gaze.
  89158. * @param color new color for the ray.
  89159. */
  89160. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  89161. if (!this._cameraGazer._gazeTracker.material) {
  89162. return;
  89163. }
  89164. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  89165. if (this.leftController) {
  89166. this.leftController._gazeTracker.material.emissiveColor = color;
  89167. }
  89168. if (this.rightController) {
  89169. this.rightController._gazeTracker.material.emissiveColor = color;
  89170. }
  89171. };
  89172. /**
  89173. * Exits VR and disposes of the vr experience helper
  89174. */
  89175. VRExperienceHelper.prototype.dispose = function () {
  89176. if (this.isInVRMode) {
  89177. this.exitVR();
  89178. }
  89179. if (this._postProcessMove) {
  89180. this._postProcessMove.dispose();
  89181. }
  89182. if (this._webVRCamera) {
  89183. this._webVRCamera.dispose();
  89184. }
  89185. if (this._vrDeviceOrientationCamera) {
  89186. this._vrDeviceOrientationCamera.dispose();
  89187. }
  89188. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  89189. document.body.removeChild(this._btnVR);
  89190. }
  89191. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  89192. this._deviceOrientationCamera.dispose();
  89193. }
  89194. if (this._cameraGazer) {
  89195. this._cameraGazer.dispose();
  89196. }
  89197. if (this.leftController) {
  89198. this.leftController.dispose();
  89199. }
  89200. if (this.rightController) {
  89201. this.rightController.dispose();
  89202. }
  89203. if (this._teleportationTarget) {
  89204. this._teleportationTarget.dispose();
  89205. }
  89206. this._floorMeshesCollection = [];
  89207. document.removeEventListener("keydown", this._onKeyDown);
  89208. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89209. window.removeEventListener("resize", this._onResize);
  89210. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  89211. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  89212. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  89213. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  89214. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  89215. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  89216. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  89217. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89218. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  89219. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  89220. this._scene.unregisterBeforeRender(this.beforeRender);
  89221. };
  89222. /**
  89223. * Gets the name of the VRExperienceHelper class
  89224. * @returns "VRExperienceHelper"
  89225. */
  89226. VRExperienceHelper.prototype.getClassName = function () {
  89227. return "VRExperienceHelper";
  89228. };
  89229. return VRExperienceHelper;
  89230. }());
  89231. BABYLON.VRExperienceHelper = VRExperienceHelper;
  89232. })(BABYLON || (BABYLON = {}));
  89233. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  89234. // Mainly based on these 2 articles :
  89235. // 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
  89236. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  89237. var BABYLON;
  89238. (function (BABYLON) {
  89239. /**
  89240. * Defines the potential axis of a Joystick
  89241. */
  89242. var JoystickAxis;
  89243. (function (JoystickAxis) {
  89244. /** X axis */
  89245. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  89246. /** Y axis */
  89247. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  89248. /** Z axis */
  89249. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  89250. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  89251. /**
  89252. * Class used to define virtual joystick (used in touch mode)
  89253. */
  89254. var VirtualJoystick = /** @class */ (function () {
  89255. /**
  89256. * Creates a new virtual joystick
  89257. * @param leftJoystick defines that the joystick is for left hand (false by default)
  89258. */
  89259. function VirtualJoystick(leftJoystick) {
  89260. var _this = this;
  89261. if (leftJoystick) {
  89262. this._leftJoystick = true;
  89263. }
  89264. else {
  89265. this._leftJoystick = false;
  89266. }
  89267. VirtualJoystick._globalJoystickIndex++;
  89268. // By default left & right arrow keys are moving the X
  89269. // and up & down keys are moving the Y
  89270. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89271. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89272. this.reverseLeftRight = false;
  89273. this.reverseUpDown = false;
  89274. // collections of pointers
  89275. this._touches = new BABYLON.StringDictionary();
  89276. this.deltaPosition = BABYLON.Vector3.Zero();
  89277. this._joystickSensibility = 25;
  89278. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89279. this._onResize = function (evt) {
  89280. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89281. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89282. if (VirtualJoystick.vjCanvas) {
  89283. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  89284. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  89285. }
  89286. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  89287. };
  89288. // injecting a canvas element on top of the canvas 3D game
  89289. if (!VirtualJoystick.vjCanvas) {
  89290. window.addEventListener("resize", this._onResize, false);
  89291. VirtualJoystick.vjCanvas = document.createElement("canvas");
  89292. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89293. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89294. VirtualJoystick.vjCanvas.width = window.innerWidth;
  89295. VirtualJoystick.vjCanvas.height = window.innerHeight;
  89296. VirtualJoystick.vjCanvas.style.width = "100%";
  89297. VirtualJoystick.vjCanvas.style.height = "100%";
  89298. VirtualJoystick.vjCanvas.style.position = "absolute";
  89299. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  89300. VirtualJoystick.vjCanvas.style.top = "0px";
  89301. VirtualJoystick.vjCanvas.style.left = "0px";
  89302. VirtualJoystick.vjCanvas.style.zIndex = "5";
  89303. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  89304. // Support for jQuery PEP polyfill
  89305. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  89306. var context = VirtualJoystick.vjCanvas.getContext('2d');
  89307. if (!context) {
  89308. throw new Error("Unable to create canvas for virtual joystick");
  89309. }
  89310. VirtualJoystick.vjCanvasContext = context;
  89311. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  89312. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89313. document.body.appendChild(VirtualJoystick.vjCanvas);
  89314. }
  89315. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  89316. this.pressed = false;
  89317. // default joystick color
  89318. this._joystickColor = "cyan";
  89319. this._joystickPointerID = -1;
  89320. // current joystick position
  89321. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89322. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89323. // origin joystick position
  89324. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89325. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89326. this._onPointerDownHandlerRef = function (evt) {
  89327. _this._onPointerDown(evt);
  89328. };
  89329. this._onPointerMoveHandlerRef = function (evt) {
  89330. _this._onPointerMove(evt);
  89331. };
  89332. this._onPointerUpHandlerRef = function (evt) {
  89333. _this._onPointerUp(evt);
  89334. };
  89335. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89336. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89337. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89338. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89339. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89340. evt.preventDefault(); // Disables system menu
  89341. }, false);
  89342. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89343. }
  89344. /**
  89345. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89346. * @param newJoystickSensibility defines the new sensibility
  89347. */
  89348. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89349. this._joystickSensibility = newJoystickSensibility;
  89350. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89351. };
  89352. VirtualJoystick.prototype._onPointerDown = function (e) {
  89353. var positionOnScreenCondition;
  89354. e.preventDefault();
  89355. if (this._leftJoystick === true) {
  89356. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89357. }
  89358. else {
  89359. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89360. }
  89361. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89362. // First contact will be dedicated to the virtual joystick
  89363. this._joystickPointerID = e.pointerId;
  89364. this._joystickPointerStartPos.x = e.clientX;
  89365. this._joystickPointerStartPos.y = e.clientY;
  89366. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89367. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89368. this._deltaJoystickVector.x = 0;
  89369. this._deltaJoystickVector.y = 0;
  89370. this.pressed = true;
  89371. this._touches.add(e.pointerId.toString(), e);
  89372. }
  89373. else {
  89374. // You can only trigger the action buttons with a joystick declared
  89375. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89376. this._action();
  89377. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89378. }
  89379. }
  89380. };
  89381. VirtualJoystick.prototype._onPointerMove = function (e) {
  89382. // If the current pointer is the one associated to the joystick (first touch contact)
  89383. if (this._joystickPointerID == e.pointerId) {
  89384. this._joystickPointerPos.x = e.clientX;
  89385. this._joystickPointerPos.y = e.clientY;
  89386. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89387. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89388. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89389. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89390. switch (this._axisTargetedByLeftAndRight) {
  89391. case JoystickAxis.X:
  89392. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89393. break;
  89394. case JoystickAxis.Y:
  89395. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89396. break;
  89397. case JoystickAxis.Z:
  89398. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89399. break;
  89400. }
  89401. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89402. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89403. switch (this._axisTargetedByUpAndDown) {
  89404. case JoystickAxis.X:
  89405. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89406. break;
  89407. case JoystickAxis.Y:
  89408. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89409. break;
  89410. case JoystickAxis.Z:
  89411. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89412. break;
  89413. }
  89414. }
  89415. else {
  89416. var data = this._touches.get(e.pointerId.toString());
  89417. if (data) {
  89418. data.x = e.clientX;
  89419. data.y = e.clientY;
  89420. }
  89421. }
  89422. };
  89423. VirtualJoystick.prototype._onPointerUp = function (e) {
  89424. if (this._joystickPointerID == e.pointerId) {
  89425. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89426. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89427. this._joystickPointerID = -1;
  89428. this.pressed = false;
  89429. }
  89430. else {
  89431. var touch = this._touches.get(e.pointerId.toString());
  89432. if (touch) {
  89433. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89434. }
  89435. }
  89436. this._deltaJoystickVector.x = 0;
  89437. this._deltaJoystickVector.y = 0;
  89438. this._touches.remove(e.pointerId.toString());
  89439. };
  89440. /**
  89441. * Change the color of the virtual joystick
  89442. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89443. */
  89444. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89445. this._joystickColor = newColor;
  89446. };
  89447. /**
  89448. * Defines a callback to call when the joystick is touched
  89449. * @param action defines the callback
  89450. */
  89451. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89452. this._action = action;
  89453. };
  89454. /**
  89455. * Defines which axis you'd like to control for left & right
  89456. * @param axis defines the axis to use
  89457. */
  89458. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89459. switch (axis) {
  89460. case JoystickAxis.X:
  89461. case JoystickAxis.Y:
  89462. case JoystickAxis.Z:
  89463. this._axisTargetedByLeftAndRight = axis;
  89464. break;
  89465. default:
  89466. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89467. break;
  89468. }
  89469. };
  89470. /**
  89471. * Defines which axis you'd like to control for up & down
  89472. * @param axis defines the axis to use
  89473. */
  89474. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89475. switch (axis) {
  89476. case JoystickAxis.X:
  89477. case JoystickAxis.Y:
  89478. case JoystickAxis.Z:
  89479. this._axisTargetedByUpAndDown = axis;
  89480. break;
  89481. default:
  89482. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89483. break;
  89484. }
  89485. };
  89486. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89487. var _this = this;
  89488. if (this.pressed) {
  89489. this._touches.forEach(function (key, touch) {
  89490. if (touch.pointerId === _this._joystickPointerID) {
  89491. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89492. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89493. VirtualJoystick.vjCanvasContext.beginPath();
  89494. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89495. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89496. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89497. VirtualJoystick.vjCanvasContext.stroke();
  89498. VirtualJoystick.vjCanvasContext.closePath();
  89499. VirtualJoystick.vjCanvasContext.beginPath();
  89500. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89501. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89502. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89503. VirtualJoystick.vjCanvasContext.stroke();
  89504. VirtualJoystick.vjCanvasContext.closePath();
  89505. VirtualJoystick.vjCanvasContext.beginPath();
  89506. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89507. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89508. VirtualJoystick.vjCanvasContext.stroke();
  89509. VirtualJoystick.vjCanvasContext.closePath();
  89510. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89511. }
  89512. else {
  89513. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89514. VirtualJoystick.vjCanvasContext.beginPath();
  89515. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89516. VirtualJoystick.vjCanvasContext.beginPath();
  89517. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89518. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89519. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89520. VirtualJoystick.vjCanvasContext.stroke();
  89521. VirtualJoystick.vjCanvasContext.closePath();
  89522. touch.prevX = touch.x;
  89523. touch.prevY = touch.y;
  89524. }
  89525. ;
  89526. });
  89527. }
  89528. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89529. };
  89530. /**
  89531. * Release internal HTML canvas
  89532. */
  89533. VirtualJoystick.prototype.releaseCanvas = function () {
  89534. if (VirtualJoystick.vjCanvas) {
  89535. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89536. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89537. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89538. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89539. window.removeEventListener("resize", this._onResize);
  89540. document.body.removeChild(VirtualJoystick.vjCanvas);
  89541. VirtualJoystick.vjCanvas = null;
  89542. }
  89543. };
  89544. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89545. VirtualJoystick._globalJoystickIndex = 0;
  89546. return VirtualJoystick;
  89547. }());
  89548. BABYLON.VirtualJoystick = VirtualJoystick;
  89549. })(BABYLON || (BABYLON = {}));
  89550. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89551. var BABYLON;
  89552. (function (BABYLON) {
  89553. // We're mainly based on the logic defined into the FreeCamera code
  89554. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89555. __extends(VirtualJoysticksCamera, _super);
  89556. function VirtualJoysticksCamera(name, position, scene) {
  89557. var _this = _super.call(this, name, position, scene) || this;
  89558. _this.inputs.addVirtualJoystick();
  89559. return _this;
  89560. }
  89561. VirtualJoysticksCamera.prototype.getClassName = function () {
  89562. return "VirtualJoysticksCamera";
  89563. };
  89564. return VirtualJoysticksCamera;
  89565. }(BABYLON.FreeCamera));
  89566. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89567. })(BABYLON || (BABYLON = {}));
  89568. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89569. var BABYLON;
  89570. (function (BABYLON) {
  89571. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89572. function FreeCameraVirtualJoystickInput() {
  89573. }
  89574. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89575. return this._leftjoystick;
  89576. };
  89577. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89578. return this._rightjoystick;
  89579. };
  89580. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89581. if (this._leftjoystick) {
  89582. var camera = this.camera;
  89583. var speed = camera._computeLocalCameraSpeed() * 50;
  89584. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89585. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89586. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89587. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89588. if (!this._leftjoystick.pressed) {
  89589. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89590. }
  89591. if (!this._rightjoystick.pressed) {
  89592. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89593. }
  89594. }
  89595. };
  89596. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89597. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89598. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89599. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89600. this._leftjoystick.setJoystickSensibility(0.15);
  89601. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89602. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89603. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89604. this._rightjoystick.reverseUpDown = true;
  89605. this._rightjoystick.setJoystickSensibility(0.05);
  89606. this._rightjoystick.setJoystickColor("yellow");
  89607. };
  89608. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89609. this._leftjoystick.releaseCanvas();
  89610. this._rightjoystick.releaseCanvas();
  89611. };
  89612. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89613. return "FreeCameraVirtualJoystickInput";
  89614. };
  89615. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89616. return "virtualJoystick";
  89617. };
  89618. return FreeCameraVirtualJoystickInput;
  89619. }());
  89620. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89621. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89622. })(BABYLON || (BABYLON = {}));
  89623. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89624. var BABYLON;
  89625. (function (BABYLON) {
  89626. var SimplificationSettings = /** @class */ (function () {
  89627. function SimplificationSettings(quality, distance, optimizeMesh) {
  89628. this.quality = quality;
  89629. this.distance = distance;
  89630. this.optimizeMesh = optimizeMesh;
  89631. }
  89632. return SimplificationSettings;
  89633. }());
  89634. BABYLON.SimplificationSettings = SimplificationSettings;
  89635. var SimplificationQueue = /** @class */ (function () {
  89636. function SimplificationQueue() {
  89637. this.running = false;
  89638. this._simplificationArray = [];
  89639. }
  89640. SimplificationQueue.prototype.addTask = function (task) {
  89641. this._simplificationArray.push(task);
  89642. };
  89643. SimplificationQueue.prototype.executeNext = function () {
  89644. var task = this._simplificationArray.pop();
  89645. if (task) {
  89646. this.running = true;
  89647. this.runSimplification(task);
  89648. }
  89649. else {
  89650. this.running = false;
  89651. }
  89652. };
  89653. SimplificationQueue.prototype.runSimplification = function (task) {
  89654. var _this = this;
  89655. if (task.parallelProcessing) {
  89656. //parallel simplifier
  89657. task.settings.forEach(function (setting) {
  89658. var simplifier = _this.getSimplifier(task);
  89659. simplifier.simplify(setting, function (newMesh) {
  89660. task.mesh.addLODLevel(setting.distance, newMesh);
  89661. newMesh.isVisible = true;
  89662. //check if it is the last
  89663. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89664. //all done, run the success callback.
  89665. task.successCallback();
  89666. }
  89667. _this.executeNext();
  89668. });
  89669. });
  89670. }
  89671. else {
  89672. //single simplifier.
  89673. var simplifier = this.getSimplifier(task);
  89674. var runDecimation = function (setting, callback) {
  89675. simplifier.simplify(setting, function (newMesh) {
  89676. task.mesh.addLODLevel(setting.distance, newMesh);
  89677. newMesh.isVisible = true;
  89678. //run the next quality level
  89679. callback();
  89680. });
  89681. };
  89682. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89683. runDecimation(task.settings[loop.index], function () {
  89684. loop.executeNext();
  89685. });
  89686. }, function () {
  89687. //execution ended, run the success callback.
  89688. if (task.successCallback) {
  89689. task.successCallback();
  89690. }
  89691. _this.executeNext();
  89692. });
  89693. }
  89694. };
  89695. SimplificationQueue.prototype.getSimplifier = function (task) {
  89696. switch (task.simplificationType) {
  89697. case SimplificationType.QUADRATIC:
  89698. default:
  89699. return new QuadraticErrorSimplification(task.mesh);
  89700. }
  89701. };
  89702. return SimplificationQueue;
  89703. }());
  89704. BABYLON.SimplificationQueue = SimplificationQueue;
  89705. /**
  89706. * The implemented types of simplification
  89707. * At the moment only Quadratic Error Decimation is implemented
  89708. */
  89709. var SimplificationType;
  89710. (function (SimplificationType) {
  89711. /** Quadratic error decimation */
  89712. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89713. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89714. var DecimationTriangle = /** @class */ (function () {
  89715. function DecimationTriangle(vertices) {
  89716. this.vertices = vertices;
  89717. this.error = new Array(4);
  89718. this.deleted = false;
  89719. this.isDirty = false;
  89720. this.deletePending = false;
  89721. this.borderFactor = 0;
  89722. }
  89723. return DecimationTriangle;
  89724. }());
  89725. BABYLON.DecimationTriangle = DecimationTriangle;
  89726. var DecimationVertex = /** @class */ (function () {
  89727. function DecimationVertex(position, id) {
  89728. this.position = position;
  89729. this.id = id;
  89730. this.isBorder = true;
  89731. this.q = new QuadraticMatrix();
  89732. this.triangleCount = 0;
  89733. this.triangleStart = 0;
  89734. this.originalOffsets = [];
  89735. }
  89736. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89737. this.position.copyFrom(newPosition);
  89738. };
  89739. return DecimationVertex;
  89740. }());
  89741. BABYLON.DecimationVertex = DecimationVertex;
  89742. var QuadraticMatrix = /** @class */ (function () {
  89743. function QuadraticMatrix(data) {
  89744. this.data = new Array(10);
  89745. for (var i = 0; i < 10; ++i) {
  89746. if (data && data[i]) {
  89747. this.data[i] = data[i];
  89748. }
  89749. else {
  89750. this.data[i] = 0;
  89751. }
  89752. }
  89753. }
  89754. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89755. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89756. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89757. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89758. return det;
  89759. };
  89760. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89761. for (var i = 0; i < 10; ++i) {
  89762. this.data[i] += matrix.data[i];
  89763. }
  89764. };
  89765. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89766. for (var i = 0; i < 10; ++i) {
  89767. this.data[i] += data[i];
  89768. }
  89769. };
  89770. QuadraticMatrix.prototype.add = function (matrix) {
  89771. var m = new QuadraticMatrix();
  89772. for (var i = 0; i < 10; ++i) {
  89773. m.data[i] = this.data[i] + matrix.data[i];
  89774. }
  89775. return m;
  89776. };
  89777. QuadraticMatrix.FromData = function (a, b, c, d) {
  89778. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89779. };
  89780. //returning an array to avoid garbage collection
  89781. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89782. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89783. };
  89784. return QuadraticMatrix;
  89785. }());
  89786. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89787. var Reference = /** @class */ (function () {
  89788. function Reference(vertexId, triangleId) {
  89789. this.vertexId = vertexId;
  89790. this.triangleId = triangleId;
  89791. }
  89792. return Reference;
  89793. }());
  89794. BABYLON.Reference = Reference;
  89795. /**
  89796. * An implementation of the Quadratic Error simplification algorithm.
  89797. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89798. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89799. * @author RaananW
  89800. */
  89801. var QuadraticErrorSimplification = /** @class */ (function () {
  89802. function QuadraticErrorSimplification(_mesh) {
  89803. this._mesh = _mesh;
  89804. this.syncIterations = 5000;
  89805. this.aggressiveness = 7;
  89806. this.decimationIterations = 100;
  89807. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89808. }
  89809. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89810. var _this = this;
  89811. this.initDecimatedMesh();
  89812. //iterating through the submeshes array, one after the other.
  89813. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89814. _this.initWithMesh(loop.index, function () {
  89815. _this.runDecimation(settings, loop.index, function () {
  89816. loop.executeNext();
  89817. });
  89818. }, settings.optimizeMesh);
  89819. }, function () {
  89820. setTimeout(function () {
  89821. successCallback(_this._reconstructedMesh);
  89822. }, 0);
  89823. });
  89824. };
  89825. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89826. var _this = this;
  89827. var targetCount = ~~(this.triangles.length * settings.quality);
  89828. var deletedTriangles = 0;
  89829. var triangleCount = this.triangles.length;
  89830. var iterationFunction = function (iteration, callback) {
  89831. setTimeout(function () {
  89832. if (iteration % 5 === 0) {
  89833. _this.updateMesh(iteration === 0);
  89834. }
  89835. for (var i = 0; i < _this.triangles.length; ++i) {
  89836. _this.triangles[i].isDirty = false;
  89837. }
  89838. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89839. var trianglesIterator = function (i) {
  89840. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89841. var t = _this.triangles[tIdx];
  89842. if (!t)
  89843. return;
  89844. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89845. return;
  89846. }
  89847. for (var j = 0; j < 3; ++j) {
  89848. if (t.error[j] < threshold) {
  89849. var deleted0 = [];
  89850. var deleted1 = [];
  89851. var v0 = t.vertices[j];
  89852. var v1 = t.vertices[(j + 1) % 3];
  89853. if (v0.isBorder || v1.isBorder)
  89854. continue;
  89855. var p = BABYLON.Vector3.Zero();
  89856. var n = BABYLON.Vector3.Zero();
  89857. var uv = BABYLON.Vector2.Zero();
  89858. var color = new BABYLON.Color4(0, 0, 0, 1);
  89859. _this.calculateError(v0, v1, p, n, uv, color);
  89860. var delTr = new Array();
  89861. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89862. continue;
  89863. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89864. continue;
  89865. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89866. continue;
  89867. var uniqueArray = new Array();
  89868. delTr.forEach(function (deletedT) {
  89869. if (uniqueArray.indexOf(deletedT) === -1) {
  89870. deletedT.deletePending = true;
  89871. uniqueArray.push(deletedT);
  89872. }
  89873. });
  89874. if (uniqueArray.length % 2 !== 0) {
  89875. continue;
  89876. }
  89877. v0.q = v1.q.add(v0.q);
  89878. v0.updatePosition(p);
  89879. var tStart = _this.references.length;
  89880. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89881. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89882. var tCount = _this.references.length - tStart;
  89883. if (tCount <= v0.triangleCount) {
  89884. if (tCount) {
  89885. for (var c = 0; c < tCount; c++) {
  89886. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89887. }
  89888. }
  89889. }
  89890. else {
  89891. v0.triangleStart = tStart;
  89892. }
  89893. v0.triangleCount = tCount;
  89894. break;
  89895. }
  89896. }
  89897. };
  89898. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89899. }, 0);
  89900. };
  89901. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89902. if (triangleCount - deletedTriangles <= targetCount)
  89903. loop.breakLoop();
  89904. else {
  89905. iterationFunction(loop.index, function () {
  89906. loop.executeNext();
  89907. });
  89908. }
  89909. }, function () {
  89910. setTimeout(function () {
  89911. //reconstruct this part of the mesh
  89912. _this.reconstructMesh(submeshIndex);
  89913. successCallback();
  89914. }, 0);
  89915. });
  89916. };
  89917. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89918. var _this = this;
  89919. this.vertices = [];
  89920. this.triangles = [];
  89921. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89922. var indices = this._mesh.getIndices();
  89923. var submesh = this._mesh.subMeshes[submeshIndex];
  89924. var findInVertices = function (positionToSearch) {
  89925. if (optimizeMesh) {
  89926. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89927. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89928. return _this.vertices[ii];
  89929. }
  89930. }
  89931. }
  89932. return null;
  89933. };
  89934. var vertexReferences = [];
  89935. var vertexInit = function (i) {
  89936. if (!positionData) {
  89937. return;
  89938. }
  89939. var offset = i + submesh.verticesStart;
  89940. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89941. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89942. vertex.originalOffsets.push(offset);
  89943. if (vertex.id === _this.vertices.length) {
  89944. _this.vertices.push(vertex);
  89945. }
  89946. vertexReferences.push(vertex.id);
  89947. };
  89948. //var totalVertices = mesh.getTotalVertices();
  89949. var totalVertices = submesh.verticesCount;
  89950. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89951. var indicesInit = function (i) {
  89952. if (!indices) {
  89953. return;
  89954. }
  89955. var offset = (submesh.indexStart / 3) + i;
  89956. var pos = (offset * 3);
  89957. var i0 = indices[pos + 0];
  89958. var i1 = indices[pos + 1];
  89959. var i2 = indices[pos + 2];
  89960. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89961. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89962. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89963. var triangle = new DecimationTriangle([v0, v1, v2]);
  89964. triangle.originalOffset = pos;
  89965. _this.triangles.push(triangle);
  89966. };
  89967. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89968. _this.init(callback);
  89969. });
  89970. });
  89971. };
  89972. QuadraticErrorSimplification.prototype.init = function (callback) {
  89973. var _this = this;
  89974. var triangleInit1 = function (i) {
  89975. var t = _this.triangles[i];
  89976. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89977. for (var j = 0; j < 3; j++) {
  89978. 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))));
  89979. }
  89980. };
  89981. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89982. var triangleInit2 = function (i) {
  89983. var t = _this.triangles[i];
  89984. for (var j = 0; j < 3; ++j) {
  89985. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89986. }
  89987. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89988. };
  89989. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89990. callback();
  89991. });
  89992. });
  89993. };
  89994. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89995. var newTriangles = [];
  89996. var i;
  89997. for (i = 0; i < this.vertices.length; ++i) {
  89998. this.vertices[i].triangleCount = 0;
  89999. }
  90000. var t;
  90001. var j;
  90002. for (i = 0; i < this.triangles.length; ++i) {
  90003. if (!this.triangles[i].deleted) {
  90004. t = this.triangles[i];
  90005. for (j = 0; j < 3; ++j) {
  90006. t.vertices[j].triangleCount = 1;
  90007. }
  90008. newTriangles.push(t);
  90009. }
  90010. }
  90011. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  90012. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  90013. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  90014. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  90015. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  90016. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  90017. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  90018. var vertexCount = 0;
  90019. for (i = 0; i < this.vertices.length; ++i) {
  90020. var vertex = this.vertices[i];
  90021. vertex.id = vertexCount;
  90022. if (vertex.triangleCount) {
  90023. vertex.originalOffsets.forEach(function (originalOffset) {
  90024. if (!normalData) {
  90025. return;
  90026. }
  90027. newPositionData.push(vertex.position.x);
  90028. newPositionData.push(vertex.position.y);
  90029. newPositionData.push(vertex.position.z);
  90030. newNormalData.push(normalData[originalOffset * 3]);
  90031. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  90032. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  90033. if (uvs && uvs.length) {
  90034. newUVsData.push(uvs[(originalOffset * 2)]);
  90035. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  90036. }
  90037. else if (colorsData && colorsData.length) {
  90038. newColorsData.push(colorsData[(originalOffset * 4)]);
  90039. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  90040. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  90041. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  90042. }
  90043. ++vertexCount;
  90044. });
  90045. }
  90046. }
  90047. var startingIndex = this._reconstructedMesh.getTotalIndices();
  90048. var startingVertex = this._reconstructedMesh.getTotalVertices();
  90049. var submeshesArray = this._reconstructedMesh.subMeshes;
  90050. this._reconstructedMesh.subMeshes = [];
  90051. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  90052. var originalIndices = this._mesh.getIndices();
  90053. for (i = 0; i < newTriangles.length; ++i) {
  90054. t = newTriangles[i]; //now get the new referencing point for each vertex
  90055. [0, 1, 2].forEach(function (idx) {
  90056. var id = originalIndices[t.originalOffset + idx];
  90057. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  90058. if (offset < 0)
  90059. offset = 0;
  90060. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  90061. });
  90062. }
  90063. //overwriting the old vertex buffers and indices.
  90064. this._reconstructedMesh.setIndices(newIndicesArray);
  90065. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  90066. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  90067. if (newUVsData.length > 0)
  90068. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  90069. if (newColorsData.length > 0)
  90070. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  90071. //create submesh
  90072. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  90073. if (submeshIndex > 0) {
  90074. this._reconstructedMesh.subMeshes = [];
  90075. submeshesArray.forEach(function (submesh) {
  90076. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  90077. });
  90078. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  90079. }
  90080. };
  90081. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  90082. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  90083. this._reconstructedMesh.material = this._mesh.material;
  90084. this._reconstructedMesh.parent = this._mesh.parent;
  90085. this._reconstructedMesh.isVisible = false;
  90086. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  90087. };
  90088. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  90089. for (var i = 0; i < vertex1.triangleCount; ++i) {
  90090. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  90091. if (t.deleted)
  90092. continue;
  90093. var s = this.references[vertex1.triangleStart + i].vertexId;
  90094. var v1 = t.vertices[(s + 1) % 3];
  90095. var v2 = t.vertices[(s + 2) % 3];
  90096. if ((v1 === vertex2 || v2 === vertex2)) {
  90097. deletedArray[i] = true;
  90098. delTr.push(t);
  90099. continue;
  90100. }
  90101. var d1 = v1.position.subtract(point);
  90102. d1 = d1.normalize();
  90103. var d2 = v2.position.subtract(point);
  90104. d2 = d2.normalize();
  90105. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  90106. return true;
  90107. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  90108. deletedArray[i] = false;
  90109. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  90110. return true;
  90111. }
  90112. return false;
  90113. };
  90114. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  90115. var newDeleted = deletedTriangles;
  90116. for (var i = 0; i < vertex.triangleCount; ++i) {
  90117. var ref = this.references[vertex.triangleStart + i];
  90118. var t = this.triangles[ref.triangleId];
  90119. if (t.deleted)
  90120. continue;
  90121. if (deletedArray[i] && t.deletePending) {
  90122. t.deleted = true;
  90123. newDeleted++;
  90124. continue;
  90125. }
  90126. t.vertices[ref.vertexId] = origVertex;
  90127. t.isDirty = true;
  90128. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  90129. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  90130. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  90131. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90132. this.references.push(ref);
  90133. }
  90134. return newDeleted;
  90135. };
  90136. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  90137. for (var i = 0; i < this.vertices.length; ++i) {
  90138. var vCount = [];
  90139. var vId = [];
  90140. var v = this.vertices[i];
  90141. var j;
  90142. for (j = 0; j < v.triangleCount; ++j) {
  90143. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  90144. for (var ii = 0; ii < 3; ii++) {
  90145. var ofs = 0;
  90146. var vv = triangle.vertices[ii];
  90147. while (ofs < vCount.length) {
  90148. if (vId[ofs] === vv.id)
  90149. break;
  90150. ++ofs;
  90151. }
  90152. if (ofs === vCount.length) {
  90153. vCount.push(1);
  90154. vId.push(vv.id);
  90155. }
  90156. else {
  90157. vCount[ofs]++;
  90158. }
  90159. }
  90160. }
  90161. for (j = 0; j < vCount.length; ++j) {
  90162. if (vCount[j] === 1) {
  90163. this.vertices[vId[j]].isBorder = true;
  90164. }
  90165. else {
  90166. this.vertices[vId[j]].isBorder = false;
  90167. }
  90168. }
  90169. }
  90170. };
  90171. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  90172. if (identifyBorders === void 0) { identifyBorders = false; }
  90173. var i;
  90174. if (!identifyBorders) {
  90175. var newTrianglesVector = [];
  90176. for (i = 0; i < this.triangles.length; ++i) {
  90177. if (!this.triangles[i].deleted) {
  90178. newTrianglesVector.push(this.triangles[i]);
  90179. }
  90180. }
  90181. this.triangles = newTrianglesVector;
  90182. }
  90183. for (i = 0; i < this.vertices.length; ++i) {
  90184. this.vertices[i].triangleCount = 0;
  90185. this.vertices[i].triangleStart = 0;
  90186. }
  90187. var t;
  90188. var j;
  90189. var v;
  90190. for (i = 0; i < this.triangles.length; ++i) {
  90191. t = this.triangles[i];
  90192. for (j = 0; j < 3; ++j) {
  90193. v = t.vertices[j];
  90194. v.triangleCount++;
  90195. }
  90196. }
  90197. var tStart = 0;
  90198. for (i = 0; i < this.vertices.length; ++i) {
  90199. this.vertices[i].triangleStart = tStart;
  90200. tStart += this.vertices[i].triangleCount;
  90201. this.vertices[i].triangleCount = 0;
  90202. }
  90203. var newReferences = new Array(this.triangles.length * 3);
  90204. for (i = 0; i < this.triangles.length; ++i) {
  90205. t = this.triangles[i];
  90206. for (j = 0; j < 3; ++j) {
  90207. v = t.vertices[j];
  90208. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  90209. v.triangleCount++;
  90210. }
  90211. }
  90212. this.references = newReferences;
  90213. if (identifyBorders) {
  90214. this.identifyBorder();
  90215. }
  90216. };
  90217. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  90218. var x = point.x;
  90219. var y = point.y;
  90220. var z = point.z;
  90221. 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
  90222. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  90223. };
  90224. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  90225. var q = vertex1.q.add(vertex2.q);
  90226. var border = vertex1.isBorder && vertex2.isBorder;
  90227. var error = 0;
  90228. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  90229. if (qDet !== 0 && !border) {
  90230. if (!pointResult) {
  90231. pointResult = BABYLON.Vector3.Zero();
  90232. }
  90233. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  90234. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  90235. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  90236. error = this.vertexError(q, pointResult);
  90237. }
  90238. else {
  90239. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  90240. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  90241. var error1 = this.vertexError(q, vertex1.position);
  90242. var error2 = this.vertexError(q, vertex2.position);
  90243. var error3 = this.vertexError(q, p3);
  90244. error = Math.min(error1, error2, error3);
  90245. if (error === error1) {
  90246. if (pointResult) {
  90247. pointResult.copyFrom(vertex1.position);
  90248. }
  90249. }
  90250. else if (error === error2) {
  90251. if (pointResult) {
  90252. pointResult.copyFrom(vertex2.position);
  90253. }
  90254. }
  90255. else {
  90256. if (pointResult) {
  90257. pointResult.copyFrom(p3);
  90258. }
  90259. }
  90260. }
  90261. return error;
  90262. };
  90263. return QuadraticErrorSimplification;
  90264. }());
  90265. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  90266. })(BABYLON || (BABYLON = {}));
  90267. //# sourceMappingURL=babylon.meshSimplification.js.map
  90268. var BABYLON;
  90269. (function (BABYLON) {
  90270. var MeshLODLevel = /** @class */ (function () {
  90271. function MeshLODLevel(distance, mesh) {
  90272. this.distance = distance;
  90273. this.mesh = mesh;
  90274. }
  90275. return MeshLODLevel;
  90276. }());
  90277. BABYLON.MeshLODLevel = MeshLODLevel;
  90278. })(BABYLON || (BABYLON = {}));
  90279. //# sourceMappingURL=babylon.meshLODLevel.js.map
  90280. var BABYLON;
  90281. (function (BABYLON) {
  90282. /**
  90283. * Defines the root class used to create scene optimization to use with SceneOptimizer
  90284. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90285. */
  90286. var SceneOptimization = /** @class */ (function () {
  90287. /**
  90288. * Creates the SceneOptimization object
  90289. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90290. * @param desc defines the description associated with the optimization
  90291. */
  90292. function SceneOptimization(
  90293. /**
  90294. * Defines the priority of this optimization (0 by default which means first in the list)
  90295. */
  90296. priority) {
  90297. if (priority === void 0) { priority = 0; }
  90298. this.priority = priority;
  90299. }
  90300. /**
  90301. * Gets a string describing the action executed by the current optimization
  90302. * @returns description string
  90303. */
  90304. SceneOptimization.prototype.getDescription = function () {
  90305. return "";
  90306. };
  90307. /**
  90308. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90309. * @param scene defines the current scene where to apply this optimization
  90310. * @param optimizer defines the current optimizer
  90311. * @returns true if everything that can be done was applied
  90312. */
  90313. SceneOptimization.prototype.apply = function (scene, optimizer) {
  90314. return true;
  90315. };
  90316. ;
  90317. return SceneOptimization;
  90318. }());
  90319. BABYLON.SceneOptimization = SceneOptimization;
  90320. /**
  90321. * Defines an optimization used to reduce the size of render target textures
  90322. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90323. */
  90324. var TextureOptimization = /** @class */ (function (_super) {
  90325. __extends(TextureOptimization, _super);
  90326. /**
  90327. * Creates the TextureOptimization object
  90328. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90329. * @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
  90330. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90331. */
  90332. function TextureOptimization(
  90333. /**
  90334. * Defines the priority of this optimization (0 by default which means first in the list)
  90335. */
  90336. priority,
  90337. /**
  90338. * 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
  90339. */
  90340. maximumSize,
  90341. /**
  90342. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90343. */
  90344. step) {
  90345. if (priority === void 0) { priority = 0; }
  90346. if (maximumSize === void 0) { maximumSize = 1024; }
  90347. if (step === void 0) { step = 0.5; }
  90348. var _this = _super.call(this, priority) || this;
  90349. _this.priority = priority;
  90350. _this.maximumSize = maximumSize;
  90351. _this.step = step;
  90352. return _this;
  90353. }
  90354. /**
  90355. * Gets a string describing the action executed by the current optimization
  90356. * @returns description string
  90357. */
  90358. TextureOptimization.prototype.getDescription = function () {
  90359. return "Reducing render target texture size to " + this.maximumSize;
  90360. };
  90361. /**
  90362. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90363. * @param scene defines the current scene where to apply this optimization
  90364. * @param optimizer defines the current optimizer
  90365. * @returns true if everything that can be done was applied
  90366. */
  90367. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90368. var allDone = true;
  90369. for (var index = 0; index < scene.textures.length; index++) {
  90370. var texture = scene.textures[index];
  90371. if (!texture.canRescale || texture.getContext) {
  90372. continue;
  90373. }
  90374. var currentSize = texture.getSize();
  90375. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90376. if (maxDimension > this.maximumSize) {
  90377. texture.scale(this.step);
  90378. allDone = false;
  90379. }
  90380. }
  90381. return allDone;
  90382. };
  90383. return TextureOptimization;
  90384. }(SceneOptimization));
  90385. BABYLON.TextureOptimization = TextureOptimization;
  90386. /**
  90387. * Defines an optimization used to increase or decrease the rendering resolution
  90388. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90389. */
  90390. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90391. __extends(HardwareScalingOptimization, _super);
  90392. /**
  90393. * Creates the HardwareScalingOptimization object
  90394. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90395. * @param maximumScale defines the maximum scale to use (2 by default)
  90396. * @param step defines the step to use between two passes (0.5 by default)
  90397. */
  90398. function HardwareScalingOptimization(
  90399. /**
  90400. * Defines the priority of this optimization (0 by default which means first in the list)
  90401. */
  90402. priority,
  90403. /**
  90404. * Defines the maximum scale to use (2 by default)
  90405. */
  90406. maximumScale,
  90407. /**
  90408. * Defines the step to use between two passes (0.5 by default)
  90409. */
  90410. step) {
  90411. if (priority === void 0) { priority = 0; }
  90412. if (maximumScale === void 0) { maximumScale = 2; }
  90413. if (step === void 0) { step = 0.25; }
  90414. var _this = _super.call(this, priority) || this;
  90415. _this.priority = priority;
  90416. _this.maximumScale = maximumScale;
  90417. _this.step = step;
  90418. _this._currentScale = -1;
  90419. _this._directionOffset = 1;
  90420. return _this;
  90421. }
  90422. /**
  90423. * Gets a string describing the action executed by the current optimization
  90424. * @return description string
  90425. */
  90426. HardwareScalingOptimization.prototype.getDescription = function () {
  90427. return "Setting hardware scaling level to " + this._currentScale;
  90428. };
  90429. /**
  90430. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90431. * @param scene defines the current scene where to apply this optimization
  90432. * @param optimizer defines the current optimizer
  90433. * @returns true if everything that can be done was applied
  90434. */
  90435. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90436. if (this._currentScale === -1) {
  90437. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90438. if (this._currentScale > this.maximumScale) {
  90439. this._directionOffset = -1;
  90440. }
  90441. }
  90442. this._currentScale += this._directionOffset * this.step;
  90443. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90444. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90445. };
  90446. ;
  90447. return HardwareScalingOptimization;
  90448. }(SceneOptimization));
  90449. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90450. /**
  90451. * Defines an optimization used to remove shadows
  90452. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90453. */
  90454. var ShadowsOptimization = /** @class */ (function (_super) {
  90455. __extends(ShadowsOptimization, _super);
  90456. function ShadowsOptimization() {
  90457. return _super !== null && _super.apply(this, arguments) || this;
  90458. }
  90459. /**
  90460. * Gets a string describing the action executed by the current optimization
  90461. * @return description string
  90462. */
  90463. ShadowsOptimization.prototype.getDescription = function () {
  90464. return "Turning shadows on/off";
  90465. };
  90466. /**
  90467. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90468. * @param scene defines the current scene where to apply this optimization
  90469. * @param optimizer defines the current optimizer
  90470. * @returns true if everything that can be done was applied
  90471. */
  90472. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90473. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90474. return true;
  90475. };
  90476. ;
  90477. return ShadowsOptimization;
  90478. }(SceneOptimization));
  90479. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90480. /**
  90481. * Defines an optimization used to turn post-processes off
  90482. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90483. */
  90484. var PostProcessesOptimization = /** @class */ (function (_super) {
  90485. __extends(PostProcessesOptimization, _super);
  90486. function PostProcessesOptimization() {
  90487. return _super !== null && _super.apply(this, arguments) || this;
  90488. }
  90489. /**
  90490. * Gets a string describing the action executed by the current optimization
  90491. * @return description string
  90492. */
  90493. PostProcessesOptimization.prototype.getDescription = function () {
  90494. return "Turning post-processes on/off";
  90495. };
  90496. /**
  90497. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90498. * @param scene defines the current scene where to apply this optimization
  90499. * @param optimizer defines the current optimizer
  90500. * @returns true if everything that can be done was applied
  90501. */
  90502. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90503. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90504. return true;
  90505. };
  90506. ;
  90507. return PostProcessesOptimization;
  90508. }(SceneOptimization));
  90509. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90510. /**
  90511. * Defines an optimization used to turn lens flares off
  90512. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90513. */
  90514. var LensFlaresOptimization = /** @class */ (function (_super) {
  90515. __extends(LensFlaresOptimization, _super);
  90516. function LensFlaresOptimization() {
  90517. return _super !== null && _super.apply(this, arguments) || this;
  90518. }
  90519. /**
  90520. * Gets a string describing the action executed by the current optimization
  90521. * @return description string
  90522. */
  90523. LensFlaresOptimization.prototype.getDescription = function () {
  90524. return "Turning lens flares on/off";
  90525. };
  90526. /**
  90527. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90528. * @param scene defines the current scene where to apply this optimization
  90529. * @param optimizer defines the current optimizer
  90530. * @returns true if everything that can be done was applied
  90531. */
  90532. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90533. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90534. return true;
  90535. };
  90536. ;
  90537. return LensFlaresOptimization;
  90538. }(SceneOptimization));
  90539. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90540. /**
  90541. * Defines an optimization based on user defined callback.
  90542. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90543. */
  90544. var CustomOptimization = /** @class */ (function (_super) {
  90545. __extends(CustomOptimization, _super);
  90546. function CustomOptimization() {
  90547. return _super !== null && _super.apply(this, arguments) || this;
  90548. }
  90549. /**
  90550. * Gets a string describing the action executed by the current optimization
  90551. * @returns description string
  90552. */
  90553. CustomOptimization.prototype.getDescription = function () {
  90554. if (this.onGetDescription) {
  90555. return this.onGetDescription();
  90556. }
  90557. return "Running user defined callback";
  90558. };
  90559. /**
  90560. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90561. * @param scene defines the current scene where to apply this optimization
  90562. * @param optimizer defines the current optimizer
  90563. * @returns true if everything that can be done was applied
  90564. */
  90565. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90566. if (this.onApply) {
  90567. return this.onApply(scene, optimizer);
  90568. }
  90569. return true;
  90570. };
  90571. ;
  90572. return CustomOptimization;
  90573. }(SceneOptimization));
  90574. BABYLON.CustomOptimization = CustomOptimization;
  90575. /**
  90576. * Defines an optimization used to turn particles off
  90577. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90578. */
  90579. var ParticlesOptimization = /** @class */ (function (_super) {
  90580. __extends(ParticlesOptimization, _super);
  90581. function ParticlesOptimization() {
  90582. return _super !== null && _super.apply(this, arguments) || this;
  90583. }
  90584. /**
  90585. * Gets a string describing the action executed by the current optimization
  90586. * @return description string
  90587. */
  90588. ParticlesOptimization.prototype.getDescription = function () {
  90589. return "Turning particles on/off";
  90590. };
  90591. /**
  90592. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90593. * @param scene defines the current scene where to apply this optimization
  90594. * @param optimizer defines the current optimizer
  90595. * @returns true if everything that can be done was applied
  90596. */
  90597. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90598. scene.particlesEnabled = optimizer.isInImprovementMode;
  90599. return true;
  90600. };
  90601. ;
  90602. return ParticlesOptimization;
  90603. }(SceneOptimization));
  90604. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90605. /**
  90606. * Defines an optimization used to turn render targets off
  90607. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90608. */
  90609. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90610. __extends(RenderTargetsOptimization, _super);
  90611. function RenderTargetsOptimization() {
  90612. return _super !== null && _super.apply(this, arguments) || this;
  90613. }
  90614. /**
  90615. * Gets a string describing the action executed by the current optimization
  90616. * @return description string
  90617. */
  90618. RenderTargetsOptimization.prototype.getDescription = function () {
  90619. return "Turning render targets off";
  90620. };
  90621. /**
  90622. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90623. * @param scene defines the current scene where to apply this optimization
  90624. * @param optimizer defines the current optimizer
  90625. * @returns true if everything that can be done was applied
  90626. */
  90627. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90628. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90629. return true;
  90630. };
  90631. ;
  90632. return RenderTargetsOptimization;
  90633. }(SceneOptimization));
  90634. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90635. /**
  90636. * Defines an optimization used to merge meshes with compatible materials
  90637. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90638. */
  90639. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90640. __extends(MergeMeshesOptimization, _super);
  90641. function MergeMeshesOptimization() {
  90642. var _this = _super !== null && _super.apply(this, arguments) || this;
  90643. _this._canBeMerged = function (abstractMesh) {
  90644. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90645. return false;
  90646. }
  90647. var mesh = abstractMesh;
  90648. if (!mesh.isVisible || !mesh.isEnabled()) {
  90649. return false;
  90650. }
  90651. if (mesh.instances.length > 0) {
  90652. return false;
  90653. }
  90654. if (mesh.skeleton || mesh.hasLODLevels) {
  90655. return false;
  90656. }
  90657. if (mesh.parent) {
  90658. return false;
  90659. }
  90660. return true;
  90661. };
  90662. return _this;
  90663. }
  90664. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90665. /**
  90666. * Gets or sets a boolean which defines if optimization octree has to be updated
  90667. */
  90668. get: function () {
  90669. return MergeMeshesOptimization._UpdateSelectionTree;
  90670. },
  90671. /**
  90672. * Gets or sets a boolean which defines if optimization octree has to be updated
  90673. */
  90674. set: function (value) {
  90675. MergeMeshesOptimization._UpdateSelectionTree = value;
  90676. },
  90677. enumerable: true,
  90678. configurable: true
  90679. });
  90680. /**
  90681. * Gets a string describing the action executed by the current optimization
  90682. * @return description string
  90683. */
  90684. MergeMeshesOptimization.prototype.getDescription = function () {
  90685. return "Merging similar meshes together";
  90686. };
  90687. /**
  90688. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90689. * @param scene defines the current scene where to apply this optimization
  90690. * @param optimizer defines the current optimizer
  90691. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90692. * @returns true if everything that can be done was applied
  90693. */
  90694. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90695. var globalPool = scene.meshes.slice(0);
  90696. var globalLength = globalPool.length;
  90697. for (var index = 0; index < globalLength; index++) {
  90698. var currentPool = new Array();
  90699. var current = globalPool[index];
  90700. // Checks
  90701. if (!this._canBeMerged(current)) {
  90702. continue;
  90703. }
  90704. currentPool.push(current);
  90705. // Find compatible meshes
  90706. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90707. var otherMesh = globalPool[subIndex];
  90708. if (!this._canBeMerged(otherMesh)) {
  90709. continue;
  90710. }
  90711. if (otherMesh.material !== current.material) {
  90712. continue;
  90713. }
  90714. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90715. continue;
  90716. }
  90717. currentPool.push(otherMesh);
  90718. globalLength--;
  90719. globalPool.splice(subIndex, 1);
  90720. subIndex--;
  90721. }
  90722. if (currentPool.length < 2) {
  90723. continue;
  90724. }
  90725. // Merge meshes
  90726. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  90727. }
  90728. if (updateSelectionTree != undefined) {
  90729. if (updateSelectionTree) {
  90730. scene.createOrUpdateSelectionOctree();
  90731. }
  90732. }
  90733. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90734. scene.createOrUpdateSelectionOctree();
  90735. }
  90736. return true;
  90737. };
  90738. ;
  90739. MergeMeshesOptimization._UpdateSelectionTree = false;
  90740. return MergeMeshesOptimization;
  90741. }(SceneOptimization));
  90742. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90743. /**
  90744. * Defines a list of options used by SceneOptimizer
  90745. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90746. */
  90747. var SceneOptimizerOptions = /** @class */ (function () {
  90748. /**
  90749. * Creates a new list of options used by SceneOptimizer
  90750. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90751. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90752. */
  90753. function SceneOptimizerOptions(
  90754. /**
  90755. * Defines the target frame rate to reach (60 by default)
  90756. */
  90757. targetFrameRate,
  90758. /**
  90759. * Defines the interval between two checkes (2000ms by default)
  90760. */
  90761. trackerDuration) {
  90762. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90763. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90764. this.targetFrameRate = targetFrameRate;
  90765. this.trackerDuration = trackerDuration;
  90766. /**
  90767. * Gets the list of optimizations to apply
  90768. */
  90769. this.optimizations = new Array();
  90770. }
  90771. /**
  90772. * Add a new optimization
  90773. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90774. * @returns the current SceneOptimizerOptions
  90775. */
  90776. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90777. this.optimizations.push(optimization);
  90778. return this;
  90779. };
  90780. /**
  90781. * Add a new custom optimization
  90782. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90783. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90784. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90785. * @returns the current SceneOptimizerOptions
  90786. */
  90787. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90788. if (priority === void 0) { priority = 0; }
  90789. var optimization = new CustomOptimization(priority);
  90790. optimization.onApply = onApply;
  90791. optimization.onGetDescription = onGetDescription;
  90792. this.optimizations.push(optimization);
  90793. return this;
  90794. };
  90795. /**
  90796. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90797. * @param targetFrameRate defines the target frame rate (60 by default)
  90798. * @returns a SceneOptimizerOptions object
  90799. */
  90800. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90801. var result = new SceneOptimizerOptions(targetFrameRate);
  90802. var priority = 0;
  90803. result.addOptimization(new MergeMeshesOptimization(priority));
  90804. result.addOptimization(new ShadowsOptimization(priority));
  90805. result.addOptimization(new LensFlaresOptimization(priority));
  90806. // Next priority
  90807. priority++;
  90808. result.addOptimization(new PostProcessesOptimization(priority));
  90809. result.addOptimization(new ParticlesOptimization(priority));
  90810. // Next priority
  90811. priority++;
  90812. result.addOptimization(new TextureOptimization(priority, 1024));
  90813. return result;
  90814. };
  90815. /**
  90816. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90817. * @param targetFrameRate defines the target frame rate (60 by default)
  90818. * @returns a SceneOptimizerOptions object
  90819. */
  90820. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90821. var result = new SceneOptimizerOptions(targetFrameRate);
  90822. var priority = 0;
  90823. result.addOptimization(new MergeMeshesOptimization(priority));
  90824. result.addOptimization(new ShadowsOptimization(priority));
  90825. result.addOptimization(new LensFlaresOptimization(priority));
  90826. // Next priority
  90827. priority++;
  90828. result.addOptimization(new PostProcessesOptimization(priority));
  90829. result.addOptimization(new ParticlesOptimization(priority));
  90830. // Next priority
  90831. priority++;
  90832. result.addOptimization(new TextureOptimization(priority, 512));
  90833. // Next priority
  90834. priority++;
  90835. result.addOptimization(new RenderTargetsOptimization(priority));
  90836. // Next priority
  90837. priority++;
  90838. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90839. return result;
  90840. };
  90841. /**
  90842. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90843. * @param targetFrameRate defines the target frame rate (60 by default)
  90844. * @returns a SceneOptimizerOptions object
  90845. */
  90846. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90847. var result = new SceneOptimizerOptions(targetFrameRate);
  90848. var priority = 0;
  90849. result.addOptimization(new MergeMeshesOptimization(priority));
  90850. result.addOptimization(new ShadowsOptimization(priority));
  90851. result.addOptimization(new LensFlaresOptimization(priority));
  90852. // Next priority
  90853. priority++;
  90854. result.addOptimization(new PostProcessesOptimization(priority));
  90855. result.addOptimization(new ParticlesOptimization(priority));
  90856. // Next priority
  90857. priority++;
  90858. result.addOptimization(new TextureOptimization(priority, 256));
  90859. // Next priority
  90860. priority++;
  90861. result.addOptimization(new RenderTargetsOptimization(priority));
  90862. // Next priority
  90863. priority++;
  90864. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90865. return result;
  90866. };
  90867. return SceneOptimizerOptions;
  90868. }());
  90869. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90870. /**
  90871. * Class used to run optimizations in order to reach a target frame rate
  90872. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90873. */
  90874. var SceneOptimizer = /** @class */ (function () {
  90875. /**
  90876. * Creates a new SceneOptimizer
  90877. * @param scene defines the scene to work on
  90878. * @param options defines the options to use with the SceneOptimizer
  90879. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90880. * @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)
  90881. */
  90882. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90883. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90884. if (improvementMode === void 0) { improvementMode = false; }
  90885. var _this = this;
  90886. this._isRunning = false;
  90887. this._currentPriorityLevel = 0;
  90888. this._targetFrameRate = 60;
  90889. this._trackerDuration = 2000;
  90890. this._currentFrameRate = 0;
  90891. this._improvementMode = false;
  90892. /**
  90893. * Defines an observable called when the optimizer reaches the target frame rate
  90894. */
  90895. this.onSuccessObservable = new BABYLON.Observable();
  90896. /**
  90897. * Defines an observable called when the optimizer enables an optimization
  90898. */
  90899. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90900. /**
  90901. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90902. */
  90903. this.onFailureObservable = new BABYLON.Observable();
  90904. if (!options) {
  90905. this._options = new SceneOptimizerOptions();
  90906. }
  90907. else {
  90908. this._options = options;
  90909. }
  90910. if (this._options.targetFrameRate) {
  90911. this._targetFrameRate = this._options.targetFrameRate;
  90912. }
  90913. if (this._options.trackerDuration) {
  90914. this._trackerDuration = this._options.trackerDuration;
  90915. }
  90916. if (autoGeneratePriorities) {
  90917. var priority = 0;
  90918. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90919. var optim = _a[_i];
  90920. optim.priority = priority++;
  90921. }
  90922. }
  90923. this._improvementMode = improvementMode;
  90924. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90925. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90926. _this._sceneDisposeObserver = null;
  90927. _this.dispose();
  90928. });
  90929. }
  90930. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90931. /**
  90932. * Gets a boolean indicating if the optimizer is in improvement mode
  90933. */
  90934. get: function () {
  90935. return this._improvementMode;
  90936. },
  90937. enumerable: true,
  90938. configurable: true
  90939. });
  90940. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90941. /**
  90942. * Gets the current priority level (0 at start)
  90943. */
  90944. get: function () {
  90945. return this._currentPriorityLevel;
  90946. },
  90947. enumerable: true,
  90948. configurable: true
  90949. });
  90950. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90951. /**
  90952. * Gets the current frame rate checked by the SceneOptimizer
  90953. */
  90954. get: function () {
  90955. return this._currentFrameRate;
  90956. },
  90957. enumerable: true,
  90958. configurable: true
  90959. });
  90960. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90961. /**
  90962. * Gets or sets the current target frame rate (60 by default)
  90963. */
  90964. get: function () {
  90965. return this._targetFrameRate;
  90966. },
  90967. /**
  90968. * Gets or sets the current target frame rate (60 by default)
  90969. */
  90970. set: function (value) {
  90971. this._targetFrameRate = value;
  90972. },
  90973. enumerable: true,
  90974. configurable: true
  90975. });
  90976. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90977. /**
  90978. * Gets or sets the current interval between two checks (every 2000ms by default)
  90979. */
  90980. get: function () {
  90981. return this._trackerDuration;
  90982. },
  90983. /**
  90984. * Gets or sets the current interval between two checks (every 2000ms by default)
  90985. */
  90986. set: function (value) {
  90987. this._trackerDuration = value;
  90988. },
  90989. enumerable: true,
  90990. configurable: true
  90991. });
  90992. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90993. /**
  90994. * Gets the list of active optimizations
  90995. */
  90996. get: function () {
  90997. return this._options.optimizations;
  90998. },
  90999. enumerable: true,
  91000. configurable: true
  91001. });
  91002. /**
  91003. * Stops the current optimizer
  91004. */
  91005. SceneOptimizer.prototype.stop = function () {
  91006. this._isRunning = false;
  91007. };
  91008. /**
  91009. * Reset the optimizer to initial step (current priority level = 0)
  91010. */
  91011. SceneOptimizer.prototype.reset = function () {
  91012. this._currentPriorityLevel = 0;
  91013. };
  91014. /**
  91015. * Start the optimizer. By default it will try to reach a specific framerate
  91016. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  91017. */
  91018. SceneOptimizer.prototype.start = function () {
  91019. var _this = this;
  91020. if (this._isRunning) {
  91021. return;
  91022. }
  91023. this._isRunning = true;
  91024. // Let's wait for the scene to be ready before running our check
  91025. this._scene.executeWhenReady(function () {
  91026. setTimeout(function () {
  91027. _this._checkCurrentState();
  91028. }, _this._trackerDuration);
  91029. });
  91030. };
  91031. SceneOptimizer.prototype._checkCurrentState = function () {
  91032. var _this = this;
  91033. if (!this._isRunning) {
  91034. return;
  91035. }
  91036. var scene = this._scene;
  91037. var options = this._options;
  91038. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  91039. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  91040. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  91041. this._isRunning = false;
  91042. this.onSuccessObservable.notifyObservers(this);
  91043. return;
  91044. }
  91045. // Apply current level of optimizations
  91046. var allDone = true;
  91047. var noOptimizationApplied = true;
  91048. for (var index = 0; index < options.optimizations.length; index++) {
  91049. var optimization = options.optimizations[index];
  91050. if (optimization.priority === this._currentPriorityLevel) {
  91051. noOptimizationApplied = false;
  91052. allDone = allDone && optimization.apply(scene, this);
  91053. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  91054. }
  91055. }
  91056. // If no optimization was applied, this is a failure :(
  91057. if (noOptimizationApplied) {
  91058. this._isRunning = false;
  91059. this.onFailureObservable.notifyObservers(this);
  91060. return;
  91061. }
  91062. // If all optimizations were done, move to next level
  91063. if (allDone) {
  91064. this._currentPriorityLevel++;
  91065. }
  91066. // Let's the system running for a specific amount of time before checking FPS
  91067. scene.executeWhenReady(function () {
  91068. setTimeout(function () {
  91069. _this._checkCurrentState();
  91070. }, _this._trackerDuration);
  91071. });
  91072. };
  91073. /**
  91074. * Release all resources
  91075. */
  91076. SceneOptimizer.prototype.dispose = function () {
  91077. this.stop();
  91078. this.onSuccessObservable.clear();
  91079. this.onFailureObservable.clear();
  91080. this.onNewOptimizationAppliedObservable.clear();
  91081. if (this._sceneDisposeObserver) {
  91082. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  91083. }
  91084. };
  91085. /**
  91086. * Helper function to create a SceneOptimizer with one single line of code
  91087. * @param scene defines the scene to work on
  91088. * @param options defines the options to use with the SceneOptimizer
  91089. * @param onSuccess defines a callback to call on success
  91090. * @param onFailure defines a callback to call on failure
  91091. * @returns the new SceneOptimizer object
  91092. */
  91093. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  91094. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  91095. if (onSuccess) {
  91096. optimizer.onSuccessObservable.add(function () {
  91097. onSuccess();
  91098. });
  91099. }
  91100. if (onFailure) {
  91101. optimizer.onFailureObservable.add(function () {
  91102. onFailure();
  91103. });
  91104. }
  91105. optimizer.start();
  91106. return optimizer;
  91107. };
  91108. return SceneOptimizer;
  91109. }());
  91110. BABYLON.SceneOptimizer = SceneOptimizer;
  91111. })(BABYLON || (BABYLON = {}));
  91112. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  91113. var BABYLON;
  91114. (function (BABYLON) {
  91115. var OutlineRenderer = /** @class */ (function () {
  91116. function OutlineRenderer(scene) {
  91117. this.zOffset = 1;
  91118. this._scene = scene;
  91119. }
  91120. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  91121. var _this = this;
  91122. if (useOverlay === void 0) { useOverlay = false; }
  91123. var scene = this._scene;
  91124. var engine = this._scene.getEngine();
  91125. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91126. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  91127. return;
  91128. }
  91129. var mesh = subMesh.getRenderingMesh();
  91130. var material = subMesh.getMaterial();
  91131. if (!material || !scene.activeCamera) {
  91132. return;
  91133. }
  91134. engine.enableEffect(this._effect);
  91135. // Logarithmic depth
  91136. if (material.useLogarithmicDepth) {
  91137. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  91138. }
  91139. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  91140. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  91141. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  91142. // Bones
  91143. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91144. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91145. }
  91146. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  91147. // Alpha test
  91148. if (material && material.needAlphaTesting()) {
  91149. var alphaTexture = material.getAlphaTestTexture();
  91150. if (alphaTexture) {
  91151. this._effect.setTexture("diffuseSampler", alphaTexture);
  91152. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  91153. }
  91154. }
  91155. engine.setZOffset(-this.zOffset);
  91156. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  91157. engine.setZOffset(0);
  91158. };
  91159. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  91160. var defines = [];
  91161. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  91162. var mesh = subMesh.getMesh();
  91163. var material = subMesh.getMaterial();
  91164. if (material) {
  91165. // Alpha test
  91166. if (material.needAlphaTesting()) {
  91167. defines.push("#define ALPHATEST");
  91168. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91169. attribs.push(BABYLON.VertexBuffer.UVKind);
  91170. defines.push("#define UV1");
  91171. }
  91172. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  91173. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91174. defines.push("#define UV2");
  91175. }
  91176. }
  91177. //Logarithmic depth
  91178. if (material.useLogarithmicDepth) {
  91179. defines.push("#define LOGARITHMICDEPTH");
  91180. }
  91181. }
  91182. // Bones
  91183. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91184. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91185. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91186. if (mesh.numBoneInfluencers > 4) {
  91187. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91188. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91189. }
  91190. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91191. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  91192. }
  91193. else {
  91194. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91195. }
  91196. // Instances
  91197. if (useInstances) {
  91198. defines.push("#define INSTANCES");
  91199. attribs.push("world0");
  91200. attribs.push("world1");
  91201. attribs.push("world2");
  91202. attribs.push("world3");
  91203. }
  91204. // Get correct effect
  91205. var join = defines.join("\n");
  91206. if (this._cachedDefines !== join) {
  91207. this._cachedDefines = join;
  91208. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  91209. }
  91210. return this._effect.isReady();
  91211. };
  91212. return OutlineRenderer;
  91213. }());
  91214. BABYLON.OutlineRenderer = OutlineRenderer;
  91215. })(BABYLON || (BABYLON = {}));
  91216. //# sourceMappingURL=babylon.outlineRenderer.js.map
  91217. var BABYLON;
  91218. (function (BABYLON) {
  91219. var FaceAdjacencies = /** @class */ (function () {
  91220. function FaceAdjacencies() {
  91221. this.edges = new Array();
  91222. this.edgesConnectedCount = 0;
  91223. }
  91224. return FaceAdjacencies;
  91225. }());
  91226. var EdgesRenderer = /** @class */ (function () {
  91227. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  91228. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  91229. if (epsilon === void 0) { epsilon = 0.95; }
  91230. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  91231. this.edgesWidthScalerForOrthographic = 1000.0;
  91232. this.edgesWidthScalerForPerspective = 50.0;
  91233. this._linesPositions = new Array();
  91234. this._linesNormals = new Array();
  91235. this._linesIndices = new Array();
  91236. this._buffers = {};
  91237. this._checkVerticesInsteadOfIndices = false;
  91238. this._source = source;
  91239. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  91240. this._epsilon = epsilon;
  91241. this._prepareRessources();
  91242. this._generateEdgesLines();
  91243. }
  91244. EdgesRenderer.prototype._prepareRessources = function () {
  91245. if (this._lineShader) {
  91246. return;
  91247. }
  91248. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  91249. attributes: ["position", "normal"],
  91250. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  91251. });
  91252. this._lineShader.disableDepthWrite = true;
  91253. this._lineShader.backFaceCulling = false;
  91254. };
  91255. EdgesRenderer.prototype._rebuild = function () {
  91256. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91257. if (buffer) {
  91258. buffer._rebuild();
  91259. }
  91260. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91261. if (buffer) {
  91262. buffer._rebuild();
  91263. }
  91264. var scene = this._source.getScene();
  91265. var engine = scene.getEngine();
  91266. this._ib = engine.createIndexBuffer(this._linesIndices);
  91267. };
  91268. EdgesRenderer.prototype.dispose = function () {
  91269. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91270. if (buffer) {
  91271. buffer.dispose();
  91272. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  91273. }
  91274. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91275. if (buffer) {
  91276. buffer.dispose();
  91277. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  91278. }
  91279. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  91280. this._lineShader.dispose();
  91281. };
  91282. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  91283. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  91284. return 0;
  91285. }
  91286. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  91287. return 1;
  91288. }
  91289. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  91290. return 2;
  91291. }
  91292. return -1;
  91293. };
  91294. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  91295. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  91296. return 0;
  91297. }
  91298. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  91299. return 1;
  91300. }
  91301. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  91302. return 2;
  91303. }
  91304. return -1;
  91305. };
  91306. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  91307. var needToCreateLine;
  91308. if (edge === undefined) {
  91309. needToCreateLine = true;
  91310. }
  91311. else {
  91312. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  91313. needToCreateLine = dotProduct < this._epsilon;
  91314. }
  91315. if (needToCreateLine) {
  91316. var offset = this._linesPositions.length / 3;
  91317. var normal = p0.subtract(p1);
  91318. normal.normalize();
  91319. // Positions
  91320. this._linesPositions.push(p0.x);
  91321. this._linesPositions.push(p0.y);
  91322. this._linesPositions.push(p0.z);
  91323. this._linesPositions.push(p0.x);
  91324. this._linesPositions.push(p0.y);
  91325. this._linesPositions.push(p0.z);
  91326. this._linesPositions.push(p1.x);
  91327. this._linesPositions.push(p1.y);
  91328. this._linesPositions.push(p1.z);
  91329. this._linesPositions.push(p1.x);
  91330. this._linesPositions.push(p1.y);
  91331. this._linesPositions.push(p1.z);
  91332. // Normals
  91333. this._linesNormals.push(p1.x);
  91334. this._linesNormals.push(p1.y);
  91335. this._linesNormals.push(p1.z);
  91336. this._linesNormals.push(-1);
  91337. this._linesNormals.push(p1.x);
  91338. this._linesNormals.push(p1.y);
  91339. this._linesNormals.push(p1.z);
  91340. this._linesNormals.push(1);
  91341. this._linesNormals.push(p0.x);
  91342. this._linesNormals.push(p0.y);
  91343. this._linesNormals.push(p0.z);
  91344. this._linesNormals.push(-1);
  91345. this._linesNormals.push(p0.x);
  91346. this._linesNormals.push(p0.y);
  91347. this._linesNormals.push(p0.z);
  91348. this._linesNormals.push(1);
  91349. // Indices
  91350. this._linesIndices.push(offset);
  91351. this._linesIndices.push(offset + 1);
  91352. this._linesIndices.push(offset + 2);
  91353. this._linesIndices.push(offset);
  91354. this._linesIndices.push(offset + 2);
  91355. this._linesIndices.push(offset + 3);
  91356. }
  91357. };
  91358. EdgesRenderer.prototype._generateEdgesLines = function () {
  91359. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91360. var indices = this._source.getIndices();
  91361. if (!indices || !positions) {
  91362. return;
  91363. }
  91364. // First let's find adjacencies
  91365. var adjacencies = new Array();
  91366. var faceNormals = new Array();
  91367. var index;
  91368. var faceAdjacencies;
  91369. // Prepare faces
  91370. for (index = 0; index < indices.length; index += 3) {
  91371. faceAdjacencies = new FaceAdjacencies();
  91372. var p0Index = indices[index];
  91373. var p1Index = indices[index + 1];
  91374. var p2Index = indices[index + 2];
  91375. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91376. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91377. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91378. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91379. faceNormal.normalize();
  91380. faceNormals.push(faceNormal);
  91381. adjacencies.push(faceAdjacencies);
  91382. }
  91383. // Scan
  91384. for (index = 0; index < adjacencies.length; index++) {
  91385. faceAdjacencies = adjacencies[index];
  91386. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91387. var otherFaceAdjacencies = adjacencies[otherIndex];
  91388. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91389. break;
  91390. }
  91391. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91392. continue;
  91393. }
  91394. var otherP0 = indices[otherIndex * 3];
  91395. var otherP1 = indices[otherIndex * 3 + 1];
  91396. var otherP2 = indices[otherIndex * 3 + 2];
  91397. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91398. var otherEdgeIndex = 0;
  91399. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91400. continue;
  91401. }
  91402. switch (edgeIndex) {
  91403. case 0:
  91404. if (this._checkVerticesInsteadOfIndices) {
  91405. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91406. }
  91407. else {
  91408. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91409. }
  91410. break;
  91411. case 1:
  91412. if (this._checkVerticesInsteadOfIndices) {
  91413. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91414. }
  91415. else {
  91416. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91417. }
  91418. break;
  91419. case 2:
  91420. if (this._checkVerticesInsteadOfIndices) {
  91421. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91422. }
  91423. else {
  91424. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91425. }
  91426. break;
  91427. }
  91428. if (otherEdgeIndex === -1) {
  91429. continue;
  91430. }
  91431. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91432. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91433. faceAdjacencies.edgesConnectedCount++;
  91434. otherFaceAdjacencies.edgesConnectedCount++;
  91435. if (faceAdjacencies.edgesConnectedCount === 3) {
  91436. break;
  91437. }
  91438. }
  91439. }
  91440. }
  91441. // Create lines
  91442. for (index = 0; index < adjacencies.length; index++) {
  91443. // 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
  91444. var current = adjacencies[index];
  91445. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91446. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91447. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91448. }
  91449. // Merge into a single mesh
  91450. var engine = this._source.getScene().getEngine();
  91451. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91452. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91453. this._ib = engine.createIndexBuffer(this._linesIndices);
  91454. this._indicesCount = this._linesIndices.length;
  91455. };
  91456. EdgesRenderer.prototype.render = function () {
  91457. var scene = this._source.getScene();
  91458. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91459. return;
  91460. }
  91461. var engine = scene.getEngine();
  91462. this._lineShader._preBind();
  91463. // VBOs
  91464. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91465. scene.resetCachedMaterial();
  91466. this._lineShader.setColor4("color", this._source.edgesColor);
  91467. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91468. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91469. }
  91470. else {
  91471. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91472. }
  91473. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91474. this._lineShader.bind(this._source.getWorldMatrix());
  91475. // Draw order
  91476. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91477. this._lineShader.unbind();
  91478. engine.setDepthWrite(true);
  91479. };
  91480. return EdgesRenderer;
  91481. }());
  91482. BABYLON.EdgesRenderer = EdgesRenderer;
  91483. })(BABYLON || (BABYLON = {}));
  91484. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91485. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91486. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91487. s = arguments[i];
  91488. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91489. t[p] = s[p];
  91490. }
  91491. return t;
  91492. };
  91493. var BABYLON;
  91494. (function (BABYLON) {
  91495. /**
  91496. * The effect layer Helps adding post process effect blended with the main pass.
  91497. *
  91498. * This can be for instance use to generate glow or higlight effects on the scene.
  91499. *
  91500. * The effect layer class can not be used directly and is intented to inherited from to be
  91501. * customized per effects.
  91502. */
  91503. var EffectLayer = /** @class */ (function () {
  91504. /**
  91505. * Instantiates a new effect Layer and references it in the scene.
  91506. * @param name The name of the layer
  91507. * @param scene The scene to use the layer in
  91508. */
  91509. function EffectLayer(
  91510. /** The Friendly of the effect in the scene */
  91511. name, scene) {
  91512. this._vertexBuffers = {};
  91513. this._maxSize = 0;
  91514. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91515. this._shouldRender = true;
  91516. this._postProcesses = [];
  91517. this._textures = [];
  91518. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91519. /**
  91520. * The clear color of the texture used to generate the glow map.
  91521. */
  91522. this.neutralColor = new BABYLON.Color4();
  91523. /**
  91524. * Specifies wether the highlight layer is enabled or not.
  91525. */
  91526. this.isEnabled = true;
  91527. /**
  91528. * An event triggered when the effect layer has been disposed.
  91529. */
  91530. this.onDisposeObservable = new BABYLON.Observable();
  91531. /**
  91532. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91533. */
  91534. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91535. /**
  91536. * An event triggered when the generated texture is being merged in the scene.
  91537. */
  91538. this.onBeforeComposeObservable = new BABYLON.Observable();
  91539. /**
  91540. * An event triggered when the generated texture has been merged in the scene.
  91541. */
  91542. this.onAfterComposeObservable = new BABYLON.Observable();
  91543. /**
  91544. * An event triggered when the efffect layer changes its size.
  91545. */
  91546. this.onSizeChangedObservable = new BABYLON.Observable();
  91547. this.name = name;
  91548. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91549. this._engine = scene.getEngine();
  91550. this._maxSize = this._engine.getCaps().maxTextureSize;
  91551. this._scene.effectLayers.push(this);
  91552. // Generate Buffers
  91553. this._generateIndexBuffer();
  91554. this._genrateVertexBuffer();
  91555. }
  91556. Object.defineProperty(EffectLayer.prototype, "camera", {
  91557. /**
  91558. * Gets the camera attached to the layer.
  91559. */
  91560. get: function () {
  91561. return this._effectLayerOptions.camera;
  91562. },
  91563. enumerable: true,
  91564. configurable: true
  91565. });
  91566. /**
  91567. * Initializes the effect layer with the required options.
  91568. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91569. */
  91570. EffectLayer.prototype._init = function (options) {
  91571. // Adapt options
  91572. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91573. this._setMainTextureSize();
  91574. this._createMainTexture();
  91575. this._createTextureAndPostProcesses();
  91576. this._mergeEffect = this._createMergeEffect();
  91577. };
  91578. /**
  91579. * Generates the index buffer of the full screen quad blending to the main canvas.
  91580. */
  91581. EffectLayer.prototype._generateIndexBuffer = function () {
  91582. // Indices
  91583. var indices = [];
  91584. indices.push(0);
  91585. indices.push(1);
  91586. indices.push(2);
  91587. indices.push(0);
  91588. indices.push(2);
  91589. indices.push(3);
  91590. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91591. };
  91592. /**
  91593. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91594. */
  91595. EffectLayer.prototype._genrateVertexBuffer = function () {
  91596. // VBO
  91597. var vertices = [];
  91598. vertices.push(1, 1);
  91599. vertices.push(-1, 1);
  91600. vertices.push(-1, -1);
  91601. vertices.push(1, -1);
  91602. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91603. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91604. };
  91605. /**
  91606. * Sets the main texture desired size which is the closest power of two
  91607. * of the engine canvas size.
  91608. */
  91609. EffectLayer.prototype._setMainTextureSize = function () {
  91610. if (this._effectLayerOptions.mainTextureFixedSize) {
  91611. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91612. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91613. }
  91614. else {
  91615. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91616. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91617. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91618. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91619. }
  91620. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91621. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91622. };
  91623. /**
  91624. * Creates the main texture for the effect layer.
  91625. */
  91626. EffectLayer.prototype._createMainTexture = function () {
  91627. var _this = this;
  91628. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91629. width: this._mainTextureDesiredSize.width,
  91630. height: this._mainTextureDesiredSize.height
  91631. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91632. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91633. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91634. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91635. this._mainTexture.anisotropicFilteringLevel = 1;
  91636. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91637. this._mainTexture.renderParticles = false;
  91638. this._mainTexture.renderList = null;
  91639. this._mainTexture.ignoreCameraViewport = true;
  91640. // Custom render function
  91641. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91642. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91643. var index;
  91644. var engine = _this._scene.getEngine();
  91645. if (depthOnlySubMeshes.length) {
  91646. engine.setColorWrite(false);
  91647. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91648. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91649. }
  91650. engine.setColorWrite(true);
  91651. }
  91652. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91653. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91654. }
  91655. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91656. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91657. }
  91658. for (index = 0; index < transparentSubMeshes.length; index++) {
  91659. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91660. }
  91661. };
  91662. this._mainTexture.onClearObservable.add(function (engine) {
  91663. engine.clear(_this.neutralColor, true, true, true);
  91664. });
  91665. };
  91666. /**
  91667. * Checks for the readiness of the element composing the layer.
  91668. * @param subMesh the mesh to check for
  91669. * @param useInstances specify wether or not to use instances to render the mesh
  91670. * @param emissiveTexture the associated emissive texture used to generate the glow
  91671. * @return true if ready otherwise, false
  91672. */
  91673. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91674. var material = subMesh.getMaterial();
  91675. if (!material) {
  91676. return false;
  91677. }
  91678. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91679. return false;
  91680. }
  91681. var defines = [];
  91682. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91683. var mesh = subMesh.getMesh();
  91684. var uv1 = false;
  91685. var uv2 = false;
  91686. // Alpha test
  91687. if (material && material.needAlphaTesting()) {
  91688. var alphaTexture = material.getAlphaTestTexture();
  91689. if (alphaTexture) {
  91690. defines.push("#define ALPHATEST");
  91691. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91692. alphaTexture.coordinatesIndex === 1) {
  91693. defines.push("#define DIFFUSEUV2");
  91694. uv2 = true;
  91695. }
  91696. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91697. defines.push("#define DIFFUSEUV1");
  91698. uv1 = true;
  91699. }
  91700. }
  91701. }
  91702. // Emissive
  91703. if (emissiveTexture) {
  91704. defines.push("#define EMISSIVE");
  91705. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91706. emissiveTexture.coordinatesIndex === 1) {
  91707. defines.push("#define EMISSIVEUV2");
  91708. uv2 = true;
  91709. }
  91710. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91711. defines.push("#define EMISSIVEUV1");
  91712. uv1 = true;
  91713. }
  91714. }
  91715. if (uv1) {
  91716. attribs.push(BABYLON.VertexBuffer.UVKind);
  91717. defines.push("#define UV1");
  91718. }
  91719. if (uv2) {
  91720. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91721. defines.push("#define UV2");
  91722. }
  91723. // Bones
  91724. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91725. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91726. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91727. if (mesh.numBoneInfluencers > 4) {
  91728. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91729. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91730. }
  91731. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91732. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91733. }
  91734. else {
  91735. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91736. }
  91737. // Morph targets
  91738. var manager = mesh.morphTargetManager;
  91739. var morphInfluencers = 0;
  91740. if (manager) {
  91741. if (manager.numInfluencers > 0) {
  91742. defines.push("#define MORPHTARGETS");
  91743. morphInfluencers = manager.numInfluencers;
  91744. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91745. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91746. }
  91747. }
  91748. // Instances
  91749. if (useInstances) {
  91750. defines.push("#define INSTANCES");
  91751. attribs.push("world0");
  91752. attribs.push("world1");
  91753. attribs.push("world2");
  91754. attribs.push("world3");
  91755. }
  91756. // Get correct effect
  91757. var join = defines.join("\n");
  91758. if (this._cachedDefines !== join) {
  91759. this._cachedDefines = join;
  91760. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91761. }
  91762. return this._effectLayerMapGenerationEffect.isReady();
  91763. };
  91764. /**
  91765. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91766. */
  91767. EffectLayer.prototype.render = function () {
  91768. var currentEffect = this._mergeEffect;
  91769. // Check
  91770. if (!currentEffect.isReady())
  91771. return;
  91772. for (var i = 0; i < this._postProcesses.length; i++) {
  91773. if (!this._postProcesses[i].isReady()) {
  91774. return;
  91775. }
  91776. }
  91777. var engine = this._scene.getEngine();
  91778. this.onBeforeComposeObservable.notifyObservers(this);
  91779. // Render
  91780. engine.enableEffect(currentEffect);
  91781. engine.setState(false);
  91782. // VBOs
  91783. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91784. // Cache
  91785. var previousAlphaMode = engine.getAlphaMode();
  91786. // Go Blend.
  91787. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91788. // Blends the map on the main canvas.
  91789. this._internalRender(currentEffect);
  91790. // Restore Alpha
  91791. engine.setAlphaMode(previousAlphaMode);
  91792. this.onAfterComposeObservable.notifyObservers(this);
  91793. // Handle size changes.
  91794. var size = this._mainTexture.getSize();
  91795. this._setMainTextureSize();
  91796. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91797. // Recreate RTT and post processes on size change.
  91798. this.onSizeChangedObservable.notifyObservers(this);
  91799. this._disposeTextureAndPostProcesses();
  91800. this._createMainTexture();
  91801. this._createTextureAndPostProcesses();
  91802. }
  91803. };
  91804. /**
  91805. * Determine if a given mesh will be used in the current effect.
  91806. * @param mesh mesh to test
  91807. * @returns true if the mesh will be used
  91808. */
  91809. EffectLayer.prototype.hasMesh = function (mesh) {
  91810. return true;
  91811. };
  91812. /**
  91813. * Returns true if the layer contains information to display, otherwise false.
  91814. * @returns true if the glow layer should be rendered
  91815. */
  91816. EffectLayer.prototype.shouldRender = function () {
  91817. return this.isEnabled && this._shouldRender;
  91818. };
  91819. /**
  91820. * Returns true if the mesh should render, otherwise false.
  91821. * @param mesh The mesh to render
  91822. * @returns true if it should render otherwise false
  91823. */
  91824. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91825. return true;
  91826. };
  91827. /**
  91828. * Returns true if the mesh should render, otherwise false.
  91829. * @param mesh The mesh to render
  91830. * @returns true if it should render otherwise false
  91831. */
  91832. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91833. return true;
  91834. };
  91835. /**
  91836. * Renders the submesh passed in parameter to the generation map.
  91837. */
  91838. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91839. var _this = this;
  91840. if (!this.shouldRender()) {
  91841. return;
  91842. }
  91843. var material = subMesh.getMaterial();
  91844. var mesh = subMesh.getRenderingMesh();
  91845. var scene = this._scene;
  91846. var engine = scene.getEngine();
  91847. if (!material) {
  91848. return;
  91849. }
  91850. // Do not block in blend mode.
  91851. if (material.needAlphaBlendingForMesh(mesh)) {
  91852. return;
  91853. }
  91854. // Culling
  91855. engine.setState(material.backFaceCulling);
  91856. // Managing instances
  91857. var batch = mesh._getInstancesRenderList(subMesh._id);
  91858. if (batch.mustReturn) {
  91859. return;
  91860. }
  91861. // Early Exit per mesh
  91862. if (!this._shouldRenderMesh(mesh)) {
  91863. return;
  91864. }
  91865. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91866. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91867. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91868. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91869. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91870. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91871. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91872. // Alpha test
  91873. if (material && material.needAlphaTesting()) {
  91874. var alphaTexture = material.getAlphaTestTexture();
  91875. if (alphaTexture) {
  91876. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91877. var textureMatrix = alphaTexture.getTextureMatrix();
  91878. if (textureMatrix) {
  91879. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91880. }
  91881. }
  91882. }
  91883. // Glow emissive only
  91884. if (this._emissiveTextureAndColor.texture) {
  91885. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91886. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91887. }
  91888. // Bones
  91889. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91890. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91891. }
  91892. // Morph targets
  91893. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91894. // Draw
  91895. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91896. }
  91897. else {
  91898. // Need to reset refresh rate of the shadowMap
  91899. this._mainTexture.resetRefreshCounter();
  91900. }
  91901. };
  91902. /**
  91903. * Rebuild the required buffers.
  91904. * @hidden Internal use only.
  91905. */
  91906. EffectLayer.prototype._rebuild = function () {
  91907. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91908. if (vb) {
  91909. vb._rebuild();
  91910. }
  91911. this._generateIndexBuffer();
  91912. };
  91913. /**
  91914. * Dispose only the render target textures and post process.
  91915. */
  91916. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91917. this._mainTexture.dispose();
  91918. for (var i = 0; i < this._postProcesses.length; i++) {
  91919. if (this._postProcesses[i]) {
  91920. this._postProcesses[i].dispose();
  91921. }
  91922. }
  91923. this._postProcesses = [];
  91924. for (var i = 0; i < this._textures.length; i++) {
  91925. if (this._textures[i]) {
  91926. this._textures[i].dispose();
  91927. }
  91928. }
  91929. this._textures = [];
  91930. };
  91931. /**
  91932. * Dispose the highlight layer and free resources.
  91933. */
  91934. EffectLayer.prototype.dispose = function () {
  91935. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91936. if (vertexBuffer) {
  91937. vertexBuffer.dispose();
  91938. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91939. }
  91940. if (this._indexBuffer) {
  91941. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91942. this._indexBuffer = null;
  91943. }
  91944. // Clean textures and post processes
  91945. this._disposeTextureAndPostProcesses();
  91946. // Remove from scene
  91947. var index = this._scene.effectLayers.indexOf(this, 0);
  91948. if (index > -1) {
  91949. this._scene.effectLayers.splice(index, 1);
  91950. }
  91951. // Callback
  91952. this.onDisposeObservable.notifyObservers(this);
  91953. this.onDisposeObservable.clear();
  91954. this.onBeforeRenderMainTextureObservable.clear();
  91955. this.onBeforeComposeObservable.clear();
  91956. this.onAfterComposeObservable.clear();
  91957. this.onSizeChangedObservable.clear();
  91958. };
  91959. /**
  91960. * Gets the class name of the effect layer
  91961. * @returns the string with the class name of the effect layer
  91962. */
  91963. EffectLayer.prototype.getClassName = function () {
  91964. return "EffectLayer";
  91965. };
  91966. /**
  91967. * Creates an effect layer from parsed effect layer data
  91968. * @param parsedEffectLayer defines effect layer data
  91969. * @param scene defines the current scene
  91970. * @param rootUrl defines the root URL containing the effect layer information
  91971. * @returns a parsed effect Layer
  91972. */
  91973. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91974. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91975. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91976. };
  91977. __decorate([
  91978. BABYLON.serialize()
  91979. ], EffectLayer.prototype, "name", void 0);
  91980. __decorate([
  91981. BABYLON.serializeAsColor4()
  91982. ], EffectLayer.prototype, "neutralColor", void 0);
  91983. __decorate([
  91984. BABYLON.serialize()
  91985. ], EffectLayer.prototype, "isEnabled", void 0);
  91986. __decorate([
  91987. BABYLON.serializeAsCameraReference()
  91988. ], EffectLayer.prototype, "camera", null);
  91989. return EffectLayer;
  91990. }());
  91991. BABYLON.EffectLayer = EffectLayer;
  91992. })(BABYLON || (BABYLON = {}));
  91993. //# sourceMappingURL=babylon.effectLayer.js.map
  91994. var BABYLON;
  91995. (function (BABYLON) {
  91996. /**
  91997. * Special Glow Blur post process only blurring the alpha channel
  91998. * It enforces keeping the most luminous color in the color channel.
  91999. */
  92000. var GlowBlurPostProcess = /** @class */ (function (_super) {
  92001. __extends(GlowBlurPostProcess, _super);
  92002. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  92003. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  92004. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  92005. _this.direction = direction;
  92006. _this.kernel = kernel;
  92007. _this.onApplyObservable.add(function (effect) {
  92008. effect.setFloat2("screenSize", _this.width, _this.height);
  92009. effect.setVector2("direction", _this.direction);
  92010. effect.setFloat("blurWidth", _this.kernel);
  92011. });
  92012. return _this;
  92013. }
  92014. return GlowBlurPostProcess;
  92015. }(BABYLON.PostProcess));
  92016. /**
  92017. * The highlight layer Helps adding a glow effect around a mesh.
  92018. *
  92019. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92020. * glowy meshes to your scene.
  92021. *
  92022. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  92023. */
  92024. var HighlightLayer = /** @class */ (function (_super) {
  92025. __extends(HighlightLayer, _super);
  92026. /**
  92027. * Instantiates a new highlight Layer and references it to the scene..
  92028. * @param name The name of the layer
  92029. * @param scene The scene to use the layer in
  92030. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  92031. */
  92032. function HighlightLayer(name, scene, options) {
  92033. var _this = _super.call(this, name, scene) || this;
  92034. _this.name = name;
  92035. /**
  92036. * Specifies whether or not the inner glow is ACTIVE in the layer.
  92037. */
  92038. _this.innerGlow = true;
  92039. /**
  92040. * Specifies whether or not the outer glow is ACTIVE in the layer.
  92041. */
  92042. _this.outerGlow = true;
  92043. /**
  92044. * An event triggered when the highlight layer is being blurred.
  92045. */
  92046. _this.onBeforeBlurObservable = new BABYLON.Observable();
  92047. /**
  92048. * An event triggered when the highlight layer has been blurred.
  92049. */
  92050. _this.onAfterBlurObservable = new BABYLON.Observable();
  92051. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  92052. _this._meshes = {};
  92053. _this._excludedMeshes = {};
  92054. _this.neutralColor = HighlightLayer.NeutralColor;
  92055. // Warn on stencil
  92056. if (!_this._engine.isStencilEnable) {
  92057. 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 }");
  92058. }
  92059. // Adapt options
  92060. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  92061. // Initialize the layer
  92062. _this._init({
  92063. alphaBlendingMode: _this._options.alphaBlendingMode,
  92064. camera: _this._options.camera,
  92065. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92066. mainTextureRatio: _this._options.mainTextureRatio
  92067. });
  92068. // Do not render as long as no meshes have been added
  92069. _this._shouldRender = false;
  92070. return _this;
  92071. }
  92072. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  92073. /**
  92074. * Gets the horizontal size of the blur.
  92075. */
  92076. get: function () {
  92077. return this._horizontalBlurPostprocess.kernel;
  92078. },
  92079. /**
  92080. * Specifies the horizontal size of the blur.
  92081. */
  92082. set: function (value) {
  92083. this._horizontalBlurPostprocess.kernel = value;
  92084. },
  92085. enumerable: true,
  92086. configurable: true
  92087. });
  92088. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  92089. /**
  92090. * Gets the vertical size of the blur.
  92091. */
  92092. get: function () {
  92093. return this._verticalBlurPostprocess.kernel;
  92094. },
  92095. /**
  92096. * Specifies the vertical size of the blur.
  92097. */
  92098. set: function (value) {
  92099. this._verticalBlurPostprocess.kernel = value;
  92100. },
  92101. enumerable: true,
  92102. configurable: true
  92103. });
  92104. /**
  92105. * Get the effect name of the layer.
  92106. * @return The effect name
  92107. */
  92108. HighlightLayer.prototype.getEffectName = function () {
  92109. return HighlightLayer.EffectName;
  92110. };
  92111. /**
  92112. * Create the merge effect. This is the shader use to blit the information back
  92113. * to the main canvas at the end of the scene rendering.
  92114. */
  92115. HighlightLayer.prototype._createMergeEffect = function () {
  92116. // Effect
  92117. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  92118. };
  92119. /**
  92120. * Creates the render target textures and post processes used in the highlight layer.
  92121. */
  92122. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  92123. var _this = this;
  92124. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  92125. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  92126. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92127. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92128. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  92129. width: blurTextureWidth,
  92130. height: blurTextureHeight
  92131. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92132. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92133. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92134. this._blurTexture.anisotropicFilteringLevel = 16;
  92135. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  92136. this._blurTexture.renderParticles = false;
  92137. this._blurTexture.ignoreCameraViewport = true;
  92138. this._textures = [this._blurTexture];
  92139. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  92140. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92141. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  92142. effect.setTexture("textureSampler", _this._mainTexture);
  92143. });
  92144. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92145. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92146. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92147. });
  92148. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92149. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  92150. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92151. });
  92152. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92153. }
  92154. else {
  92155. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  92156. width: blurTextureWidth,
  92157. height: blurTextureHeight
  92158. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92159. this._horizontalBlurPostprocess.width = blurTextureWidth;
  92160. this._horizontalBlurPostprocess.height = blurTextureHeight;
  92161. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92162. effect.setTexture("textureSampler", _this._mainTexture);
  92163. });
  92164. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  92165. width: blurTextureWidth,
  92166. height: blurTextureHeight
  92167. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92168. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92169. }
  92170. this._mainTexture.onAfterUnbindObservable.add(function () {
  92171. _this.onBeforeBlurObservable.notifyObservers(_this);
  92172. var internalTexture = _this._blurTexture.getInternalTexture();
  92173. if (internalTexture) {
  92174. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  92175. }
  92176. _this.onAfterBlurObservable.notifyObservers(_this);
  92177. });
  92178. // Prevent autoClear.
  92179. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92180. };
  92181. /**
  92182. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92183. */
  92184. HighlightLayer.prototype.needStencil = function () {
  92185. return true;
  92186. };
  92187. /**
  92188. * Checks for the readiness of the element composing the layer.
  92189. * @param subMesh the mesh to check for
  92190. * @param useInstances specify wether or not to use instances to render the mesh
  92191. * @param emissiveTexture the associated emissive texture used to generate the glow
  92192. * @return true if ready otherwise, false
  92193. */
  92194. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  92195. var material = subMesh.getMaterial();
  92196. var mesh = subMesh.getRenderingMesh();
  92197. if (!material || !mesh || !this._meshes) {
  92198. return false;
  92199. }
  92200. var emissiveTexture = null;
  92201. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92202. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92203. emissiveTexture = material.emissiveTexture;
  92204. }
  92205. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92206. };
  92207. /**
  92208. * Implementation specific of rendering the generating effect on the main canvas.
  92209. * @param effect The effect used to render through
  92210. */
  92211. HighlightLayer.prototype._internalRender = function (effect) {
  92212. // Texture
  92213. effect.setTexture("textureSampler", this._blurTexture);
  92214. // Cache
  92215. var engine = this._engine;
  92216. var previousStencilBuffer = engine.getStencilBuffer();
  92217. var previousStencilFunction = engine.getStencilFunction();
  92218. var previousStencilMask = engine.getStencilMask();
  92219. var previousStencilOperationPass = engine.getStencilOperationPass();
  92220. var previousStencilOperationFail = engine.getStencilOperationFail();
  92221. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  92222. var previousStencilReference = engine.getStencilFunctionReference();
  92223. // Stencil operations
  92224. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  92225. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  92226. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  92227. // Draw order
  92228. engine.setStencilMask(0x00);
  92229. engine.setStencilBuffer(true);
  92230. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  92231. // 2 passes inner outer
  92232. if (this.outerGlow) {
  92233. effect.setFloat("offset", 0);
  92234. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  92235. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92236. }
  92237. if (this.innerGlow) {
  92238. effect.setFloat("offset", 1);
  92239. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  92240. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92241. }
  92242. // Restore Cache
  92243. engine.setStencilFunction(previousStencilFunction);
  92244. engine.setStencilMask(previousStencilMask);
  92245. engine.setStencilBuffer(previousStencilBuffer);
  92246. engine.setStencilOperationPass(previousStencilOperationPass);
  92247. engine.setStencilOperationFail(previousStencilOperationFail);
  92248. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  92249. engine.setStencilFunctionReference(previousStencilReference);
  92250. };
  92251. /**
  92252. * Returns true if the layer contains information to display, otherwise false.
  92253. */
  92254. HighlightLayer.prototype.shouldRender = function () {
  92255. if (_super.prototype.shouldRender.call(this)) {
  92256. return this._meshes ? true : false;
  92257. }
  92258. return false;
  92259. };
  92260. /**
  92261. * Returns true if the mesh should render, otherwise false.
  92262. * @param mesh The mesh to render
  92263. * @returns true if it should render otherwise false
  92264. */
  92265. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  92266. // Excluded Mesh
  92267. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  92268. return false;
  92269. }
  92270. ;
  92271. return true;
  92272. };
  92273. /**
  92274. * Sets the required values for both the emissive texture and and the main color.
  92275. */
  92276. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92277. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92278. if (highlightLayerMesh) {
  92279. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  92280. }
  92281. else {
  92282. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92283. }
  92284. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92285. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92286. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  92287. }
  92288. else {
  92289. this._emissiveTextureAndColor.texture = null;
  92290. }
  92291. };
  92292. /**
  92293. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  92294. * @param mesh The mesh to exclude from the highlight layer
  92295. */
  92296. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  92297. if (!this._excludedMeshes) {
  92298. return;
  92299. }
  92300. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92301. if (!meshExcluded) {
  92302. this._excludedMeshes[mesh.uniqueId] = {
  92303. mesh: mesh,
  92304. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  92305. mesh.getEngine().setStencilBuffer(false);
  92306. }),
  92307. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  92308. mesh.getEngine().setStencilBuffer(true);
  92309. }),
  92310. };
  92311. }
  92312. };
  92313. /**
  92314. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  92315. * @param mesh The mesh to highlight
  92316. */
  92317. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  92318. if (!this._excludedMeshes) {
  92319. return;
  92320. }
  92321. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92322. if (meshExcluded) {
  92323. if (meshExcluded.beforeRender) {
  92324. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92325. }
  92326. if (meshExcluded.afterRender) {
  92327. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92328. }
  92329. }
  92330. this._excludedMeshes[mesh.uniqueId] = null;
  92331. };
  92332. /**
  92333. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92334. * @param mesh mesh to test
  92335. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92336. */
  92337. HighlightLayer.prototype.hasMesh = function (mesh) {
  92338. if (!this._meshes) {
  92339. return false;
  92340. }
  92341. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92342. };
  92343. /**
  92344. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92345. * @param mesh The mesh to highlight
  92346. * @param color The color of the highlight
  92347. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92348. */
  92349. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92350. var _this = this;
  92351. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92352. if (!this._meshes) {
  92353. return;
  92354. }
  92355. var meshHighlight = this._meshes[mesh.uniqueId];
  92356. if (meshHighlight) {
  92357. meshHighlight.color = color;
  92358. }
  92359. else {
  92360. this._meshes[mesh.uniqueId] = {
  92361. mesh: mesh,
  92362. color: color,
  92363. // Lambda required for capture due to Observable this context
  92364. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92365. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92366. _this._defaultStencilReference(mesh);
  92367. }
  92368. else {
  92369. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92370. }
  92371. }),
  92372. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92373. glowEmissiveOnly: glowEmissiveOnly
  92374. };
  92375. }
  92376. this._shouldRender = true;
  92377. };
  92378. /**
  92379. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92380. * @param mesh The mesh to highlight
  92381. */
  92382. HighlightLayer.prototype.removeMesh = function (mesh) {
  92383. if (!this._meshes) {
  92384. return;
  92385. }
  92386. var meshHighlight = this._meshes[mesh.uniqueId];
  92387. if (meshHighlight) {
  92388. if (meshHighlight.observerHighlight) {
  92389. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92390. }
  92391. if (meshHighlight.observerDefault) {
  92392. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92393. }
  92394. delete this._meshes[mesh.uniqueId];
  92395. }
  92396. this._shouldRender = false;
  92397. for (var meshHighlightToCheck in this._meshes) {
  92398. if (this._meshes[meshHighlightToCheck]) {
  92399. this._shouldRender = true;
  92400. break;
  92401. }
  92402. }
  92403. };
  92404. /**
  92405. * Force the stencil to the normal expected value for none glowing parts
  92406. */
  92407. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92408. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92409. };
  92410. /**
  92411. * Free any resources and references associated to a mesh.
  92412. * Internal use
  92413. * @param mesh The mesh to free.
  92414. */
  92415. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92416. this.removeMesh(mesh);
  92417. this.removeExcludedMesh(mesh);
  92418. };
  92419. /**
  92420. * Dispose the highlight layer and free resources.
  92421. */
  92422. HighlightLayer.prototype.dispose = function () {
  92423. if (this._meshes) {
  92424. // Clean mesh references
  92425. for (var id in this._meshes) {
  92426. var meshHighlight = this._meshes[id];
  92427. if (meshHighlight && meshHighlight.mesh) {
  92428. if (meshHighlight.observerHighlight) {
  92429. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92430. }
  92431. if (meshHighlight.observerDefault) {
  92432. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92433. }
  92434. }
  92435. }
  92436. this._meshes = null;
  92437. }
  92438. if (this._excludedMeshes) {
  92439. for (var id in this._excludedMeshes) {
  92440. var meshHighlight = this._excludedMeshes[id];
  92441. if (meshHighlight) {
  92442. if (meshHighlight.beforeRender) {
  92443. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92444. }
  92445. if (meshHighlight.afterRender) {
  92446. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92447. }
  92448. }
  92449. }
  92450. this._excludedMeshes = null;
  92451. }
  92452. _super.prototype.dispose.call(this);
  92453. };
  92454. /**
  92455. * Gets the class name of the effect layer
  92456. * @returns the string with the class name of the effect layer
  92457. */
  92458. HighlightLayer.prototype.getClassName = function () {
  92459. return "HighlightLayer";
  92460. };
  92461. /**
  92462. * Serializes this Highlight layer
  92463. * @returns a serialized Highlight layer object
  92464. */
  92465. HighlightLayer.prototype.serialize = function () {
  92466. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92467. serializationObject.customType = "BABYLON.HighlightLayer";
  92468. // Highlighted meshes
  92469. serializationObject.meshes = [];
  92470. if (this._meshes) {
  92471. for (var m in this._meshes) {
  92472. var mesh = this._meshes[m];
  92473. if (mesh) {
  92474. serializationObject.meshes.push({
  92475. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92476. color: mesh.color.asArray(),
  92477. meshId: mesh.mesh.id
  92478. });
  92479. }
  92480. }
  92481. }
  92482. // Excluded meshes
  92483. serializationObject.excludedMeshes = [];
  92484. if (this._excludedMeshes) {
  92485. for (var e in this._excludedMeshes) {
  92486. var excludedMesh = this._excludedMeshes[e];
  92487. if (excludedMesh) {
  92488. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92489. }
  92490. }
  92491. }
  92492. return serializationObject;
  92493. };
  92494. /**
  92495. * Creates a Highlight layer from parsed Highlight layer data
  92496. * @param parsedHightlightLayer defines the Highlight layer data
  92497. * @param scene defines the current scene
  92498. * @param rootUrl defines the root URL containing the Highlight layer information
  92499. * @returns a parsed Highlight layer
  92500. */
  92501. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92502. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92503. var index;
  92504. // Excluded meshes
  92505. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92506. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92507. if (mesh) {
  92508. hl.addExcludedMesh(mesh);
  92509. }
  92510. }
  92511. // Included meshes
  92512. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92513. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92514. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92515. if (mesh) {
  92516. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92517. }
  92518. }
  92519. return hl;
  92520. };
  92521. /**
  92522. * Effect Name of the highlight layer.
  92523. */
  92524. HighlightLayer.EffectName = "HighlightLayer";
  92525. /**
  92526. * The neutral color used during the preparation of the glow effect.
  92527. * This is black by default as the blend operation is a blend operation.
  92528. */
  92529. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92530. /**
  92531. * Stencil value used for glowing meshes.
  92532. */
  92533. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92534. /**
  92535. * Stencil value used for the other meshes in the scene.
  92536. */
  92537. HighlightLayer.NormalMeshStencilReference = 0x01;
  92538. __decorate([
  92539. BABYLON.serialize()
  92540. ], HighlightLayer.prototype, "innerGlow", void 0);
  92541. __decorate([
  92542. BABYLON.serialize()
  92543. ], HighlightLayer.prototype, "outerGlow", void 0);
  92544. __decorate([
  92545. BABYLON.serialize()
  92546. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92547. __decorate([
  92548. BABYLON.serialize()
  92549. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92550. __decorate([
  92551. BABYLON.serialize("options")
  92552. ], HighlightLayer.prototype, "_options", void 0);
  92553. return HighlightLayer;
  92554. }(BABYLON.EffectLayer));
  92555. BABYLON.HighlightLayer = HighlightLayer;
  92556. })(BABYLON || (BABYLON = {}));
  92557. //# sourceMappingURL=babylon.highlightLayer.js.map
  92558. var BABYLON;
  92559. (function (BABYLON) {
  92560. /**
  92561. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92562. *
  92563. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92564. * glowy meshes to your scene.
  92565. *
  92566. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92567. */
  92568. var GlowLayer = /** @class */ (function (_super) {
  92569. __extends(GlowLayer, _super);
  92570. /**
  92571. * Instantiates a new glow Layer and references it to the scene.
  92572. * @param name The name of the layer
  92573. * @param scene The scene to use the layer in
  92574. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92575. */
  92576. function GlowLayer(name, scene, options) {
  92577. var _this = _super.call(this, name, scene) || this;
  92578. _this._intensity = 1.0;
  92579. _this._includedOnlyMeshes = [];
  92580. _this._excludedMeshes = [];
  92581. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92582. // Adapt options
  92583. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92584. // Initialize the layer
  92585. _this._init({
  92586. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92587. camera: _this._options.camera,
  92588. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92589. mainTextureRatio: _this._options.mainTextureRatio
  92590. });
  92591. return _this;
  92592. }
  92593. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92594. /**
  92595. * Gets the kernel size of the blur.
  92596. */
  92597. get: function () {
  92598. return this._horizontalBlurPostprocess1.kernel;
  92599. },
  92600. /**
  92601. * Sets the kernel size of the blur.
  92602. */
  92603. set: function (value) {
  92604. this._horizontalBlurPostprocess1.kernel = value;
  92605. this._verticalBlurPostprocess1.kernel = value;
  92606. this._horizontalBlurPostprocess2.kernel = value;
  92607. this._verticalBlurPostprocess2.kernel = value;
  92608. },
  92609. enumerable: true,
  92610. configurable: true
  92611. });
  92612. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92613. /**
  92614. * Gets the glow intensity.
  92615. */
  92616. get: function () {
  92617. return this._intensity;
  92618. },
  92619. /**
  92620. * Sets the glow intensity.
  92621. */
  92622. set: function (value) {
  92623. this._intensity = value;
  92624. },
  92625. enumerable: true,
  92626. configurable: true
  92627. });
  92628. /**
  92629. * Get the effect name of the layer.
  92630. * @return The effect name
  92631. */
  92632. GlowLayer.prototype.getEffectName = function () {
  92633. return GlowLayer.EffectName;
  92634. };
  92635. /**
  92636. * Create the merge effect. This is the shader use to blit the information back
  92637. * to the main canvas at the end of the scene rendering.
  92638. */
  92639. GlowLayer.prototype._createMergeEffect = function () {
  92640. // Effect
  92641. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92642. };
  92643. /**
  92644. * Creates the render target textures and post processes used in the glow layer.
  92645. */
  92646. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92647. var _this = this;
  92648. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92649. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92650. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92651. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92652. var textureType = 0;
  92653. if (this._engine.getCaps().textureHalfFloatRender) {
  92654. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92655. }
  92656. else {
  92657. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92658. }
  92659. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92660. width: blurTextureWidth,
  92661. height: blurTextureHeight
  92662. }, this._scene, false, true, textureType);
  92663. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92664. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92665. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92666. this._blurTexture1.renderParticles = false;
  92667. this._blurTexture1.ignoreCameraViewport = true;
  92668. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92669. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92670. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92671. width: blurTextureWidth2,
  92672. height: blurTextureHeight2
  92673. }, this._scene, false, true, textureType);
  92674. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92675. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92676. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92677. this._blurTexture2.renderParticles = false;
  92678. this._blurTexture2.ignoreCameraViewport = true;
  92679. this._textures = [this._blurTexture1, this._blurTexture2];
  92680. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92681. width: blurTextureWidth,
  92682. height: blurTextureHeight
  92683. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92684. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92685. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92686. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92687. effect.setTexture("textureSampler", _this._mainTexture);
  92688. });
  92689. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92690. width: blurTextureWidth,
  92691. height: blurTextureHeight
  92692. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92693. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92694. width: blurTextureWidth2,
  92695. height: blurTextureHeight2
  92696. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92697. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92698. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92699. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92700. effect.setTexture("textureSampler", _this._blurTexture1);
  92701. });
  92702. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92703. width: blurTextureWidth2,
  92704. height: blurTextureHeight2
  92705. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92706. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92707. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92708. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92709. this._mainTexture.samples = this._options.mainTextureSamples;
  92710. this._mainTexture.onAfterUnbindObservable.add(function () {
  92711. var internalTexture = _this._blurTexture1.getInternalTexture();
  92712. if (internalTexture) {
  92713. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92714. internalTexture = _this._blurTexture2.getInternalTexture();
  92715. if (internalTexture) {
  92716. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92717. }
  92718. }
  92719. });
  92720. // Prevent autoClear.
  92721. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92722. };
  92723. /**
  92724. * Checks for the readiness of the element composing the layer.
  92725. * @param subMesh the mesh to check for
  92726. * @param useInstances specify wether or not to use instances to render the mesh
  92727. * @param emissiveTexture the associated emissive texture used to generate the glow
  92728. * @return true if ready otherwise, false
  92729. */
  92730. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92731. var material = subMesh.getMaterial();
  92732. var mesh = subMesh.getRenderingMesh();
  92733. if (!material || !mesh) {
  92734. return false;
  92735. }
  92736. var emissiveTexture = material.emissiveTexture;
  92737. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92738. };
  92739. /**
  92740. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92741. */
  92742. GlowLayer.prototype.needStencil = function () {
  92743. return false;
  92744. };
  92745. /**
  92746. * Implementation specific of rendering the generating effect on the main canvas.
  92747. * @param effect The effect used to render through
  92748. */
  92749. GlowLayer.prototype._internalRender = function (effect) {
  92750. // Texture
  92751. effect.setTexture("textureSampler", this._blurTexture1);
  92752. effect.setTexture("textureSampler2", this._blurTexture2);
  92753. effect.setFloat("offset", this._intensity);
  92754. // Cache
  92755. var engine = this._engine;
  92756. var previousStencilBuffer = engine.getStencilBuffer();
  92757. // Draw order
  92758. engine.setStencilBuffer(false);
  92759. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92760. // Draw order
  92761. engine.setStencilBuffer(previousStencilBuffer);
  92762. };
  92763. /**
  92764. * Sets the required values for both the emissive texture and and the main color.
  92765. */
  92766. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92767. var textureLevel = 1.0;
  92768. if (this.customEmissiveTextureSelector) {
  92769. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92770. }
  92771. else {
  92772. if (material) {
  92773. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92774. if (this._emissiveTextureAndColor.texture) {
  92775. textureLevel = this._emissiveTextureAndColor.texture.level;
  92776. }
  92777. }
  92778. else {
  92779. this._emissiveTextureAndColor.texture = null;
  92780. }
  92781. }
  92782. if (this.customEmissiveColorSelector) {
  92783. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92784. }
  92785. else {
  92786. if (material.emissiveColor) {
  92787. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92788. }
  92789. else {
  92790. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92791. }
  92792. }
  92793. };
  92794. /**
  92795. * Returns true if the mesh should render, otherwise false.
  92796. * @param mesh The mesh to render
  92797. * @returns true if it should render otherwise false
  92798. */
  92799. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92800. return this.hasMesh(mesh);
  92801. };
  92802. /**
  92803. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92804. * @param mesh The mesh to exclude from the glow layer
  92805. */
  92806. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92807. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92808. this._excludedMeshes.push(mesh.uniqueId);
  92809. }
  92810. };
  92811. /**
  92812. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92813. * @param mesh The mesh to remove
  92814. */
  92815. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92816. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92817. if (index !== -1) {
  92818. this._excludedMeshes.splice(index, 1);
  92819. }
  92820. };
  92821. /**
  92822. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92823. * @param mesh The mesh to include in the glow layer
  92824. */
  92825. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92826. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92827. this._includedOnlyMeshes.push(mesh.uniqueId);
  92828. }
  92829. };
  92830. /**
  92831. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92832. * @param mesh The mesh to remove
  92833. */
  92834. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92835. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92836. if (index !== -1) {
  92837. this._includedOnlyMeshes.splice(index, 1);
  92838. }
  92839. };
  92840. /**
  92841. * Determine if a given mesh will be used in the glow layer
  92842. * @param mesh The mesh to test
  92843. * @returns true if the mesh will be highlighted by the current glow layer
  92844. */
  92845. GlowLayer.prototype.hasMesh = function (mesh) {
  92846. // Included Mesh
  92847. if (this._includedOnlyMeshes.length) {
  92848. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92849. }
  92850. ;
  92851. // Excluded Mesh
  92852. if (this._excludedMeshes.length) {
  92853. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92854. }
  92855. ;
  92856. return true;
  92857. };
  92858. /**
  92859. * Free any resources and references associated to a mesh.
  92860. * Internal use
  92861. * @param mesh The mesh to free.
  92862. */
  92863. GlowLayer.prototype._disposeMesh = function (mesh) {
  92864. this.removeIncludedOnlyMesh(mesh);
  92865. this.removeExcludedMesh(mesh);
  92866. };
  92867. /**
  92868. * Gets the class name of the effect layer
  92869. * @returns the string with the class name of the effect layer
  92870. */
  92871. GlowLayer.prototype.getClassName = function () {
  92872. return "GlowLayer";
  92873. };
  92874. /**
  92875. * Serializes this glow layer
  92876. * @returns a serialized glow layer object
  92877. */
  92878. GlowLayer.prototype.serialize = function () {
  92879. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92880. serializationObject.customType = "BABYLON.GlowLayer";
  92881. var index;
  92882. // Included meshes
  92883. serializationObject.includedMeshes = [];
  92884. if (this._includedOnlyMeshes.length) {
  92885. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92886. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92887. if (mesh) {
  92888. serializationObject.includedMeshes.push(mesh.id);
  92889. }
  92890. }
  92891. }
  92892. // Excluded meshes
  92893. serializationObject.excludedMeshes = [];
  92894. if (this._excludedMeshes.length) {
  92895. for (index = 0; index < this._excludedMeshes.length; index++) {
  92896. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92897. if (mesh) {
  92898. serializationObject.excludedMeshes.push(mesh.id);
  92899. }
  92900. }
  92901. }
  92902. return serializationObject;
  92903. };
  92904. /**
  92905. * Creates a Glow Layer from parsed glow layer data
  92906. * @param parsedGlowLayer defines glow layer data
  92907. * @param scene defines the current scene
  92908. * @param rootUrl defines the root URL containing the glow layer information
  92909. * @returns a parsed Glow Layer
  92910. */
  92911. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92912. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92913. var index;
  92914. // Excluded meshes
  92915. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92916. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92917. if (mesh) {
  92918. gl.addExcludedMesh(mesh);
  92919. }
  92920. }
  92921. // Included meshes
  92922. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92923. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92924. if (mesh) {
  92925. gl.addIncludedOnlyMesh(mesh);
  92926. }
  92927. }
  92928. return gl;
  92929. };
  92930. /**
  92931. * Effect Name of the layer.
  92932. */
  92933. GlowLayer.EffectName = "GlowLayer";
  92934. /**
  92935. * The default blur kernel size used for the glow.
  92936. */
  92937. GlowLayer.DefaultBlurKernelSize = 32;
  92938. /**
  92939. * The default texture size ratio used for the glow.
  92940. */
  92941. GlowLayer.DefaultTextureRatio = 0.5;
  92942. __decorate([
  92943. BABYLON.serialize()
  92944. ], GlowLayer.prototype, "blurKernelSize", null);
  92945. __decorate([
  92946. BABYLON.serialize()
  92947. ], GlowLayer.prototype, "intensity", null);
  92948. __decorate([
  92949. BABYLON.serialize("options")
  92950. ], GlowLayer.prototype, "_options", void 0);
  92951. return GlowLayer;
  92952. }(BABYLON.EffectLayer));
  92953. BABYLON.GlowLayer = GlowLayer;
  92954. })(BABYLON || (BABYLON = {}));
  92955. //# sourceMappingURL=babylon.glowLayer.js.map
  92956. var BABYLON;
  92957. (function (BABYLON) {
  92958. /**
  92959. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92960. */
  92961. var AssetTaskState;
  92962. (function (AssetTaskState) {
  92963. /**
  92964. * Initialization
  92965. */
  92966. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92967. /**
  92968. * Running
  92969. */
  92970. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92971. /**
  92972. * Done
  92973. */
  92974. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92975. /**
  92976. * Error
  92977. */
  92978. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92979. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92980. /**
  92981. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92982. */
  92983. var AbstractAssetTask = /** @class */ (function () {
  92984. /**
  92985. * Creates a new {BABYLON.AssetsManager}
  92986. * @param name defines the name of the task
  92987. */
  92988. function AbstractAssetTask(
  92989. /**
  92990. * Task name
  92991. */ name) {
  92992. this.name = name;
  92993. this._isCompleted = false;
  92994. this._taskState = AssetTaskState.INIT;
  92995. }
  92996. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92997. /**
  92998. * Get if the task is completed
  92999. */
  93000. get: function () {
  93001. return this._isCompleted;
  93002. },
  93003. enumerable: true,
  93004. configurable: true
  93005. });
  93006. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  93007. /**
  93008. * Gets the current state of the task
  93009. */
  93010. get: function () {
  93011. return this._taskState;
  93012. },
  93013. enumerable: true,
  93014. configurable: true
  93015. });
  93016. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  93017. /**
  93018. * Gets the current error object (if task is in error)
  93019. */
  93020. get: function () {
  93021. return this._errorObject;
  93022. },
  93023. enumerable: true,
  93024. configurable: true
  93025. });
  93026. /**
  93027. * Internal only
  93028. * @hidden
  93029. */
  93030. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  93031. if (this._errorObject) {
  93032. return;
  93033. }
  93034. this._errorObject = {
  93035. message: message,
  93036. exception: exception
  93037. };
  93038. };
  93039. /**
  93040. * Execute the current task
  93041. * @param scene defines the scene where you want your assets to be loaded
  93042. * @param onSuccess is a callback called when the task is successfully executed
  93043. * @param onError is a callback called if an error occurs
  93044. */
  93045. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93046. var _this = this;
  93047. this._taskState = AssetTaskState.RUNNING;
  93048. this.runTask(scene, function () {
  93049. _this.onDoneCallback(onSuccess, onError);
  93050. }, function (msg, exception) {
  93051. _this.onErrorCallback(onError, msg, exception);
  93052. });
  93053. };
  93054. /**
  93055. * Execute the current task
  93056. * @param scene defines the scene where you want your assets to be loaded
  93057. * @param onSuccess is a callback called when the task is successfully executed
  93058. * @param onError is a callback called if an error occurs
  93059. */
  93060. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93061. throw new Error("runTask is not implemented");
  93062. };
  93063. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  93064. this._taskState = AssetTaskState.ERROR;
  93065. this._errorObject = {
  93066. message: message,
  93067. exception: exception
  93068. };
  93069. if (this.onError) {
  93070. this.onError(this, message, exception);
  93071. }
  93072. onError();
  93073. };
  93074. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  93075. try {
  93076. this._taskState = AssetTaskState.DONE;
  93077. this._isCompleted = true;
  93078. if (this.onSuccess) {
  93079. this.onSuccess(this);
  93080. }
  93081. onSuccess();
  93082. }
  93083. catch (e) {
  93084. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  93085. }
  93086. };
  93087. return AbstractAssetTask;
  93088. }());
  93089. BABYLON.AbstractAssetTask = AbstractAssetTask;
  93090. /**
  93091. * Class used to share progress information about assets loading
  93092. */
  93093. var AssetsProgressEvent = /** @class */ (function () {
  93094. /**
  93095. * Creates a {BABYLON.AssetsProgressEvent}
  93096. * @param remainingCount defines the number of remaining tasks to process
  93097. * @param totalCount defines the total number of tasks
  93098. * @param task defines the task that was just processed
  93099. */
  93100. function AssetsProgressEvent(remainingCount, totalCount, task) {
  93101. this.remainingCount = remainingCount;
  93102. this.totalCount = totalCount;
  93103. this.task = task;
  93104. }
  93105. return AssetsProgressEvent;
  93106. }());
  93107. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  93108. /**
  93109. * Define a task used by {BABYLON.AssetsManager} to load meshes
  93110. */
  93111. var MeshAssetTask = /** @class */ (function (_super) {
  93112. __extends(MeshAssetTask, _super);
  93113. /**
  93114. * Creates a new {BABYLON.MeshAssetTask}
  93115. * @param name defines the name of the task
  93116. * @param meshesNames defines the list of mesh's names you want to load
  93117. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  93118. * @param sceneFilename defines the filename of the scene to load from
  93119. */
  93120. function MeshAssetTask(
  93121. /**
  93122. * Defines the name of the task
  93123. */
  93124. name,
  93125. /**
  93126. * Defines the list of mesh's names you want to load
  93127. */
  93128. meshesNames,
  93129. /**
  93130. * Defines the root url to use as a base to load your meshes and associated resources
  93131. */
  93132. rootUrl,
  93133. /**
  93134. * Defines the filename of the scene to load from
  93135. */
  93136. sceneFilename) {
  93137. var _this = _super.call(this, name) || this;
  93138. _this.name = name;
  93139. _this.meshesNames = meshesNames;
  93140. _this.rootUrl = rootUrl;
  93141. _this.sceneFilename = sceneFilename;
  93142. return _this;
  93143. }
  93144. /**
  93145. * Execute the current task
  93146. * @param scene defines the scene where you want your assets to be loaded
  93147. * @param onSuccess is a callback called when the task is successfully executed
  93148. * @param onError is a callback called if an error occurs
  93149. */
  93150. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93151. var _this = this;
  93152. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  93153. _this.loadedMeshes = meshes;
  93154. _this.loadedParticleSystems = particleSystems;
  93155. _this.loadedSkeletons = skeletons;
  93156. onSuccess();
  93157. }, null, function (scene, message, exception) {
  93158. onError(message, exception);
  93159. });
  93160. };
  93161. return MeshAssetTask;
  93162. }(AbstractAssetTask));
  93163. BABYLON.MeshAssetTask = MeshAssetTask;
  93164. /**
  93165. * Define a task used by {BABYLON.AssetsManager} to load text content
  93166. */
  93167. var TextFileAssetTask = /** @class */ (function (_super) {
  93168. __extends(TextFileAssetTask, _super);
  93169. /**
  93170. * Creates a new TextFileAssetTask object
  93171. * @param name defines the name of the task
  93172. * @param url defines the location of the file to load
  93173. */
  93174. function TextFileAssetTask(
  93175. /**
  93176. * Defines the name of the task
  93177. */
  93178. name,
  93179. /**
  93180. * Defines the location of the file to load
  93181. */
  93182. url) {
  93183. var _this = _super.call(this, name) || this;
  93184. _this.name = name;
  93185. _this.url = url;
  93186. return _this;
  93187. }
  93188. /**
  93189. * Execute the current task
  93190. * @param scene defines the scene where you want your assets to be loaded
  93191. * @param onSuccess is a callback called when the task is successfully executed
  93192. * @param onError is a callback called if an error occurs
  93193. */
  93194. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93195. var _this = this;
  93196. scene._loadFile(this.url, function (data) {
  93197. _this.text = data;
  93198. onSuccess();
  93199. }, undefined, false, false, function (request, exception) {
  93200. if (request) {
  93201. onError(request.status + " " + request.statusText, exception);
  93202. }
  93203. });
  93204. };
  93205. return TextFileAssetTask;
  93206. }(AbstractAssetTask));
  93207. BABYLON.TextFileAssetTask = TextFileAssetTask;
  93208. /**
  93209. * Define a task used by {BABYLON.AssetsManager} to load binary data
  93210. */
  93211. var BinaryFileAssetTask = /** @class */ (function (_super) {
  93212. __extends(BinaryFileAssetTask, _super);
  93213. /**
  93214. * Creates a new BinaryFileAssetTask object
  93215. * @param name defines the name of the new task
  93216. * @param url defines the location of the file to load
  93217. */
  93218. function BinaryFileAssetTask(
  93219. /**
  93220. * Defines the name of the task
  93221. */
  93222. name,
  93223. /**
  93224. * Defines the location of the file to load
  93225. */
  93226. url) {
  93227. var _this = _super.call(this, name) || this;
  93228. _this.name = name;
  93229. _this.url = url;
  93230. return _this;
  93231. }
  93232. /**
  93233. * Execute the current task
  93234. * @param scene defines the scene where you want your assets to be loaded
  93235. * @param onSuccess is a callback called when the task is successfully executed
  93236. * @param onError is a callback called if an error occurs
  93237. */
  93238. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93239. var _this = this;
  93240. scene._loadFile(this.url, function (data) {
  93241. _this.data = data;
  93242. onSuccess();
  93243. }, undefined, true, true, function (request, exception) {
  93244. if (request) {
  93245. onError(request.status + " " + request.statusText, exception);
  93246. }
  93247. });
  93248. };
  93249. return BinaryFileAssetTask;
  93250. }(AbstractAssetTask));
  93251. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  93252. /**
  93253. * Define a task used by {BABYLON.AssetsManager} to load images
  93254. */
  93255. var ImageAssetTask = /** @class */ (function (_super) {
  93256. __extends(ImageAssetTask, _super);
  93257. /**
  93258. * Creates a new ImageAssetTask
  93259. * @param name defines the name of the task
  93260. * @param url defines the location of the image to load
  93261. */
  93262. function ImageAssetTask(
  93263. /**
  93264. * Defines the name of the task
  93265. */
  93266. name,
  93267. /**
  93268. * Defines the location of the image to load
  93269. */
  93270. url) {
  93271. var _this = _super.call(this, name) || this;
  93272. _this.name = name;
  93273. _this.url = url;
  93274. return _this;
  93275. }
  93276. /**
  93277. * Execute the current task
  93278. * @param scene defines the scene where you want your assets to be loaded
  93279. * @param onSuccess is a callback called when the task is successfully executed
  93280. * @param onError is a callback called if an error occurs
  93281. */
  93282. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93283. var _this = this;
  93284. var img = new Image();
  93285. BABYLON.Tools.SetCorsBehavior(this.url, img);
  93286. img.onload = function () {
  93287. _this.image = img;
  93288. onSuccess();
  93289. };
  93290. img.onerror = function (err) {
  93291. onError("Error loading image", err);
  93292. };
  93293. img.src = this.url;
  93294. };
  93295. return ImageAssetTask;
  93296. }(AbstractAssetTask));
  93297. BABYLON.ImageAssetTask = ImageAssetTask;
  93298. /**
  93299. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  93300. */
  93301. var TextureAssetTask = /** @class */ (function (_super) {
  93302. __extends(TextureAssetTask, _super);
  93303. /**
  93304. * Creates a new TextureAssetTask object
  93305. * @param name defines the name of the task
  93306. * @param url defines the location of the file to load
  93307. * @param noMipmap defines if mipmap should not be generated (default is false)
  93308. * @param invertY defines if texture must be inverted on Y axis (default is false)
  93309. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93310. */
  93311. function TextureAssetTask(
  93312. /**
  93313. * Defines the name of the task
  93314. */
  93315. name,
  93316. /**
  93317. * Defines the location of the file to load
  93318. */
  93319. url,
  93320. /**
  93321. * Defines if mipmap should not be generated (default is false)
  93322. */
  93323. noMipmap,
  93324. /**
  93325. * Defines if texture must be inverted on Y axis (default is false)
  93326. */
  93327. invertY,
  93328. /**
  93329. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93330. */
  93331. samplingMode) {
  93332. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93333. var _this = _super.call(this, name) || this;
  93334. _this.name = name;
  93335. _this.url = url;
  93336. _this.noMipmap = noMipmap;
  93337. _this.invertY = invertY;
  93338. _this.samplingMode = samplingMode;
  93339. return _this;
  93340. }
  93341. /**
  93342. * Execute the current task
  93343. * @param scene defines the scene where you want your assets to be loaded
  93344. * @param onSuccess is a callback called when the task is successfully executed
  93345. * @param onError is a callback called if an error occurs
  93346. */
  93347. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93348. var onload = function () {
  93349. onSuccess();
  93350. };
  93351. var onerror = function (message, exception) {
  93352. onError(message, exception);
  93353. };
  93354. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93355. };
  93356. return TextureAssetTask;
  93357. }(AbstractAssetTask));
  93358. BABYLON.TextureAssetTask = TextureAssetTask;
  93359. /**
  93360. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93361. */
  93362. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93363. __extends(CubeTextureAssetTask, _super);
  93364. /**
  93365. * Creates a new CubeTextureAssetTask
  93366. * @param name defines the name of the task
  93367. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93368. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93369. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93370. * @param files defines the explicit list of files (undefined by default)
  93371. */
  93372. function CubeTextureAssetTask(
  93373. /**
  93374. * Defines the name of the task
  93375. */
  93376. name,
  93377. /**
  93378. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93379. */
  93380. url,
  93381. /**
  93382. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93383. */
  93384. extensions,
  93385. /**
  93386. * Defines if mipmaps should not be generated (default is false)
  93387. */
  93388. noMipmap,
  93389. /**
  93390. * Defines the explicit list of files (undefined by default)
  93391. */
  93392. files) {
  93393. var _this = _super.call(this, name) || this;
  93394. _this.name = name;
  93395. _this.url = url;
  93396. _this.extensions = extensions;
  93397. _this.noMipmap = noMipmap;
  93398. _this.files = files;
  93399. return _this;
  93400. }
  93401. /**
  93402. * Execute the current task
  93403. * @param scene defines the scene where you want your assets to be loaded
  93404. * @param onSuccess is a callback called when the task is successfully executed
  93405. * @param onError is a callback called if an error occurs
  93406. */
  93407. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93408. var onload = function () {
  93409. onSuccess();
  93410. };
  93411. var onerror = function (message, exception) {
  93412. onError(message, exception);
  93413. };
  93414. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93415. };
  93416. return CubeTextureAssetTask;
  93417. }(AbstractAssetTask));
  93418. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93419. /**
  93420. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93421. */
  93422. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93423. __extends(HDRCubeTextureAssetTask, _super);
  93424. /**
  93425. * Creates a new HDRCubeTextureAssetTask object
  93426. * @param name defines the name of the task
  93427. * @param url defines the location of the file to load
  93428. * @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.
  93429. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93430. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93431. * @param gammaSpace 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)
  93432. * @param reserved Internal use only
  93433. */
  93434. function HDRCubeTextureAssetTask(
  93435. /**
  93436. * Defines the name of the task
  93437. */
  93438. name,
  93439. /**
  93440. * Defines the location of the file to load
  93441. */
  93442. url,
  93443. /**
  93444. * Defines the desired size (the more it increases the longer the generation will be)
  93445. */
  93446. size,
  93447. /**
  93448. * Defines if mipmaps should not be generated (default is false)
  93449. */
  93450. noMipmap,
  93451. /**
  93452. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93453. */
  93454. generateHarmonics,
  93455. /**
  93456. * 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)
  93457. */
  93458. gammaSpace,
  93459. /**
  93460. * Internal Use Only
  93461. */
  93462. reserved) {
  93463. if (noMipmap === void 0) { noMipmap = false; }
  93464. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93465. if (gammaSpace === void 0) { gammaSpace = false; }
  93466. if (reserved === void 0) { reserved = false; }
  93467. var _this = _super.call(this, name) || this;
  93468. _this.name = name;
  93469. _this.url = url;
  93470. _this.size = size;
  93471. _this.noMipmap = noMipmap;
  93472. _this.generateHarmonics = generateHarmonics;
  93473. _this.gammaSpace = gammaSpace;
  93474. _this.reserved = reserved;
  93475. return _this;
  93476. }
  93477. /**
  93478. * Execute the current task
  93479. * @param scene defines the scene where you want your assets to be loaded
  93480. * @param onSuccess is a callback called when the task is successfully executed
  93481. * @param onError is a callback called if an error occurs
  93482. */
  93483. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93484. var onload = function () {
  93485. onSuccess();
  93486. };
  93487. var onerror = function (message, exception) {
  93488. onError(message, exception);
  93489. };
  93490. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93491. };
  93492. return HDRCubeTextureAssetTask;
  93493. }(AbstractAssetTask));
  93494. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93495. /**
  93496. * This class can be used to easily import assets into a scene
  93497. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93498. */
  93499. var AssetsManager = /** @class */ (function () {
  93500. /**
  93501. * Creates a new AssetsManager
  93502. * @param scene defines the scene to work on
  93503. */
  93504. function AssetsManager(scene) {
  93505. this._isLoading = false;
  93506. this._tasks = new Array();
  93507. this._waitingTasksCount = 0;
  93508. this._totalTasksCount = 0;
  93509. /**
  93510. * Observable called when all tasks are processed
  93511. */
  93512. this.onTaskSuccessObservable = new BABYLON.Observable();
  93513. /**
  93514. * Observable called when a task had an error
  93515. */
  93516. this.onTaskErrorObservable = new BABYLON.Observable();
  93517. /**
  93518. * Observable called when a task is successful
  93519. */
  93520. this.onTasksDoneObservable = new BABYLON.Observable();
  93521. /**
  93522. * Observable called when a task is done (whatever the result is)
  93523. */
  93524. this.onProgressObservable = new BABYLON.Observable();
  93525. /**
  93526. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93527. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93528. */
  93529. this.useDefaultLoadingScreen = true;
  93530. this._scene = scene;
  93531. }
  93532. /**
  93533. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93534. * @param taskName defines the name of the new task
  93535. * @param meshesNames defines the name of meshes to load
  93536. * @param rootUrl defines the root url to use to locate files
  93537. * @param sceneFilename defines the filename of the scene file
  93538. * @returns a new {BABYLON.MeshAssetTask} object
  93539. */
  93540. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93541. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93542. this._tasks.push(task);
  93543. return task;
  93544. };
  93545. /**
  93546. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93547. * @param taskName defines the name of the new task
  93548. * @param url defines the url of the file to load
  93549. * @returns a new {BABYLON.TextFileAssetTask} object
  93550. */
  93551. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93552. var task = new TextFileAssetTask(taskName, url);
  93553. this._tasks.push(task);
  93554. return task;
  93555. };
  93556. /**
  93557. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93558. * @param taskName defines the name of the new task
  93559. * @param url defines the url of the file to load
  93560. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93561. */
  93562. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93563. var task = new BinaryFileAssetTask(taskName, url);
  93564. this._tasks.push(task);
  93565. return task;
  93566. };
  93567. /**
  93568. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93569. * @param taskName defines the name of the new task
  93570. * @param url defines the url of the file to load
  93571. * @returns a new {BABYLON.ImageAssetTask} object
  93572. */
  93573. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93574. var task = new ImageAssetTask(taskName, url);
  93575. this._tasks.push(task);
  93576. return task;
  93577. };
  93578. /**
  93579. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93580. * @param taskName defines the name of the new task
  93581. * @param url defines the url of the file to load
  93582. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93583. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93584. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93585. * @returns a new {BABYLON.TextureAssetTask} object
  93586. */
  93587. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93588. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93589. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93590. this._tasks.push(task);
  93591. return task;
  93592. };
  93593. /**
  93594. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93595. * @param taskName defines the name of the new task
  93596. * @param url defines the url of the file to load
  93597. * @param extensions defines the extension to use to load the cube map (can be null)
  93598. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93599. * @param files defines the list of files to load (can be null)
  93600. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93601. */
  93602. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93603. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93604. this._tasks.push(task);
  93605. return task;
  93606. };
  93607. /**
  93608. *
  93609. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93610. * @param taskName defines the name of the new task
  93611. * @param url defines the url of the file to load
  93612. * @param size defines the size you want for the cubemap (can be null)
  93613. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93614. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93615. * @param gammaSpace 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)
  93616. * @param reserved Internal use only
  93617. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93618. */
  93619. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  93620. if (noMipmap === void 0) { noMipmap = false; }
  93621. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93622. if (gammaSpace === void 0) { gammaSpace = false; }
  93623. if (reserved === void 0) { reserved = false; }
  93624. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  93625. this._tasks.push(task);
  93626. return task;
  93627. };
  93628. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93629. var _this = this;
  93630. this._waitingTasksCount--;
  93631. try {
  93632. if (task.taskState === AssetTaskState.DONE) {
  93633. // Let's remove successfull tasks
  93634. BABYLON.Tools.SetImmediate(function () {
  93635. var index = _this._tasks.indexOf(task);
  93636. if (index > -1) {
  93637. _this._tasks.splice(index, 1);
  93638. }
  93639. });
  93640. }
  93641. if (this.onProgress) {
  93642. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93643. }
  93644. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93645. }
  93646. catch (e) {
  93647. BABYLON.Tools.Error("Error running progress callbacks.");
  93648. console.log(e);
  93649. }
  93650. if (this._waitingTasksCount === 0) {
  93651. try {
  93652. if (this.onFinish) {
  93653. this.onFinish(this._tasks);
  93654. }
  93655. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93656. }
  93657. catch (e) {
  93658. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93659. console.log(e);
  93660. }
  93661. this._isLoading = false;
  93662. this._scene.getEngine().hideLoadingUI();
  93663. }
  93664. };
  93665. AssetsManager.prototype._runTask = function (task) {
  93666. var _this = this;
  93667. var done = function () {
  93668. try {
  93669. if (_this.onTaskSuccess) {
  93670. _this.onTaskSuccess(task);
  93671. }
  93672. _this.onTaskSuccessObservable.notifyObservers(task);
  93673. _this._decreaseWaitingTasksCount(task);
  93674. }
  93675. catch (e) {
  93676. error("Error executing task success callbacks", e);
  93677. }
  93678. };
  93679. var error = function (message, exception) {
  93680. task._setErrorObject(message, exception);
  93681. if (_this.onTaskError) {
  93682. _this.onTaskError(task);
  93683. }
  93684. _this.onTaskErrorObservable.notifyObservers(task);
  93685. _this._decreaseWaitingTasksCount(task);
  93686. };
  93687. task.run(this._scene, done, error);
  93688. };
  93689. /**
  93690. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93691. * @return the current instance of the {BABYLON.AssetsManager}
  93692. */
  93693. AssetsManager.prototype.reset = function () {
  93694. this._isLoading = false;
  93695. this._tasks = new Array();
  93696. return this;
  93697. };
  93698. /**
  93699. * Start the loading process
  93700. * @return the current instance of the {BABYLON.AssetsManager}
  93701. */
  93702. AssetsManager.prototype.load = function () {
  93703. if (this._isLoading) {
  93704. return this;
  93705. }
  93706. this._isLoading = true;
  93707. this._waitingTasksCount = this._tasks.length;
  93708. this._totalTasksCount = this._tasks.length;
  93709. if (this._waitingTasksCount === 0) {
  93710. this._isLoading = false;
  93711. if (this.onFinish) {
  93712. this.onFinish(this._tasks);
  93713. }
  93714. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93715. return this;
  93716. }
  93717. if (this.useDefaultLoadingScreen) {
  93718. this._scene.getEngine().displayLoadingUI();
  93719. }
  93720. for (var index = 0; index < this._tasks.length; index++) {
  93721. var task = this._tasks[index];
  93722. this._runTask(task);
  93723. }
  93724. return this;
  93725. };
  93726. return AssetsManager;
  93727. }());
  93728. BABYLON.AssetsManager = AssetsManager;
  93729. })(BABYLON || (BABYLON = {}));
  93730. //# sourceMappingURL=babylon.assetsManager.js.map
  93731. var BABYLON;
  93732. (function (BABYLON) {
  93733. var serializedGeometries = [];
  93734. var serializeGeometry = function (geometry, serializationGeometries) {
  93735. if (serializedGeometries[geometry.id]) {
  93736. return;
  93737. }
  93738. if (geometry.doNotSerialize) {
  93739. return;
  93740. }
  93741. if (geometry instanceof BABYLON.BoxGeometry) {
  93742. serializationGeometries.boxes.push(geometry.serialize());
  93743. }
  93744. else if (geometry instanceof BABYLON.SphereGeometry) {
  93745. serializationGeometries.spheres.push(geometry.serialize());
  93746. }
  93747. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93748. serializationGeometries.cylinders.push(geometry.serialize());
  93749. }
  93750. else if (geometry instanceof BABYLON.TorusGeometry) {
  93751. serializationGeometries.toruses.push(geometry.serialize());
  93752. }
  93753. else if (geometry instanceof BABYLON.GroundGeometry) {
  93754. serializationGeometries.grounds.push(geometry.serialize());
  93755. }
  93756. else if (geometry instanceof BABYLON.Plane) {
  93757. serializationGeometries.planes.push(geometry.serialize());
  93758. }
  93759. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93760. serializationGeometries.torusKnots.push(geometry.serialize());
  93761. }
  93762. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93763. throw new Error("Unknown primitive type");
  93764. }
  93765. else {
  93766. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93767. }
  93768. serializedGeometries[geometry.id] = true;
  93769. };
  93770. var serializeMesh = function (mesh, serializationScene) {
  93771. var serializationObject = {};
  93772. // Geometry
  93773. var geometry = mesh._geometry;
  93774. if (geometry) {
  93775. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93776. // 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
  93777. serializeGeometry(geometry, serializationScene.geometries);
  93778. }
  93779. }
  93780. // Custom
  93781. if (mesh.serialize) {
  93782. mesh.serialize(serializationObject);
  93783. }
  93784. return serializationObject;
  93785. };
  93786. var finalizeSingleMesh = function (mesh, serializationObject) {
  93787. //only works if the mesh is already loaded
  93788. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93789. //serialize material
  93790. if (mesh.material) {
  93791. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93792. serializationObject.materials = serializationObject.materials || [];
  93793. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93794. serializationObject.materials.push(mesh.material.serialize());
  93795. }
  93796. }
  93797. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93798. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93799. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93800. serializationObject.multiMaterials.push(mesh.material.serialize());
  93801. }
  93802. }
  93803. }
  93804. //serialize geometry
  93805. var geometry = mesh._geometry;
  93806. if (geometry) {
  93807. if (!serializationObject.geometries) {
  93808. serializationObject.geometries = {};
  93809. serializationObject.geometries.boxes = [];
  93810. serializationObject.geometries.spheres = [];
  93811. serializationObject.geometries.cylinders = [];
  93812. serializationObject.geometries.toruses = [];
  93813. serializationObject.geometries.grounds = [];
  93814. serializationObject.geometries.planes = [];
  93815. serializationObject.geometries.torusKnots = [];
  93816. serializationObject.geometries.vertexData = [];
  93817. }
  93818. serializeGeometry(geometry, serializationObject.geometries);
  93819. }
  93820. // Skeletons
  93821. if (mesh.skeleton) {
  93822. serializationObject.skeletons = serializationObject.skeletons || [];
  93823. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93824. }
  93825. //serialize the actual mesh
  93826. serializationObject.meshes = serializationObject.meshes || [];
  93827. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93828. }
  93829. };
  93830. var SceneSerializer = /** @class */ (function () {
  93831. function SceneSerializer() {
  93832. }
  93833. SceneSerializer.ClearCache = function () {
  93834. serializedGeometries = [];
  93835. };
  93836. SceneSerializer.Serialize = function (scene) {
  93837. var serializationObject = {};
  93838. SceneSerializer.ClearCache();
  93839. // Scene
  93840. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93841. serializationObject.autoClear = scene.autoClear;
  93842. serializationObject.clearColor = scene.clearColor.asArray();
  93843. serializationObject.ambientColor = scene.ambientColor.asArray();
  93844. serializationObject.gravity = scene.gravity.asArray();
  93845. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93846. serializationObject.workerCollisions = scene.workerCollisions;
  93847. // Fog
  93848. if (scene.fogMode && scene.fogMode !== 0) {
  93849. serializationObject.fogMode = scene.fogMode;
  93850. serializationObject.fogColor = scene.fogColor.asArray();
  93851. serializationObject.fogStart = scene.fogStart;
  93852. serializationObject.fogEnd = scene.fogEnd;
  93853. serializationObject.fogDensity = scene.fogDensity;
  93854. }
  93855. //Physics
  93856. if (scene.isPhysicsEnabled()) {
  93857. var physicEngine = scene.getPhysicsEngine();
  93858. if (physicEngine) {
  93859. serializationObject.physicsEnabled = true;
  93860. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93861. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93862. }
  93863. }
  93864. // Metadata
  93865. if (scene.metadata) {
  93866. serializationObject.metadata = scene.metadata;
  93867. }
  93868. // Morph targets
  93869. serializationObject.morphTargetManagers = [];
  93870. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93871. var abstractMesh = _a[_i];
  93872. var manager = abstractMesh.morphTargetManager;
  93873. if (manager) {
  93874. serializationObject.morphTargetManagers.push(manager.serialize());
  93875. }
  93876. }
  93877. // Lights
  93878. serializationObject.lights = [];
  93879. var index;
  93880. var light;
  93881. for (index = 0; index < scene.lights.length; index++) {
  93882. light = scene.lights[index];
  93883. if (!light.doNotSerialize) {
  93884. serializationObject.lights.push(light.serialize());
  93885. }
  93886. }
  93887. // Cameras
  93888. serializationObject.cameras = [];
  93889. for (index = 0; index < scene.cameras.length; index++) {
  93890. var camera = scene.cameras[index];
  93891. if (!camera.doNotSerialize) {
  93892. serializationObject.cameras.push(camera.serialize());
  93893. }
  93894. }
  93895. if (scene.activeCamera) {
  93896. serializationObject.activeCameraID = scene.activeCamera.id;
  93897. }
  93898. // Animations
  93899. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93900. // Materials
  93901. serializationObject.materials = [];
  93902. serializationObject.multiMaterials = [];
  93903. var material;
  93904. for (index = 0; index < scene.materials.length; index++) {
  93905. material = scene.materials[index];
  93906. if (!material.doNotSerialize) {
  93907. serializationObject.materials.push(material.serialize());
  93908. }
  93909. }
  93910. // MultiMaterials
  93911. serializationObject.multiMaterials = [];
  93912. for (index = 0; index < scene.multiMaterials.length; index++) {
  93913. var multiMaterial = scene.multiMaterials[index];
  93914. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93915. }
  93916. // Environment texture
  93917. if (scene.environmentTexture) {
  93918. serializationObject.environmentTexture = scene.environmentTexture.name;
  93919. }
  93920. // Skeletons
  93921. serializationObject.skeletons = [];
  93922. for (index = 0; index < scene.skeletons.length; index++) {
  93923. var skeleton = scene.skeletons[index];
  93924. if (!skeleton.doNotSerialize) {
  93925. serializationObject.skeletons.push(skeleton.serialize());
  93926. }
  93927. }
  93928. // Transform nodes
  93929. serializationObject.transformNodes = [];
  93930. for (index = 0; index < scene.transformNodes.length; index++) {
  93931. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93932. }
  93933. // Geometries
  93934. serializationObject.geometries = {};
  93935. serializationObject.geometries.boxes = [];
  93936. serializationObject.geometries.spheres = [];
  93937. serializationObject.geometries.cylinders = [];
  93938. serializationObject.geometries.toruses = [];
  93939. serializationObject.geometries.grounds = [];
  93940. serializationObject.geometries.planes = [];
  93941. serializationObject.geometries.torusKnots = [];
  93942. serializationObject.geometries.vertexData = [];
  93943. serializedGeometries = [];
  93944. var geometries = scene.getGeometries();
  93945. for (index = 0; index < geometries.length; index++) {
  93946. var geometry = geometries[index];
  93947. if (geometry.isReady()) {
  93948. serializeGeometry(geometry, serializationObject.geometries);
  93949. }
  93950. }
  93951. // Meshes
  93952. serializationObject.meshes = [];
  93953. for (index = 0; index < scene.meshes.length; index++) {
  93954. var abstractMesh = scene.meshes[index];
  93955. if (abstractMesh instanceof BABYLON.Mesh) {
  93956. var mesh = abstractMesh;
  93957. if (!mesh.doNotSerialize) {
  93958. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93959. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93960. }
  93961. }
  93962. }
  93963. }
  93964. // Particles Systems
  93965. serializationObject.particleSystems = [];
  93966. for (index = 0; index < scene.particleSystems.length; index++) {
  93967. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93968. }
  93969. // Lens flares
  93970. serializationObject.lensFlareSystems = [];
  93971. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93972. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93973. }
  93974. // Shadows
  93975. serializationObject.shadowGenerators = [];
  93976. for (index = 0; index < scene.lights.length; index++) {
  93977. light = scene.lights[index];
  93978. var shadowGenerator = light.getShadowGenerator();
  93979. if (shadowGenerator) {
  93980. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93981. }
  93982. }
  93983. // Action Manager
  93984. if (scene.actionManager) {
  93985. serializationObject.actions = scene.actionManager.serialize("scene");
  93986. }
  93987. // Audio
  93988. serializationObject.sounds = [];
  93989. for (index = 0; index < scene.soundTracks.length; index++) {
  93990. var soundtrack = scene.soundTracks[index];
  93991. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93992. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93993. }
  93994. }
  93995. // Effect layers
  93996. serializationObject.effectLayers = [];
  93997. for (index = 0; index < scene.effectLayers.length; index++) {
  93998. var layer = scene.effectLayers[index];
  93999. if (layer.serialize) {
  94000. serializationObject.effectLayers.push(layer.serialize());
  94001. }
  94002. }
  94003. return serializationObject;
  94004. };
  94005. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  94006. if (withParents === void 0) { withParents = false; }
  94007. if (withChildren === void 0) { withChildren = false; }
  94008. var serializationObject = {};
  94009. SceneSerializer.ClearCache();
  94010. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  94011. if (withParents || withChildren) {
  94012. //deliberate for loop! not for each, appended should be processed as well.
  94013. for (var i = 0; i < toSerialize.length; ++i) {
  94014. if (withChildren) {
  94015. toSerialize[i].getDescendants().forEach(function (node) {
  94016. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  94017. toSerialize.push(node);
  94018. }
  94019. });
  94020. }
  94021. //make sure the array doesn't contain the object already
  94022. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  94023. toSerialize.push(toSerialize[i].parent);
  94024. }
  94025. }
  94026. }
  94027. toSerialize.forEach(function (mesh) {
  94028. finalizeSingleMesh(mesh, serializationObject);
  94029. });
  94030. return serializationObject;
  94031. };
  94032. return SceneSerializer;
  94033. }());
  94034. BABYLON.SceneSerializer = SceneSerializer;
  94035. })(BABYLON || (BABYLON = {}));
  94036. //# sourceMappingURL=babylon.sceneSerializer.js.map
  94037. var BABYLON;
  94038. (function (BABYLON) {
  94039. var ReflectionProbe = /** @class */ (function () {
  94040. function ReflectionProbe(name, size, scene, generateMipMaps) {
  94041. if (generateMipMaps === void 0) { generateMipMaps = true; }
  94042. var _this = this;
  94043. this.name = name;
  94044. this._viewMatrix = BABYLON.Matrix.Identity();
  94045. this._target = BABYLON.Vector3.Zero();
  94046. this._add = BABYLON.Vector3.Zero();
  94047. this._invertYAxis = false;
  94048. this.position = BABYLON.Vector3.Zero();
  94049. this._scene = scene;
  94050. this._scene.reflectionProbes.push(this);
  94051. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  94052. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  94053. switch (faceIndex) {
  94054. case 0:
  94055. _this._add.copyFromFloats(1, 0, 0);
  94056. break;
  94057. case 1:
  94058. _this._add.copyFromFloats(-1, 0, 0);
  94059. break;
  94060. case 2:
  94061. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  94062. break;
  94063. case 3:
  94064. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  94065. break;
  94066. case 4:
  94067. _this._add.copyFromFloats(0, 0, 1);
  94068. break;
  94069. case 5:
  94070. _this._add.copyFromFloats(0, 0, -1);
  94071. break;
  94072. }
  94073. if (_this._attachedMesh) {
  94074. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  94075. }
  94076. _this.position.addToRef(_this._add, _this._target);
  94077. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  94078. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  94079. scene._forcedViewPosition = _this.position;
  94080. });
  94081. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  94082. scene._forcedViewPosition = null;
  94083. scene.updateTransformMatrix(true);
  94084. });
  94085. if (scene.activeCamera) {
  94086. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  94087. }
  94088. }
  94089. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  94090. get: function () {
  94091. return this._renderTargetTexture.samples;
  94092. },
  94093. set: function (value) {
  94094. this._renderTargetTexture.samples = value;
  94095. },
  94096. enumerable: true,
  94097. configurable: true
  94098. });
  94099. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  94100. get: function () {
  94101. return this._renderTargetTexture.refreshRate;
  94102. },
  94103. set: function (value) {
  94104. this._renderTargetTexture.refreshRate = value;
  94105. },
  94106. enumerable: true,
  94107. configurable: true
  94108. });
  94109. ReflectionProbe.prototype.getScene = function () {
  94110. return this._scene;
  94111. };
  94112. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  94113. get: function () {
  94114. return this._renderTargetTexture;
  94115. },
  94116. enumerable: true,
  94117. configurable: true
  94118. });
  94119. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  94120. get: function () {
  94121. return this._renderTargetTexture.renderList;
  94122. },
  94123. enumerable: true,
  94124. configurable: true
  94125. });
  94126. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  94127. this._attachedMesh = mesh;
  94128. };
  94129. /**
  94130. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  94131. *
  94132. * @param renderingGroupId The rendering group id corresponding to its index
  94133. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  94134. */
  94135. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  94136. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  94137. };
  94138. ReflectionProbe.prototype.dispose = function () {
  94139. var index = this._scene.reflectionProbes.indexOf(this);
  94140. if (index !== -1) {
  94141. // Remove from the scene if found
  94142. this._scene.reflectionProbes.splice(index, 1);
  94143. }
  94144. if (this._renderTargetTexture) {
  94145. this._renderTargetTexture.dispose();
  94146. this._renderTargetTexture = null;
  94147. }
  94148. };
  94149. return ReflectionProbe;
  94150. }());
  94151. BABYLON.ReflectionProbe = ReflectionProbe;
  94152. })(BABYLON || (BABYLON = {}));
  94153. //# sourceMappingURL=babylon.reflectionProbe.js.map
  94154. var BABYLON;
  94155. (function (BABYLON) {
  94156. var Layer = /** @class */ (function () {
  94157. function Layer(name, imgUrl, scene, isBackground, color) {
  94158. this.name = name;
  94159. this.scale = new BABYLON.Vector2(1, 1);
  94160. this.offset = new BABYLON.Vector2(0, 0);
  94161. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  94162. this.layerMask = 0x0FFFFFFF;
  94163. this._vertexBuffers = {};
  94164. // Events
  94165. /**
  94166. * An event triggered when the layer is disposed.
  94167. */
  94168. this.onDisposeObservable = new BABYLON.Observable();
  94169. /**
  94170. * An event triggered before rendering the scene
  94171. */
  94172. this.onBeforeRenderObservable = new BABYLON.Observable();
  94173. /**
  94174. * An event triggered after rendering the scene
  94175. */
  94176. this.onAfterRenderObservable = new BABYLON.Observable();
  94177. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  94178. this.isBackground = isBackground === undefined ? true : isBackground;
  94179. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  94180. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  94181. this._scene.layers.push(this);
  94182. var engine = this._scene.getEngine();
  94183. // VBO
  94184. var vertices = [];
  94185. vertices.push(1, 1);
  94186. vertices.push(-1, 1);
  94187. vertices.push(-1, -1);
  94188. vertices.push(1, -1);
  94189. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94190. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  94191. this._createIndexBuffer();
  94192. // Effects
  94193. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  94194. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  94195. }
  94196. Object.defineProperty(Layer.prototype, "onDispose", {
  94197. set: function (callback) {
  94198. if (this._onDisposeObserver) {
  94199. this.onDisposeObservable.remove(this._onDisposeObserver);
  94200. }
  94201. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  94202. },
  94203. enumerable: true,
  94204. configurable: true
  94205. });
  94206. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  94207. set: function (callback) {
  94208. if (this._onBeforeRenderObserver) {
  94209. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  94210. }
  94211. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  94212. },
  94213. enumerable: true,
  94214. configurable: true
  94215. });
  94216. Object.defineProperty(Layer.prototype, "onAfterRender", {
  94217. set: function (callback) {
  94218. if (this._onAfterRenderObserver) {
  94219. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  94220. }
  94221. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  94222. },
  94223. enumerable: true,
  94224. configurable: true
  94225. });
  94226. Layer.prototype._createIndexBuffer = function () {
  94227. var engine = this._scene.getEngine();
  94228. // Indices
  94229. var indices = [];
  94230. indices.push(0);
  94231. indices.push(1);
  94232. indices.push(2);
  94233. indices.push(0);
  94234. indices.push(2);
  94235. indices.push(3);
  94236. this._indexBuffer = engine.createIndexBuffer(indices);
  94237. };
  94238. Layer.prototype._rebuild = function () {
  94239. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94240. if (vb) {
  94241. vb._rebuild();
  94242. }
  94243. this._createIndexBuffer();
  94244. };
  94245. Layer.prototype.render = function () {
  94246. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  94247. // Check
  94248. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  94249. return;
  94250. var engine = this._scene.getEngine();
  94251. this.onBeforeRenderObservable.notifyObservers(this);
  94252. // Render
  94253. engine.enableEffect(currentEffect);
  94254. engine.setState(false);
  94255. // Texture
  94256. currentEffect.setTexture("textureSampler", this.texture);
  94257. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  94258. // Color
  94259. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  94260. // Scale / offset
  94261. currentEffect.setVector2("offset", this.offset);
  94262. currentEffect.setVector2("scale", this.scale);
  94263. // VBOs
  94264. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94265. // Draw order
  94266. if (!this.alphaTest) {
  94267. engine.setAlphaMode(this.alphaBlendingMode);
  94268. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94269. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94270. }
  94271. else {
  94272. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94273. }
  94274. this.onAfterRenderObservable.notifyObservers(this);
  94275. };
  94276. Layer.prototype.dispose = function () {
  94277. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94278. if (vertexBuffer) {
  94279. vertexBuffer.dispose();
  94280. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94281. }
  94282. if (this._indexBuffer) {
  94283. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94284. this._indexBuffer = null;
  94285. }
  94286. if (this.texture) {
  94287. this.texture.dispose();
  94288. this.texture = null;
  94289. }
  94290. // Remove from scene
  94291. var index = this._scene.layers.indexOf(this);
  94292. this._scene.layers.splice(index, 1);
  94293. // Callback
  94294. this.onDisposeObservable.notifyObservers(this);
  94295. this.onDisposeObservable.clear();
  94296. this.onAfterRenderObservable.clear();
  94297. this.onBeforeRenderObservable.clear();
  94298. };
  94299. return Layer;
  94300. }());
  94301. BABYLON.Layer = Layer;
  94302. })(BABYLON || (BABYLON = {}));
  94303. //# sourceMappingURL=babylon.layer.js.map
  94304. var BABYLON;
  94305. (function (BABYLON) {
  94306. var TextureTools = /** @class */ (function () {
  94307. function TextureTools() {
  94308. }
  94309. /**
  94310. * Uses the GPU to create a copy texture rescaled at a given size
  94311. * @param texture Texture to copy from
  94312. * @param width Desired width
  94313. * @param height Desired height
  94314. * @return Generated texture
  94315. */
  94316. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  94317. if (useBilinearMode === void 0) { useBilinearMode = true; }
  94318. var scene = texture.getScene();
  94319. var engine = scene.getEngine();
  94320. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94321. rtt.wrapU = texture.wrapU;
  94322. rtt.wrapV = texture.wrapV;
  94323. rtt.uOffset = texture.uOffset;
  94324. rtt.vOffset = texture.vOffset;
  94325. rtt.uScale = texture.uScale;
  94326. rtt.vScale = texture.vScale;
  94327. rtt.uAng = texture.uAng;
  94328. rtt.vAng = texture.vAng;
  94329. rtt.wAng = texture.wAng;
  94330. rtt.coordinatesIndex = texture.coordinatesIndex;
  94331. rtt.level = texture.level;
  94332. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94333. rtt._texture.isReady = false;
  94334. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94335. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94336. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94337. passPostProcess.getEffect().executeWhenCompiled(function () {
  94338. passPostProcess.onApply = function (effect) {
  94339. effect.setTexture("textureSampler", texture);
  94340. };
  94341. var internalTexture = rtt.getInternalTexture();
  94342. if (internalTexture) {
  94343. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94344. engine.unBindFramebuffer(internalTexture);
  94345. rtt.disposeFramebufferObjects();
  94346. passPostProcess.dispose();
  94347. internalTexture.isReady = true;
  94348. }
  94349. });
  94350. return rtt;
  94351. };
  94352. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94353. if (!scene._environmentBRDFTexture) {
  94354. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94355. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94356. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94357. scene._environmentBRDFTexture = texture;
  94358. }
  94359. return scene._environmentBRDFTexture;
  94360. };
  94361. 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=";
  94362. return TextureTools;
  94363. }());
  94364. BABYLON.TextureTools = TextureTools;
  94365. })(BABYLON || (BABYLON = {}));
  94366. //# sourceMappingURL=babylon.textureTools.js.map
  94367. var BABYLON;
  94368. (function (BABYLON) {
  94369. var FramingBehavior = /** @class */ (function () {
  94370. function FramingBehavior() {
  94371. this._mode = FramingBehavior.FitFrustumSidesMode;
  94372. this._radiusScale = 1.0;
  94373. this._positionScale = 0.5;
  94374. this._defaultElevation = 0.3;
  94375. this._elevationReturnTime = 1500;
  94376. this._elevationReturnWaitTime = 1000;
  94377. this._zoomStopsAnimation = false;
  94378. this._framingTime = 1500;
  94379. this._isPointerDown = false;
  94380. this._lastInteractionTime = -Infinity;
  94381. // Framing control
  94382. this._animatables = new Array();
  94383. this._betaIsAnimating = false;
  94384. }
  94385. Object.defineProperty(FramingBehavior.prototype, "name", {
  94386. get: function () {
  94387. return "Framing";
  94388. },
  94389. enumerable: true,
  94390. configurable: true
  94391. });
  94392. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94393. /**
  94394. * Gets current mode used by the behavior.
  94395. */
  94396. get: function () {
  94397. return this._mode;
  94398. },
  94399. /**
  94400. * Sets the current mode used by the behavior
  94401. */
  94402. set: function (mode) {
  94403. this._mode = mode;
  94404. },
  94405. enumerable: true,
  94406. configurable: true
  94407. });
  94408. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94409. /**
  94410. * Gets the scale applied to the radius
  94411. */
  94412. get: function () {
  94413. return this._radiusScale;
  94414. },
  94415. /**
  94416. * Sets the scale applied to the radius (1 by default)
  94417. */
  94418. set: function (radius) {
  94419. this._radiusScale = radius;
  94420. },
  94421. enumerable: true,
  94422. configurable: true
  94423. });
  94424. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94425. /**
  94426. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94427. */
  94428. get: function () {
  94429. return this._positionScale;
  94430. },
  94431. /**
  94432. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94433. */
  94434. set: function (scale) {
  94435. this._positionScale = scale;
  94436. },
  94437. enumerable: true,
  94438. configurable: true
  94439. });
  94440. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94441. /**
  94442. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94443. * behaviour is triggered, in radians.
  94444. */
  94445. get: function () {
  94446. return this._defaultElevation;
  94447. },
  94448. /**
  94449. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94450. * behaviour is triggered, in radians.
  94451. */
  94452. set: function (elevation) {
  94453. this._defaultElevation = elevation;
  94454. },
  94455. enumerable: true,
  94456. configurable: true
  94457. });
  94458. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94459. /**
  94460. * Gets the time (in milliseconds) taken to return to the default beta position.
  94461. * Negative value indicates camera should not return to default.
  94462. */
  94463. get: function () {
  94464. return this._elevationReturnTime;
  94465. },
  94466. /**
  94467. * Sets the time (in milliseconds) taken to return to the default beta position.
  94468. * Negative value indicates camera should not return to default.
  94469. */
  94470. set: function (speed) {
  94471. this._elevationReturnTime = speed;
  94472. },
  94473. enumerable: true,
  94474. configurable: true
  94475. });
  94476. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94477. /**
  94478. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94479. */
  94480. get: function () {
  94481. return this._elevationReturnWaitTime;
  94482. },
  94483. /**
  94484. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94485. */
  94486. set: function (time) {
  94487. this._elevationReturnWaitTime = time;
  94488. },
  94489. enumerable: true,
  94490. configurable: true
  94491. });
  94492. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94493. /**
  94494. * Gets the flag that indicates if user zooming should stop animation.
  94495. */
  94496. get: function () {
  94497. return this._zoomStopsAnimation;
  94498. },
  94499. /**
  94500. * Sets the flag that indicates if user zooming should stop animation.
  94501. */
  94502. set: function (flag) {
  94503. this._zoomStopsAnimation = flag;
  94504. },
  94505. enumerable: true,
  94506. configurable: true
  94507. });
  94508. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94509. /**
  94510. * Gets the transition time when framing the mesh, in milliseconds
  94511. */
  94512. get: function () {
  94513. return this._framingTime;
  94514. },
  94515. /**
  94516. * Sets the transition time when framing the mesh, in milliseconds
  94517. */
  94518. set: function (time) {
  94519. this._framingTime = time;
  94520. },
  94521. enumerable: true,
  94522. configurable: true
  94523. });
  94524. FramingBehavior.prototype.init = function () {
  94525. // Do notihng
  94526. };
  94527. FramingBehavior.prototype.attach = function (camera) {
  94528. var _this = this;
  94529. this._attachedCamera = camera;
  94530. var scene = this._attachedCamera.getScene();
  94531. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94532. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94533. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94534. _this._isPointerDown = true;
  94535. return;
  94536. }
  94537. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94538. _this._isPointerDown = false;
  94539. }
  94540. });
  94541. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94542. if (mesh) {
  94543. _this.zoomOnMesh(mesh);
  94544. }
  94545. });
  94546. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94547. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94548. _this._applyUserInteraction();
  94549. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94550. // back to the default position after a given timeout
  94551. _this._maintainCameraAboveGround();
  94552. });
  94553. };
  94554. FramingBehavior.prototype.detach = function () {
  94555. if (!this._attachedCamera) {
  94556. return;
  94557. }
  94558. var scene = this._attachedCamera.getScene();
  94559. if (this._onPrePointerObservableObserver) {
  94560. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94561. }
  94562. if (this._onAfterCheckInputsObserver) {
  94563. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94564. }
  94565. if (this._onMeshTargetChangedObserver) {
  94566. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94567. }
  94568. this._attachedCamera = null;
  94569. };
  94570. /**
  94571. * Targets the given mesh and updates zoom level accordingly.
  94572. * @param mesh The mesh to target.
  94573. * @param radius Optional. If a cached radius position already exists, overrides default.
  94574. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94575. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94576. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94577. */
  94578. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94579. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94580. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94581. mesh.computeWorldMatrix(true);
  94582. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94583. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94584. };
  94585. /**
  94586. * Targets the given mesh with its children and updates zoom level accordingly.
  94587. * @param mesh The mesh to target.
  94588. * @param radius Optional. If a cached radius position already exists, overrides default.
  94589. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94590. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94591. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94592. */
  94593. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94594. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94595. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94596. mesh.computeWorldMatrix(true);
  94597. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94598. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94599. };
  94600. /**
  94601. * Targets the given meshes with their children and updates zoom level accordingly.
  94602. * @param meshes The mesh to target.
  94603. * @param radius Optional. If a cached radius position already exists, overrides default.
  94604. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94605. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94606. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94607. */
  94608. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94609. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94610. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94611. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94612. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94613. for (var i = 0; i < meshes.length; i++) {
  94614. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94615. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94616. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94617. }
  94618. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94619. };
  94620. /**
  94621. * Targets the given mesh and updates zoom level accordingly.
  94622. * @param mesh The mesh to target.
  94623. * @param radius Optional. If a cached radius position already exists, overrides default.
  94624. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94625. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94626. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94627. */
  94628. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94629. var _this = this;
  94630. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94631. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94632. var zoomTarget;
  94633. if (!this._attachedCamera) {
  94634. return;
  94635. }
  94636. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94637. var bottom = minimumWorld.y;
  94638. var top = maximumWorld.y;
  94639. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94640. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94641. if (focusOnOriginXZ) {
  94642. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94643. }
  94644. else {
  94645. var centerWorld = minimumWorld.add(radiusWorld);
  94646. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94647. }
  94648. if (!this._vectorTransition) {
  94649. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94650. }
  94651. this._betaIsAnimating = true;
  94652. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94653. if (animatable) {
  94654. this._animatables.push(animatable);
  94655. }
  94656. // sets the radius and lower radius bounds
  94657. // Small delta ensures camera is not always at lower zoom limit.
  94658. var radius = 0;
  94659. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94660. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94661. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94662. radius = position;
  94663. }
  94664. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94665. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94666. if (this._attachedCamera.lowerRadiusLimit === null) {
  94667. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94668. }
  94669. }
  94670. // Set sensibilities
  94671. var extend = maximumWorld.subtract(minimumWorld).length();
  94672. this._attachedCamera.panningSensibility = 5000 / extend;
  94673. this._attachedCamera.wheelPrecision = 100 / radius;
  94674. // transition to new radius
  94675. if (!this._radiusTransition) {
  94676. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94677. }
  94678. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94679. _this.stopAllAnimations();
  94680. if (onAnimationEnd) {
  94681. onAnimationEnd();
  94682. }
  94683. if (_this._attachedCamera) {
  94684. _this._attachedCamera.storeState();
  94685. }
  94686. });
  94687. if (animatable) {
  94688. this._animatables.push(animatable);
  94689. }
  94690. };
  94691. /**
  94692. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94693. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94694. * frustum width.
  94695. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94696. * to fully enclose the mesh in the viewing frustum.
  94697. */
  94698. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94699. var size = maximumWorld.subtract(minimumWorld);
  94700. var boxVectorGlobalDiagonal = size.length();
  94701. var frustumSlope = this._getFrustumSlope();
  94702. // Formula for setting distance
  94703. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94704. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94705. // Horizon distance
  94706. var radius = radiusWithoutFraming * this._radiusScale;
  94707. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94708. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94709. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94710. var camera = this._attachedCamera;
  94711. if (!camera) {
  94712. return 0;
  94713. }
  94714. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94715. // Don't exceed the requested limit
  94716. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94717. }
  94718. // Don't exceed the upper radius limit
  94719. if (camera.upperRadiusLimit) {
  94720. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94721. }
  94722. return distance;
  94723. };
  94724. /**
  94725. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94726. * is automatically returned to its default position (expected to be above ground plane).
  94727. */
  94728. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94729. var _this = this;
  94730. if (this._elevationReturnTime < 0) {
  94731. return;
  94732. }
  94733. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94734. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94735. var limitBeta = Math.PI * 0.5;
  94736. // Bring the camera back up if below the ground plane
  94737. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94738. this._betaIsAnimating = true;
  94739. //Transition to new position
  94740. this.stopAllAnimations();
  94741. if (!this._betaTransition) {
  94742. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94743. }
  94744. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94745. _this._clearAnimationLocks();
  94746. _this.stopAllAnimations();
  94747. });
  94748. if (animatabe) {
  94749. this._animatables.push(animatabe);
  94750. }
  94751. }
  94752. };
  94753. /**
  94754. * Returns the frustum slope based on the canvas ratio and camera FOV
  94755. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94756. */
  94757. FramingBehavior.prototype._getFrustumSlope = function () {
  94758. // Calculate the viewport ratio
  94759. // Aspect Ratio is Height/Width.
  94760. var camera = this._attachedCamera;
  94761. if (!camera) {
  94762. return BABYLON.Vector2.Zero();
  94763. }
  94764. var engine = camera.getScene().getEngine();
  94765. var aspectRatio = engine.getAspectRatio(camera);
  94766. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94767. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94768. var frustumSlopeY = Math.tan(camera.fov / 2);
  94769. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94770. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94771. // along the forward vector.
  94772. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94773. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94774. };
  94775. /**
  94776. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94777. */
  94778. FramingBehavior.prototype._clearAnimationLocks = function () {
  94779. this._betaIsAnimating = false;
  94780. };
  94781. /**
  94782. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94783. */
  94784. FramingBehavior.prototype._applyUserInteraction = function () {
  94785. if (this.isUserIsMoving) {
  94786. this._lastInteractionTime = BABYLON.Tools.Now;
  94787. this.stopAllAnimations();
  94788. this._clearAnimationLocks();
  94789. }
  94790. };
  94791. /**
  94792. * Stops and removes all animations that have been applied to the camera
  94793. */
  94794. FramingBehavior.prototype.stopAllAnimations = function () {
  94795. if (this._attachedCamera) {
  94796. this._attachedCamera.animations = [];
  94797. }
  94798. while (this._animatables.length) {
  94799. if (this._animatables[0]) {
  94800. this._animatables[0].onAnimationEnd = null;
  94801. this._animatables[0].stop();
  94802. }
  94803. this._animatables.shift();
  94804. }
  94805. };
  94806. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94807. /**
  94808. * Gets a value indicating if the user is moving the camera
  94809. */
  94810. get: function () {
  94811. if (!this._attachedCamera) {
  94812. return false;
  94813. }
  94814. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94815. this._attachedCamera.inertialBetaOffset !== 0 ||
  94816. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94817. this._attachedCamera.inertialPanningX !== 0 ||
  94818. this._attachedCamera.inertialPanningY !== 0 ||
  94819. this._isPointerDown;
  94820. },
  94821. enumerable: true,
  94822. configurable: true
  94823. });
  94824. /**
  94825. * The easing function used by animations
  94826. */
  94827. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94828. /**
  94829. * The easing mode used by animations
  94830. */
  94831. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94832. // Statics
  94833. /**
  94834. * The camera can move all the way towards the mesh.
  94835. */
  94836. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94837. /**
  94838. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94839. */
  94840. FramingBehavior.FitFrustumSidesMode = 1;
  94841. return FramingBehavior;
  94842. }());
  94843. BABYLON.FramingBehavior = FramingBehavior;
  94844. })(BABYLON || (BABYLON = {}));
  94845. //# sourceMappingURL=babylon.framingBehavior.js.map
  94846. var BABYLON;
  94847. (function (BABYLON) {
  94848. /**
  94849. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94850. */
  94851. var BouncingBehavior = /** @class */ (function () {
  94852. function BouncingBehavior() {
  94853. /**
  94854. * The duration of the animation, in milliseconds
  94855. */
  94856. this.transitionDuration = 450;
  94857. /**
  94858. * Length of the distance animated by the transition when lower radius is reached
  94859. */
  94860. this.lowerRadiusTransitionRange = 2;
  94861. /**
  94862. * Length of the distance animated by the transition when upper radius is reached
  94863. */
  94864. this.upperRadiusTransitionRange = -2;
  94865. this._autoTransitionRange = false;
  94866. // Animations
  94867. this._radiusIsAnimating = false;
  94868. this._radiusBounceTransition = null;
  94869. this._animatables = new Array();
  94870. }
  94871. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94872. get: function () {
  94873. return "Bouncing";
  94874. },
  94875. enumerable: true,
  94876. configurable: true
  94877. });
  94878. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94879. /**
  94880. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94881. */
  94882. get: function () {
  94883. return this._autoTransitionRange;
  94884. },
  94885. /**
  94886. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94887. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94888. */
  94889. set: function (value) {
  94890. var _this = this;
  94891. if (this._autoTransitionRange === value) {
  94892. return;
  94893. }
  94894. this._autoTransitionRange = value;
  94895. var camera = this._attachedCamera;
  94896. if (!camera) {
  94897. return;
  94898. }
  94899. if (value) {
  94900. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94901. if (!mesh) {
  94902. return;
  94903. }
  94904. mesh.computeWorldMatrix(true);
  94905. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94906. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94907. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94908. });
  94909. }
  94910. else if (this._onMeshTargetChangedObserver) {
  94911. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94912. }
  94913. },
  94914. enumerable: true,
  94915. configurable: true
  94916. });
  94917. BouncingBehavior.prototype.init = function () {
  94918. // Do notihng
  94919. };
  94920. BouncingBehavior.prototype.attach = function (camera) {
  94921. var _this = this;
  94922. this._attachedCamera = camera;
  94923. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94924. if (!_this._attachedCamera) {
  94925. return;
  94926. }
  94927. // Add the bounce animation to the lower radius limit
  94928. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94929. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94930. }
  94931. // Add the bounce animation to the upper radius limit
  94932. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94933. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94934. }
  94935. });
  94936. };
  94937. BouncingBehavior.prototype.detach = function () {
  94938. if (!this._attachedCamera) {
  94939. return;
  94940. }
  94941. if (this._onAfterCheckInputsObserver) {
  94942. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94943. }
  94944. if (this._onMeshTargetChangedObserver) {
  94945. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94946. }
  94947. this._attachedCamera = null;
  94948. };
  94949. /**
  94950. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94951. * @param radiusLimit The limit to check against.
  94952. * @return Bool to indicate if at limit.
  94953. */
  94954. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94955. if (!this._attachedCamera) {
  94956. return false;
  94957. }
  94958. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94959. return true;
  94960. }
  94961. return false;
  94962. };
  94963. /**
  94964. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94965. * @param radiusDelta The delta by which to animate to. Can be negative.
  94966. */
  94967. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94968. var _this = this;
  94969. if (!this._attachedCamera) {
  94970. return;
  94971. }
  94972. if (!this._radiusBounceTransition) {
  94973. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94974. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94975. }
  94976. // Prevent zoom until bounce has completed
  94977. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94978. this._attachedCamera.wheelPrecision = Infinity;
  94979. this._attachedCamera.inertialRadiusOffset = 0;
  94980. // Animate to the radius limit
  94981. this.stopAllAnimations();
  94982. this._radiusIsAnimating = true;
  94983. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94984. if (animatable) {
  94985. this._animatables.push(animatable);
  94986. }
  94987. };
  94988. /**
  94989. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94990. */
  94991. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94992. this._radiusIsAnimating = false;
  94993. if (this._attachedCamera) {
  94994. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94995. }
  94996. };
  94997. /**
  94998. * Stops and removes all animations that have been applied to the camera
  94999. */
  95000. BouncingBehavior.prototype.stopAllAnimations = function () {
  95001. if (this._attachedCamera) {
  95002. this._attachedCamera.animations = [];
  95003. }
  95004. while (this._animatables.length) {
  95005. this._animatables[0].onAnimationEnd = null;
  95006. this._animatables[0].stop();
  95007. this._animatables.shift();
  95008. }
  95009. };
  95010. /**
  95011. * The easing function used by animations
  95012. */
  95013. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  95014. /**
  95015. * The easing mode used by animations
  95016. */
  95017. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  95018. return BouncingBehavior;
  95019. }());
  95020. BABYLON.BouncingBehavior = BouncingBehavior;
  95021. })(BABYLON || (BABYLON = {}));
  95022. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  95023. var BABYLON;
  95024. (function (BABYLON) {
  95025. var AutoRotationBehavior = /** @class */ (function () {
  95026. function AutoRotationBehavior() {
  95027. this._zoomStopsAnimation = false;
  95028. this._idleRotationSpeed = 0.05;
  95029. this._idleRotationWaitTime = 2000;
  95030. this._idleRotationSpinupTime = 2000;
  95031. this._isPointerDown = false;
  95032. this._lastFrameTime = null;
  95033. this._lastInteractionTime = -Infinity;
  95034. this._cameraRotationSpeed = 0;
  95035. this._lastFrameRadius = 0;
  95036. }
  95037. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  95038. get: function () {
  95039. return "AutoRotation";
  95040. },
  95041. enumerable: true,
  95042. configurable: true
  95043. });
  95044. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  95045. /**
  95046. * Gets the flag that indicates if user zooming should stop animation.
  95047. */
  95048. get: function () {
  95049. return this._zoomStopsAnimation;
  95050. },
  95051. /**
  95052. * Sets the flag that indicates if user zooming should stop animation.
  95053. */
  95054. set: function (flag) {
  95055. this._zoomStopsAnimation = flag;
  95056. },
  95057. enumerable: true,
  95058. configurable: true
  95059. });
  95060. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  95061. /**
  95062. * Gets the default speed at which the camera rotates around the model.
  95063. */
  95064. get: function () {
  95065. return this._idleRotationSpeed;
  95066. },
  95067. /**
  95068. * Sets the default speed at which the camera rotates around the model.
  95069. */
  95070. set: function (speed) {
  95071. this._idleRotationSpeed = speed;
  95072. },
  95073. enumerable: true,
  95074. configurable: true
  95075. });
  95076. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  95077. /**
  95078. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  95079. */
  95080. get: function () {
  95081. return this._idleRotationWaitTime;
  95082. },
  95083. /**
  95084. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  95085. */
  95086. set: function (time) {
  95087. this._idleRotationWaitTime = time;
  95088. },
  95089. enumerable: true,
  95090. configurable: true
  95091. });
  95092. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  95093. /**
  95094. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95095. */
  95096. get: function () {
  95097. return this._idleRotationSpinupTime;
  95098. },
  95099. /**
  95100. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95101. */
  95102. set: function (time) {
  95103. this._idleRotationSpinupTime = time;
  95104. },
  95105. enumerable: true,
  95106. configurable: true
  95107. });
  95108. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  95109. /**
  95110. * Gets a value indicating if the camera is currently rotating because of this behavior
  95111. */
  95112. get: function () {
  95113. return Math.abs(this._cameraRotationSpeed) > 0;
  95114. },
  95115. enumerable: true,
  95116. configurable: true
  95117. });
  95118. AutoRotationBehavior.prototype.init = function () {
  95119. // Do notihng
  95120. };
  95121. AutoRotationBehavior.prototype.attach = function (camera) {
  95122. var _this = this;
  95123. this._attachedCamera = camera;
  95124. var scene = this._attachedCamera.getScene();
  95125. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  95126. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95127. _this._isPointerDown = true;
  95128. return;
  95129. }
  95130. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  95131. _this._isPointerDown = false;
  95132. }
  95133. });
  95134. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95135. var now = BABYLON.Tools.Now;
  95136. var dt = 0;
  95137. if (_this._lastFrameTime != null) {
  95138. dt = now - _this._lastFrameTime;
  95139. }
  95140. _this._lastFrameTime = now;
  95141. // Stop the animation if there is user interaction and the animation should stop for this interaction
  95142. _this._applyUserInteraction();
  95143. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  95144. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  95145. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  95146. // Step camera rotation by rotation speed
  95147. if (_this._attachedCamera) {
  95148. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  95149. }
  95150. });
  95151. };
  95152. AutoRotationBehavior.prototype.detach = function () {
  95153. if (!this._attachedCamera) {
  95154. return;
  95155. }
  95156. var scene = this._attachedCamera.getScene();
  95157. if (this._onPrePointerObservableObserver) {
  95158. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95159. }
  95160. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95161. this._attachedCamera = null;
  95162. };
  95163. /**
  95164. * Returns true if user is scrolling.
  95165. * @return true if user is scrolling.
  95166. */
  95167. AutoRotationBehavior.prototype._userIsZooming = function () {
  95168. if (!this._attachedCamera) {
  95169. return false;
  95170. }
  95171. return this._attachedCamera.inertialRadiusOffset !== 0;
  95172. };
  95173. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  95174. if (!this._attachedCamera) {
  95175. return false;
  95176. }
  95177. var zoomHasHitLimit = false;
  95178. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  95179. zoomHasHitLimit = true;
  95180. }
  95181. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  95182. this._lastFrameRadius = this._attachedCamera.radius;
  95183. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  95184. };
  95185. /**
  95186. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95187. */
  95188. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  95189. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  95190. this._lastInteractionTime = BABYLON.Tools.Now;
  95191. }
  95192. };
  95193. // Tools
  95194. AutoRotationBehavior.prototype._userIsMoving = function () {
  95195. if (!this._attachedCamera) {
  95196. return false;
  95197. }
  95198. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95199. this._attachedCamera.inertialBetaOffset !== 0 ||
  95200. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95201. this._attachedCamera.inertialPanningX !== 0 ||
  95202. this._attachedCamera.inertialPanningY !== 0 ||
  95203. this._isPointerDown;
  95204. };
  95205. return AutoRotationBehavior;
  95206. }());
  95207. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  95208. })(BABYLON || (BABYLON = {}));
  95209. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  95210. var BABYLON;
  95211. (function (BABYLON) {
  95212. var NullEngineOptions = /** @class */ (function () {
  95213. function NullEngineOptions() {
  95214. this.renderWidth = 512;
  95215. this.renderHeight = 256;
  95216. this.textureSize = 512;
  95217. this.deterministicLockstep = false;
  95218. this.lockstepMaxSteps = 4;
  95219. }
  95220. return NullEngineOptions;
  95221. }());
  95222. BABYLON.NullEngineOptions = NullEngineOptions;
  95223. /**
  95224. * The null engine class provides support for headless version of babylon.js.
  95225. * This can be used in server side scenario or for testing purposes
  95226. */
  95227. var NullEngine = /** @class */ (function (_super) {
  95228. __extends(NullEngine, _super);
  95229. function NullEngine(options) {
  95230. if (options === void 0) { options = new NullEngineOptions(); }
  95231. var _this = _super.call(this, null) || this;
  95232. if (options.deterministicLockstep === undefined) {
  95233. options.deterministicLockstep = false;
  95234. }
  95235. if (options.lockstepMaxSteps === undefined) {
  95236. options.lockstepMaxSteps = 4;
  95237. }
  95238. _this._options = options;
  95239. // Init caps
  95240. // We consider we are on a webgl1 capable device
  95241. _this._caps = new BABYLON.EngineCapabilities();
  95242. _this._caps.maxTexturesImageUnits = 16;
  95243. _this._caps.maxVertexTextureImageUnits = 16;
  95244. _this._caps.maxTextureSize = 512;
  95245. _this._caps.maxCubemapTextureSize = 512;
  95246. _this._caps.maxRenderTextureSize = 512;
  95247. _this._caps.maxVertexAttribs = 16;
  95248. _this._caps.maxVaryingVectors = 16;
  95249. _this._caps.maxFragmentUniformVectors = 16;
  95250. _this._caps.maxVertexUniformVectors = 16;
  95251. // Extensions
  95252. _this._caps.standardDerivatives = false;
  95253. _this._caps.astc = null;
  95254. _this._caps.s3tc = null;
  95255. _this._caps.pvrtc = null;
  95256. _this._caps.etc1 = null;
  95257. _this._caps.etc2 = null;
  95258. _this._caps.textureAnisotropicFilterExtension = null;
  95259. _this._caps.maxAnisotropy = 0;
  95260. _this._caps.uintIndices = false;
  95261. _this._caps.fragmentDepthSupported = false;
  95262. _this._caps.highPrecisionShaderSupported = true;
  95263. _this._caps.colorBufferFloat = false;
  95264. _this._caps.textureFloat = false;
  95265. _this._caps.textureFloatLinearFiltering = false;
  95266. _this._caps.textureFloatRender = false;
  95267. _this._caps.textureHalfFloat = false;
  95268. _this._caps.textureHalfFloatLinearFiltering = false;
  95269. _this._caps.textureHalfFloatRender = false;
  95270. _this._caps.textureLOD = false;
  95271. _this._caps.drawBuffersExtension = false;
  95272. _this._caps.depthTextureExtension = false;
  95273. _this._caps.vertexArrayObject = false;
  95274. _this._caps.instancedArrays = false;
  95275. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  95276. // Wrappers
  95277. if (typeof URL === "undefined") {
  95278. URL = {
  95279. createObjectURL: function () { },
  95280. revokeObjectURL: function () { }
  95281. };
  95282. }
  95283. if (typeof Blob === "undefined") {
  95284. Blob = function () { };
  95285. }
  95286. return _this;
  95287. }
  95288. NullEngine.prototype.isDeterministicLockStep = function () {
  95289. return this._options.deterministicLockstep;
  95290. };
  95291. NullEngine.prototype.getLockstepMaxSteps = function () {
  95292. return this._options.lockstepMaxSteps;
  95293. };
  95294. NullEngine.prototype.getHardwareScalingLevel = function () {
  95295. return 1.0;
  95296. };
  95297. NullEngine.prototype.createVertexBuffer = function (vertices) {
  95298. return {
  95299. capacity: 0,
  95300. references: 1,
  95301. is32Bits: false
  95302. };
  95303. };
  95304. NullEngine.prototype.createIndexBuffer = function (indices) {
  95305. return {
  95306. capacity: 0,
  95307. references: 1,
  95308. is32Bits: false
  95309. };
  95310. };
  95311. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  95312. if (stencil === void 0) { stencil = false; }
  95313. };
  95314. NullEngine.prototype.getRenderWidth = function (useScreen) {
  95315. if (useScreen === void 0) { useScreen = false; }
  95316. if (!useScreen && this._currentRenderTarget) {
  95317. return this._currentRenderTarget.width;
  95318. }
  95319. return this._options.renderWidth;
  95320. };
  95321. NullEngine.prototype.getRenderHeight = function (useScreen) {
  95322. if (useScreen === void 0) { useScreen = false; }
  95323. if (!useScreen && this._currentRenderTarget) {
  95324. return this._currentRenderTarget.height;
  95325. }
  95326. return this._options.renderHeight;
  95327. };
  95328. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  95329. this._cachedViewport = viewport;
  95330. };
  95331. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  95332. return {
  95333. transformFeedback: null,
  95334. __SPECTOR_rebuildProgram: null
  95335. };
  95336. };
  95337. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  95338. return [];
  95339. };
  95340. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  95341. return [];
  95342. };
  95343. NullEngine.prototype.bindSamplers = function (effect) {
  95344. this._currentEffect = null;
  95345. };
  95346. NullEngine.prototype.enableEffect = function (effect) {
  95347. this._currentEffect = effect;
  95348. if (effect.onBind) {
  95349. effect.onBind(effect);
  95350. }
  95351. effect.onBindObservable.notifyObservers(effect);
  95352. };
  95353. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  95354. if (zOffset === void 0) { zOffset = 0; }
  95355. if (reverseSide === void 0) { reverseSide = false; }
  95356. };
  95357. NullEngine.prototype.setIntArray = function (uniform, array) {
  95358. };
  95359. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  95360. };
  95361. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  95362. };
  95363. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  95364. };
  95365. NullEngine.prototype.setFloatArray = function (uniform, array) {
  95366. };
  95367. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  95368. };
  95369. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  95370. };
  95371. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  95372. };
  95373. NullEngine.prototype.setArray = function (uniform, array) {
  95374. };
  95375. NullEngine.prototype.setArray2 = function (uniform, array) {
  95376. };
  95377. NullEngine.prototype.setArray3 = function (uniform, array) {
  95378. };
  95379. NullEngine.prototype.setArray4 = function (uniform, array) {
  95380. };
  95381. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  95382. };
  95383. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  95384. };
  95385. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  95386. };
  95387. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  95388. };
  95389. NullEngine.prototype.setFloat = function (uniform, value) {
  95390. };
  95391. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  95392. };
  95393. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  95394. };
  95395. NullEngine.prototype.setBool = function (uniform, bool) {
  95396. };
  95397. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  95398. };
  95399. NullEngine.prototype.setColor3 = function (uniform, color3) {
  95400. };
  95401. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  95402. };
  95403. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  95404. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  95405. if (this._alphaMode === mode) {
  95406. return;
  95407. }
  95408. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  95409. if (!noDepthWriteChange) {
  95410. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95411. }
  95412. this._alphaMode = mode;
  95413. };
  95414. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95415. };
  95416. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95417. if (this.preventCacheWipeBetweenFrames) {
  95418. return;
  95419. }
  95420. this.resetTextureCache();
  95421. this._currentEffect = null;
  95422. if (bruteForce) {
  95423. this._currentProgram = null;
  95424. this._stencilState.reset();
  95425. this._depthCullingState.reset();
  95426. this._alphaState.reset();
  95427. }
  95428. this._cachedVertexBuffers = null;
  95429. this._cachedIndexBuffer = null;
  95430. this._cachedEffectForVertexBuffers = null;
  95431. };
  95432. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95433. };
  95434. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95435. };
  95436. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95437. };
  95438. NullEngine.prototype._createTexture = function () {
  95439. return {};
  95440. };
  95441. NullEngine.prototype._releaseTexture = function (texture) {
  95442. };
  95443. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95444. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95445. if (onLoad === void 0) { onLoad = null; }
  95446. if (onError === void 0) { onError = null; }
  95447. if (buffer === void 0) { buffer = null; }
  95448. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95449. var url = String(urlArg);
  95450. texture.url = url;
  95451. texture.generateMipMaps = !noMipmap;
  95452. texture.samplingMode = samplingMode;
  95453. texture.invertY = invertY;
  95454. texture.baseWidth = this._options.textureSize;
  95455. texture.baseHeight = this._options.textureSize;
  95456. texture.width = this._options.textureSize;
  95457. texture.height = this._options.textureSize;
  95458. if (format) {
  95459. texture.format = format;
  95460. }
  95461. texture.isReady = true;
  95462. if (onLoad) {
  95463. onLoad();
  95464. }
  95465. this._internalTexturesCache.push(texture);
  95466. return texture;
  95467. };
  95468. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95469. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95470. if (options !== undefined && typeof options === "object") {
  95471. fullOptions.generateMipMaps = options.generateMipMaps;
  95472. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95473. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95474. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95475. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95476. }
  95477. else {
  95478. fullOptions.generateMipMaps = options;
  95479. fullOptions.generateDepthBuffer = true;
  95480. fullOptions.generateStencilBuffer = false;
  95481. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95482. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95483. }
  95484. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95485. var width = size.width || size;
  95486. var height = size.height || size;
  95487. texture._depthStencilBuffer = {};
  95488. texture._framebuffer = {};
  95489. texture.baseWidth = width;
  95490. texture.baseHeight = height;
  95491. texture.width = width;
  95492. texture.height = height;
  95493. texture.isReady = true;
  95494. texture.samples = 1;
  95495. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95496. texture.samplingMode = fullOptions.samplingMode;
  95497. texture.type = fullOptions.type;
  95498. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95499. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95500. this._internalTexturesCache.push(texture);
  95501. return texture;
  95502. };
  95503. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95504. texture.samplingMode = samplingMode;
  95505. };
  95506. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95507. if (this._currentRenderTarget) {
  95508. this.unBindFramebuffer(this._currentRenderTarget);
  95509. }
  95510. this._currentRenderTarget = texture;
  95511. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95512. if (this._cachedViewport && !forceFullscreenViewport) {
  95513. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95514. }
  95515. };
  95516. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95517. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95518. this._currentRenderTarget = null;
  95519. if (onBeforeUnbind) {
  95520. if (texture._MSAAFramebuffer) {
  95521. this._currentFramebuffer = texture._framebuffer;
  95522. }
  95523. onBeforeUnbind();
  95524. }
  95525. this._currentFramebuffer = null;
  95526. };
  95527. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95528. var vbo = {
  95529. capacity: 1,
  95530. references: 1,
  95531. is32Bits: false
  95532. };
  95533. return vbo;
  95534. };
  95535. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95536. if (offset === void 0) { offset = 0; }
  95537. };
  95538. /**
  95539. * Updates a dynamic vertex buffer.
  95540. * @param vertexBuffer the vertex buffer to update
  95541. * @param data the data used to update the vertex buffer
  95542. * @param byteOffset the byte offset of the data (optional)
  95543. * @param byteLength the byte length of the data (optional)
  95544. */
  95545. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95546. };
  95547. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95548. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95549. this._boundTexturesCache[this._activeChannel] = texture;
  95550. }
  95551. };
  95552. NullEngine.prototype._bindTexture = function (channel, texture) {
  95553. if (channel < 0) {
  95554. return;
  95555. }
  95556. this._bindTextureDirectly(0, texture);
  95557. };
  95558. NullEngine.prototype._releaseBuffer = function (buffer) {
  95559. buffer.references--;
  95560. if (buffer.references === 0) {
  95561. return true;
  95562. }
  95563. return false;
  95564. };
  95565. NullEngine.prototype.releaseEffects = function () {
  95566. };
  95567. return NullEngine;
  95568. }(BABYLON.Engine));
  95569. BABYLON.NullEngine = NullEngine;
  95570. })(BABYLON || (BABYLON = {}));
  95571. //# sourceMappingURL=babylon.nullEngine.js.map
  95572. var BABYLON;
  95573. (function (BABYLON) {
  95574. /**
  95575. * This class can be used to get instrumentation data from a Babylon engine
  95576. */
  95577. var EngineInstrumentation = /** @class */ (function () {
  95578. function EngineInstrumentation(engine) {
  95579. this.engine = engine;
  95580. this._captureGPUFrameTime = false;
  95581. this._gpuFrameTime = new BABYLON.PerfCounter();
  95582. this._captureShaderCompilationTime = false;
  95583. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95584. // Observers
  95585. this._onBeginFrameObserver = null;
  95586. this._onEndFrameObserver = null;
  95587. this._onBeforeShaderCompilationObserver = null;
  95588. this._onAfterShaderCompilationObserver = null;
  95589. }
  95590. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95591. // Properties
  95592. /**
  95593. * Gets the perf counter used for GPU frame time
  95594. */
  95595. get: function () {
  95596. return this._gpuFrameTime;
  95597. },
  95598. enumerable: true,
  95599. configurable: true
  95600. });
  95601. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95602. /**
  95603. * Gets the GPU frame time capture status
  95604. */
  95605. get: function () {
  95606. return this._captureGPUFrameTime;
  95607. },
  95608. /**
  95609. * Enable or disable the GPU frame time capture
  95610. */
  95611. set: function (value) {
  95612. var _this = this;
  95613. if (value === this._captureGPUFrameTime) {
  95614. return;
  95615. }
  95616. this._captureGPUFrameTime = value;
  95617. if (value) {
  95618. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95619. if (!_this._gpuFrameTimeToken) {
  95620. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95621. }
  95622. });
  95623. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95624. if (!_this._gpuFrameTimeToken) {
  95625. return;
  95626. }
  95627. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95628. if (time > -1) {
  95629. _this._gpuFrameTimeToken = null;
  95630. _this._gpuFrameTime.fetchNewFrame();
  95631. _this._gpuFrameTime.addCount(time, true);
  95632. }
  95633. });
  95634. }
  95635. else {
  95636. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95637. this._onBeginFrameObserver = null;
  95638. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95639. this._onEndFrameObserver = null;
  95640. }
  95641. },
  95642. enumerable: true,
  95643. configurable: true
  95644. });
  95645. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95646. /**
  95647. * Gets the perf counter used for shader compilation time
  95648. */
  95649. get: function () {
  95650. return this._shaderCompilationTime;
  95651. },
  95652. enumerable: true,
  95653. configurable: true
  95654. });
  95655. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95656. /**
  95657. * Gets the shader compilation time capture status
  95658. */
  95659. get: function () {
  95660. return this._captureShaderCompilationTime;
  95661. },
  95662. /**
  95663. * Enable or disable the shader compilation time capture
  95664. */
  95665. set: function (value) {
  95666. var _this = this;
  95667. if (value === this._captureShaderCompilationTime) {
  95668. return;
  95669. }
  95670. this._captureShaderCompilationTime = value;
  95671. if (value) {
  95672. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95673. _this._shaderCompilationTime.fetchNewFrame();
  95674. _this._shaderCompilationTime.beginMonitoring();
  95675. });
  95676. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95677. _this._shaderCompilationTime.endMonitoring();
  95678. });
  95679. }
  95680. else {
  95681. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95682. this._onBeforeShaderCompilationObserver = null;
  95683. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95684. this._onAfterShaderCompilationObserver = null;
  95685. }
  95686. },
  95687. enumerable: true,
  95688. configurable: true
  95689. });
  95690. EngineInstrumentation.prototype.dispose = function () {
  95691. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95692. this._onBeginFrameObserver = null;
  95693. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95694. this._onEndFrameObserver = null;
  95695. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95696. this._onBeforeShaderCompilationObserver = null;
  95697. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95698. this._onAfterShaderCompilationObserver = null;
  95699. this.engine = null;
  95700. };
  95701. return EngineInstrumentation;
  95702. }());
  95703. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95704. })(BABYLON || (BABYLON = {}));
  95705. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95706. var BABYLON;
  95707. (function (BABYLON) {
  95708. /**
  95709. * This class can be used to get instrumentation data from a Babylon engine
  95710. */
  95711. var SceneInstrumentation = /** @class */ (function () {
  95712. function SceneInstrumentation(scene) {
  95713. var _this = this;
  95714. this.scene = scene;
  95715. this._captureActiveMeshesEvaluationTime = false;
  95716. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95717. this._captureRenderTargetsRenderTime = false;
  95718. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95719. this._captureFrameTime = false;
  95720. this._frameTime = new BABYLON.PerfCounter();
  95721. this._captureRenderTime = false;
  95722. this._renderTime = new BABYLON.PerfCounter();
  95723. this._captureInterFrameTime = false;
  95724. this._interFrameTime = new BABYLON.PerfCounter();
  95725. this._captureParticlesRenderTime = false;
  95726. this._particlesRenderTime = new BABYLON.PerfCounter();
  95727. this._captureSpritesRenderTime = false;
  95728. this._spritesRenderTime = new BABYLON.PerfCounter();
  95729. this._capturePhysicsTime = false;
  95730. this._physicsTime = new BABYLON.PerfCounter();
  95731. this._captureAnimationsTime = false;
  95732. this._animationsTime = new BABYLON.PerfCounter();
  95733. // Observers
  95734. this._onBeforeActiveMeshesEvaluationObserver = null;
  95735. this._onAfterActiveMeshesEvaluationObserver = null;
  95736. this._onBeforeRenderTargetsRenderObserver = null;
  95737. this._onAfterRenderTargetsRenderObserver = null;
  95738. this._onAfterRenderObserver = null;
  95739. this._onBeforeDrawPhaseObserver = null;
  95740. this._onAfterDrawPhaseObserver = null;
  95741. this._onBeforeAnimationsObserver = null;
  95742. this._onBeforeParticlesRenderingObserver = null;
  95743. this._onAfterParticlesRenderingObserver = null;
  95744. this._onBeforeSpritesRenderingObserver = null;
  95745. this._onAfterSpritesRenderingObserver = null;
  95746. this._onBeforePhysicsObserver = null;
  95747. this._onAfterPhysicsObserver = null;
  95748. this._onAfterAnimationsObserver = null;
  95749. // Before render
  95750. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95751. if (_this._captureActiveMeshesEvaluationTime) {
  95752. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95753. }
  95754. if (_this._captureRenderTargetsRenderTime) {
  95755. _this._renderTargetsRenderTime.fetchNewFrame();
  95756. }
  95757. if (_this._captureFrameTime) {
  95758. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95759. _this._frameTime.beginMonitoring();
  95760. }
  95761. if (_this._captureInterFrameTime) {
  95762. _this._interFrameTime.endMonitoring();
  95763. }
  95764. if (_this._captureParticlesRenderTime) {
  95765. _this._particlesRenderTime.fetchNewFrame();
  95766. }
  95767. if (_this._captureSpritesRenderTime) {
  95768. _this._spritesRenderTime.fetchNewFrame();
  95769. }
  95770. if (_this._captureAnimationsTime) {
  95771. _this._animationsTime.beginMonitoring();
  95772. }
  95773. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95774. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95775. });
  95776. // After render
  95777. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95778. if (_this._captureFrameTime) {
  95779. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95780. _this._frameTime.endMonitoring();
  95781. }
  95782. if (_this._captureRenderTime) {
  95783. _this._renderTime.endMonitoring(false);
  95784. }
  95785. if (_this._captureInterFrameTime) {
  95786. _this._interFrameTime.beginMonitoring();
  95787. }
  95788. });
  95789. }
  95790. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95791. // Properties
  95792. /**
  95793. * Gets the perf counter used for active meshes evaluation time
  95794. */
  95795. get: function () {
  95796. return this._activeMeshesEvaluationTime;
  95797. },
  95798. enumerable: true,
  95799. configurable: true
  95800. });
  95801. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95802. /**
  95803. * Gets the active meshes evaluation time capture status
  95804. */
  95805. get: function () {
  95806. return this._captureActiveMeshesEvaluationTime;
  95807. },
  95808. /**
  95809. * Enable or disable the active meshes evaluation time capture
  95810. */
  95811. set: function (value) {
  95812. var _this = this;
  95813. if (value === this._captureActiveMeshesEvaluationTime) {
  95814. return;
  95815. }
  95816. this._captureActiveMeshesEvaluationTime = value;
  95817. if (value) {
  95818. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95819. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95820. _this._activeMeshesEvaluationTime.beginMonitoring();
  95821. });
  95822. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95823. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95824. _this._activeMeshesEvaluationTime.endMonitoring();
  95825. });
  95826. }
  95827. else {
  95828. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95829. this._onBeforeActiveMeshesEvaluationObserver = null;
  95830. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95831. this._onAfterActiveMeshesEvaluationObserver = null;
  95832. }
  95833. },
  95834. enumerable: true,
  95835. configurable: true
  95836. });
  95837. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95838. /**
  95839. * Gets the perf counter used for render targets render time
  95840. */
  95841. get: function () {
  95842. return this._renderTargetsRenderTime;
  95843. },
  95844. enumerable: true,
  95845. configurable: true
  95846. });
  95847. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95848. /**
  95849. * Gets the render targets render time capture status
  95850. */
  95851. get: function () {
  95852. return this._captureRenderTargetsRenderTime;
  95853. },
  95854. /**
  95855. * Enable or disable the render targets render time capture
  95856. */
  95857. set: function (value) {
  95858. var _this = this;
  95859. if (value === this._captureRenderTargetsRenderTime) {
  95860. return;
  95861. }
  95862. this._captureRenderTargetsRenderTime = value;
  95863. if (value) {
  95864. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95865. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95866. _this._renderTargetsRenderTime.beginMonitoring();
  95867. });
  95868. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95869. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95870. _this._renderTargetsRenderTime.endMonitoring(false);
  95871. });
  95872. }
  95873. else {
  95874. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95875. this._onBeforeRenderTargetsRenderObserver = null;
  95876. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95877. this._onAfterRenderTargetsRenderObserver = null;
  95878. }
  95879. },
  95880. enumerable: true,
  95881. configurable: true
  95882. });
  95883. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95884. /**
  95885. * Gets the perf counter used for particles render time
  95886. */
  95887. get: function () {
  95888. return this._particlesRenderTime;
  95889. },
  95890. enumerable: true,
  95891. configurable: true
  95892. });
  95893. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95894. /**
  95895. * Gets the particles render time capture status
  95896. */
  95897. get: function () {
  95898. return this._captureParticlesRenderTime;
  95899. },
  95900. /**
  95901. * Enable or disable the particles render time capture
  95902. */
  95903. set: function (value) {
  95904. var _this = this;
  95905. if (value === this._captureParticlesRenderTime) {
  95906. return;
  95907. }
  95908. this._captureParticlesRenderTime = value;
  95909. if (value) {
  95910. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95911. BABYLON.Tools.StartPerformanceCounter("Particles");
  95912. _this._particlesRenderTime.beginMonitoring();
  95913. });
  95914. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95915. BABYLON.Tools.EndPerformanceCounter("Particles");
  95916. _this._particlesRenderTime.endMonitoring(false);
  95917. });
  95918. }
  95919. else {
  95920. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95921. this._onBeforeParticlesRenderingObserver = null;
  95922. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95923. this._onAfterParticlesRenderingObserver = null;
  95924. }
  95925. },
  95926. enumerable: true,
  95927. configurable: true
  95928. });
  95929. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95930. /**
  95931. * Gets the perf counter used for sprites render time
  95932. */
  95933. get: function () {
  95934. return this._spritesRenderTime;
  95935. },
  95936. enumerable: true,
  95937. configurable: true
  95938. });
  95939. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95940. /**
  95941. * Gets the sprites render time capture status
  95942. */
  95943. get: function () {
  95944. return this._captureSpritesRenderTime;
  95945. },
  95946. /**
  95947. * Enable or disable the sprites render time capture
  95948. */
  95949. set: function (value) {
  95950. var _this = this;
  95951. if (value === this._captureSpritesRenderTime) {
  95952. return;
  95953. }
  95954. this._captureSpritesRenderTime = value;
  95955. if (value) {
  95956. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95957. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95958. _this._spritesRenderTime.beginMonitoring();
  95959. });
  95960. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95961. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95962. _this._spritesRenderTime.endMonitoring(false);
  95963. });
  95964. }
  95965. else {
  95966. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95967. this._onBeforeSpritesRenderingObserver = null;
  95968. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95969. this._onAfterSpritesRenderingObserver = null;
  95970. }
  95971. },
  95972. enumerable: true,
  95973. configurable: true
  95974. });
  95975. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95976. /**
  95977. * Gets the perf counter used for physics time
  95978. */
  95979. get: function () {
  95980. return this._physicsTime;
  95981. },
  95982. enumerable: true,
  95983. configurable: true
  95984. });
  95985. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95986. /**
  95987. * Gets the physics time capture status
  95988. */
  95989. get: function () {
  95990. return this._capturePhysicsTime;
  95991. },
  95992. /**
  95993. * Enable or disable the physics time capture
  95994. */
  95995. set: function (value) {
  95996. var _this = this;
  95997. if (value === this._capturePhysicsTime) {
  95998. return;
  95999. }
  96000. this._capturePhysicsTime = value;
  96001. if (value) {
  96002. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  96003. BABYLON.Tools.StartPerformanceCounter("Physics");
  96004. _this._physicsTime.beginMonitoring();
  96005. });
  96006. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  96007. BABYLON.Tools.EndPerformanceCounter("Physics");
  96008. _this._physicsTime.endMonitoring();
  96009. });
  96010. }
  96011. else {
  96012. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96013. this._onBeforePhysicsObserver = null;
  96014. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96015. this._onAfterPhysicsObserver = null;
  96016. }
  96017. },
  96018. enumerable: true,
  96019. configurable: true
  96020. });
  96021. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  96022. /**
  96023. * Gets the perf counter used for animations time
  96024. */
  96025. get: function () {
  96026. return this._animationsTime;
  96027. },
  96028. enumerable: true,
  96029. configurable: true
  96030. });
  96031. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  96032. /**
  96033. * Gets the animations time capture status
  96034. */
  96035. get: function () {
  96036. return this._captureAnimationsTime;
  96037. },
  96038. /**
  96039. * Enable or disable the animations time capture
  96040. */
  96041. set: function (value) {
  96042. var _this = this;
  96043. if (value === this._captureAnimationsTime) {
  96044. return;
  96045. }
  96046. this._captureAnimationsTime = value;
  96047. if (value) {
  96048. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  96049. _this._animationsTime.endMonitoring();
  96050. });
  96051. }
  96052. else {
  96053. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96054. this._onAfterAnimationsObserver = null;
  96055. }
  96056. },
  96057. enumerable: true,
  96058. configurable: true
  96059. });
  96060. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  96061. /**
  96062. * Gets the perf counter used for frame time capture
  96063. */
  96064. get: function () {
  96065. return this._frameTime;
  96066. },
  96067. enumerable: true,
  96068. configurable: true
  96069. });
  96070. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  96071. /**
  96072. * Gets the frame time capture status
  96073. */
  96074. get: function () {
  96075. return this._captureFrameTime;
  96076. },
  96077. /**
  96078. * Enable or disable the frame time capture
  96079. */
  96080. set: function (value) {
  96081. this._captureFrameTime = value;
  96082. },
  96083. enumerable: true,
  96084. configurable: true
  96085. });
  96086. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  96087. /**
  96088. * Gets the perf counter used for inter-frames time capture
  96089. */
  96090. get: function () {
  96091. return this._interFrameTime;
  96092. },
  96093. enumerable: true,
  96094. configurable: true
  96095. });
  96096. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  96097. /**
  96098. * Gets the inter-frames time capture status
  96099. */
  96100. get: function () {
  96101. return this._captureInterFrameTime;
  96102. },
  96103. /**
  96104. * Enable or disable the inter-frames time capture
  96105. */
  96106. set: function (value) {
  96107. this._captureInterFrameTime = value;
  96108. },
  96109. enumerable: true,
  96110. configurable: true
  96111. });
  96112. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  96113. /**
  96114. * Gets the perf counter used for render time capture
  96115. */
  96116. get: function () {
  96117. return this._renderTime;
  96118. },
  96119. enumerable: true,
  96120. configurable: true
  96121. });
  96122. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  96123. /**
  96124. * Gets the render time capture status
  96125. */
  96126. get: function () {
  96127. return this._captureRenderTime;
  96128. },
  96129. /**
  96130. * Enable or disable the render time capture
  96131. */
  96132. set: function (value) {
  96133. var _this = this;
  96134. if (value === this._captureRenderTime) {
  96135. return;
  96136. }
  96137. this._captureRenderTime = value;
  96138. if (value) {
  96139. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  96140. _this._renderTime.beginMonitoring();
  96141. BABYLON.Tools.StartPerformanceCounter("Main render");
  96142. });
  96143. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  96144. _this._renderTime.endMonitoring(false);
  96145. BABYLON.Tools.EndPerformanceCounter("Main render");
  96146. });
  96147. }
  96148. else {
  96149. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96150. this._onBeforeDrawPhaseObserver = null;
  96151. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96152. this._onAfterDrawPhaseObserver = null;
  96153. }
  96154. },
  96155. enumerable: true,
  96156. configurable: true
  96157. });
  96158. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  96159. /**
  96160. * Gets the perf counter used for draw calls
  96161. */
  96162. get: function () {
  96163. return this.scene.getEngine()._drawCalls;
  96164. },
  96165. enumerable: true,
  96166. configurable: true
  96167. });
  96168. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  96169. /**
  96170. * Gets the perf counter used for texture collisions
  96171. */
  96172. get: function () {
  96173. return this.scene.getEngine()._textureCollisions;
  96174. },
  96175. enumerable: true,
  96176. configurable: true
  96177. });
  96178. SceneInstrumentation.prototype.dispose = function () {
  96179. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96180. this._onAfterRenderObserver = null;
  96181. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96182. this._onBeforeActiveMeshesEvaluationObserver = null;
  96183. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96184. this._onAfterActiveMeshesEvaluationObserver = null;
  96185. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96186. this._onBeforeRenderTargetsRenderObserver = null;
  96187. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96188. this._onAfterRenderTargetsRenderObserver = null;
  96189. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  96190. this._onBeforeAnimationsObserver = null;
  96191. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96192. this._onBeforeParticlesRenderingObserver = null;
  96193. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96194. this._onAfterParticlesRenderingObserver = null;
  96195. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96196. this._onBeforeSpritesRenderingObserver = null;
  96197. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96198. this._onAfterSpritesRenderingObserver = null;
  96199. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96200. this._onBeforeDrawPhaseObserver = null;
  96201. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96202. this._onAfterDrawPhaseObserver = null;
  96203. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96204. this._onBeforePhysicsObserver = null;
  96205. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96206. this._onAfterPhysicsObserver = null;
  96207. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96208. this._onAfterAnimationsObserver = null;
  96209. this.scene = null;
  96210. };
  96211. return SceneInstrumentation;
  96212. }());
  96213. BABYLON.SceneInstrumentation = SceneInstrumentation;
  96214. })(BABYLON || (BABYLON = {}));
  96215. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  96216. var BABYLON;
  96217. (function (BABYLON) {
  96218. /**
  96219. * @hidden
  96220. **/
  96221. var _TimeToken = /** @class */ (function () {
  96222. function _TimeToken() {
  96223. this._timeElapsedQueryEnded = false;
  96224. }
  96225. return _TimeToken;
  96226. }());
  96227. BABYLON._TimeToken = _TimeToken;
  96228. })(BABYLON || (BABYLON = {}));
  96229. //# sourceMappingURL=babylon.timeToken.js.map
  96230. var BABYLON;
  96231. (function (BABYLON) {
  96232. /**
  96233. * Background material defines definition.
  96234. * @hidden Mainly internal Use
  96235. */
  96236. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  96237. __extends(BackgroundMaterialDefines, _super);
  96238. /**
  96239. * Constructor of the defines.
  96240. */
  96241. function BackgroundMaterialDefines() {
  96242. var _this = _super.call(this) || this;
  96243. /**
  96244. * True if the diffuse texture is in use.
  96245. */
  96246. _this.DIFFUSE = false;
  96247. /**
  96248. * The direct UV channel to use.
  96249. */
  96250. _this.DIFFUSEDIRECTUV = 0;
  96251. /**
  96252. * True if the diffuse texture is in gamma space.
  96253. */
  96254. _this.GAMMADIFFUSE = false;
  96255. /**
  96256. * True if the diffuse texture has opacity in the alpha channel.
  96257. */
  96258. _this.DIFFUSEHASALPHA = false;
  96259. /**
  96260. * True if you want the material to fade to transparent at grazing angle.
  96261. */
  96262. _this.OPACITYFRESNEL = false;
  96263. /**
  96264. * True if an extra blur needs to be added in the reflection.
  96265. */
  96266. _this.REFLECTIONBLUR = false;
  96267. /**
  96268. * True if you want the material to fade to reflection at grazing angle.
  96269. */
  96270. _this.REFLECTIONFRESNEL = false;
  96271. /**
  96272. * True if you want the material to falloff as far as you move away from the scene center.
  96273. */
  96274. _this.REFLECTIONFALLOFF = false;
  96275. /**
  96276. * False if the current Webgl implementation does not support the texture lod extension.
  96277. */
  96278. _this.TEXTURELODSUPPORT = false;
  96279. /**
  96280. * True to ensure the data are premultiplied.
  96281. */
  96282. _this.PREMULTIPLYALPHA = false;
  96283. /**
  96284. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  96285. */
  96286. _this.USERGBCOLOR = false;
  96287. /**
  96288. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  96289. * stays aligned with the desired configuration.
  96290. */
  96291. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  96292. /**
  96293. * True to add noise in order to reduce the banding effect.
  96294. */
  96295. _this.NOISE = false;
  96296. /**
  96297. * is the reflection texture in BGR color scheme?
  96298. * Mainly used to solve a bug in ios10 video tag
  96299. */
  96300. _this.REFLECTIONBGR = false;
  96301. _this.IMAGEPROCESSING = false;
  96302. _this.VIGNETTE = false;
  96303. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  96304. _this.VIGNETTEBLENDMODEOPAQUE = false;
  96305. _this.TONEMAPPING = false;
  96306. _this.CONTRAST = false;
  96307. _this.COLORCURVES = false;
  96308. _this.COLORGRADING = false;
  96309. _this.COLORGRADING3D = false;
  96310. _this.SAMPLER3DGREENDEPTH = false;
  96311. _this.SAMPLER3DBGRMAP = false;
  96312. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  96313. _this.EXPOSURE = false;
  96314. // Reflection.
  96315. _this.REFLECTION = false;
  96316. _this.REFLECTIONMAP_3D = false;
  96317. _this.REFLECTIONMAP_SPHERICAL = false;
  96318. _this.REFLECTIONMAP_PLANAR = false;
  96319. _this.REFLECTIONMAP_CUBIC = false;
  96320. _this.REFLECTIONMAP_PROJECTION = false;
  96321. _this.REFLECTIONMAP_SKYBOX = false;
  96322. _this.REFLECTIONMAP_EXPLICIT = false;
  96323. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96324. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96325. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96326. _this.INVERTCUBICMAP = false;
  96327. _this.REFLECTIONMAP_OPPOSITEZ = false;
  96328. _this.LODINREFLECTIONALPHA = false;
  96329. _this.GAMMAREFLECTION = false;
  96330. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  96331. // Default BJS.
  96332. _this.MAINUV1 = false;
  96333. _this.MAINUV2 = false;
  96334. _this.UV1 = false;
  96335. _this.UV2 = false;
  96336. _this.CLIPPLANE = false;
  96337. _this.POINTSIZE = false;
  96338. _this.FOG = false;
  96339. _this.NORMAL = false;
  96340. _this.NUM_BONE_INFLUENCERS = 0;
  96341. _this.BonesPerMesh = 0;
  96342. _this.INSTANCES = false;
  96343. _this.SHADOWFLOAT = false;
  96344. _this.rebuild();
  96345. return _this;
  96346. }
  96347. return BackgroundMaterialDefines;
  96348. }(BABYLON.MaterialDefines));
  96349. /**
  96350. * Background material used to create an efficient environement around your scene.
  96351. */
  96352. var BackgroundMaterial = /** @class */ (function (_super) {
  96353. __extends(BackgroundMaterial, _super);
  96354. /**
  96355. * Instantiates a Background Material in the given scene
  96356. * @param name The friendly name of the material
  96357. * @param scene The scene to add the material to
  96358. */
  96359. function BackgroundMaterial(name, scene) {
  96360. var _this = _super.call(this, name, scene) || this;
  96361. /**
  96362. * Key light Color (multiply against the environement texture)
  96363. */
  96364. _this.primaryColor = BABYLON.Color3.White();
  96365. _this._primaryColorShadowLevel = 0;
  96366. _this._primaryColorHighlightLevel = 0;
  96367. /**
  96368. * Reflection Texture used in the material.
  96369. * Should be author in a specific way for the best result (refer to the documentation).
  96370. */
  96371. _this.reflectionTexture = null;
  96372. /**
  96373. * Reflection Texture level of blur.
  96374. *
  96375. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  96376. * texture twice.
  96377. */
  96378. _this.reflectionBlur = 0;
  96379. /**
  96380. * Diffuse Texture used in the material.
  96381. * Should be author in a specific way for the best result (refer to the documentation).
  96382. */
  96383. _this.diffuseTexture = null;
  96384. _this._shadowLights = null;
  96385. /**
  96386. * Specify the list of lights casting shadow on the material.
  96387. * All scene shadow lights will be included if null.
  96388. */
  96389. _this.shadowLights = null;
  96390. /**
  96391. * Helps adjusting the shadow to a softer level if required.
  96392. * 0 means black shadows and 1 means no shadows.
  96393. */
  96394. _this.shadowLevel = 0;
  96395. /**
  96396. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  96397. * It is usually zero but might be interesting to modify according to your setup.
  96398. */
  96399. _this.sceneCenter = BABYLON.Vector3.Zero();
  96400. /**
  96401. * This helps specifying that the material is falling off to the sky box at grazing angle.
  96402. * This helps ensuring a nice transition when the camera goes under the ground.
  96403. */
  96404. _this.opacityFresnel = true;
  96405. /**
  96406. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  96407. * This helps adding a mirror texture on the ground.
  96408. */
  96409. _this.reflectionFresnel = false;
  96410. /**
  96411. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96412. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96413. */
  96414. _this.reflectionFalloffDistance = 0.0;
  96415. /**
  96416. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96417. */
  96418. _this.reflectionAmount = 1.0;
  96419. /**
  96420. * This specifies the weight of the reflection at grazing angle.
  96421. */
  96422. _this.reflectionReflectance0 = 0.05;
  96423. /**
  96424. * This specifies the weight of the reflection at a perpendicular point of view.
  96425. */
  96426. _this.reflectionReflectance90 = 0.5;
  96427. /**
  96428. * Helps to directly use the maps channels instead of their level.
  96429. */
  96430. _this.useRGBColor = true;
  96431. /**
  96432. * This helps reducing the banding effect that could occur on the background.
  96433. */
  96434. _this.enableNoise = false;
  96435. _this._fovMultiplier = 1.0;
  96436. /**
  96437. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96438. */
  96439. _this.useEquirectangularFOV = false;
  96440. _this._maxSimultaneousLights = 4;
  96441. /**
  96442. * Number of Simultaneous lights allowed on the material.
  96443. */
  96444. _this.maxSimultaneousLights = 4;
  96445. /**
  96446. * Keep track of the image processing observer to allow dispose and replace.
  96447. */
  96448. _this._imageProcessingObserver = null;
  96449. /**
  96450. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96451. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96452. */
  96453. _this.switchToBGR = false;
  96454. // Temp values kept as cache in the material.
  96455. _this._renderTargets = new BABYLON.SmartArray(16);
  96456. _this._reflectionControls = BABYLON.Vector4.Zero();
  96457. _this._white = BABYLON.Color3.White();
  96458. _this._primaryShadowColor = BABYLON.Color3.Black();
  96459. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96460. // Setup the default processing configuration to the scene.
  96461. _this._attachImageProcessingConfiguration(null);
  96462. _this.getRenderTargetTextures = function () {
  96463. _this._renderTargets.reset();
  96464. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96465. _this._renderTargets.push(_this._diffuseTexture);
  96466. }
  96467. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96468. _this._renderTargets.push(_this._reflectionTexture);
  96469. }
  96470. return _this._renderTargets;
  96471. };
  96472. return _this;
  96473. }
  96474. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96475. /**
  96476. * Experimental Internal Use Only.
  96477. *
  96478. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96479. * This acts as a helper to set the primary color to a more "human friendly" value.
  96480. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96481. * output color as close as possible from the chosen value.
  96482. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96483. * part of lighting setup.)
  96484. */
  96485. get: function () {
  96486. return this.__perceptualColor;
  96487. },
  96488. set: function (value) {
  96489. this.__perceptualColor = value;
  96490. this._computePrimaryColorFromPerceptualColor();
  96491. this._markAllSubMeshesAsLightsDirty();
  96492. },
  96493. enumerable: true,
  96494. configurable: true
  96495. });
  96496. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96497. /**
  96498. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96499. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96500. */
  96501. get: function () {
  96502. return this._primaryColorShadowLevel;
  96503. },
  96504. set: function (value) {
  96505. this._primaryColorShadowLevel = value;
  96506. this._computePrimaryColors();
  96507. this._markAllSubMeshesAsLightsDirty();
  96508. },
  96509. enumerable: true,
  96510. configurable: true
  96511. });
  96512. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96513. /**
  96514. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96515. * The primary color is used at the level chosen to define what the white area would look.
  96516. */
  96517. get: function () {
  96518. return this._primaryColorHighlightLevel;
  96519. },
  96520. set: function (value) {
  96521. this._primaryColorHighlightLevel = value;
  96522. this._computePrimaryColors();
  96523. this._markAllSubMeshesAsLightsDirty();
  96524. },
  96525. enumerable: true,
  96526. configurable: true
  96527. });
  96528. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96529. /**
  96530. * Sets the reflection reflectance fresnel values according to the default standard
  96531. * empirically know to work well :-)
  96532. */
  96533. set: function (value) {
  96534. var reflectionWeight = value;
  96535. if (reflectionWeight < 0.5) {
  96536. reflectionWeight = reflectionWeight * 2.0;
  96537. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96538. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96539. }
  96540. else {
  96541. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96542. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96543. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96544. }
  96545. },
  96546. enumerable: true,
  96547. configurable: true
  96548. });
  96549. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96550. /**
  96551. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96552. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96553. * Recommended to be keep at 1.0 except for special cases.
  96554. */
  96555. get: function () {
  96556. return this._fovMultiplier;
  96557. },
  96558. set: function (value) {
  96559. if (isNaN(value)) {
  96560. value = 1.0;
  96561. }
  96562. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96563. },
  96564. enumerable: true,
  96565. configurable: true
  96566. });
  96567. /**
  96568. * Attaches a new image processing configuration to the PBR Material.
  96569. * @param configuration (if null the scene configuration will be use)
  96570. */
  96571. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96572. var _this = this;
  96573. if (configuration === this._imageProcessingConfiguration) {
  96574. return;
  96575. }
  96576. // Detaches observer.
  96577. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96578. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96579. }
  96580. // Pick the scene configuration if needed.
  96581. if (!configuration) {
  96582. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96583. }
  96584. else {
  96585. this._imageProcessingConfiguration = configuration;
  96586. }
  96587. // Attaches observer.
  96588. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96589. _this._computePrimaryColorFromPerceptualColor();
  96590. _this._markAllSubMeshesAsImageProcessingDirty();
  96591. });
  96592. };
  96593. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96594. /**
  96595. * Gets the image processing configuration used either in this material.
  96596. */
  96597. get: function () {
  96598. return this._imageProcessingConfiguration;
  96599. },
  96600. /**
  96601. * Sets the Default image processing configuration used either in the this material.
  96602. *
  96603. * If sets to null, the scene one is in use.
  96604. */
  96605. set: function (value) {
  96606. this._attachImageProcessingConfiguration(value);
  96607. // Ensure the effect will be rebuilt.
  96608. this._markAllSubMeshesAsTexturesDirty();
  96609. },
  96610. enumerable: true,
  96611. configurable: true
  96612. });
  96613. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96614. /**
  96615. * Gets wether the color curves effect is enabled.
  96616. */
  96617. get: function () {
  96618. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96619. },
  96620. /**
  96621. * Sets wether the color curves effect is enabled.
  96622. */
  96623. set: function (value) {
  96624. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96625. },
  96626. enumerable: true,
  96627. configurable: true
  96628. });
  96629. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96630. /**
  96631. * Gets wether the color grading effect is enabled.
  96632. */
  96633. get: function () {
  96634. return this.imageProcessingConfiguration.colorGradingEnabled;
  96635. },
  96636. /**
  96637. * Gets wether the color grading effect is enabled.
  96638. */
  96639. set: function (value) {
  96640. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96641. },
  96642. enumerable: true,
  96643. configurable: true
  96644. });
  96645. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96646. /**
  96647. * Gets wether tonemapping is enabled or not.
  96648. */
  96649. get: function () {
  96650. return this._imageProcessingConfiguration.toneMappingEnabled;
  96651. },
  96652. /**
  96653. * Sets wether tonemapping is enabled or not
  96654. */
  96655. set: function (value) {
  96656. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96657. },
  96658. enumerable: true,
  96659. configurable: true
  96660. });
  96661. ;
  96662. ;
  96663. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96664. /**
  96665. * The camera exposure used on this material.
  96666. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96667. * This corresponds to a photographic exposure.
  96668. */
  96669. get: function () {
  96670. return this._imageProcessingConfiguration.exposure;
  96671. },
  96672. /**
  96673. * The camera exposure used on this material.
  96674. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96675. * This corresponds to a photographic exposure.
  96676. */
  96677. set: function (value) {
  96678. this._imageProcessingConfiguration.exposure = value;
  96679. },
  96680. enumerable: true,
  96681. configurable: true
  96682. });
  96683. ;
  96684. ;
  96685. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96686. /**
  96687. * Gets The camera contrast used on this material.
  96688. */
  96689. get: function () {
  96690. return this._imageProcessingConfiguration.contrast;
  96691. },
  96692. /**
  96693. * Sets The camera contrast used on this material.
  96694. */
  96695. set: function (value) {
  96696. this._imageProcessingConfiguration.contrast = value;
  96697. },
  96698. enumerable: true,
  96699. configurable: true
  96700. });
  96701. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96702. /**
  96703. * Gets the Color Grading 2D Lookup Texture.
  96704. */
  96705. get: function () {
  96706. return this._imageProcessingConfiguration.colorGradingTexture;
  96707. },
  96708. /**
  96709. * Sets the Color Grading 2D Lookup Texture.
  96710. */
  96711. set: function (value) {
  96712. this.imageProcessingConfiguration.colorGradingTexture = value;
  96713. },
  96714. enumerable: true,
  96715. configurable: true
  96716. });
  96717. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96718. /**
  96719. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96720. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96721. * 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;
  96722. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96723. */
  96724. get: function () {
  96725. return this.imageProcessingConfiguration.colorCurves;
  96726. },
  96727. /**
  96728. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96729. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96730. * 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;
  96731. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96732. */
  96733. set: function (value) {
  96734. this.imageProcessingConfiguration.colorCurves = value;
  96735. },
  96736. enumerable: true,
  96737. configurable: true
  96738. });
  96739. /**
  96740. * The entire material has been created in order to prevent overdraw.
  96741. * @returns false
  96742. */
  96743. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96744. return true;
  96745. };
  96746. /**
  96747. * The entire material has been created in order to prevent overdraw.
  96748. * @returns true if blending is enable
  96749. */
  96750. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96751. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96752. };
  96753. /**
  96754. * Checks wether the material is ready to be rendered for a given mesh.
  96755. * @param mesh The mesh to render
  96756. * @param subMesh The submesh to check against
  96757. * @param useInstances Specify wether or not the material is used with instances
  96758. * @returns true if all the dependencies are ready (Textures, Effects...)
  96759. */
  96760. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96761. var _this = this;
  96762. if (useInstances === void 0) { useInstances = false; }
  96763. if (subMesh.effect && this.isFrozen) {
  96764. if (this._wasPreviouslyReady) {
  96765. return true;
  96766. }
  96767. }
  96768. if (!subMesh._materialDefines) {
  96769. subMesh._materialDefines = new BackgroundMaterialDefines();
  96770. }
  96771. var scene = this.getScene();
  96772. var defines = subMesh._materialDefines;
  96773. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96774. if (defines._renderId === scene.getRenderId()) {
  96775. return true;
  96776. }
  96777. }
  96778. var engine = scene.getEngine();
  96779. // Lights
  96780. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96781. defines._needNormals = true;
  96782. // Textures
  96783. if (defines._areTexturesDirty) {
  96784. defines._needUVs = false;
  96785. if (scene.texturesEnabled) {
  96786. if (scene.getEngine().getCaps().textureLOD) {
  96787. defines.TEXTURELODSUPPORT = true;
  96788. }
  96789. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96790. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96791. return false;
  96792. }
  96793. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96794. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96795. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96796. defines.OPACITYFRESNEL = this._opacityFresnel;
  96797. }
  96798. else {
  96799. defines.DIFFUSE = false;
  96800. defines.DIFFUSEHASALPHA = false;
  96801. defines.GAMMADIFFUSE = false;
  96802. defines.OPACITYFRESNEL = false;
  96803. }
  96804. var reflectionTexture = this._reflectionTexture;
  96805. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96806. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96807. return false;
  96808. }
  96809. defines.REFLECTION = true;
  96810. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96811. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96812. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96813. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96814. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96815. defines.REFLECTIONBGR = this.switchToBGR;
  96816. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96817. defines.INVERTCUBICMAP = true;
  96818. }
  96819. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96820. switch (reflectionTexture.coordinatesMode) {
  96821. case BABYLON.Texture.EXPLICIT_MODE:
  96822. defines.REFLECTIONMAP_EXPLICIT = true;
  96823. break;
  96824. case BABYLON.Texture.PLANAR_MODE:
  96825. defines.REFLECTIONMAP_PLANAR = true;
  96826. break;
  96827. case BABYLON.Texture.PROJECTION_MODE:
  96828. defines.REFLECTIONMAP_PROJECTION = true;
  96829. break;
  96830. case BABYLON.Texture.SKYBOX_MODE:
  96831. defines.REFLECTIONMAP_SKYBOX = true;
  96832. break;
  96833. case BABYLON.Texture.SPHERICAL_MODE:
  96834. defines.REFLECTIONMAP_SPHERICAL = true;
  96835. break;
  96836. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96837. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96838. break;
  96839. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96840. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96841. break;
  96842. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96843. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96844. break;
  96845. case BABYLON.Texture.CUBIC_MODE:
  96846. case BABYLON.Texture.INVCUBIC_MODE:
  96847. default:
  96848. defines.REFLECTIONMAP_CUBIC = true;
  96849. break;
  96850. }
  96851. if (this.reflectionFresnel) {
  96852. defines.REFLECTIONFRESNEL = true;
  96853. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96854. this._reflectionControls.x = this.reflectionAmount;
  96855. this._reflectionControls.y = this.reflectionReflectance0;
  96856. this._reflectionControls.z = this.reflectionReflectance90;
  96857. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96858. }
  96859. else {
  96860. defines.REFLECTIONFRESNEL = false;
  96861. defines.REFLECTIONFALLOFF = false;
  96862. }
  96863. }
  96864. else {
  96865. defines.REFLECTION = false;
  96866. defines.REFLECTIONFRESNEL = false;
  96867. defines.REFLECTIONFALLOFF = false;
  96868. defines.REFLECTIONBLUR = false;
  96869. defines.REFLECTIONMAP_3D = false;
  96870. defines.REFLECTIONMAP_SPHERICAL = false;
  96871. defines.REFLECTIONMAP_PLANAR = false;
  96872. defines.REFLECTIONMAP_CUBIC = false;
  96873. defines.REFLECTIONMAP_PROJECTION = false;
  96874. defines.REFLECTIONMAP_SKYBOX = false;
  96875. defines.REFLECTIONMAP_EXPLICIT = false;
  96876. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96877. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96878. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96879. defines.INVERTCUBICMAP = false;
  96880. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96881. defines.LODINREFLECTIONALPHA = false;
  96882. defines.GAMMAREFLECTION = false;
  96883. }
  96884. }
  96885. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96886. defines.USERGBCOLOR = this._useRGBColor;
  96887. defines.NOISE = this._enableNoise;
  96888. }
  96889. if (defines._areLightsDirty) {
  96890. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96891. }
  96892. if (defines._areImageProcessingDirty) {
  96893. if (!this._imageProcessingConfiguration.isReady()) {
  96894. return false;
  96895. }
  96896. this._imageProcessingConfiguration.prepareDefines(defines);
  96897. }
  96898. // Misc.
  96899. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96900. // Values that need to be evaluated on every frame
  96901. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96902. // Attribs
  96903. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96904. if (mesh) {
  96905. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96906. mesh.createNormals(true);
  96907. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96908. }
  96909. }
  96910. }
  96911. // Get correct effect
  96912. if (defines.isDirty) {
  96913. defines.markAsProcessed();
  96914. scene.resetCachedMaterial();
  96915. // Fallbacks
  96916. var fallbacks = new BABYLON.EffectFallbacks();
  96917. if (defines.FOG) {
  96918. fallbacks.addFallback(0, "FOG");
  96919. }
  96920. if (defines.POINTSIZE) {
  96921. fallbacks.addFallback(1, "POINTSIZE");
  96922. }
  96923. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96924. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96925. fallbacks.addCPUSkinningFallback(0, mesh);
  96926. }
  96927. //Attributes
  96928. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96929. if (defines.NORMAL) {
  96930. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96931. }
  96932. if (defines.UV1) {
  96933. attribs.push(BABYLON.VertexBuffer.UVKind);
  96934. }
  96935. if (defines.UV2) {
  96936. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96937. }
  96938. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96939. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96940. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96941. "vFogInfos", "vFogColor", "pointSize",
  96942. "vClipPlane", "mBones",
  96943. "vPrimaryColor", "vPrimaryColorShadow",
  96944. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96945. "shadowLevel", "alpha",
  96946. "vBackgroundCenter", "vReflectionControl",
  96947. "vDiffuseInfos", "diffuseMatrix",
  96948. ];
  96949. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96950. var uniformBuffers = ["Material", "Scene"];
  96951. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96952. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96953. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96954. uniformsNames: uniforms,
  96955. uniformBuffersNames: uniformBuffers,
  96956. samplers: samplers,
  96957. defines: defines,
  96958. maxSimultaneousLights: this._maxSimultaneousLights
  96959. });
  96960. var onCompiled = function (effect) {
  96961. if (_this.onCompiled) {
  96962. _this.onCompiled(effect);
  96963. }
  96964. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96965. };
  96966. var join = defines.toString();
  96967. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96968. attributes: attribs,
  96969. uniformsNames: uniforms,
  96970. uniformBuffersNames: uniformBuffers,
  96971. samplers: samplers,
  96972. defines: join,
  96973. fallbacks: fallbacks,
  96974. onCompiled: onCompiled,
  96975. onError: this.onError,
  96976. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96977. }, engine), defines);
  96978. this.buildUniformLayout();
  96979. }
  96980. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96981. return false;
  96982. }
  96983. defines._renderId = scene.getRenderId();
  96984. this._wasPreviouslyReady = true;
  96985. return true;
  96986. };
  96987. /**
  96988. * Compute the primary color according to the chosen perceptual color.
  96989. */
  96990. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96991. if (!this.__perceptualColor) {
  96992. return;
  96993. }
  96994. this._primaryColor.copyFrom(this.__perceptualColor);
  96995. // Revert gamma space.
  96996. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96997. // Revert image processing configuration.
  96998. if (this._imageProcessingConfiguration) {
  96999. // Revert Exposure.
  97000. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  97001. }
  97002. this._computePrimaryColors();
  97003. };
  97004. /**
  97005. * Compute the highlights and shadow colors according to their chosen levels.
  97006. */
  97007. BackgroundMaterial.prototype._computePrimaryColors = function () {
  97008. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  97009. return;
  97010. }
  97011. // Find the highlight color based on the configuration.
  97012. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  97013. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  97014. // Find the shadow color based on the configuration.
  97015. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  97016. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  97017. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  97018. };
  97019. /**
  97020. * Build the uniform buffer used in the material.
  97021. */
  97022. BackgroundMaterial.prototype.buildUniformLayout = function () {
  97023. // Order is important !
  97024. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  97025. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  97026. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  97027. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  97028. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  97029. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  97030. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  97031. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  97032. this._uniformBuffer.addUniform("pointSize", 1);
  97033. this._uniformBuffer.addUniform("shadowLevel", 1);
  97034. this._uniformBuffer.addUniform("alpha", 1);
  97035. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  97036. this._uniformBuffer.addUniform("vReflectionControl", 4);
  97037. this._uniformBuffer.create();
  97038. };
  97039. /**
  97040. * Unbind the material.
  97041. */
  97042. BackgroundMaterial.prototype.unbind = function () {
  97043. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  97044. this._uniformBuffer.setTexture("diffuseSampler", null);
  97045. }
  97046. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  97047. this._uniformBuffer.setTexture("reflectionSampler", null);
  97048. }
  97049. _super.prototype.unbind.call(this);
  97050. };
  97051. /**
  97052. * Bind only the world matrix to the material.
  97053. * @param world The world matrix to bind.
  97054. */
  97055. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  97056. this._activeEffect.setMatrix("world", world);
  97057. };
  97058. /**
  97059. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  97060. * @param world The world matrix to bind.
  97061. * @param subMesh The submesh to bind for.
  97062. */
  97063. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  97064. var scene = this.getScene();
  97065. var defines = subMesh._materialDefines;
  97066. if (!defines) {
  97067. return;
  97068. }
  97069. var effect = subMesh.effect;
  97070. if (!effect) {
  97071. return;
  97072. }
  97073. this._activeEffect = effect;
  97074. // Matrices
  97075. this.bindOnlyWorldMatrix(world);
  97076. // Bones
  97077. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  97078. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  97079. if (mustRebind) {
  97080. this._uniformBuffer.bindToEffect(effect, "Material");
  97081. this.bindViewProjection(effect);
  97082. var reflectionTexture = this._reflectionTexture;
  97083. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  97084. // Texture uniforms
  97085. if (scene.texturesEnabled) {
  97086. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97087. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  97088. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  97089. }
  97090. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97091. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  97092. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  97093. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  97094. }
  97095. }
  97096. if (this.shadowLevel > 0) {
  97097. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  97098. }
  97099. this._uniformBuffer.updateFloat("alpha", this.alpha);
  97100. // Point size
  97101. if (this.pointsCloud) {
  97102. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  97103. }
  97104. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  97105. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  97106. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  97107. }
  97108. else {
  97109. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  97110. }
  97111. }
  97112. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  97113. // Textures
  97114. if (scene.texturesEnabled) {
  97115. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97116. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  97117. }
  97118. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97119. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  97120. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97121. }
  97122. else if (!defines.REFLECTIONBLUR) {
  97123. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97124. }
  97125. else {
  97126. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  97127. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  97128. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  97129. }
  97130. if (defines.REFLECTIONFRESNEL) {
  97131. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  97132. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  97133. }
  97134. }
  97135. }
  97136. // Clip plane
  97137. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  97138. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  97139. }
  97140. if (mustRebind || !this.isFrozen) {
  97141. if (scene.lightsEnabled) {
  97142. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  97143. }
  97144. // View
  97145. this.bindView(effect);
  97146. // Fog
  97147. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  97148. // image processing
  97149. this._imageProcessingConfiguration.bind(this._activeEffect);
  97150. }
  97151. this._uniformBuffer.update();
  97152. this._afterBind(mesh);
  97153. };
  97154. /**
  97155. * Dispose the material.
  97156. * @param forceDisposeEffect Force disposal of the associated effect.
  97157. * @param forceDisposeTextures Force disposal of the associated textures.
  97158. */
  97159. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  97160. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  97161. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  97162. if (forceDisposeTextures) {
  97163. if (this.diffuseTexture) {
  97164. this.diffuseTexture.dispose();
  97165. }
  97166. if (this.reflectionTexture) {
  97167. this.reflectionTexture.dispose();
  97168. }
  97169. }
  97170. this._renderTargets.dispose();
  97171. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97172. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97173. }
  97174. _super.prototype.dispose.call(this, forceDisposeEffect);
  97175. };
  97176. /**
  97177. * Clones the material.
  97178. * @param name The cloned name.
  97179. * @returns The cloned material.
  97180. */
  97181. BackgroundMaterial.prototype.clone = function (name) {
  97182. var _this = this;
  97183. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  97184. };
  97185. /**
  97186. * Serializes the current material to its JSON representation.
  97187. * @returns The JSON representation.
  97188. */
  97189. BackgroundMaterial.prototype.serialize = function () {
  97190. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97191. serializationObject.customType = "BABYLON.BackgroundMaterial";
  97192. return serializationObject;
  97193. };
  97194. /**
  97195. * Gets the class name of the material
  97196. * @returns "BackgroundMaterial"
  97197. */
  97198. BackgroundMaterial.prototype.getClassName = function () {
  97199. return "BackgroundMaterial";
  97200. };
  97201. /**
  97202. * Parse a JSON input to create back a background material.
  97203. * @param source The JSON data to parse
  97204. * @param scene The scene to create the parsed material in
  97205. * @param rootUrl The root url of the assets the material depends upon
  97206. * @returns the instantiated BackgroundMaterial.
  97207. */
  97208. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  97209. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  97210. };
  97211. /**
  97212. * Standard reflectance value at parallel view angle.
  97213. */
  97214. BackgroundMaterial.StandardReflectance0 = 0.05;
  97215. /**
  97216. * Standard reflectance value at grazing angle.
  97217. */
  97218. BackgroundMaterial.StandardReflectance90 = 0.5;
  97219. __decorate([
  97220. BABYLON.serializeAsColor3()
  97221. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  97222. __decorate([
  97223. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97224. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  97225. __decorate([
  97226. BABYLON.serializeAsColor3()
  97227. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  97228. __decorate([
  97229. BABYLON.serialize()
  97230. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  97231. __decorate([
  97232. BABYLON.serialize()
  97233. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  97234. __decorate([
  97235. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97236. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  97237. __decorate([
  97238. BABYLON.serializeAsTexture()
  97239. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  97240. __decorate([
  97241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97242. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  97243. __decorate([
  97244. BABYLON.serialize()
  97245. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  97246. __decorate([
  97247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97248. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  97249. __decorate([
  97250. BABYLON.serializeAsTexture()
  97251. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  97252. __decorate([
  97253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97254. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  97255. __decorate([
  97256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97257. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  97258. __decorate([
  97259. BABYLON.serialize()
  97260. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  97261. __decorate([
  97262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97263. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  97264. __decorate([
  97265. BABYLON.serializeAsVector3()
  97266. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  97267. __decorate([
  97268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97269. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  97270. __decorate([
  97271. BABYLON.serialize()
  97272. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  97273. __decorate([
  97274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97275. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  97276. __decorate([
  97277. BABYLON.serialize()
  97278. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  97279. __decorate([
  97280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97281. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  97282. __decorate([
  97283. BABYLON.serialize()
  97284. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  97285. __decorate([
  97286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97287. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  97288. __decorate([
  97289. BABYLON.serialize()
  97290. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  97291. __decorate([
  97292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97293. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  97294. __decorate([
  97295. BABYLON.serialize()
  97296. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  97297. __decorate([
  97298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97299. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  97300. __decorate([
  97301. BABYLON.serialize()
  97302. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  97303. __decorate([
  97304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97305. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  97306. __decorate([
  97307. BABYLON.serialize()
  97308. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  97309. __decorate([
  97310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97311. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  97312. __decorate([
  97313. BABYLON.serialize()
  97314. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  97315. __decorate([
  97316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97317. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  97318. __decorate([
  97319. BABYLON.serialize()
  97320. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  97321. __decorate([
  97322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97323. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  97324. __decorate([
  97325. BABYLON.serializeAsImageProcessingConfiguration()
  97326. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  97327. return BackgroundMaterial;
  97328. }(BABYLON.PushMaterial));
  97329. BABYLON.BackgroundMaterial = BackgroundMaterial;
  97330. })(BABYLON || (BABYLON = {}));
  97331. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  97332. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97333. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97334. s = arguments[i];
  97335. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97336. t[p] = s[p];
  97337. }
  97338. return t;
  97339. };
  97340. var BABYLON;
  97341. (function (BABYLON) {
  97342. /**
  97343. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  97344. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  97345. * It also helps with the default setup of your imageProcessing configuration.
  97346. */
  97347. var EnvironmentHelper = /** @class */ (function () {
  97348. /**
  97349. * constructor
  97350. * @param options
  97351. * @param scene The scene to add the material to
  97352. */
  97353. function EnvironmentHelper(options, scene) {
  97354. var _this = this;
  97355. this._errorHandler = function (message, exception) {
  97356. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  97357. };
  97358. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  97359. this._scene = scene;
  97360. this.onErrorObservable = new BABYLON.Observable();
  97361. this._setupBackground();
  97362. this._setupImageProcessing();
  97363. }
  97364. /**
  97365. * Creates the default options for the helper.
  97366. */
  97367. EnvironmentHelper._getDefaultOptions = function () {
  97368. return {
  97369. createGround: true,
  97370. groundSize: 15,
  97371. groundTexture: this._groundTextureCDNUrl,
  97372. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97373. groundOpacity: 0.9,
  97374. enableGroundShadow: true,
  97375. groundShadowLevel: 0.5,
  97376. enableGroundMirror: false,
  97377. groundMirrorSizeRatio: 0.3,
  97378. groundMirrorBlurKernel: 64,
  97379. groundMirrorAmount: 1,
  97380. groundMirrorFresnelWeight: 1,
  97381. groundMirrorFallOffDistance: 0,
  97382. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  97383. groundYBias: 0.00001,
  97384. createSkybox: true,
  97385. skyboxSize: 20,
  97386. skyboxTexture: this._skyboxTextureCDNUrl,
  97387. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97388. backgroundYRotation: 0,
  97389. sizeAuto: true,
  97390. rootPosition: BABYLON.Vector3.Zero(),
  97391. setupImageProcessing: true,
  97392. environmentTexture: this._environmentTextureCDNUrl,
  97393. cameraExposure: 0.8,
  97394. cameraContrast: 1.2,
  97395. toneMappingEnabled: true,
  97396. };
  97397. };
  97398. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  97399. /**
  97400. * Gets the root mesh created by the helper.
  97401. */
  97402. get: function () {
  97403. return this._rootMesh;
  97404. },
  97405. enumerable: true,
  97406. configurable: true
  97407. });
  97408. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  97409. /**
  97410. * Gets the skybox created by the helper.
  97411. */
  97412. get: function () {
  97413. return this._skybox;
  97414. },
  97415. enumerable: true,
  97416. configurable: true
  97417. });
  97418. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97419. /**
  97420. * Gets the skybox texture created by the helper.
  97421. */
  97422. get: function () {
  97423. return this._skyboxTexture;
  97424. },
  97425. enumerable: true,
  97426. configurable: true
  97427. });
  97428. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97429. /**
  97430. * Gets the skybox material created by the helper.
  97431. */
  97432. get: function () {
  97433. return this._skyboxMaterial;
  97434. },
  97435. enumerable: true,
  97436. configurable: true
  97437. });
  97438. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97439. /**
  97440. * Gets the ground mesh created by the helper.
  97441. */
  97442. get: function () {
  97443. return this._ground;
  97444. },
  97445. enumerable: true,
  97446. configurable: true
  97447. });
  97448. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97449. /**
  97450. * Gets the ground texture created by the helper.
  97451. */
  97452. get: function () {
  97453. return this._groundTexture;
  97454. },
  97455. enumerable: true,
  97456. configurable: true
  97457. });
  97458. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97459. /**
  97460. * Gets the ground mirror created by the helper.
  97461. */
  97462. get: function () {
  97463. return this._groundMirror;
  97464. },
  97465. enumerable: true,
  97466. configurable: true
  97467. });
  97468. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97469. /**
  97470. * Gets the ground mirror render list to helps pushing the meshes
  97471. * you wish in the ground reflection.
  97472. */
  97473. get: function () {
  97474. if (this._groundMirror) {
  97475. return this._groundMirror.renderList;
  97476. }
  97477. return null;
  97478. },
  97479. enumerable: true,
  97480. configurable: true
  97481. });
  97482. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97483. /**
  97484. * Gets the ground material created by the helper.
  97485. */
  97486. get: function () {
  97487. return this._groundMaterial;
  97488. },
  97489. enumerable: true,
  97490. configurable: true
  97491. });
  97492. /**
  97493. * Updates the background according to the new options
  97494. * @param options
  97495. */
  97496. EnvironmentHelper.prototype.updateOptions = function (options) {
  97497. var newOptions = __assign({}, this._options, options);
  97498. if (this._ground && !newOptions.createGround) {
  97499. this._ground.dispose();
  97500. this._ground = null;
  97501. }
  97502. if (this._groundMaterial && !newOptions.createGround) {
  97503. this._groundMaterial.dispose();
  97504. this._groundMaterial = null;
  97505. }
  97506. if (this._groundTexture) {
  97507. if (this._options.groundTexture != newOptions.groundTexture) {
  97508. this._groundTexture.dispose();
  97509. this._groundTexture = null;
  97510. }
  97511. }
  97512. if (this._skybox && !newOptions.createSkybox) {
  97513. this._skybox.dispose();
  97514. this._skybox = null;
  97515. }
  97516. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97517. this._skyboxMaterial.dispose();
  97518. this._skyboxMaterial = null;
  97519. }
  97520. if (this._skyboxTexture) {
  97521. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97522. this._skyboxTexture.dispose();
  97523. this._skyboxTexture = null;
  97524. }
  97525. }
  97526. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97527. this._groundMirror.dispose();
  97528. this._groundMirror = null;
  97529. }
  97530. if (this._scene.environmentTexture) {
  97531. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97532. this._scene.environmentTexture.dispose();
  97533. }
  97534. }
  97535. this._options = newOptions;
  97536. this._setupBackground();
  97537. this._setupImageProcessing();
  97538. };
  97539. /**
  97540. * Sets the primary color of all the available elements.
  97541. * @param color the main color to affect to the ground and the background
  97542. */
  97543. EnvironmentHelper.prototype.setMainColor = function (color) {
  97544. if (this.groundMaterial) {
  97545. this.groundMaterial.primaryColor = color;
  97546. }
  97547. if (this.skyboxMaterial) {
  97548. this.skyboxMaterial.primaryColor = color;
  97549. }
  97550. if (this.groundMirror) {
  97551. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97552. }
  97553. };
  97554. /**
  97555. * Setup the image processing according to the specified options.
  97556. */
  97557. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97558. if (this._options.setupImageProcessing) {
  97559. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97560. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97561. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97562. this._setupEnvironmentTexture();
  97563. }
  97564. };
  97565. /**
  97566. * Setup the environment texture according to the specified options.
  97567. */
  97568. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97569. if (this._scene.environmentTexture) {
  97570. return;
  97571. }
  97572. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97573. this._scene.environmentTexture = this._options.environmentTexture;
  97574. return;
  97575. }
  97576. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97577. this._scene.environmentTexture = environmentTexture;
  97578. };
  97579. /**
  97580. * Setup the background according to the specified options.
  97581. */
  97582. EnvironmentHelper.prototype._setupBackground = function () {
  97583. if (!this._rootMesh) {
  97584. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97585. }
  97586. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97587. var sceneSize = this._getSceneSize();
  97588. if (this._options.createGround) {
  97589. this._setupGround(sceneSize);
  97590. this._setupGroundMaterial();
  97591. this._setupGroundDiffuseTexture();
  97592. if (this._options.enableGroundMirror) {
  97593. this._setupGroundMirrorTexture(sceneSize);
  97594. }
  97595. this._setupMirrorInGroundMaterial();
  97596. }
  97597. if (this._options.createSkybox) {
  97598. this._setupSkybox(sceneSize);
  97599. this._setupSkyboxMaterial();
  97600. this._setupSkyboxReflectionTexture();
  97601. }
  97602. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97603. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97604. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97605. };
  97606. /**
  97607. * Get the scene sizes according to the setup.
  97608. */
  97609. EnvironmentHelper.prototype._getSceneSize = function () {
  97610. var _this = this;
  97611. var groundSize = this._options.groundSize;
  97612. var skyboxSize = this._options.skyboxSize;
  97613. var rootPosition = this._options.rootPosition;
  97614. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97615. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97616. }
  97617. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97618. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97619. });
  97620. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97621. if (this._options.sizeAuto) {
  97622. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97623. this._scene.activeCamera.upperRadiusLimit) {
  97624. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97625. skyboxSize = groundSize;
  97626. }
  97627. var sceneDiagonalLenght = sceneDiagonal.length();
  97628. if (sceneDiagonalLenght > groundSize) {
  97629. groundSize = sceneDiagonalLenght * 2;
  97630. skyboxSize = groundSize;
  97631. }
  97632. // 10 % bigger.
  97633. groundSize *= 1.1;
  97634. skyboxSize *= 1.5;
  97635. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97636. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97637. }
  97638. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97639. };
  97640. /**
  97641. * Setup the ground according to the specified options.
  97642. */
  97643. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97644. var _this = this;
  97645. if (!this._ground) {
  97646. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97647. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97648. this._ground.parent = this._rootMesh;
  97649. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97650. }
  97651. this._ground.receiveShadows = this._options.enableGroundShadow;
  97652. };
  97653. /**
  97654. * Setup the ground material according to the specified options.
  97655. */
  97656. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97657. if (!this._groundMaterial) {
  97658. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97659. }
  97660. this._groundMaterial.alpha = this._options.groundOpacity;
  97661. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97662. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97663. this._groundMaterial.primaryColor = this._options.groundColor;
  97664. this._groundMaterial.useRGBColor = false;
  97665. this._groundMaterial.enableNoise = true;
  97666. if (this._ground) {
  97667. this._ground.material = this._groundMaterial;
  97668. }
  97669. };
  97670. /**
  97671. * Setup the ground diffuse texture according to the specified options.
  97672. */
  97673. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97674. if (!this._groundMaterial) {
  97675. return;
  97676. }
  97677. if (this._groundTexture) {
  97678. return;
  97679. }
  97680. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97681. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97682. return;
  97683. }
  97684. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97685. diffuseTexture.gammaSpace = false;
  97686. diffuseTexture.hasAlpha = true;
  97687. this._groundMaterial.diffuseTexture = diffuseTexture;
  97688. };
  97689. /**
  97690. * Setup the ground mirror texture according to the specified options.
  97691. */
  97692. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97693. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97694. if (!this._groundMirror) {
  97695. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97696. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97697. this._groundMirror.anisotropicFilteringLevel = 1;
  97698. this._groundMirror.wrapU = wrapping;
  97699. this._groundMirror.wrapV = wrapping;
  97700. this._groundMirror.gammaSpace = false;
  97701. if (this._groundMirror.renderList) {
  97702. for (var i = 0; i < this._scene.meshes.length; i++) {
  97703. var mesh = this._scene.meshes[i];
  97704. if (mesh !== this._ground &&
  97705. mesh !== this._skybox &&
  97706. mesh !== this._rootMesh) {
  97707. this._groundMirror.renderList.push(mesh);
  97708. }
  97709. }
  97710. }
  97711. }
  97712. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97713. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97714. };
  97715. /**
  97716. * Setup the ground to receive the mirror texture.
  97717. */
  97718. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97719. if (this._groundMaterial) {
  97720. this._groundMaterial.reflectionTexture = this._groundMirror;
  97721. this._groundMaterial.reflectionFresnel = true;
  97722. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97723. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97724. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97725. }
  97726. };
  97727. /**
  97728. * Setup the skybox according to the specified options.
  97729. */
  97730. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97731. var _this = this;
  97732. if (!this._skybox) {
  97733. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97734. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97735. }
  97736. this._skybox.parent = this._rootMesh;
  97737. };
  97738. /**
  97739. * Setup the skybox material according to the specified options.
  97740. */
  97741. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97742. if (!this._skybox) {
  97743. return;
  97744. }
  97745. if (!this._skyboxMaterial) {
  97746. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97747. }
  97748. this._skyboxMaterial.useRGBColor = false;
  97749. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97750. this._skyboxMaterial.enableNoise = true;
  97751. this._skybox.material = this._skyboxMaterial;
  97752. };
  97753. /**
  97754. * Setup the skybox reflection texture according to the specified options.
  97755. */
  97756. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97757. if (!this._skyboxMaterial) {
  97758. return;
  97759. }
  97760. if (this._skyboxTexture) {
  97761. return;
  97762. }
  97763. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97764. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97765. return;
  97766. }
  97767. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97768. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97769. this._skyboxTexture.gammaSpace = false;
  97770. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97771. };
  97772. /**
  97773. * Dispose all the elements created by the Helper.
  97774. */
  97775. EnvironmentHelper.prototype.dispose = function () {
  97776. if (this._groundMaterial) {
  97777. this._groundMaterial.dispose(true, true);
  97778. }
  97779. if (this._skyboxMaterial) {
  97780. this._skyboxMaterial.dispose(true, true);
  97781. }
  97782. this._rootMesh.dispose(false);
  97783. };
  97784. /**
  97785. * Default ground texture URL.
  97786. */
  97787. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97788. /**
  97789. * Default skybox texture URL.
  97790. */
  97791. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97792. /**
  97793. * Default environment texture URL.
  97794. */
  97795. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97796. return EnvironmentHelper;
  97797. }());
  97798. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97799. })(BABYLON || (BABYLON = {}));
  97800. //# sourceMappingURL=babylon.environmentHelper.js.map
  97801. var BABYLON;
  97802. (function (BABYLON) {
  97803. /**
  97804. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97805. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97806. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97807. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97808. */
  97809. var VideoDome = /** @class */ (function (_super) {
  97810. __extends(VideoDome, _super);
  97811. /**
  97812. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97813. * @param name Element's name, child elements will append suffixes for their own names.
  97814. * @param urlsOrVideo
  97815. * @param options An object containing optional or exposed sub element properties:
  97816. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97817. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97818. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97819. * @param options **loop=true** Automatically loop video on end.
  97820. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97821. */
  97822. function VideoDome(name, urlsOrVideo, options, scene) {
  97823. var _this = _super.call(this, name, scene) || this;
  97824. // set defaults and manage values
  97825. name = name || "videoDome";
  97826. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97827. options.clickToPlay = Boolean(options.clickToPlay);
  97828. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97829. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97830. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97831. // create
  97832. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97833. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97834. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97835. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97836. flat: false,
  97837. radius: options.size,
  97838. subdivisions: options.resolution,
  97839. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97840. }, scene);
  97841. // configure material
  97842. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97843. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97844. material.reflectionTexture = _this._videoTexture;
  97845. material.useEquirectangularFOV = true;
  97846. material.fovMultiplier = 1.0;
  97847. // configure mesh
  97848. _this._mesh.material = material;
  97849. _this._mesh.parent = _this;
  97850. // optional configuration
  97851. if (options.clickToPlay) {
  97852. scene.onPointerUp = function () {
  97853. _this._videoTexture.video.play();
  97854. };
  97855. }
  97856. return _this;
  97857. }
  97858. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97859. /**
  97860. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97861. * Also see the options.resolution property.
  97862. */
  97863. get: function () {
  97864. return this._material.fovMultiplier;
  97865. },
  97866. set: function (value) {
  97867. this._material.fovMultiplier = value;
  97868. },
  97869. enumerable: true,
  97870. configurable: true
  97871. });
  97872. /**
  97873. * Releases resources associated with this node.
  97874. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97875. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97876. */
  97877. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97878. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97879. this._videoTexture.dispose();
  97880. this._mesh.dispose();
  97881. this._material.dispose();
  97882. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97883. };
  97884. return VideoDome;
  97885. }(BABYLON.Node));
  97886. BABYLON.VideoDome = VideoDome;
  97887. })(BABYLON || (BABYLON = {}));
  97888. //# sourceMappingURL=babylon.videoDome.js.map
  97889. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\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#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\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}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  97890. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};